/*!
- Ripple Mobile Environment Emulator v0.9.8 :: Built On Mon Jan 20 2014 11:00:22 GMT+0800 (CST)
+ Ripple Mobile Environment Emulator v0.9.8 :: Built On Mon Mar 10 2014 17:37:19 GMT+0800 (CST)
Apache License
Version 2.0, January 2004
};
})();
-define.unordered = true;define('ripple/accelerometer', function (require, exports, module) {
+define.unordered = true;define('ripple/db', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var _self,
+ _db,
utils = require('ripple/utils'),
- exception = require('ripple/exception'),
+ constants = require('ripple/constants'),
event = require('ripple/event'),
- Rotation = require('ripple/platform/w3c/1.0/Rotation'),
- Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
- _motion = {
- acceleration: new Acceleration(0, 0, 0),
- accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
- rotationRate: new Rotation(0, 0, 0),
- orientation: new Rotation(0, 0, 0),
- interval: 60000,
- timestamp: new Date().getTime()
+ _cache = {};
+
+function _validateAndSetPrefix(prefix) {
+ if (prefix) {
+ utils.validateArgumentType(prefix, "string");
+ }
+
+ return prefix || constants.COMMON.PREFIX;
+}
+
+function _createKey(key, prefix) {
+ return _validateAndSetPrefix(prefix) + key;
+}
+
+function _createItem(key, value, prefix) {
+ return {
+ id: _createKey(key, prefix),
+ key: key,
+ value: value,
+ prefix: _validateAndSetPrefix(prefix)
};
+}
-function _validateAccelerometerInfo(x, y, z) {
- return !(isNaN(x) || isNaN(y) || isNaN(z));
+function _save(key, value, prefix, callback) {
+ var item = _createItem(key, value, prefix);
+ _cache[item.id] = item;
+
+ _db.transaction(function (tx) {
+ tx.executeSql('REPLACE INTO persistence (id, key, value, prefix) VALUES (?, ?, ?, ?)', [item.id, item.key, item.value, item.prefix], function () {
+ return callback && callback();
+ });
+ });
}
-_self = {
- getInfo: function () {
- return utils.copy(_motion);
- },
+function _retrieve(key, prefix) {
+ var item = _cache[_createKey(key, prefix)];
+ return item ? item.value : undefined;
+}
- setInfo: function (e) {
- var triggerDeviceMotion = false,
- triggerDeviceOrientation = false;
+function _retrieveAll(prefix, callback) {
+ var result = {};
- if (e.x !== undefined && e.y !== undefined && e.z !== undefined) {
- _motion = {
- acceleration: new Acceleration(e.x, e.y, e.z),
- accelerationIncludingGravity: new Acceleration(e.x, e.y, e.z),
- rotationRate: new Rotation(0, 0, 0),
- orientation: new Rotation(e.alpha, e.beta, e.gamma),
- timestamp: new Date().getTime()
- };
- triggerDeviceMotion = true;
- triggerDeviceOrientation = true;
- }
- else {
- _motion = {
- acceleration: new Acceleration(0, 0, 0),
- accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
- rotationRate: new Rotation(0, 0, 0),
- orientation: new Rotation(0, 0, 0),
- timestamp: new Date().getTime()
- };
- }
+ if (prefix) {
+ utils.forEach(_cache, function (value, key) {
+ if (value.prefix === prefix) {
+ result[value.key] = value.value;
+ }
+ });
+ }
- if (triggerDeviceMotion) {
- event.trigger("DeviceMotionEvent", [_motion]);
+ callback.apply(null, [result]);
+}
+
+function _remove(key, prefix, callback) {
+ delete _cache[_createKey(key, prefix)];
+
+ _db.transaction(function (tx) {
+ tx.executeSql('DELETE FROM persistence WHERE key = ? AND prefix = ?', [key, _validateAndSetPrefix(prefix)], function () {
+ return callback && callback();
+ });
+ });
+}
+
+function _removeAll(prefix, callback) {
+ utils.forEach(_cache, function (value, key) {
+ if (!prefix || key.indexOf(prefix) === 0) {
+ delete _cache[key];
}
+ });
- if (triggerDeviceOrientation) {
- event.trigger("DeviceOrientationEvent", [_motion]);
+ _db.transaction(function (tx) {
+ if (prefix) {
+ tx.executeSql('DELETE FROM persistence WHERE prefix = ?', [prefix], function () {
+ return callback && callback();
+ });
+ } else {
+ tx.executeSql('DELETE FROM persistence', [], function () {
+ return callback && callback();
+ });
}
+ });
+}
- event.trigger("AccelerometerInfoChangedEvent", [_motion]);
+_self = {
+ save: function (key, value, prefix, callback) {
+ _save(key, value, prefix, callback);
+ event.trigger("StorageUpdatedEvent");
},
- triggerEvent: function() {
- event.trigger("DeviceMotionEvent", [_motion]);
- event.trigger("DeviceOrientationEvent", [_motion]);
- event.trigger("AccelerometerInfoChangedEvent", [_motion]);
+ saveObject: function (key, obj, prefix, callback) {
+ _save(key, JSON.stringify(obj), prefix, callback);
+ event.trigger("StorageUpdatedEvent");
},
- shake: function (shakeXtimes) {
- var id,
- count = 1,
- stopCount = shakeXtimes || 17,
- oldX = _motion.accelerationIncludingGravity.x;
+ retrieve: function (key, prefix) {
+ return _retrieve(key, prefix);
+ },
- id = setInterval(function () {
- var freq = 1,
- amp = 30,
- value = Math.round(amp * Math.sin(freq * count * (180 / Math.PI)) * 100) / 100;
+ retrieveObject: function (key, prefix) {
+ var retrievedValue = _retrieve(key, prefix);
+ return retrievedValue ? JSON.parse(retrievedValue) : retrievedValue;
+ },
- if (count > stopCount) {
- _motion.acceleration.x = oldX;
- _motion.accelerationIncludingGravity.x = oldX;
- event.trigger("AccelerometerInfoChangedEvent", [_motion]);
- clearInterval(id);
- return;
- }
+ retrieveAll: function (prefix, callback) {
+ return _retrieveAll(prefix, callback);
+ },
- _motion.acceleration.x = value;
- _motion.accelerationIncludingGravity.x = value;
+ remove: function (key, prefix, callback) {
+ event.trigger("StorageUpdatedEvent");
+ _remove(key, prefix, callback);
+ },
- event.trigger("AccelerometerInfoChangedEvent", [_motion]);
+ removeAll: function (prefix, callback) {
+ _removeAll(prefix, callback);
+ event.trigger("StorageUpdatedEvent");
+ },
- count++;
+ initialize: function (previous, baton) {
+ baton.take();
- }, 80);
- },
+ _db = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence', 2 * 1024 * 1024);
+ _db.transaction(function (tx) {
+ tx.executeSql('CREATE TABLE IF NOT EXISTS persistence (id unique, key, value, prefix)');
- init: function () {
- event.on("DeviceMotionEventAddedEvent", function () {
- _self.triggerEvent();
- });
- event.on("DeviceOrientationEventAddedEvent", function () {
- _self.triggerEvent();
+ tx.executeSql('SELECT id, key, value, prefix FROM persistence', [], function (tx, results) {
+ var len = results.rows.length, i, item;
+
+ for (i = 0; i < len; i++) {
+ item = results.rows.item(i);
+ _cache[item.id] = item;
+ }
+
+ baton.pass();
+ });
});
}
};
module.exports = _self;
});
-define('ripple/app', function (require, exports, module) {
+define('ripple/fileSystem', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _data = {},
+var constants = require('ripple/constants'),
+ db = require('ripple/db'),
+ exception = require('ripple/exception'),
+ event = require('ripple/event'),
+ _console = require('ripple/console'),
utils = require('ripple/utils'),
- _self;
-
-_self = {
- setInfo: function (info) {
- if (!info) {
- _data = {};
- }
- _data = info;
+ _fileSystemPaths = {
+ "photos": { "uri": "" },
+ "videos": { "uri": "" },
+ "music": { "uri": "" },
+ "downloads": { "uri": "" },
+ "widgethome": { "uri": "" }
},
-
- getInfo: function () {
- return utils.copy(_data);
+ _fileSystemRegex = {
+ "photos": { "virtualPathRegex": /^\/virtual\/photos\//i },
+ "videos": { "virtualPathRegex": /^\/virtual\/videos\//i },
+ "music": { "virtualPathRegex": /^\/virtual\/music\//i },
+ "downloads": { "virtualPathRegex": /^\/virtual\/downloads\//i },
+ "widgethome": { "virtualPathRegex": /^\/virtual\/widgethome\//i }
},
+ _overrides = {};
- isPreferenceReadOnly: function (key) {
- return (_data.preferences &&
- _data.preferences[key] &&
- _data.preferences[key].readonly &&
- _data.preferences[key].readonly === true);
+module.exports = {
+ initialize: function () {
+ _fileSystemPaths = db.retrieveObject(constants.FILESYSTEM.PERSISTENCE_KEY) || _fileSystemPaths;
+ _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
},
- validateVersion: function (configValidationObject) {
- // TODO: WTF figure this out, platform is empty object when require at require time
- // could be that the new platform _getBuilder code dies when called, beforre it is initialized
- var spec = require('ripple/platform').current();
- if (typeof spec.config.validateVersion === "function" && configValidationObject) {
- return spec.config.validateVersion(configValidationObject);
+ getURI: function getURI(origURI) {
+ var newURI = origURI,
+ found = false;
+
+ if (_overrides[origURI]) {
+ return _overrides[origURI];
}
- return true;
+ utils.forEach(_fileSystemPaths, function (value, key) {
+ if (found) {
+ return;
+ }
+
+ var uri = value.uri.replace(/\/$/, "");
+ if (origURI.match(_fileSystemRegex[key].virtualPathRegex)) {
+ newURI = origURI.replace(_fileSystemRegex[key].virtualPathRegex, uri + "/");
+ found = true;
+ }
+ });
+
+ return newURI;
},
- saveInfo: function (configValidationObject) {
- var spec = require('ripple/platform').current(),
- info = null;
- if (typeof spec.config.extractInfo === "function") {
- info = spec.config.extractInfo(configValidationObject);
- }
+ exists: function (path) {
+ try {
+ var scrubbedUri = this.getURI(path),
+ xhr = new XMLHttpRequest();
- if (info) {
- _self.setInfo(info);
+ xhr.open("GET", scrubbedUri, false);
+ xhr.send();
+
+ //HACK: this should return maybe for 403
+ return xhr.status !== 404;
}
- }
+ catch (e) {
+ exception.handle(e);
+ _console.log("failed to check if [" + path + "] exists");
+ return false;
+ }
+ },
-};
-module.exports = _self;
+ getFileSystemPaths: function getFileSystemPaths() {
+ return utils.copy(_fileSystemPaths);
+ },
-});
-define('ripple/appcache', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- initialize: function () {
- window.addEventListener('load', function (e) {
- window.applicationCache.addEventListener('updateready', function (e) {
- if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
- window.applicationCache.swapCache();
- window.location.reload();
- }
- }, false);
- }, false);
+ updateFileSystemPaths: function updateFileSystemPaths(filePathsObject) {
+ _fileSystemPaths = utils.copy(filePathsObject);
+ _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname;
+ db.saveObject(constants.FILESYSTEM.PERSISTENCE_KEY, filePathsObject);
+ },
+
+ override : function (from, to) {
+ _overrides[from] = to;
}
};
});
-define('ripple/bootstrap', function (require, exports, module) {
+define('ripple/notifications', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _bound,
- _console = require('ripple/console'),
+var constants = require('ripple/constants'),
+ exception = require('ripple/exception'),
utils = require('ripple/utils'),
- ui = require('ripple/ui'),
- db = require('ripple/db'),
- _CURRENT_URL = "current-url",
- resizer = require('ripple/resizer'),
- platform = require('ripple/platform');
-
-var _srcChangedObserver = new WebKitMutationObserver(function (mutations) {
- utils.forEach(mutations, function (mutation) {
- _bindObjectsToFrame(mutation.target);
- });
- });
-
-function _observeIframeAdded(doc) {
- doc._iframeAddedObserver.observe(doc, {childList: true, subtree: true});
-}
-
-function _bindObjects(win, doc) {
- if (!win.tinyHippos) {
- require('ripple/emulatorBridge').link(win, doc);
- /// require('ripple/platform/tizen/2.0/touchEvent').mask(win, doc);
- require('ripple/touchEventEmulator').mask(win, doc);
- require('ripple/hwKeyEmulator').init(win, doc);
- require('ripple/documentEventListener').mask(win, doc);
- require('ripple/deviceMotionEmulator').init(win, doc);
- require('ripple/resizer').init(win, doc);
- win.addEventListener("DOMContentLoaded", function () {
- var iframes = $(this.document).find("iframe");
- // Observe iframe added event so that we can bind objects to newly added iframes
- if (!this.document._iframeAddedObserver) {
- this.document._iframeAddedObserver = new WebKitMutationObserver(function (mutations) {
- utils.forEach(mutations, function (mutation) {
- for (var i in mutation.addedNodes) {
- var node = mutation.addedNodes[i];
- if (node.tagName && (node.tagName.toUpperCase() === "IFRAME")) {
- _bindObjectsToFrame(node);
- }
- }
- });
- });
- _observeIframeAdded(this.document);
- }
- iframes.each(function () {
- _bindObjectsToFrame(this);
- });
-
- });
- win.frameElement._bound = true;
- }
-}
-
-function _beforeLoad() {
- this._bound = false;
- _bindObjects(this.contentWindow, this.contentDocument);
- this._intervalId = window.setInterval(function () {
- if (this._bound) {
- window.clearInterval(this._intervalId);
- } else {
- _bindObjects(this.contentWindow, this.contentDocument);
- }
- }.bind(this), 1);
-}
-
-function _bindObjectsToFrame(frame) {
- _srcChangedObserver.observe(frame, {attributes: true, attributeFilter: ["src"]});
- frame.addEventListener("beforeload", _beforeLoad);
- // beforeload event of an iframe will not be triggered unless we detach and
- // then attach the iframe to the dom tree
- var parentNode = frame.parentNode;
- var nextNode = frame.nextNode;
- if (parentNode) {
- // Disable iframe added observer to avoid infinite loop of binding objects
- if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
- frame.ownerDocument._iframeAddedObserver.disconnect();
- }
- parentNode.removeChild(frame);
- if (nextNode)
- nextNode.insertBefore(frame);
- else
- parentNode.appendChild(frame);
-
- if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
- _observeIframeAdded(frame.ownerDocument);
- }
- }
-}
+ event = require('ripple/event');
-function _createFrame(src) {
- var frame = document.createElement("iframe");
- frame.setAttribute("id", "document");
- frame.src = src;
+function _validateAndInitNType(nType) {
+ nType = nType || "normal";
- if (ui.registered("omnibar")) {
- _bindObjectsToFrame(frame);
+ if (nType !== "normal" && nType !== "error") {
+ exception.raise(exception.types.NotificationType, "Unknown Notification Type == " + nType + ",when dealing with Console notification.");
}
- return frame;
-}
-
-function _cleanBody() {
- require('ripple/utils').forEach(document.body.children, function (child) {
- if (child && child.id && !child.id.match(/ui|tooltip|bus/)) {
- document.body.removeChild(child);
- }
-
- document.body.removeAttribute("style");
- document.body.removeAttribute("id");
- document.body.removeAttribute("class");
- });
-}
-
-function reload() {
- window.tinyHipposReload = true;
- location.reload();
+ return nType;
}
-function _post(src) {
- var event = require('ripple/event'),
- frame = _createFrame(src);
-
- _console.log("Initialization Finished (Make it so.)");
-
- frame.onload = function () {
- var bootLoader = document.querySelector("#emulator-booting"),
- id,
- iframe = document.getElementById('document'),
- viewportTagFound = false,
- viewportTagContent = {},
- viewportTagStr = "",
- tagProperties = [],
- propertyKey ="",
- propertyValue = "",
- curViewPortWidth = "",
- curViewPortHeight = "",
- layout = db.retrieve("layout") || "portrait",
- preLayout = "";
-
- if (bootLoader) {
- document.querySelector("#ui").removeChild(bootLoader);
- }
-
- // Workaround to enforce the content of iframe to rerender when scrolling
- document.getElementById('document').contentWindow.onscroll = function() {
- jQuery("#device-maskmask").show();
- setTimeout(function() {
- jQuery("#device-maskmask").hide();
- }, 50);
- }
-
- event.trigger("TinyHipposLoaded");
- _cleanBody();
- id = window.setInterval(_cleanBody, 20);
-
- window.setTimeout(function () {
- window.clearInterval(id);
- }, 1200);
+function _processNotification(nType, stateType, message) {
+ nType = _validateAndInitNType(nType);
+ message = message || "";
- // Clean data for different app
- if (db.retrieve("current-url") !== db.retrieve("previous-url")) {
- db.remove("viewport_width");
- db.remove("viewport_height");
- db.remove("viewportTag");
- db.remove("prelayout");
- }
+ var display,
+ displayText,
+ className,
+ notificationIcon,
+ box = document.getElementById(constants.NOTIFICATIONS.MAIN_CONTAINER_CLASS),
+ msgBox = document.getElementById(constants.NOTIFICATIONS.MESSAGE_TEXT_CONTAINER_CLASS);
- curViewPortWidth = db.retrieve("viewport_width");
- curViewPortHeight = db.retrieve("viewport_height");
- preLayout = db.retrieve("prelayout") || "portrait";
- db.save("previous-url", db.retrieve("current-url"));
+ className = "ui-widget";
- if (iframe.contentDocument.getElementsByName('viewport')[0] !== undefined) {
- viewportTagStr = iframe.contentDocument.getElementsByName('viewport')[0].getAttribute("content");
- viewportTagStr = viewportTagStr.replace(/\s/g, '');
- tagProperties = viewportTagStr.split(",");
+ switch (stateType) {
- for (var i in tagProperties) {
- propertyKey = tagProperties[i].split("=")[0];
- propertyValue = tagProperties[i].split("=")[1];
- viewportTagContent[propertyKey] = propertyValue;
- }
- viewportTagFound = true;
- }
+ case constants.NOTIFICATIONS.STATE_TYPES.CLOSE:
+ display = "display: none;"; //need to do this better.
+ displayText = "";
+ break;
- // if viewport tag found (width, height)
- if (viewportTagFound && ((viewportTagContent['width'] !== undefined) || (viewportTagContent['height'] !== undefined))) {
- if ((viewportTagContent['width'] !== undefined)) {
- if (curViewPortWidth !== viewportTagContent['width']) {
- db.saveObject("viewportTag", viewportTagContent);
- if (layout !== preLayout) {
- db.save("prelayout", layout);
- resizer.changeLayoutType(layout);
- event.trigger("LayoutChanged", [layout], true);
- frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
- } else {
- resizer.changeLayoutType(layout);
- }
- }
- } else {
- if (curViewPortHeight !== viewportTagContent['height']) {
- db.saveObject("viewportTag", viewportTagContent);
- if (layout !== preLayout) {
- db.save("prelayout", layout);
- resizer.changeLayoutType(layout);
- event.trigger("LayoutChanged", [layout], true);
- frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
- } else {
- resizer.changeLayoutType(layout);
- }
- }
- }
- } else {
- // Set layout to portrait if no viewport tag detected
- resizer.changeLayoutType('portrait');
- event.trigger("LayoutChanged", ['portrait'], true);
+ case constants.NOTIFICATIONS.STATE_TYPES.OPEN:
+ display = "display: block;"; //need to do this better.
+ displayText = message;
+ if (nType === "error") {
+ displayText = "Oh Snap!\n\n" + displayText;
+ className += " ui-state-error ui-corner-all";
+ notificationIcon = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>';
}
-
- if (ui.registered("omnibar")) {
- //reset the onload function so that when navigating we can destroy
- //the iframe and create a new one so we can reinject the platform by
- //calling post again.
- frame.onload = function () {
- var url = frame.contentWindow.location.href;
- document.getElementById("viewport-container").removeChild(frame);
- event.trigger("FrameHistoryChange", [url]);
- _console.log("-----------------------------------------------------------");
- _console.log("Pay no attention to that man behind the curtain.");
- _console.log("Environment Warning up again (Set main batteries to auto-fire cycle)");
- _post(url);
- };
+ else {
+ className += " ui-state-highlight ui-corner-all";
+ notificationIcon = '<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>';
}
- };
-
- // append frame
- document.getElementById("viewport-container").appendChild(frame);
-
- delete tinyHippos.boot;
-}
-
-function _bootstrap() {
- // TODO: figure this out for web and ext
- //_console.log("-----------------------------------------------------------");
- //_console.log("There be dragons above here!");
- _console.log("Web Simulator :: Environment Warming Up (Tea. Earl Gray. Hot.)");
+ break;
- window.tinyHippos = require('ripple');
+ default:
+ exception.raise(exception.types.NotificationStateType, "Unknown StateType == " + stateType.toString());
+ }
- tinyHippos.boot(function () {
- var uri = ui.registered('omnibar') ?
- db.retrieve(_CURRENT_URL) || "about:blank" :
- document.documentURI.replace(/enableripple=[^&]*[&]?/i, "").replace(/[\?&]*$/, "");
+ msgBox.innerHTML = notificationIcon + displayText;
+ box.setAttribute("class", className);
+ box.setAttribute("style", display);
- _post(uri);
- delete tinyHippos.boot;
- });
}
module.exports = {
- bootstrap: _bootstrap,
- inject: function (frameWindow, frameDocument) {
- _bindObjects(frameWindow, frameDocument);
+ openNotification: function (nType, msg) {
+ _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.OPEN, msg);
+ },
+
+ closeNotification: function (nType) {
+ _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.CLOSE);
}
};
});
-define('ripple/bus', function (require, exports, module) {
+define('ripple/exception', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var _console = require('ripple/console');
-var _send = document.getElementById("bus-send"),
- _receive = document.getElementById("bus-receive"),
- _evt = document.createEvent("Events");
-
-_evt.initEvent('bus-init', true, true);
-document.dispatchEvent(_evt);
+function _getStack(depth) {
+ var caller,
+ stack = "",
+ count = 0;
-module.exports = {
- send: function (msg, data, callback) {
- var m = document.createElement("span");
- m.dataset.msg = msg;
- m.innerHTML = JSON.stringify(data);
+ try {
+ caller = arguments.callee.caller.arguments.callee.caller;
- if (callback) {
- m.dataset.callback = Math.uuid();
- this.receive(m.dataset.callback, callback);
+ while (count <= depth && caller) {
+ stack += "function: " + caller.toString().match(/function\s?(.*)\{/)[1] + "\n";
+ caller = caller.arguments.callee.caller;
+ count++;
}
+ } catch (e) {
+ stack = "failed to determine stack trace (" + (e.name || e.type) + " :: " + e.message + ")";
+ }
- _send.appendChild(m);
- },
+ return stack;
+}
- receive: function (msg, handler) {
- if (!handler) {
- return;
- }
+module.exports = {
- _receive.addEventListener("DOMNodeInserted", function (evt) {
- if (evt.target.dataset.msg === msg) {
- handler(JSON.parse(evt.target.innerHTML));
- }
- });
+ types: {
+ Application: "Application",
+ ArgumentLength: "ArgumentLength",
+ ArgumentType: "ArgumentType",
+ Argument: "Argument",
+ NotificationType: "NotificationType",
+ NotificationStateType: "NotificationStateType",
+ DomObjectNotFound: "DomObjectNotFound",
+ LayoutType: "LayoutType",
+ OrientationType: "OrientationType",
+ DeviceNotFound: "DeviceNotFound",
+ tinyHipposMaskedException: "tinyHipposMaskedException",
+ Geo: "Geo",
+ Accelerometer: "Accelerometer",
+ MethodNotImplemented: "MethodNotImplemented",
+ InvalidState: "InvalidState",
+ ApplicationState: "ApplicationState"
},
- ajax: function (method, url, data, success, fail) {
- this.send("xhr", {
- method: method,
- url: url,
- data: data
- }, function (result) {
- if (result.code === 200) {
- success(result.data);
- }
- else {
- fail(result);
- }
- });
- }
-};
+ handle: function handle(exception, reThrow) {
+ reThrow = reThrow || false;
-});
-define('ripple/console', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self;
+ var eMsg = exception.message || "exception caught!",
+ msg = eMsg + "\n\n" + (exception.stack || "*no stack provided*") + "\n\n";
-function _log(msg, method) {
- try {
- console[method](_self.prefix ? _self.prefix + " :: " + msg : msg);
- } catch (e) {
- // silent
- }
-}
+ _console.error(msg);
-_self = {
- log: function (msg) {
- _log(msg, "log");
+ if (reThrow) {
+ throw exception;
+ }
},
- warn: function (msg) {
- _log(msg, "warn");
+ raise: function raise(exceptionType, message, customExceptionObject) {
+ var obj = customExceptionObject || {
+ type: "",
+ message: "",
+
+ toString: function () {
+ var result = this.name + ': "' + this.message + '"';
+
+ if (this.stack) {
+ result += "\n" + this.stack;
+ }
+ return result;
+ }
+ };
+
+ message = message || "";
+
+ obj.name = exceptionType;
+ obj.type = exceptionType;
+ // TODO: include the exception objects original message if exists
+ obj.message = message;
+ obj.stack = _getStack(5);
+
+ throw obj;
},
- error: function (msg) {
- _log(msg, "error");
+ throwMaskedException: function throwMaskedException(exceptionType, message, customExceptionObject) {
+ try {
+ this.raise.apply(this, arguments);
+ } catch (e) {
+ this.handle(e);
+ }
+ this.raise(this.types.tinyHipposMaskedException, "tinyhippos terminated your script due to exception");
}
-};
-module.exports = _self;
+};
});
-define('ripple/constants', function (require, exports, module) {
+define('ripple/widgetConfig', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- "API_URL": "http://api.tinyhippos.com",
-
- "RELEASE_VERSION": "simulator-release-version",
-
- "SERVICES": {
- "GOOGLE_MAPS_URI": "http://maps.google.com/maps/api/staticmap?size=476x476&maptype=roadmap",
- "GOOGLE_MAPS_API_KEY": "ABQIAAAA-CaPZHXR-0Tzhui_h6gpjhSE_2rGlnYiB7L-ZGVwgaut5s7OYRSlBAaHCzBuZf2_23_vrCOfPxXHjA"
+var exception = require('ripple/exception'),
+ event = require('ripple/event'),
+ app = require('ripple/app'),
+ _console = require('ripple/console'),
+ utils = require('ripple/utils'),
+ platform = require('ripple/platform'),
+ _validationResult = {
+ valid: false,
+ message: "",
+ value: null
},
+ _configValidationResults = null;
- "FS_SIZE": 1024 * 1024 * 10,
+function _failNodeValidation(schemaNode, message, value, node) {
+ var validationResult = utils.copy(_validationResult);
- "COMMON": {
- "APPLICATION_STATE": "ui-application-state-",
- "PREFIX": "tinyhippos-",
- "DEVICE_CONTAINER" : "device-container",
- "MENU_BUTTON" : "menu-button",
- "BACK_BUTTON" : "back-button",
- "HTML_CONTAINER" : "document",
- "INFO_SECTION": "information-sub-container",
- "ORIENTATION_SELECT_PORTRAIT_ID" : "layout-portrait",
- "ORIENTATION_SELECT_LANDSCAPE_ID" : "layout-landscape",
- "PLATFORM_SELECT_ID": "platform-select",
- "DEVICE_SELECT_ID": "device-select",
- "STORAGE_TABLE_BODY_CLASS": "preferences-list-body",
- "STORAGE_COUNT_CONTAINER_ID": "preferences-count",
- "GEO_MAP_CONTAINER_ID": "geo-map",
- "FILESYSTEM_UPDATE_BUTTON_ID_WITH_HASH": "#update-filesystem-button",
- "USER_AGENT_DEFAULT": "default",
- "APPLICATIONS_CONTAINER_ID": "widget-applications-content",
- "STORAGE_CLEAR_BUTTON_ID": "preferences-clear-button",
- "AJAX_LOADER_CONTAINER_CLASS": ".loader",
- "IRRELEVANT_CLASS": "irrelevant",
- "MULTIMEDIA_VOLUME_SLIDER_ID": "media-volume",
- "MULTIMEDIA_VOLUME_FIELD_ID": "media-volume-value",
- "MULTIMEDIA_AUDIO_STATE_FIELD_ID": "media-audio-state",
- "MULTIMEDIA_AUDIO_PLAYING_FIELD_ID": "multimedia-isaudioplaying",
- "MULTIMEDIA_AUDIO_PROGRESS_ID": "media-audio-progress",
- "MULTIMEDIA_AUDIO_FILE_FIELD_ID": "media-audio-file",
- "MULTIMEDIA_VIDEO_STATE_FIELD_ID": "media-video-state",
- "MULTIMEDIA_VIDEO_PLAYING_FIELD_ID": "multimedia-isvideoplaying",
- "MULTIMEDIA_VIDEO_PROGRESS_ID": "media-video-progress",
- "MULTIMEDIA_VIDEO_FILE_FIELD_ID": "media-video-file",
- "EXTENSION_URL_CONTAINER": "extension-url",
- "SECURITY_LEVEL": "security-level"
- },
- "LAUNCHING_HISTORY": "application-launching-history",
+ if (!schemaNode.validationResult) {
+ schemaNode.validationResult = [];
+ }
+ validationResult.valid = false;
+ if (value) {
+ validationResult.value = value;
+ }
+ else {
+ delete(validationResult.value);
+ }
+ validationResult.message = schemaNode.nodeName + message;
+ validationResult.node = node;
- "FILESYSTEM": {
- "PERSISTENCE_KEY": "filesystem",
- "INPUT_PREFIX_ID": "#panel-filesystem-"
- },
+ schemaNode.validationResult.push(validationResult);
+}
- "PLATFORM": {
- "DEFAULT": {
- "name": "tizen",
- "version": "1.0"
- }
- },
+function _createEmptyNodeValidation(node) {
- "DEVICE": {
- "SAVED_KEY": "device-key"
- },
+ var validationResult = utils.copy(_validationResult),
+ attributeValidationResult, attribute;
- "BATTERY": {
- "TIME": "charging-time",
- "VOLUME": "battery-volume",
- "CHARGING": "is-charging"
- },
+ if (!node.validationResult) {
+ node.validationResult = [];
+ }
- "TOUCHEVENT": {
- "OPTION": "touch_option",
- "ALTKEY": "touch_altKey",
- "METAKEY": "touch_metaKey",
- "CTRLKEY": "touch_ctrlKey",
- "SHIFTKEY": "touch_shiftKey",
- "CANVAS": "touch_canvas"
- },
+ validationResult.value = "";
+ delete(validationResult.valid);
+ delete(validationResult.message);
- "ENCAPSULATOR": {
- "DEFAULT_HEIGHT": 684,
- "DEFAULT_WIDTH": 480,
- "LAYOUT": "layout",
- "DISPLAY_LAYOUT": {
- "LANDSCAPE": "landscape",
- "PORTRAIT": "portrait"
- },
- "ZOOMING": "screen-zooming"
- },
+ if (node.attributes) {
+ for (attribute in node.attributes) {
+ if (node.attributes.hasOwnProperty(attribute)) {
+ if (!validationResult.attributes) {
+ validationResult.attributes = {};
+ }
- "GEO": {
- "OPTIONS" : {
- "LATITUDE" : "geo-latitude",
- "LONGITUDE" : "geo-longitude",
- "ALTITUDE" : "geo-altitude",
- "CELL_ID" : "geo-cellid",
- "ACCURACY" : "geo-accuracy",
- "ALTITUDE_ACCURACY" : "geo-altitudeaccuracy",
- "HEADING" : "geo-heading",
- "SPEED" : "geo-speed",
- "TIME_STAMP" : "geo-timestamp",
- "DELAY" : "geo-delay",
- "DELAY_LABEL" : "geo-delay-label",
- "HEADING_LABEL" : "geo-heading-label",
- "HEADING_MAP_LABEL" : "geo-map-direction-label",
- "IMAGE" : "geo-map-img",
- "MAP_CONTAINER" : "geo-map-container",
- "TIMEOUT" : "geo-timeout",
- "GPXFILE": "geo-gpxfile",
- "GPXGO": "geo-gpx-go",
- "GPXMULTIPLIER": "geo-gpxmultiplier-select",
- "GPXREPLAYSTATUS": "geo-gpxreplaystatus"
- },
- "MAP_ZOOM_MAX": 18,
- "MAP_ZOOM_MIN": 0,
- "MAP_ZOOM_LEVEL_CONTAINER": "geo-map-zoomlevel-value",
- "MAP_ZOOM_KEY": "geo-map-zoom-key",
- "GPXGO_LABELS": {
+ attributeValidationResult = utils.copy(_validationResult);
- "GO": "Go",
- "STOP": "Stop"
- }
- },
+ attributeValidationResult.attributeName = node.attributes[attribute].attributeName;
+ delete(attributeValidationResult.value);
+ delete(attributeValidationResult.valid);
+ delete(attributeValidationResult.message);
- "PUSH": {
- "OPTIONS" : {
- "PAYLOAD" : "push-text"
+ validationResult.attributes[attributeValidationResult.attributeName] = attributeValidationResult;
+ }
}
- },
-
- "TELEPHONY": {
- "CALL_LIST_KEY": "telephony-call-list-key"
- },
-
- "PIM": {
- "ADDRESS_LIST_KEY": "pim-address-list-key",
- "CALENDAR_LIST_KEY": "pim-calendar-list-key"
- },
-
- "CAMERA": {
- "WINDOW_ANIMATION": "images/tizen-wave.gif",
- "WARNING_TEXT": "The runtime simulated saving the camera file to {file}. If you need to access this file in your application, please copy a file to the saved location"
- },
+ }
- "AUDIOPLAYER" : {
- "WARNING_TEXT": "The runtime simulated saving the audio file to {file}. If you need to access this file in your application, please copy a file to the saved location"
- },
+ node.validationResult.push(validationResult);
+}
- "API_APPLICATION": {
- "NO_APPLICATIONS_MESSAGE": "No applications available for your platform"
- },
+function _validateValue(valueToTest, schemaNode) {
+ var failMessage = "",
+ nodeValue,
+ numbers,
+ numberRangeIndex,
+ numberRange,
+ range1,
+ range2;
- "NOTIFICATIONS": {
- "MESSAGE_CONTAINER_CLASS": "notification-message-div",
- "MAIN_CONTAINER_CLASS": "panel-notification",
- "CLOSE_BUTTON_CLASS": "panel-notification-closebtn",
- "MESSAGE_TEXT_CONTAINER_CLASS": "panel-notification-text",
- "CSS_PREFIX": "panel-notification-",
- "STATE_TYPES": {
- "OPEN": 1,
- "CLOSE": 2
+ switch (schemaNode.type) {
+ case "string":
+ if (typeof valueToTest !== "string") {
+ failMessage = " value was expected to be of type string but was typeof: " + typeof(valueToTest);
}
- },
-
- "CSS_PREFIX": {
- "IRRELEVANT" : "irrelevant"
- },
-
- "STORAGE": {
- "PAIR_DELIMETER" : ",",
- "KEY_VALUE_DELIMETER" : "|"
- },
-
- "REGEX": {
- "GEO" : /^geo-/,
- "URL": /^((https?|ftp|gopher|telnet|file|notes|ms-help):((\/\/)|(\\\\))+[\w\d:#@%\/;$()~_?\+-=\\\.&]*)$/,
- //"Email": /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
- "EMAIL": /^([^@\s]+)@((?:[\-a-z0-9]+\.)+[a-z]{2,})$/,
- "WC3_DTF": /^((\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)|(\d{4})-(\d\d)|(\d\d\d\d))$/,
- "LOCAL_URI": /^https?:\/\/(127\.0\.0\.1|localhost)|^file:\/\//,
- "EXTERNAL_URI": /(?:(?:[a-zA-Z0-9\/;\?&=:\-_\$\+!\*'\(\|\\~\[\]#%\.](?!www))+(?:\.[Cc]om|\.[Ee]du|\.[gG]ov|\.[Ii]nt|\.[Mm]il|\.[Nn]et|\.[Oo]rg|\.[Bb]iz|\.[Ii]nfo|\.[Nn]ame|\.[Pp]ro|\.[Aa]ero|\.[cC]oop|\.[mM]useum|\.[Cc]at|\.[Jj]obs|\.[Tt]ravel|\.[Aa]rpa|\.[Mm]obi|\.[Aa]c|\.[Aa]d|\.[aA]e|\.[aA]f|\.[aA]g|\.[aA]i|\.[aA]l|\.[aA]m|\.[aA]n|\.[aA]o|\.[aA]q|\.[aA]r|\.[aA]s|\.[aA]t|\.[aA]u|\.[aA]w|\.[aA]z|\.[aA]x|\.[bB]a|\.[bB]b|\.[bB]d|\.[bB]e|\.[bB]f|\.[bB]g|\.[bB]h|\.[bB]i|\.[bB]j|\.[bB]m|\.[bB]n|\.[bB]o|\.[bB]r|\.[bB]s|\.[bB]t|\.[bB]v|\.[bB]w|\.[bB]y|\.[bB]z|\.[cC]a|\.[cC]c|\.[cC]d|\.[cC]f|\.[cC]g|\.[cC]h|\.[cC]i|\.[cC]k|\.[cC]l|\.[cC]m|\.[cC]n|\.[cC]o|\.[cC]r|\.[cC]s|\.[cC]u|\.[cC]v|\.[cC]x|\.[cC]y|\.[cC]z|\.[dD]e|\.[dD]j|\.[dD]k|\.[dD]m|\.[dD]o|\.[dD]z|\.[eE]c|\.[eE]e|\.[eE]g|\.[eE]h|\.[eE]r|\.[eE]s|\.[eE]t|\.[eE]u|\.[fF]i|\.[fF]j|\.[fF]k|\.[fF]m|\.[fF]o|\.[fF]r|\.[gG]a|\.[gG]b|\.[gG]d|\.[gG]e|\.[gG]f|\.[gG]g|\.[gG]h|\.[gG]i|\.[gG]l|\.[gG]m|\.[gG]n|\.[gG]p|\.[gG]q|\.[gG]r|\.[gG]s|\.[gG]t|\.[gG]u|\.[gG]w|\.[gG]y|\.[hH]k|\.[hH]m|\.[hH]n|\.[hH]r|\.[hH]t^[ml]?|\.[hH]u|\.[iI]d|\.[iI]e|\.[iI]l|\.[iI]m|\.[iI]n|\.[iI]o|\.[iI]q|\.[iI]r|\.[iI]s|\.[iI]t|\.[jJ]e|\.[jJ]m|\.[jJ]o|\.[jJ]p|\.[kK]e|\.[kK]g|\.[kK]h|\.[kK]i|\.[kK]m|\.[kK]n|\.[kK]p|\.[kK]r|\.[kK]w|\.[kK]y|\.[kK]z|\.[lL]a|\.[lL]b|\.[lL]c|\.[lL]i|\.[lL]k|\.[lL]r|\.[lL]s|\.[lL]t|\.[lL]u|\.[lL]v|\.[lL]y|\.[mM]a|\.[mM]c|\.[mM]d|\.[mM]g|\.[mM]h|\.[mM]k|\.[mM]l|\.[mM]m|\.[mM]n|\.[mM]o|\.[mM]p|\.[mM]q|\.[mM]r|\.[mM]s|\.[mM]t|\.[mM]u|\.[mM]v|\.[mM]w|\.[mM]x|\.[mM]y|\.[mM]z|\.[nN]a|\.[nN]c|\.[nN]e|\.[nN]f|\.[nN]g|\.[nN]i|\.[nN]l|\.[nN]o|\.[nN]p|\.[nN]r|\.[nN]u|\.[nN]z|\.[oO]m|\.[pP]a|\.[pP]e|\.[pP]f|\.[pP]g|\.[pP]h|\.[pP]k|\.[pP]l|\.[pP]m|\.[pP]n|\.[pP]r|\.[pP]s|\.[pP]t|\.[pP]w|\.[pP]y|\.[qP]a|\.[rR]e|\.[rR]o|\.[rR]u|\.[rR]w|\.[sS]a|\.[sS]b|\.[sS]c|\.[sS]d|\.[sS]e|\.[sS]g|\.[sS]h|\.[Ss]i|\.[sS]j|\.[sS]k|\.[sS]l|\.[sS]m|\.[sS]n|\.[sS]o|\.[sS]r|\.[sS]t|\.[sS]v[^c]|\.[sS]y|\.[sS]z|\.[tT]c|\.[tT]d|\.[tT]f|\.[tT]g|\.[tT]h|\.[tT]j|\.[tT]k|\.[tT]l|\.[tT]m|\.[tT]n|\.[tT]o|\.[tT]p|\.[tT]r|\.[tT]t|\.[tT]v|\.[tT]w|\.[tT]z|\.[uU]a|\.[uU]g|\.[uU]k|\.[uU]m|\.[uU]s|\.[uU]y|\.[uU]z|\.[vV]a|\.[vV]c|\.[vV]e|\.[vV]g|\.[vV]i|\.[vV]n|\.[vV]u|\.[wW]f|\.[wW]s|\.[yY]e|\.[yY]t|\.[yY]u|\.[zZ]a|\.[zZ]m|\.[zZ]w))/
- },
-
- "CONFIG": {
- "SUCCESS_CSS": {
- "true": "ui-text-pass",
- "false": "ui-text-fail",
- "missing": "ui-text-missing"
+ break;
+ case "number":
+ nodeValue = parseFloat(valueToTest);
+ if (isNaN(nodeValue)) {
+ failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
}
- },
-
- "SETTINGS": {
- "TOOLTIPS_TOGGLE_DIV": "#settings-toggletooltips",
- "TOOLTIPS_KEY": "tool-tips-key"
- },
-
- "PANEL": {
- "PANEL_CONFIG_ENABLE": "panel-config-enable"
- },
-
- "UI": {
- "JQUERY_UI_BUTTON_CLASSES": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",
- "JQUERY_UI_INPUT_CLASSES": "ui-state-default ui-corner-all",
- "PANEL_TABLE_CLASS": "panel-table",
- "RIGHT_RANGE_LABEL_CLASS": "range-label",
- "LEFT_RANGE_LABEL_CLASS": "range-label-left",
- "TEXT_LABEL_CLASS": "ui-text-label",
- "SCREEN_PPI": 96
- },
-
- "MULTIMEDIA": {
- "AUDIO_STATES": {
- "OPENED": "opened",
- "STOPPED": "stopped",
- "PAUSED": "paused",
- "PLAYING": "playing",
- "COMPLETED": "completed"
+ break;
+ case "integer":
+ nodeValue = parseInt(valueToTest, 10);
+ if (isNaN(nodeValue)) {
+ failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
}
- },
-
- "LANG": {
- "ISO6392_LIST": ["abk", "ace", "ach", "ada", "ady", "aar", "afh", "afr", "afa", "ain", "aka", "akk", "alb/sqi", "gsw", "ale", "alg", "tut", "amh", "anp", "apa", "ara", "arg", "arp", "arw", "arm/hye", "rup", "art", "asm", "ast", "ath", "aus", "map", "ava", "ave", "awa", "aym", "aze", "ban", "bat", "bal", "bam", "bai", "bad", "bnt", "bas", "bak", "baq/eus", "btk", "bej", "bel", "bem", "ben", "ber", "bho", "bih", "bik", "byn", "bin", "bis", "zbl", "nob", "bos", "bra", "bre", "bug", "bul", "bua", "bur/mya", "cad", "spa", "cat", "cau", "ceb", "cel", "cai", "khm", "chg", "cmc", "cha", "che", "chr", "nya", "chy", "chb", "chi/zho", "chn", "chp", "cho", "zha", "chu", "chk", "chv", "nwc", "syc", "rar", "cop", "cor", "cos", "cre", "mus", "crp", "cpe", "cpf", "cpp", "crh", "hrv", "cus", "cze/ces", "dak", "dan", "dar", "del", "div", "zza", "din", "doi", "dgr", "dra", "dua", "dut/nld", "dum", "dyu", "dzo", "frs", "efi", "egy", "eka", "elx", "eng", "enm", "ang", "myv", "epo", "est", "ewe", "ewo", "fan", "fat", "fao", "fij", "fil", "fin", "fiu", "fon", "fre/fra", "frm", "fro", "fur", "ful", "gaa", "gla", "car", "glg", "lug", "gay", "gba", "gez", "geo/kat", "ger/deu", "nds", "gmh", "goh", "gem", "kik", "gil", "gon", "gor", "got", "grb", "grc", "gre/ell", "kal", "grn", "guj", "gwi", "hai", "hat", "hau", "haw", "heb", "her", "hil", "him", "hin", "hmo", "hit", "hmn", "hun", "hup", "iba", "ice/isl", "ido", "ibo", "ijo", "ilo", "arc", "smn", "inc", "ine", "ind", "inh", "ina", "ile", "iku", "ipk", "ira", "gle", "mga", "sga", "iro", "ita", "jpn", "jav", "kac", "jrb", "jpr", "kbd", "kab", "xal", "kam", "kan", "kau", "pam", "kaa", "krc", "krl", "kar", "kas", "csb", "kaw", "kaz", "kha", "khi", "kho", "kmb", "kin", "kir", "tlh", "kom", "kon", "kok", "kor", "kos", "kpe", "kro", "kua", "kum", "kur", "kru", "kut", "lad", "lah", "lam", "day", "lao", "lat", "lav", "ltz", "lez", "lim", "lin", "lit", "jbo", "dsb", "loz", "lub", "lua", "lui", "smj", "lun", "luo", "lus", "mac/mkd", "mad", "mag", "mai", "mak", "mlg", "may/msa", "mal", "mlt", "mnc", "mdr", "man", "mni", "mno", "glv", "mao/mri", "arn", "mar", "chm", "mah", "mwr", "mas", "myn", "men", "mic", "min", "mwl", "moh", "mdf", "rum/ron", "mkh", "lol", "mon", "mos", "mul", "mun", "nqo", "nah", "nau", "nav", "nde", "nbl", "ndo", "nap", "new", "nep", "nia", "nic", "ssa", "niu", "zxx", "nog", "non", "nai", "frr", "sme", "nso", "nor", "nno", "nub", "iii", "nym", "nyn", "nyo", "nzi", "oci", "pro", "oji", "ori", "orm", "osa", "oss", "oto", "pal", "pau", "pli", "pag", "pan", "pap", "paa", "pus", "per/fas", "peo", "phi", "phn", "pon", "pol", "por", "pra", "que", "raj", "rap", "qaa-qtz", "roa", "roh", "rom", "run", "rus", "sal", "sam", "smi", "smo", "sad", "sag", "san", "sat", "srd", "sas", "sco", "sel", "sem", "srp", "srr", "shn", "sna", "scn", "sid", "sgn", "bla", "snd", "sin", "sit", "sio", "sms", "den", "sla", "slo/slk", "slv", "sog", "som", "son", "snk", "wen", "sot", "sai", "alt", "sma", "srn", "suk", "sux", "sun", "sus", "swa", "ssw", "swe", "syr", "tgl", "tah", "tai", "tgk", "tmh", "tam", "tat", "tel", "ter", "tet", "tha", "tib/bod", "tig", "tir", "tem", "tiv", "tli", "tpi", "tkl", "tog", "ton", "tsi", "tso", "tsn", "tum", "tup", "tur", "ota", "tuk", "tvl", "tyv", "twi", "udm", "uga", "uig", "ukr", "umb", "mis", "und", "hsb", "urd", "uzb", "vai", "ven", "vie", "vol", "vot", "wak", "wln", "war", "was", "wel/cym", "fry", "wal", "wol", "xho", "sah", "yao", "yap", "yid", "yor", "ypk", "znd", "zap", "zen", "zul", "zun"]
- },
-
- "XHR": {
- "PROXY_DISABLED_BUTTON": "settings-xhrproxy-disabled"
- },
-
- "PLATFORMS": {
- "WAC": {
- "APPLICATIONS": [
- "ALARM",
- "BROWSER",
- "CALCULATOR",
- "CALENDAR",
- "CAMERA",
- "CONTACTS",
- "FILES",
- "GAMES",
- "MAIL",
- "MEDIAPLAYER",
- "MESSAGING",
- "PHONECALL",
- "PICTURES",
- "PROG_MANAGER",
- "SETTINGS",
- "TASKS",
- "WIDGET_MANAGER"
- ],
- "DEVICE": {
- "WIDGET_ENGINE_NAME": "Generic",
- "WIDGET_ENGINE_PROVIDER": "tinyHippos",
- "WIDGET_ENGINE_VERSION": "x.x"
- }
+ break;
+ case "boolean":
+ if (valueToTest !== "false" && valueToTest !== "true") {
+ failMessage = " value was expected to be of type boolean (i.e. 'true' or 'false' but was: " + valueToTest;
}
- },
+ break;
+ case "list":
+ if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
+ failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
+ "</span><br/><br/>Valid values are:<p class=\"ui-text-pass\">" + schemaNode.listValues.join(" <br/> ") + "</p>";
+ }
+ break;
+ case "listBoolean":
+ case "listDefault":
+ if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
+ failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
+ "</span><br/><br/>The framework will assume the value to be:<p class=\"ui-text-pass\">" + schemaNode.defaultValue + "</p>";
+ }
+ break;
+ case "listNumbers":
+ numbers = valueToTest.split(",");
- "POWER_RESOURCE": {
- "SCREEN": {
- "NAME": "SCREEN",
- "STATE": {
- "SCREEN_OFF": {
- "NAME": "SCREEN_OFF",
- "MIN": 0,
- "MAX": 0,
- "VALUE": 0
- },
- "SCREEN_DIM": {
- "NAME": "SCREEN_DIM",
- "MIN": 0,
- "MAX": 0.2,
- "VALUE": 0.15
- },
- "SCREEN_NORMAL": {
- "NAME": "SCREEN_NORMAL",
- "MIN": 0.2,
- "MAX": 1,
- "VALUE": 0.8
- },
- "SCREEN_BRIGHT": {
- "NAME": "SCREEN_BRIGHT",
- "MIN": 1,
- "MAX": 1,
- "VALUE": 1
+ for (numberRangeIndex = 0; numberRangeIndex < numbers.length; numberRangeIndex++) {
+ numberRange = valueToTest.split("-");
+ if (numberRange.length > 1) {
+ range1 = parseInt(numberRange[0], 10);
+ range2 = parseInt(numberRange[1], 10);
+ if (isNaN(range1) || isNaN(range2)) {
+ failMessage = " range values where not recognized as being valid, they was: " + range1 +
+ " and " + range2 + " :: valid values should be of type 'integer'";
+ break;
}
}
- },
- "CPU": {
- "NAME": "CPU",
- "STATE": {
- "CPU_AWAKE": {
- "NAME": "CPU_AWAKE",
- "DEFAULT_VALUE" : 0.5
+ else if (numberRange.length === 1) {
+ range1 = parseInt(numberRange[0], 10);
+ if (isNaN(range1)) {
+ failMessage = " value was not recognized as being valid, it was: " + range1 +
+ " :: valid values should be of type 'integer'";
+ break;
}
}
}
+ break;
+ case "regex":
+ if (!valueToTest.match(schemaNode.regex)) {
+ failMessage = " value does not match expected format. Value should pass this regular expression validation: " + schemaNode.regex;
+ }
+ break;
+ case "iso-language":
+ break;
+ default:
+ exception.raise(exception.types.Application, "Schema node with value type of: " + schemaNode.type + " is not known");
}
-};
-
-});
-define('ripple/db', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- _db,
- utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- event = require('ripple/event'),
- _cache = {};
-
-function _validateAndSetPrefix(prefix) {
- if (prefix) {
- utils.validateArgumentType(prefix, "string");
- }
-
- return prefix || constants.COMMON.PREFIX;
-}
-function _createKey(key, prefix) {
- return _validateAndSetPrefix(prefix) + key;
-}
-
-function _createItem(key, value, prefix) {
- return {
- id: _createKey(key, prefix),
- key: key,
- value: value,
- prefix: _validateAndSetPrefix(prefix)
- };
-}
-
-function _save(key, value, prefix, callback) {
- var item = _createItem(key, value, prefix);
- _cache[item.id] = item;
-
- _db.transaction(function (tx) {
- tx.executeSql('REPLACE INTO persistence (id, key, value, prefix) VALUES (?, ?, ?, ?)', [item.id, item.key, item.value, item.prefix], function () {
- return callback && callback();
- });
- });
-}
-
-function _retrieve(key, prefix) {
- var item = _cache[_createKey(key, prefix)];
- return item ? item.value : undefined;
+ return failMessage;
}
-function _retrieveAll(prefix, callback) {
- var result = {};
+function _passNodeValidation(schemaNode, value, node) {
+ var validationResult = utils.copy(_validationResult);
- if (prefix) {
- utils.forEach(_cache, function (value, key) {
- if (value.prefix === prefix) {
- result[value.key] = value.value;
- }
- });
+ if (!schemaNode.validationResult) {
+ schemaNode.validationResult = [];
+ }
+ validationResult.valid = true;
+ validationResult.node = node;
+ if (value) {
+ validationResult.value = value;
+ }
+ else {
+ delete(validationResult.value);
}
+ delete(validationResult.message);
- callback.apply(null, [result]);
+ schemaNode.validationResult.push(validationResult);
}
-function _remove(key, prefix, callback) {
- delete _cache[_createKey(key, prefix)];
+function _validateNodeValue(schemaNode, node) {
+ var failMessage,
+ valueToTest = node && node.nodeValue ? node.nodeValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;
- _db.transaction(function (tx) {
- tx.executeSql('DELETE FROM persistence WHERE key = ? AND prefix = ?', [key, _validateAndSetPrefix(prefix)], function () {
- return callback && callback();
- });
- });
-}
+ if (schemaNode.type && valueToTest) {
-function _removeAll(prefix, callback) {
- utils.forEach(_cache, function (value, key) {
- if (!prefix || key.indexOf(prefix) === 0) {
- delete _cache[key];
- }
- });
+ failMessage = _validateValue(valueToTest, schemaNode);
- _db.transaction(function (tx) {
- if (prefix) {
- tx.executeSql('DELETE FROM persistence WHERE prefix = ?', [prefix], function () {
- return callback && callback();
- });
- } else {
- tx.executeSql('DELETE FROM persistence', [], function () {
- return callback && callback();
- });
+ if (failMessage !== "") {
+ _failNodeValidation(schemaNode, failMessage, valueToTest, node);
+ return;
}
- });
+ }
+ _passNodeValidation(schemaNode, valueToTest, node);
}
-_self = {
- save: function (key, value, prefix, callback) {
- _save(key, value, prefix, callback);
- event.trigger("StorageUpdatedEvent");
- },
-
- saveObject: function (key, obj, prefix, callback) {
- _save(key, JSON.stringify(obj), prefix, callback);
- event.trigger("StorageUpdatedEvent");
- },
-
- retrieve: function (key, prefix) {
- return _retrieve(key, prefix);
- },
-
- retrieveObject: function (key, prefix) {
- var retrievedValue = _retrieve(key, prefix);
- return retrievedValue ? JSON.parse(retrievedValue) : retrievedValue;
- },
-
- retrieveAll: function (prefix, callback) {
- return _retrieveAll(prefix, callback);
- },
-
- remove: function (key, prefix, callback) {
- event.trigger("StorageUpdatedEvent");
- _remove(key, prefix, callback);
- },
+function _failNodeAttributeValidation(node, attribute, message, value) {
+ var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
+ attributeValidationResult = utils.copy(_validationResult);
- removeAll: function (prefix, callback) {
- _removeAll(prefix, callback);
- event.trigger("StorageUpdatedEvent");
- },
+ if (!nodeValidationResult.attributes) {
+ nodeValidationResult.attributes = {};
+ }
- initialize: function (previous, baton) {
- baton.take();
+ nodeValidationResult.valid = false;
+ nodeValidationResult.message = "One or more attributes failed validation";
- _db = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence', 2 * 1024 * 1024);
- _db.transaction(function (tx) {
- tx.executeSql('CREATE TABLE IF NOT EXISTS persistence (id unique, key, value, prefix)');
+ attributeValidationResult.attributeName = attribute.attributeName;
+ attributeValidationResult.valid = false;
+ if (value) {
+ attributeValidationResult.value = value;
+ }
+ else {
+ delete(attributeValidationResult.value);
+ }
+ attributeValidationResult.message = node.nodeName + "." + attribute.attributeName + message;
- tx.executeSql('SELECT id, key, value, prefix FROM persistence', [], function (tx, results) {
- var len = results.rows.length, i, item;
+ nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
+ node.validationResult.push(nodeValidationResult);
+}
- for (i = 0; i < len; i++) {
- item = results.rows.item(i);
- _cache[item.id] = item;
- }
+function _passNodeAttributeValidation(node, attribute, value) {
+ var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
+ attributeValidationResult = utils.copy(_validationResult);
- baton.pass();
- });
- });
+ if (!nodeValidationResult.attributes) {
+ nodeValidationResult.attributes = {};
}
-};
-
-module.exports = _self;
-});
-define('ripple/dbfs', function (require, exports, module) {
-/*
- * Copyright 2011 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 db = require('ripple/db'),
- utils = require('ripple/utils'),
- event = require('ripple/event'),
- _cache = {},
- _self;
+ attributeValidationResult.attributeName = attribute.attributeName;
+ attributeValidationResult.valid = true;
+ if (value) {
+ attributeValidationResult.value = value;
+ }
+ else {
+ delete(attributeValidationResult.value);
+ }
+ delete(attributeValidationResult.message);
-function _get(path) {
- return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
- return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
- }, _cache);
+ nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
+ node.validationResult.push(nodeValidationResult);
}
-function _getInfo(path) {
- var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
- name = parent.splice(parent.length - 1, 1).join(""),
- ext = name.split(".");
-
- return {
- name: name,
- extension: ext.length > 1 ? ext[ext.length - 1] : "",
- hidden: (name.length > 0 && name[0] === ".") || false,
- parent: parent.join("/") || "/"
- };
-}
+function _validateNodeAttributeValue(schemaNode, schemaNodeAttribute, attribute) {
+ var failMessage,
+ valueToTest = attribute ? attribute.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;
-function _set(path, obj) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ if (schemaNodeAttribute.type && valueToTest) {
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ failMessage = _validateValue(valueToTest, schemaNodeAttribute);
- parent.children = parent.children || {};
- obj.properties = obj.properties || {};
- parent.children[child] = obj;
+ if (failMessage !== "") {
+ _failNodeAttributeValidation(schemaNode, schemaNodeAttribute, failMessage, valueToTest);
+ return;
+ }
+ }
+ _passNodeAttributeValidation(schemaNode, schemaNodeAttribute, valueToTest);
}
-function _delete(path) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+function _validateNodeAttributes(schemaNode, node, children) {
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ var siblings = utils.filter(children, function (child) {
+ return child !== node;
+ }),
+ attributeConverter = function (attribute) {
+ var _self = {
+ toValue: function (n) {
+ var obj = _self.toNode(n);
+ return obj ? obj.value : null;
+ },
+ toNode: function (n) {
+ return n.attributes.getNamedItem(attribute.attributeName);
+ }
+ };
- delete parent.children[child];
-}
+ return _self;
+ };
-function _save() {
- db.saveObject("db-filesystem", _cache);
-}
+ utils.forEach(schemaNode.attributes, function (attribute) {
-_self = {
+ var convert = attributeConverter(attribute),
+ dupe = false;
- initialize: function (prev, baton) {
- _cache = db.retrieveObject("db-filesystem") || {};
- event.trigger("FileSystemInitialized", null, true);
- },
+ if (attribute.unique) {
+ // this means we need to check and see if there are other node with the same name
+ // and ensure that they have a different value for this attributes, if not... fail
- ls: function (path, success, error) {
- try {
- var dir = _get(path),
- items = [];
+ dupe = siblings.some(function (sibling) {
+ return convert.toValue(sibling) === convert.toValue(node);
+ });
- if (dir) {
- utils.forEach(dir.children, function (item) {
- if (!item.isDirectory) {
- item.file = function (callback) {
- callback({});
- };
- }
- items.push(item);
- });
- }
- else {
- items = {};
+ if (dupe) {
+ _failNodeAttributeValidation(schemaNode,
+ attribute,
+ " node is allowed to appear multiple times, however it must be unique based on this attribute and in this case another node with an identical attribute vale was found",
+ convert.toValue(node));
+ return;
}
-
- success(utils.copy(items));
- }
- catch (e) {
- e.code = 1;
- error(e);
}
- },
-
- rm: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
-
- rmdir: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
- mkdir: function (path, success, error) {
- var entry = _get(path),
- info = _getInfo(path);
-
- if (!entry) {
- _set(path, {
- name: info.name,
- isDirectory: true,
- fullPath: path
- });
- entry = _get(path);
- }
-
- _save();
- if (entry) {
- success(utils.copy(entry));
+ if (attribute.required && !convert.toValue(node)) {
+ _failNodeAttributeValidation(schemaNode, attribute, " attribute was expected but not found", null);
}
else {
- error({code: 1});
+ _validateNodeAttributeValue(schemaNode, attribute, convert.toNode(node));
}
- },
+ });
+}
- mv: function (from, to, success, error) {
- try {
- var fromEntry = _get(from),
- toInfo = _getInfo(to);
- fromEntry.fullPath = to;
- fromEntry.name = toInfo.name;
+function _validateNode(schemaNode, parentNode) {
+ var children = utils.filter(parentNode.childNodes, function (child) {
+ return child && child.nodeName === schemaNode.nodeName;
+ });
- _set(to, fromEntry);
- _delete(from);
- _save();
- success(utils.copy(_get(to)));
- }
- catch (e) {
- e.code = 1;
- error(e);
+ if (children.length === 0) {
+ if (schemaNode.required) {
+ _failNodeValidation(schemaNode, " node expected, but not found", null, null);
}
- },
+ }
- touch: function (path, success, error) {
- if (!_get(path)) {
- _set(path, {
- fullPath: path
- });
+ utils.forEach(children, function (child) {
+ if (schemaNode.occurrence !== 0 && schemaNode.occurrence < children.length) {
+ _failNodeValidation(schemaNode, " node: more then " + schemaNode.occurrence + " node(s) found", null, child);
}
- _save();
- success(utils.copy(_get(path)));
- },
+ else {
+ _validateNodeValue(schemaNode, child.childNodes[0] || child);
- cp: function (from, to, success, error) {
- try {
- var fromEntry = _get(from);
- fromEntry.fullPath = to;
- _set(to, fromEntry);
- _save();
- success(utils.copy(_get(to)));
- }
- catch (e) {
- e.code = 1;
- error(e);
+ _validateNodeAttributes(schemaNode, child, children);
}
- },
- stat: function (path, success, error) {
- var entry = _get(path);
- success(utils.copy(entry));
- },
-
- write: function (path, contents, success, error, options) {
- var info = _getInfo(path);
-
- _set(path, {
- lastModifiedDate: new Date(),
- name: info.name,
- fullPath: path,
- isDirectory: false,
- properties: {
- type: "",
- size: contents.size
- },
- data: contents,
- file: function (callback) {
- callback({});
- }
+ utils.forEach(schemaNode.children, function (schema) {
+ _validateNode(schema, child);
});
-
- success(utils.copy(_get(path)));
- },
-
- read: function (path, success, error) {
- var entry = _get(path);
-
- if (entry) {
- success(utils.copy(entry.data));
- }
- else {
- error({code: 1});
- }
- }
-};
-
-module.exports = _self;
-
-});
-define('ripple/deviceMotionEmulator', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- platform = require('ripple/platform'),
- INTERVAL = 60000,
- _self;
-
-function _bind(name, win) {
- var callback = null;
-
- win.__defineGetter__(name, function () {
- return callback;
- });
-
- win.__defineSetter__(name, function (cb) {
- callback = cb;
});
-
- return {
- get: function () {
- return callback;
- },
- set: function (value) {
- callback = value;
- },
- exec: function (arg) {
- return callback && callback(arg);
- },
- unbind: function (cb) {
- callback = cb === callback ? null : callback;
- }
- };
}
-_self = {
- init: function (win, doc) {
- var widgetWindow = win,
- _motion,
- _orientation,
- _calibration,
- add = widgetWindow.addEventListener,
- remove = widgetWindow.removeEventListener;
-
- //Hang events off window (these are used to check for API existence by developer)
- widgetWindow.DeviceMotionEvent = function DeviceMotionEvent() {};
- widgetWindow.DeviceOrientationEvent = function DeviceOrientationEvent() {};
-
- _motion = _bind("ondevicemotion", widgetWindow);
- _orientation = _bind("ondeviceorientation", widgetWindow);
- _calibration = _bind("oncompassneedscalibration", widgetWindow);
+function _validateAgainstSchemaNode(configSchema, configXML) {
+ var results = utils.copy(configSchema);
+ try {
+ _validateNode(results[configSchema.rootElement], configXML);
+ }
+ catch (e) {
+ exception.handle(e, true);
+ }
- widgetWindow.addEventListener = function (e, callback, useCapture) {
- switch (e) {
- case "deviceorientation":
- _orientation.set(callback);
- event.trigger("DeviceOrientationEventAddedEvent");
- break;
- case "devicemotion":
- _motion.set(callback);
- event.trigger("DeviceMotionEventAddedEvent");
- break;
- case "compassneedscalibration":
- _calibration.set(callback);
- break;
+ return results;
+}
- default:
- add.apply(widgetWindow, arguments);
- break;
- }
- };
+function _validate(configXML) {
+ // traverse the config schema JSON object
+ // TODO: update to get platform.getPlatformConfigSpec().schema
+ return _validateAgainstSchemaNode(platform.current().config.schema, configXML);
+}
- widgetWindow.removeEventListener = function (event, callback) {
- _motion.unbind(callback);
- _orientation.unbind(callback);
- _calibration.unbind(callback);
- remove.apply(widgetWindow, arguments);
- };
+function _process(results) {
+ // Check to make sure that widget is the correct version (i.e. config.xml needs to match selected platform)
+ var validVersion = app.validateVersion(results);
- event.on("DeviceMotionEvent", function (motion) {
- var _motionEvent, DeviceMotionEvent;
+ if (!validVersion) {
+ _console.warn("Your application does not appear to match" +
+ " the platform you have selected. The version number in your configuration might not " +
+ "match the selected platform version or your configuration file has errors in it.");
+ }
- if (platform.current().DeviceMotionEvent) {
- DeviceMotionEvent = platform.current().DeviceMotionEvent;
- if (typeof DeviceMotionEvent !== "function")
- return;
+ // save widget info
+ app.saveInfo(results);
+ event.trigger("WidgetInformationUpdated");
- _motionEvent = new DeviceMotionEvent();
- _motionEvent.initAccelerometerEvent("devicemotion", true, false, motion.acceleration, motion.accelerationIncludingGravity,
- motion.rotationRate, INTERVAL);
- }
- else {
- _motionEvent = {
- acceleration: motion.acceleration,
- accelerationIncludingGravity: motion.accelerationIncludingGravity,
- rotationRate: motion.rotationRate
- };
- }
+ // Check for readonly preferences (WAC only?)
- _motion.exec(_motionEvent);
- });
+ if (app.getInfo().preferences !== {}) {
+ event.trigger("StorageUpdatedEvent");
+ }
+}
- event.on("DeviceOrientationEvent", function (motion) {
- var _orientationEvent, DeviceOrientationEvent;
+function _xmlToJson(xml) {
+ var obj = {};
- if (platform.current().DeviceOrientationEvent) {
- DeviceOrientationEvent = platform.current().DeviceOrientationEvent;
- if (typeof DeviceOrientationEvent !== "function")
- return;
+ if (xml.nodeType === 1) { // element
+ if (xml.attributes.length > 0) {
+ obj["@attributes"] = {};
+ utils.forEach(xml.attributes, function (attribute) {
+ obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
+ });
+ }
+ }
+ else if (xml.nodeType === 3) { // text node
+ obj = xml.nodeValue;
+ }
- _orientationEvent = new DeviceOrientationEvent();
- _orientationEvent.initDeviceOrientationEvent("deviceorientation", true, false, motion.orientation.alpha,
- motion.orientation.beta, motion.orientation.gamma, true);
+ if (xml.hasChildNodes && xml.hasChildNodes()) {
+ utils.forEach(xml.childNodes, function (child) {
+ if (!child.nodeName) {
+ return;
}
- else {
- _orientationEvent = motion.orientation;
+ if (!obj[child.nodeName]) {
+ obj[child.nodeName] = [];
}
-
- _orientation.exec(_orientationEvent);
+ obj[child.nodeName].push(_xmlToJson(child));
});
}
-};
-
-module.exports = _self;
-
-});
-define('ripple/deviceSettings', function (require, exports, module) {
-/*
- * Copyright 2011 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.
- */
-/* DeviceSettings
- * A per object store for a platform's settings.
- * For example, RadioInfo object in WAC has isRadioEnabled that can be true/false
- * setting => {key: {key1: "test"}}
- */
-var _PERSISTENCE_KEY = "devicesettings",
- db = require('ripple/db'),
- platform = require('ripple/platform'),
- _currentDeviceSettings = {},
- _self;
-function _default(key) {
- var keys = key.split("."),
- defaults = platform.current().device;
- if (keys.length === 1)
- return defaults[key];
- return keys.length === 2 &&
- defaults[keys[0]] &&
- defaults[keys[0]][keys[1]] &&
- defaults[keys[0]][keys[1]].control ?
- defaults[keys[0]][keys[1]].control.value : undefined;
+ return obj;
}
-_self = {
- initialize: function () {
- // TODO: remove deprecated DeviceSettings from persisted ones.
- _currentDeviceSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
- },
- register: function (key, obj) {
- _currentDeviceSettings[key] = obj;
- },
+module.exports = {
- persist: function (key, obj) {
- if (key) {
- _currentDeviceSettings[key] = obj;
- }
- db.saveObject(_PERSISTENCE_KEY, _currentDeviceSettings);
+ validate: function (configXML) {
+ utils.validateNumberOfArguments(1, 1, arguments.length);
+ return _validate(configXML);
},
- retrieve: function (key) {
- return _currentDeviceSettings.hasOwnProperty(key) ?
- _currentDeviceSettings[key] : _default(key);
- },
+ initialize: function (previous, baton) {
+ var xmlHttp = new XMLHttpRequest(),
+ config = platform.current().config,
+ fileName = config ? config.fileName : null,
+ results;
- retrieveAsInt: function (key) {
- return parseInt(_self.retrieve(key), 10);
+ if (!fileName) {
+ return;
+ }
+
+ try {
+ xmlHttp.open("GET", utils.appLocation() + fileName, false);
+ xmlHttp.send();
+ if (xmlHttp.responseXML) {
+ results = _validate(xmlHttp.responseXML);
+ results.rawJSON = _xmlToJson(xmlHttp.responseXML);
+ _process(results);
+ _configValidationResults = results;
+ }
+ else {
+ _process();
+ _configValidationResults = null;
+ require('ripple/ui/plugins/widgetConfig').initialize();
+ }
+ }
+ catch (e) {
+ exception.handle(e);
+ }
},
- retrieveAsBoolean: function (key) {
- return !!_self.retrieve(key);
+ getValidationResults: function () {
+ return _configValidationResults;
}
};
-module.exports = _self;
-
});
-define('ripple/devices/Bold9700', function (require, exports, module) {
+define('ripple/devices/PalmPre', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Bold9700",
- "name": "BlackBerry Bold 9700",
- "model": "9700",
- "osName": "BlackBerry OS",
- "uuid": "42",
- "osVersion": "6",
- "manufacturer": "Research In Motion",
-
- "skin": "Bold9700",
-
- "capabilities": [
- "location.gps",
- "location.maps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "storage.memorycard",
- "network.bluetooth",
- "network.wlan",
- "network.3gpp"
- ],
+ "id": "PalmPre",
+ "name": "Palm Pre",
+ "manufacturer": "Palm",
+ "model": "Pre",
+ "osName": "WebOS",
+ "osVersion": "1.x",
"screen": {
- "width": 480,
- "height": 360
+ "width": 320,
+ "height": 480
},
"viewPort": {
"portrait": {
+ "width": 320,
+ "height": 480,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
"width": 480,
- "height": 360,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 245.00,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9700; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
- "platforms": ["web", "phonegap", "webworks.handset", "cordova"]
+ "ppi": 186.09,
+ "userAgent": "Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0",
+ "platforms": ["web", "phonegap"],
+
+ "notes": {
+ "1": "<a href=\"http://www.palm.com/us/products/phones/pre/#tab2\" target=\"_blank\">Specs</a>"
+ }
};
});
};
});
-define('ripple/devices/Colt', function (require, exports, module) {
+define('ripple/devices/NexusS', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Colt",
- "name": "BlackBerry 10 Dev Alpha",
- "model": "Colt",
- "osName": "BlackBerry",
- "uuid": "42",
- "osVersion": "10.0.6.99",
- "manufacturer": "Research In Motion",
- "hardwareId": "0x8500240a",
-
- "skin": "Colt",
-
- "capabilities": [
- "input.touch",
- "location.gps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "network.bluetooth",
- "network.wlan"
- ],
+ "id" : "NexusS",
+ "name": "Nexus S",
+ "manufacturer": "Samsung",
+ "model": "Nexux S",
+ "osName": "Android",
+ "uuid" : "F54E13F1-C1B7-4212-BFA8-AB3C9C3F088F",
+ "osVersion": "2.3.x",
"screen": {
- "width": 768,
- "height": 1280
+ "width": 480,
+ "height": 800
},
"viewPort": {
"portrait": {
- "width": 768,
- "height": 1280,
+ "width": 480,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 1280,
- "height": 768,
+ "width": 800,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "defaultOrientation": "portrait",
+ "ppi": 235,
+ "userAgent": "Mozilla/5.0 (Linux; U; Android 2.3.2; en-us; Nexus S Build/GRH78C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
+ "platforms": ["web", "phonegap", "cordova"],
+
+ "notes": {
+ "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
+ }
- "ppi": 355,
- "userAgent": "Mozilla/5.0 (BlackBerry) AppleWebKit/536.2+ (KHTML, like Gecko) Version/10.0.4.182 Mobile Safari/536.2+",
- "platforms": ["web", "webworks.bb10", "cordova"]
};
});
-define('ripple/devices/Curve9300', function (require, exports, module) {
+define('ripple/devices/Playbook', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "Curve9300",
- "name": "BlackBerry Curve 9300",
- "model": "9300",
- "osName": "BlackBerry OS",
+ "id": "Playbook",
+ "name": "BlackBerry Playbook",
+ "model": "100669958",
+ "osName": "BlackBerry PlayBook OS",
"uuid": "42",
- "osVersion": "6",
+ "osVersion": "BlackBerry PlayBook OS",
"manufacturer": "Research In Motion",
- "skin": "Curve9300",
+ "skin": "Playbook",
"capabilities": [
+ "input.touch",
"location.gps",
- "location.maps",
"media.audio.capture",
"media.video.capture",
"media.recording",
- "storage.memorycard",
"network.bluetooth",
- "network.wlan",
- "network.3gpp"
+ "network.wlan"
],
"screen": {
- "width": 320,
- "height": 240
+ "width": 1024,
+ "height": 600
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 240,
+ "width": 1024,
+ "height": 600,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 600,
+ "height": 1024,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 163,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
- "platforms": ["web", "phonegap", "webworks.handset"]
+ "defaultOrientation": "landscape",
+
+ "ppi": 169.55,
+ "userAgent": "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+",
+ "platforms": ["web", "webworks.tablet", "phonegap", "cordova"]
};
});
-define('ripple/devices/Curve9350-9360-9370', function (require, exports, module) {
+define('ripple/devices/tizen-WVGA', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Curve9350-9360-9370",
- "name": "BlackBerry Curve 9350/9360/9370",
- "model": "9350-9360-9370",
- "osName": "BlackBerry OS",
+ "id": "tizen-WVGA",
+ "name": "Tizen WVGA (480x800)",
+ "osName": "Generic",
+ "osVersion": "Generic",
+ "manufacturer": "Tizen",
+ "model": "Generic",
"uuid": "42",
- "osVersion": "7",
- "manufacturer": "Research In Motion",
-
- "skin": "Curve9350-9360-9370",
-
- "capabilities": [
- "location.gps",
- "location.maps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "storage.memorycard",
- "network.bluetooth",
- "network.wlan",
- "network.3gpp"
- ],
"screen": {
"width": 480,
- "height": 360
+ "height": 800
},
"viewPort": {
"portrait": {
- "width": 480,
- "height": 360,
+ "width": 320,
+ "height": 534,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 534,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 246.00,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9350; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
- "platforms": ["web", "phonegap", "webworks.handset"]
+ "ppi": 316,
+ "browser": ["Generic"],
+ "platforms": ["web", "phonegap", "tizen", "cordova"],
+ "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/FWVGA', function (require, exports, module) {
+define('ripple/devices/Pearl9100', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "group": "Generic Devices",
- "id": "FWVGA",
- "name": "Generic - FWVGA (480x854)",
- "osName": "Generic",
- "osVersion": "Generic",
- "manufacturer": "Generic",
- "model": "Generic",
+ "id": "Pearl9100",
+ "name": "BlackBerry Pearl 9100",
+ "model": "9100",
+ "osName": "BlackBerry OS",
"uuid": "42",
+ "osVersion": "6",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Pearl9100",
+
+ "capabilities": [
+ "input.keyboard.issuretype",
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
"screen": {
- "width": 480,
- "height": 854
+ "width": 360,
+ "height": 400
},
"viewPort": {
"portrait": {
- "width": 480,
- "height": 854,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 854,
- "height": 480,
+ "width": 360,
+ "height": 400,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 96,
- "platforms": ["web", "phonegap", "cordova"],
- "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
+ "ppi": 239,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9100; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
+ "platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/G1', function (require, exports, module) {
+define('ripple/devices/iPhone3', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "G1",
- "name": "HTC G1",
- "model": "G1",
- "osName": "Android",
- "osVersion": "1.6",
- "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
- "manufacturer": "HTC",
+ "id": "iPhone3",
+ "name": "iPhone 3G/3Gs/4/4s",
+ "model": "3G",
+ "osName": "iPhone",
+ "osVersion": "3",
+ "uuid": "e0101010d38bde8e6740011221af335301010333",
+ "manufacturer": "Apple",
"screen": {
"width": 320,
}
},
- "ppi": 180.28,
- "platforms": ["web", "phonegap"],
- "userAgent": "Mozilla/5.0 (Linux; U; Android 1.0; en-us; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2",
-
- "notes": {
- "1": "<a href=\"http://www.htc.com/www/product/g1/specification.html\" target=\"_blank\">Specs</a>"
- }
+ "ppi": 164.8,
+ "userAgent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3",
+ "platforms": ["web", "phonegap", "cordova"]
};
});
};
});
-define('ripple/devices/HPPre3', function (require, exports, module) {
+define('ripple/devices/Tattoo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "HPPre3",
- "name": "HP Pre 3",
- "manufacturer": "HP",
- "model": "Pre",
- "osName": "WebOS",
- "osVersion": "2.x",
+ "id": "Tattoo",
+ "name": "HTC Tattoo",
+ "manufacturer": "HTC",
+ "model": "Tattoo",
+ "osVersion": "1.6",
+ "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
+ "osName": "Android",
"screen": {
- "width": 480,
+ "width": 240,
+ "height": 320
+ },
+ "viewPort": {
+ "portrait": {
+ "width": 240,
+ "height": 320,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ }
+ },
+
+ "ppi": 142.9,
+ "userAgent": "Mozilla/5.0 (Linux; U; Android 1.6; en-us; HTC_TATTOO_A3288 Build/DRC79) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
+ "platforms": ["web", "phonegap"]
+};
+
+});
+define('ripple/devices/custom', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation
+ *
+ * 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 = {
+ "id": "CUSTOM",
+ "name": "Custom",
+ "osName": "Generic",
+ "osVersion": "Generic",
+ "manufacturer": "Generic",
+ "model": "Generic",
+ "uuid": "42",
+ "firmware": "Generic",
+
+ "screen": {
+ "width": 600,
"height": 800
},
"viewPort": {
"portrait": {
- "width": 480,
+ "width": 600,
"height": 800,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 800,
- "height": 480,
+ "width": 600,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 260,
- // TODO :: not exactly the correct userAgent webkit version is probably different
- "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
- "platforms": ["web", "phonegap"],
-
- "notes": {
- "1": "<a href=\"http://www.palm.com/us/products/phones/pre3/index.html\" target=\"_blank\">Specs</a>"
- }
+ "ppi": 316,
+ "browser": ["Generic"],
+ "platforms": [],
+ "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/HPVeer', function (require, exports, module) {
+define('ripple/devices/Torch9860-9850', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "HPVeer",
- "name": "HP Veer",
- "manufacturer": "HP",
- "model": "Veer",
- "osName": "WebOS",
- "osVersion": "2.x",
+
+ "id": "Torch9860-9850",
+ "name": "BlackBerry Torch 9860/9850",
+ "model": "9860-9850",
+ "osName": "BlackBerry OS",
+ "uuid": "42",
+ "osVersion": "7",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Torch9860-9850",
+
+ "capabilities": [
+ "input.touch",
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
"screen": {
- "width": 320,
- "height": 400
+ "width": 480,
+ "height": 800
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 400,
+ "width": 480,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 400,
- "height": 320,
+ "width": 800,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 197,
- // TODO :: not exactly the correct userAgent webkit version is probably different
- "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
- "platforms": ["web", "phonegap"],
-
- "notes": {
- "1": "<a href=\"http://www.palm.com/us/products/phones/veer/index.html\" target=\"_blank\">Specs</a>"
- }
+ "ppi": 253,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9860; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
+ "platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/HVGA', function (require, exports, module) {
+define('ripple/devices/WVGA', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "group": "Generic Devices",
-
- "id": "HVGA",
- "name": "HVGA (320x480)",
+ "id": "WVGA",
+ "name": "WVGA (480x800)",
"osName": "Generic",
"osVersion": "Generic",
"manufacturer": "Generic",
"uuid": "42",
"screen": {
- "width": 320,
- "height": 480
+ "width": 480,
+ "height": 800
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 480,
+ "width": 480,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 480,
- "height": 320,
+ "width": 800,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
"ppi": 316,
- "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
+ "browser": ["Generic"],
+ "platforms": ["web", "phonegap", "tizen", "cordova"],
"userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/IVI-HD', function (require, exports, module) {
+define('ripple/devices/tizen-HD', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation
*
*/
module.exports = {
- "id": "IVI-HD",
- "name": "IVI HD (800x480)",
+ "id": "tizen-HD",
+ "name": "Tizen HD (720x1280)",
"osName": "Generic",
"osVersion": "Generic",
"manufacturer": "Tizen",
"firmware": "Generic",
"screen": {
- "width": 800,
- "height": 480
+ "width": 720,
+ "height": 1280
},
"viewPort": {
"portrait": {
- "width": 1024,
+ "width": 360,
"height": 640,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
"width": 640,
- "height": 1024,
+ "height": 360,
"paddingTop": 0,
"paddingLeft": 0
}
"ppi": 316,
"browser": ["Generic"],
- "platforms": ["ivi"],
+ "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
"userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/Legend', function (require, exports, module) {
+define('ripple/devices/iPad', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "Legend",
- "name": "HTC Legend",
- "osName": "Android",
+
+ "id": "iPad",
+ "name": "iPad",
+ "model": "iPad",
+ "osName": "iOS",
+ "uuid": "e0101010d38bde8e6740011221af335301010333",
"osVersion": "1.6",
- "manufacturer": "HTC",
- "model": "Legend",
- "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
+ "manufacturer": "Apple",
"screen": {
- "width": 320,
- "height": 480
+ "width": 768,
+ "height": 1024
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 480,
+ "width": 768,
+ "height": 1024,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 480,
- "height": 320,
+ "width": 1024,
+ "height": 768,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 180.3,
- "userAgent": "Mozilla/5.0 (Linux; U; Android 2.1; fr-fr; HTC Legend 1.32.163.1 Build/ERD79) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
+ "ppi": 132,
+ "userAgent": "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10",
+ "platforms": ["web", "phonegap", "cordova"],
+
+ "notes": {
+ "1": "<a href=\"http://www.apple.com/ipad/specs/\" target=\"_blank\">Specs</a>"
+ }
+};
+
+});
+define('ripple/devices/NokiaN97', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ "id": "NokiaN97",
+ "name": "Nokia N97/5800 (touch)",
+ "manufacturer": "Nokia",
+ "model": "N97",
+ "osName": "S60",
+ "osVersion": "v5",
+ "uuid": "42",
+
+ "screen": {
+ "width": 360,
+ "height": 640
+ },
+ "viewPort": {
+ "portrait": {
+ "width": 360,
+ "height": 640,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 640,
+ "height": 360,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ }
+ },
+
+ "ppi": 232,
+ "userAgent": "?",
"platforms": ["web", "phonegap"]
};
});
+define('ripple/devices/Style9670', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+
+ "id": "Style9670",
+ "name": "BlackBerry Style 9670",
+ "model": "9670",
+ "osName": "BlackBerry OS",
+ "uuid": "42",
+ "osVersion": "6",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Style9670",
+
+ "capabilities": [
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
+
+ "screen": {
+ "width": 360,
+ "height": 400
+ },
+ "viewPort": {
+ "portrait": {
+ "width": 360,
+ "height": 400,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ }
+ },
+
+ "ppi": 200,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9670; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
+ "platforms": ["web", "phonegap", "webworks.handset"]
+};
+
+});
define('ripple/devices/Nexus', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
};
});
-define('ripple/devices/Nexus7', function (require, exports, module) {
+define('ripple/devices/HVGA', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id" : "Nexus7",
- "name": "Nexus 7 (Tablet)",
- "manufacturer": "Asus",
- "model": "Nexus 7 8/16 GB",
- "osName": "Android",
- "uuid" : "903802EA-1786-4175-B0F1-1FDF87813CAA",
- "osVersion": "4.x.x",
+ "group": "Generic Devices",
+
+ "id": "HVGA",
+ "name": "HVGA (320x480)",
+ "osName": "Generic",
+ "osVersion": "Generic",
+ "manufacturer": "Generic",
+ "model": "Generic",
+ "uuid": "42",
"screen": {
- "width": 800,
- "height": 1280
+ "width": 320,
+ "height": 480
},
"viewPort": {
"portrait": {
- "width": 800,
- "height": 1280,
+ "width": 320,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 1280,
- "height": 800,
+ "width": 480,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 215,
- "userAgent": "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19",
- "platforms": ["web", "phonegap", "cordova"],
-
- "notes": {
- "1": "<a href=\"http://www.google.com/nexus/#/7/specs\" target=\"_blank\">Specs</a>"
- }
-
+ "ppi": 316,
+ "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
+ "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/NexusGalaxy', function (require, exports, module) {
+define('ripple/devices/QVGA', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id" : "NexusGalaxy",
- "name": "Nexus (Galaxy)",
- "manufacturer": "Samsung",
- "model": "Galaxy Nexus (generic)",
- "osName": "Android",
- "uuid" : "3D0AD03B-8B46-431A-BEF5-FF01B96BA990",
- "osVersion": "4.x.x",
+ "id": "QVGA",
+ "name": "Generic - QVGA (240X320)",
+ "osName": "Generic",
+ "osVersion": "Generic",
+ "manufacturer": "Generic",
+ "model": "Generic",
+ "uuid": "42",
"screen": {
- "width": 720,
- "height": 1280
+ "width": 240,
+ "height": 320
},
"viewPort": {
"portrait": {
- "width": 720,
- "height": 1280,
+ "width": 240,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 1280,
- "height": 720,
+ "width": 320,
+ "height": 240,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 315,
- "userAgent": "Mozilla/5.0 (Linux; Android 4.0.1; Galaxy Nexus Build/ITL41F) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
- "platforms": ["web", "phonegap", "cordova"],
-
- "notes": {
- "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
- }
-
+ "ppi": 96,
+ "platforms": ["web", "phonegap", "cordova", "tizen"],
+ "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/NexusS', function (require, exports, module) {
+define('ripple/devices/HPPre3', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id" : "NexusS",
- "name": "Nexus S",
- "manufacturer": "Samsung",
- "model": "Nexux S",
- "osName": "Android",
- "uuid" : "F54E13F1-C1B7-4212-BFA8-AB3C9C3F088F",
- "osVersion": "2.3.x",
+ "id": "HPPre3",
+ "name": "HP Pre 3",
+ "manufacturer": "HP",
+ "model": "Pre",
+ "osName": "WebOS",
+ "osVersion": "2.x",
"screen": {
"width": 480,
}
},
- "ppi": 235,
- "userAgent": "Mozilla/5.0 (Linux; U; Android 2.3.2; en-us; Nexus S Build/GRH78C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
- "platforms": ["web", "phonegap", "cordova"],
+ "ppi": 260,
+ // TODO :: not exactly the correct userAgent webkit version is probably different
+ "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
+ "platforms": ["web", "phonegap"],
"notes": {
- "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
+ "1": "<a href=\"http://www.palm.com/us/products/phones/pre3/index.html\" target=\"_blank\">Specs</a>"
}
-
};
});
-define('ripple/devices/NokiaN8', function (require, exports, module) {
+define('ripple/devices/Curve9300', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "NokiaN8",
- "name": "Nokia N8",
- "model": "N8",
- "osName": "SymbianOS",
+ "id": "Curve9300",
+ "name": "BlackBerry Curve 9300",
+ "model": "9300",
+ "osName": "BlackBerry OS",
"uuid": "42",
- "osVersion": "3",
- "manufacturer": "Nokia",
+ "osVersion": "6",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Curve9300",
+
+ "capabilities": [
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
"screen": {
- "width": 360,
- "height": 640
+ "width": 320,
+ "height": 240
},
"viewPort": {
"portrait": {
- "width": 360,
- "height": 640,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 640,
- "height": 360,
+ "width": 320,
+ "height": 240,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 209.8,
- "userAgent": "(Symbian/3; S60/5.2 Mozilla/5.0; NokiaN8-00/10.0.000; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.2",
- "platforms": ["web", "phonegap"],
-
- "notes": {
- "1": "<a href=\"http://www.forum.nokia.com/Devices/Device_specifications/N8-00/\" target=\"_blank\">Specs</a>"
- }
+ "ppi": 163,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
+ "platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/NokiaN97', function (require, exports, module) {
+define('ripple/devices/Bold9700', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "NokiaN97",
- "name": "Nokia N97/5800 (touch)",
- "manufacturer": "Nokia",
- "model": "N97",
- "osName": "S60",
- "osVersion": "v5",
+
+ "id": "Bold9700",
+ "name": "BlackBerry Bold 9700",
+ "model": "9700",
+ "osName": "BlackBerry OS",
"uuid": "42",
+ "osVersion": "6",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Bold9700",
+
+ "capabilities": [
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
"screen": {
- "width": 360,
- "height": 640
+ "width": 480,
+ "height": 360
},
"viewPort": {
"portrait": {
- "width": 360,
- "height": 640,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 640,
+ "width": 480,
"height": 360,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 232,
- "userAgent": "?",
- "platforms": ["web", "phonegap"]
+ "ppi": 245.00,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9700; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
+ "platforms": ["web", "phonegap", "webworks.handset", "cordova"]
};
});
-define('ripple/devices/PalmPre', function (require, exports, module) {
+define('ripple/devices/G1', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "PalmPre",
- "name": "Palm Pre",
- "manufacturer": "Palm",
- "model": "Pre",
- "osName": "WebOS",
- "osVersion": "1.x",
+
+ "id": "G1",
+ "name": "HTC G1",
+ "model": "G1",
+ "osName": "Android",
+ "osVersion": "1.6",
+ "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
+ "manufacturer": "HTC",
"screen": {
"width": 320,
}
},
- "ppi": 186.09,
- "userAgent": "Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0",
+ "ppi": 180.28,
"platforms": ["web", "phonegap"],
+ "userAgent": "Mozilla/5.0 (Linux; U; Android 1.0; en-us; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2",
"notes": {
- "1": "<a href=\"http://www.palm.com/us/products/phones/pre/#tab2\" target=\"_blank\">Specs</a>"
+ "1": "<a href=\"http://www.htc.com/www/product/g1/specification.html\" target=\"_blank\">Specs</a>"
}
};
});
-define('ripple/devices/PalmPre2', function (require, exports, module) {
+define('ripple/devices/NexusGalaxy', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "PalmPre2",
- "name": "Palm Pre 2",
- "manufacturer": "Palm",
- "model": "Pre",
- "osName": "WebOS",
- "osVersion": "2.x",
+ "id" : "NexusGalaxy",
+ "name": "Nexus (Galaxy)",
+ "manufacturer": "Samsung",
+ "model": "Galaxy Nexus (generic)",
+ "osName": "Android",
+ "uuid" : "3D0AD03B-8B46-431A-BEF5-FF01B96BA990",
+ "osVersion": "4.x.x",
"screen": {
- "width": 320,
- "height": 480
+ "width": 720,
+ "height": 1280
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 480,
+ "width": 720,
+ "height": 1280,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 480,
- "height": 320,
+ "width": 1280,
+ "height": 720,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 186.09,
- // TODO :: not exactly the correct userAgent webkit version is probably different
- "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
- "platforms": ["web", "phonegap"],
+ "ppi": 315,
+ "userAgent": "Mozilla/5.0 (Linux; Android 4.0.1; Galaxy Nexus Build/ITL41F) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
+ "platforms": ["web", "phonegap", "cordova"],
"notes": {
- "1": "<a href=\"http://www.palm.com/us/products/phones/pre2/#tab2\" target=\"_blank\">Specs</a>"
+ "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
}
+
};
});
-define('ripple/devices/Pearl9100', function (require, exports, module) {
+define('ripple/devices/Torch9810', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "Pearl9100",
- "name": "BlackBerry Pearl 9100",
- "model": "9100",
+ "id": "Torch9810",
+ "name": "BlackBerry Torch 9810",
+ "model": "9810",
"osName": "BlackBerry OS",
"uuid": "42",
- "osVersion": "6",
+ "osVersion": "7",
"manufacturer": "Research In Motion",
- "skin": "Pearl9100",
+ "skin": "Torch9810",
"capabilities": [
- "input.keyboard.issuretype",
+ "input.touch",
"location.gps",
"location.maps",
"media.audio.capture",
],
"screen": {
- "width": 360,
- "height": 400
+ "width": 480,
+ "height": 640
},
"viewPort": {
"portrait": {
- "width": 360,
- "height": 400,
+ "width": 480,
+ "height": 640,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 640,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 239,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9100; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
+ "ppi": 253,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9810; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
"platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/Playbook', function (require, exports, module) {
+define('ripple/devices/PalmPre2', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Playbook",
- "name": "BlackBerry Playbook",
- "model": "100669958",
- "osName": "BlackBerry PlayBook OS",
- "uuid": "42",
- "osVersion": "BlackBerry PlayBook OS",
- "manufacturer": "Research In Motion",
-
- "skin": "Playbook",
-
- "capabilities": [
- "input.touch",
- "location.gps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "network.bluetooth",
- "network.wlan"
- ],
+ "id": "PalmPre2",
+ "name": "Palm Pre 2",
+ "manufacturer": "Palm",
+ "model": "Pre",
+ "osName": "WebOS",
+ "osVersion": "2.x",
"screen": {
- "width": 1024,
- "height": 600
+ "width": 320,
+ "height": 480
},
"viewPort": {
"portrait": {
- "width": 1024,
- "height": 600,
+ "width": 320,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 600,
- "height": 1024,
+ "width": 480,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "defaultOrientation": "landscape",
+ "ppi": 186.09,
+ // TODO :: not exactly the correct userAgent webkit version is probably different
+ "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
+ "platforms": ["web", "phonegap"],
- "ppi": 169.55,
- "userAgent": "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+",
- "platforms": ["web", "webworks.tablet", "phonegap", "cordova"]
+ "notes": {
+ "1": "<a href=\"http://www.palm.com/us/products/phones/pre2/#tab2\" target=\"_blank\">Specs</a>"
+ }
};
});
-define('ripple/devices/QVGA', function (require, exports, module) {
+define('ripple/devices/Curve9350-9360-9370', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "QVGA",
- "name": "Generic - QVGA (240X320)",
- "osName": "Generic",
- "osVersion": "Generic",
- "manufacturer": "Generic",
- "model": "Generic",
+
+ "id": "Curve9350-9360-9370",
+ "name": "BlackBerry Curve 9350/9360/9370",
+ "model": "9350-9360-9370",
+ "osName": "BlackBerry OS",
"uuid": "42",
+ "osVersion": "7",
+ "manufacturer": "Research In Motion",
+
+ "skin": "Curve9350-9360-9370",
+
+ "capabilities": [
+ "location.gps",
+ "location.maps",
+ "media.audio.capture",
+ "media.video.capture",
+ "media.recording",
+ "storage.memorycard",
+ "network.bluetooth",
+ "network.wlan",
+ "network.3gpp"
+ ],
"screen": {
- "width": 240,
- "height": 320
+ "width": 480,
+ "height": 360
},
"viewPort": {
"portrait": {
- "width": 240,
- "height": 320,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 320,
- "height": 240,
+ "width": 480,
+ "height": 360,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 96,
- "platforms": ["web", "phonegap", "cordova", "tizen"],
- "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
+ "ppi": 246.00,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9350; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
+ "platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/Style9670', function (require, exports, module) {
+define('ripple/devices/Colt', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "Style9670",
- "name": "BlackBerry Style 9670",
- "model": "9670",
- "osName": "BlackBerry OS",
+ "id": "Colt",
+ "name": "BlackBerry 10 Dev Alpha",
+ "model": "Colt",
+ "osName": "BlackBerry",
"uuid": "42",
- "osVersion": "6",
+ "osVersion": "10.0.6.99",
"manufacturer": "Research In Motion",
+ "hardwareId": "0x8500240a",
- "skin": "Style9670",
+ "skin": "Colt",
"capabilities": [
+ "input.touch",
"location.gps",
- "location.maps",
"media.audio.capture",
"media.video.capture",
"media.recording",
- "storage.memorycard",
"network.bluetooth",
- "network.wlan",
- "network.3gpp"
+ "network.wlan"
],
"screen": {
- "width": 360,
- "height": 400
+ "width": 768,
+ "height": 1280
},
"viewPort": {
"portrait": {
- "width": 360,
- "height": 400,
+ "width": 768,
+ "height": 1280,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 1280,
+ "height": 768,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 200,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9670; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
- "platforms": ["web", "phonegap", "webworks.handset"]
+ "defaultOrientation": "portrait",
+
+ "ppi": 355,
+ "userAgent": "Mozilla/5.0 (BlackBerry) AppleWebKit/536.2+ (KHTML, like Gecko) Version/10.0.4.182 Mobile Safari/536.2+",
+ "platforms": ["web", "webworks.bb10", "cordova"]
};
});
-define('ripple/devices/Tattoo', function (require, exports, module) {
+define('ripple/devices/Nexus7', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "Tattoo",
- "name": "HTC Tattoo",
- "manufacturer": "HTC",
- "model": "Tattoo",
- "osVersion": "1.6",
- "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
+ "id" : "Nexus7",
+ "name": "Nexus 7 (Tablet)",
+ "manufacturer": "Asus",
+ "model": "Nexus 7 8/16 GB",
"osName": "Android",
+ "uuid" : "903802EA-1786-4175-B0F1-1FDF87813CAA",
+ "osVersion": "4.x.x",
"screen": {
- "width": 240,
- "height": 320
+ "width": 800,
+ "height": 1280
},
"viewPort": {
"portrait": {
- "width": 240,
- "height": 320,
+ "width": 800,
+ "height": 1280,
+ "paddingTop": 0,
+ "paddingLeft": 0
+ },
+ "landscape": {
+ "width": 1280,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 142.9,
- "userAgent": "Mozilla/5.0 (Linux; U; Android 1.6; en-us; HTC_TATTOO_A3288 Build/DRC79) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
- "platforms": ["web", "phonegap"]
+ "ppi": 215,
+ "userAgent": "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19",
+ "platforms": ["web", "phonegap", "cordova"],
+
+ "notes": {
+ "1": "<a href=\"http://www.google.com/nexus/#/7/specs\" target=\"_blank\">Specs</a>"
+ }
+
};
});
-define('ripple/devices/Torch9800', function (require, exports, module) {
+define('ripple/devices/Legend', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Torch9800",
- "name": "BlackBerry Torch 9800",
- "model": "9800",
- "osName": "BlackBerry OS",
- "uuid": "42",
- "osVersion": "6",
- "manufacturer": "Research In Motion",
-
- "skin": "Torch9800",
-
- "capabilities": [
- "input.touch",
- "location.gps",
- "location.maps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "storage.memorycard",
- "network.bluetooth",
- "network.wlan",
- "network.3gpp"
- ],
+ "id": "Legend",
+ "name": "HTC Legend",
+ "osName": "Android",
+ "osVersion": "1.6",
+ "manufacturer": "HTC",
+ "model": "Legend",
+ "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
"screen": {
- "width": 360,
+ "width": 320,
"height": 480
},
"viewPort": {
"portrait": {
- "width": 360,
+ "width": 320,
"height": 480,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
"width": 480,
- "height": 360,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 188.68,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
- "platforms": ["web", "phonegap", "webworks.handset"]
+ "ppi": 180.3,
+ "userAgent": "Mozilla/5.0 (Linux; U; Android 2.1; fr-fr; HTC Legend 1.32.163.1 Build/ERD79) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
+ "platforms": ["web", "phonegap"]
};
});
-define('ripple/devices/Torch9810', function (require, exports, module) {
+define('ripple/devices/Torch9800', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
*/
module.exports = {
- "id": "Torch9810",
- "name": "BlackBerry Torch 9810",
- "model": "9810",
+ "id": "Torch9800",
+ "name": "BlackBerry Torch 9800",
+ "model": "9800",
"osName": "BlackBerry OS",
"uuid": "42",
- "osVersion": "7",
+ "osVersion": "6",
"manufacturer": "Research In Motion",
- "skin": "Torch9810",
+ "skin": "Torch9800",
"capabilities": [
"input.touch",
],
"screen": {
- "width": 480,
- "height": 640
+ "width": 360,
+ "height": 480
},
"viewPort": {
"portrait": {
- "width": 480,
- "height": 640,
+ "width": 360,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 640,
- "height": 480,
+ "width": 480,
+ "height": 360,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 253,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9810; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
+ "ppi": 188.68,
+ "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
"platforms": ["web", "phonegap", "webworks.handset"]
};
});
-define('ripple/devices/Torch9860-9850', function (require, exports, module) {
+define('ripple/devices/HPVeer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "Torch9860-9850",
- "name": "BlackBerry Torch 9860/9850",
- "model": "9860-9850",
- "osName": "BlackBerry OS",
- "uuid": "42",
- "osVersion": "7",
- "manufacturer": "Research In Motion",
-
- "skin": "Torch9860-9850",
-
- "capabilities": [
- "input.touch",
- "location.gps",
- "location.maps",
- "media.audio.capture",
- "media.video.capture",
- "media.recording",
- "storage.memorycard",
- "network.bluetooth",
- "network.wlan",
- "network.3gpp"
- ],
+ "id": "HPVeer",
+ "name": "HP Veer",
+ "manufacturer": "HP",
+ "model": "Veer",
+ "osName": "WebOS",
+ "osVersion": "2.x",
"screen": {
- "width": 480,
- "height": 800
+ "width": 320,
+ "height": 400
},
"viewPort": {
"portrait": {
- "width": 480,
- "height": 800,
+ "width": 320,
+ "height": 400,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 800,
- "height": 480,
+ "width": 400,
+ "height": 320,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 253,
- "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9860; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
- "platforms": ["web", "phonegap", "webworks.handset"]
+ "ppi": 197,
+ // TODO :: not exactly the correct userAgent webkit version is probably different
+ "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
+ "platforms": ["web", "phonegap"],
+
+ "notes": {
+ "1": "<a href=\"http://www.palm.com/us/products/phones/veer/index.html\" target=\"_blank\">Specs</a>"
+ }
};
});
};
});
-define('ripple/devices/WVGA', function (require, exports, module) {
+define('ripple/devices/FWVGA', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "WVGA",
- "name": "WVGA (480x800)",
+ "group": "Generic Devices",
+
+ "id": "FWVGA",
+ "name": "Generic - FWVGA (480x854)",
"osName": "Generic",
"osVersion": "Generic",
"manufacturer": "Generic",
"screen": {
"width": 480,
- "height": 800
+ "height": 854
},
"viewPort": {
"portrait": {
"width": 480,
- "height": 800,
+ "height": 854,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 800,
+ "width": 854,
"height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 316,
- "browser": ["Generic"],
- "platforms": ["web", "phonegap", "tizen", "cordova"],
+ "ppi": 96,
+ "platforms": ["web", "phonegap", "cordova"],
"userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/Wave', function (require, exports, module) {
+define('ripple/devices/NokiaN8', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- "id": "Wave",
- "name": "Samsung Wave",
- "manufacturer": "Samsung",
- "model": "Wave",
- "osName": "Bada",
- "osVersion": "n/a",
-
- "screen": {
- "width": 480,
- "height": 800
- },
- "viewPort": {
- "portrait": {
- "width": 480,
- "height": 800,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 800,
- "height": 480,
- "paddingTop": 0,
- "paddingLeft": 0
- }
- },
-
- "ppi": 283,
- "userAgent": "?",
- "platforms": ["web"]
-};
-
-});
-define('ripple/devices/custom', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation
- *
- * 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 = {
- "id": "CUSTOM",
- "name": "Custom",
- "osName": "Generic",
- "osVersion": "Generic",
- "manufacturer": "Generic",
- "model": "Generic",
+ "id": "NokiaN8",
+ "name": "Nokia N8",
+ "model": "N8",
+ "osName": "SymbianOS",
"uuid": "42",
- "firmware": "Generic",
-
- "screen": {
- "width": 600,
- "height": 800
- },
- "viewPort": {
- "portrait": {
- "width": 600,
- "height": 800,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 600,
- "height": 800,
- "paddingTop": 0,
- "paddingLeft": 0
- }
- },
-
- "ppi": 316,
- "browser": ["Generic"],
- "platforms": [],
- "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
-};
-
-});
-define('ripple/devices/iPad', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
-
- "id": "iPad",
- "name": "iPad",
- "model": "iPad",
- "osName": "iOS",
- "uuid": "e0101010d38bde8e6740011221af335301010333",
- "osVersion": "1.6",
- "manufacturer": "Apple",
+ "osVersion": "3",
+ "manufacturer": "Nokia",
"screen": {
- "width": 768,
- "height": 1024
+ "width": 360,
+ "height": 640
},
"viewPort": {
"portrait": {
- "width": 768,
- "height": 1024,
+ "width": 360,
+ "height": 640,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 1024,
- "height": 768,
+ "width": 640,
+ "height": 360,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 132,
- "userAgent": "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10",
- "platforms": ["web", "phonegap", "cordova"],
+ "ppi": 209.8,
+ "userAgent": "(Symbian/3; S60/5.2 Mozilla/5.0; NokiaN8-00/10.0.000; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.2",
+ "platforms": ["web", "phonegap"],
"notes": {
- "1": "<a href=\"http://www.apple.com/ipad/specs/\" target=\"_blank\">Specs</a>"
+ "1": "<a href=\"http://www.forum.nokia.com/Devices/Device_specifications/N8-00/\" target=\"_blank\">Specs</a>"
}
};
});
-define('ripple/devices/iPhone3', function (require, exports, module) {
+define('ripple/devices/Wave', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
-
- "id": "iPhone3",
- "name": "iPhone 3G/3Gs/4/4s",
- "model": "3G",
- "osName": "iPhone",
- "osVersion": "3",
- "uuid": "e0101010d38bde8e6740011221af335301010333",
- "manufacturer": "Apple",
+ "id": "Wave",
+ "name": "Samsung Wave",
+ "manufacturer": "Samsung",
+ "model": "Wave",
+ "osName": "Bada",
+ "osVersion": "n/a",
"screen": {
- "width": 320,
- "height": 480
+ "width": 480,
+ "height": 800
},
"viewPort": {
"portrait": {
- "width": 320,
- "height": 480,
+ "width": 480,
+ "height": 800,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
- "width": 480,
- "height": 320,
+ "width": 800,
+ "height": 480,
"paddingTop": 0,
"paddingLeft": 0
}
},
- "ppi": 164.8,
- "userAgent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3",
- "platforms": ["web", "phonegap", "cordova"]
+ "ppi": 283,
+ "userAgent": "?",
+ "platforms": ["web"]
};
});
-define('ripple/devices/tizen-HD', function (require, exports, module) {
+define('ripple/devices/IVI-HD', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation
*
*/
module.exports = {
- "id": "tizen-HD",
- "name": "Tizen HD (720x1280)",
+ "id": "IVI-HD",
+ "name": "IVI HD (800x480)",
"osName": "Generic",
"osVersion": "Generic",
"manufacturer": "Tizen",
"firmware": "Generic",
"screen": {
- "width": 720,
- "height": 1280
+ "width": 800,
+ "height": 480
},
"viewPort": {
"portrait": {
- "width": 360,
+ "width": 1024,
"height": 640,
"paddingTop": 0,
"paddingLeft": 0
},
"landscape": {
"width": 640,
- "height": 360,
+ "height": 1024,
"paddingTop": 0,
"paddingLeft": 0
}
"ppi": 316,
"browser": ["Generic"],
- "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
+ "platforms": ["ivi"],
"userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};
});
-define('ripple/devices/tizen-WVGA', function (require, exports, module) {
+define('ripple/event', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ _listeners = {};
+
+function _on(eventType, listener, scope, once) {
+ if (!eventType) {
+ throw "eventType must be truthy";
+ }
+ _listeners[eventType] = _listeners[eventType] || [];
+ _listeners[eventType].push({
+ func: listener,
+ scope: scope,
+ once: !!once
+ });
+}
+
+function _deleteEventHandler(eventType, listenerFunc, scope) {
+ var i, listeners;
+
+ if (!eventType) {
+ throw "eventType must be truthy";
+ }
+
+ listeners = _listeners[eventType];
+
+ // only delete once
+ for (i = 0; i < listeners.length; i++) {
+ if (listeners[i].func === listenerFunc) {
+ listeners.splice(i, 1);
+ break;
+ }
+ }
+}
+
+function _trigger(listener, args, sync) {
+ try {
+ if (sync) {
+ listener.func.apply(listener.scope, args);
+ }
+ else {
+ setTimeout(function () {
+ listener.func.apply(listener.scope, args);
+ }, 1);
+ }
+ }
+ catch (e) {
+ exception.handle(e);
+ }
+}
+
module.exports = {
- "id": "tizen-WVGA",
- "name": "Tizen WVGA (480x800)",
- "osName": "Generic",
- "osVersion": "Generic",
- "manufacturer": "Tizen",
- "model": "Generic",
- "uuid": "42",
+ on: function (eventType, listener, scope) {
+ _on(eventType, listener, scope, false);
+ },
- "screen": {
- "width": 480,
- "height": 800
+ once: function (eventType, listener, scope) {
+ _on(eventType, listener, scope, true);
},
- "viewPort": {
- "portrait": {
- "width": 320,
- "height": 534,
- "paddingTop": 0,
- "paddingLeft": 0
- },
- "landscape": {
- "width": 534,
- "height": 320,
- "paddingTop": 0,
- "paddingLeft": 0
+
+ trigger: function (eventType, args, sync) {
+ args = args || [];
+ sync = sync || false;
+
+ var listeners = _listeners[eventType];
+
+ if (listeners) {
+ listeners.forEach(function (listener) {
+ _trigger(listener, args, sync);
+ });
+
+ _listeners[eventType] = listeners.filter(function (listener) {
+ return !listener.once;
+ });
}
},
- "ppi": 316,
- "browser": ["Generic"],
- "platforms": ["web", "phonegap", "tizen", "cordova"],
- "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
+ eventHasSubscriber: function (eventType) {
+ return !!_listeners[eventType];
+ },
+
+ getEventSubscribers: function (eventType) {
+ return utils.copy(_listeners[eventType]) || [];
+ },
+
+ clear: function (eventType) {
+ if (eventType) {
+ delete _listeners[eventType];
+ }
+ },
+
+ deleteEventHandler: function (eventType, listener, scope) {
+ _deleteEventHandler(eventType, listener, scope);
+ }
};
});
};
});
-define('ripple/documentEventListener', function (require, exports, module) {
+define('ripple/dbfs', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ _cache = {},
+ _self;
-var event = require('ripple/event'),
- constants = require('ripple/constants'),
- deviceSettings = require('ripple/deviceSettings'),
- ui = require('ripple/ui'),
- _self,
- _ComWinShow = false;
+function _get(path) {
+ return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
+ return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
+ }, _cache);
+}
-function _bind(name, win) {
- var _listeners = [];
+function _getInfo(path) {
+ var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
+ name = parent.splice(parent.length - 1, 1).join(""),
+ ext = name.split(".");
return {
- add: function (callback, useCapture) {
- // ignore non-function
- if (typeof callback === "function") {
- // ignore useCapture as we could not handle it
- if (!useCapture) {
- if (!_listeners.some(function (listener) {
- return (listener === callback);
- })) {
- _listeners.push(callback);
+ name: name,
+ extension: ext.length > 1 ? ext[ext.length - 1] : "",
+ hidden: (name.length > 0 && name[0] === ".") || false,
+ parent: parent.join("/") || "/"
+ };
+}
+
+function _set(path, obj) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
+
+ parent.children = parent.children || {};
+ obj.properties = obj.properties || {};
+ parent.children[child] = obj;
+}
+
+function _delete(path) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
+
+ delete parent.children[child];
+}
+
+function _save() {
+ db.saveObject("db-filesystem", _cache);
+}
+
+_self = {
+
+ initialize: function (prev, baton) {
+ _cache = db.retrieveObject("db-filesystem") || {};
+ event.trigger("FileSystemInitialized", null, true);
+ },
+
+ ls: function (path, success, error) {
+ try {
+ var dir = _get(path),
+ items = [];
+
+ if (dir) {
+ utils.forEach(dir.children, function (item) {
+ if (!item.isDirectory) {
+ item.file = function (callback) {
+ callback({});
+ };
}
- }
+ items.push(item);
+ });
+ }
+ else {
+ items = {};
+ }
+
+ success(utils.copy(items));
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+
+ rm: function (path, success, error, options) {
+ _delete(path);
+ _save();
+ success();
+ },
+
+ rmdir: function (path, success, error, options) {
+ _delete(path);
+ _save();
+ success();
+ },
+
+ mkdir: function (path, success, error) {
+ var entry = _get(path),
+ info = _getInfo(path);
+
+ if (!entry) {
+ _set(path, {
+ name: info.name,
+ isDirectory: true,
+ fullPath: path
+ });
+ entry = _get(path);
+ }
+
+ _save();
+ if (entry) {
+ success(utils.copy(entry));
+ }
+ else {
+ error({code: 1});
+ }
+ },
+
+ mv: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from),
+ toInfo = _getInfo(to);
+
+ fromEntry.fullPath = to;
+ fromEntry.name = toInfo.name;
+
+ _set(to, fromEntry);
+ _delete(from);
+ _save();
+ success(utils.copy(_get(to)));
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+
+ touch: function (path, success, error) {
+ if (!_get(path)) {
+ _set(path, {
+ fullPath: path
+ });
+ }
+ _save();
+ success(utils.copy(_get(path)));
+ },
+
+ cp: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from);
+ fromEntry.fullPath = to;
+ _set(to, fromEntry);
+ _save();
+ success(utils.copy(_get(to)));
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+
+ stat: function (path, success, error) {
+ var entry = _get(path);
+ success(utils.copy(entry));
+ },
+
+ write: function (path, contents, success, error, options) {
+ var info = _getInfo(path);
+
+ _set(path, {
+ lastModifiedDate: new Date(),
+ name: info.name,
+ fullPath: path,
+ isDirectory: false,
+ properties: {
+ type: "",
+ size: contents.size
+ },
+ data: contents,
+ file: function (callback) {
+ callback({});
}
+ });
+
+ success(utils.copy(_get(path)));
+ },
+
+ read: function (path, success, error) {
+ var entry = _get(path);
+
+ if (entry) {
+ success(utils.copy(entry.data));
+ }
+ else {
+ error({code: 1});
+ }
+ }
+};
+
+module.exports = _self;
+
+});
+define('ripple/deviceMotionEmulator', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ platform = require('ripple/platform'),
+ INTERVAL = 60000,
+ _self;
+
+function _bind(name, win) {
+ var callback = null;
+
+ win.__defineGetter__(name, function () {
+ return callback;
+ });
+
+ win.__defineSetter__(name, function (cb) {
+ callback = cb;
+ });
+
+ return {
+ get: function () {
+ return callback;
+ },
+ set: function (value) {
+ callback = value;
},
exec: function (arg) {
- _listeners.forEach(function (listener) {
- listener.apply(win, arg);
- });
+ return callback && callback(arg);
},
- remove: function (callback, useCapture) {
- // ignore non-function
- if (typeof callback === "function") {
- // ignore useCapture as we do not add them into _listeners
- if (!useCapture) {
- _listeners = _listeners.filter(function (listener) {
- return (listener !== callback);
- });
- }
- }
+ unbind: function (cb) {
+ callback = cb === callback ? null : callback;
}
};
}
-function _isComWinSHow() {
- return _ComWinShow;
-}
-
_self = {
- mask: function (frame, doc) {
- /*
- * The current issue is that "document.addEventListener(visibilitychange, function(){...})"
- * does not work if it is invoked in the document.DOMContentLoaded listeners, for example, at
- * JQuery(document).ready function.
+ init: function (win, doc) {
+ var widgetWindow = win,
+ _motion,
+ _orientation,
+ _calibration,
+ add = widgetWindow.addEventListener,
+ remove = widgetWindow.removeEventListener;
- * The reason is that window.DOMContentLoaded is fired after the document.DOMContentLoaded.
- * Currently we have not found a proper event to override the document.addEventListener.
- * The beforeload is fine for window.addEventListener, while does not work for document.addEventListener
- * because the contentDocument will be reset after loading.
- */
- frame.addEventListener("DOMContentLoaded", function () {
- var widgetDocument = doc,
- _pageVisibility,
- add = widgetDocument.addEventListener,
- remove = widgetDocument.removeEventListener;
+ //Hang events off window (these are used to check for API existence by developer)
+ widgetWindow.DeviceMotionEvent = function DeviceMotionEvent() {};
+ widgetWindow.DeviceOrientationEvent = function DeviceOrientationEvent() {};
- widgetDocument.PAGE_HIDDEN = "hidden";
- widgetDocument.PAGE_VISIBLE = "visible";
- widgetDocument.PAGE_PREVIEW = "preview";
+ _motion = _bind("ondevicemotion", widgetWindow);
+ _orientation = _bind("ondeviceorientation", widgetWindow);
+ _calibration = _bind("oncompassneedscalibration", widgetWindow);
- function _lockScreen(on) {
- var hidden = on;
+ widgetWindow.addEventListener = function (e, callback, useCapture) {
+ switch (e) {
+ case "deviceorientation":
+ _orientation.set(callback);
+ event.trigger("DeviceOrientationEventAddedEvent");
+ break;
+ case "devicemotion":
+ _motion.set(callback);
+ event.trigger("DeviceMotionEventAddedEvent");
+ break;
+ case "compassneedscalibration":
+ _calibration.set(callback);
+ break;
- if (on) {
- ui.showOverlay("lock-screen-window", function (background) {});
- } else {
- ui.hideOverlay("lock-screen-window", function (background) {});
- }
+ default:
+ add.apply(widgetWindow, arguments);
+ break;
+ }
+ };
- event.trigger("visibilitychange", [hidden]);
+ widgetWindow.removeEventListener = function (event, callback) {
+ _motion.unbind(callback);
+ _orientation.unbind(callback);
+ _calibration.unbind(callback);
+ remove.apply(widgetWindow, arguments);
+ };
+
+ event.on("DeviceMotionEvent", function (motion) {
+ var _motionEvent, DeviceMotionEvent;
+
+ if (platform.current().DeviceMotionEvent) {
+ DeviceMotionEvent = platform.current().DeviceMotionEvent;
+ if (typeof DeviceMotionEvent !== "function")
+ return;
+
+ _motionEvent = new DeviceMotionEvent();
+ _motionEvent.initAccelerometerEvent("devicemotion", true, false, motion.acceleration, motion.accelerationIncludingGravity,
+ motion.rotationRate, INTERVAL);
+ }
+ else {
+ _motionEvent = {
+ acceleration: motion.acceleration,
+ accelerationIncludingGravity: motion.accelerationIncludingGravity,
+ rotationRate: motion.rotationRate
+ };
}
- function _isLockScreenOn() {
- return deviceSettings.retrieve("Config.lockScreen");
+ _motion.exec(_motionEvent);
+ });
+
+ event.on("DeviceOrientationEvent", function (motion) {
+ var _orientationEvent, DeviceOrientationEvent;
+
+ if (platform.current().DeviceOrientationEvent) {
+ DeviceOrientationEvent = platform.current().DeviceOrientationEvent;
+ if (typeof DeviceOrientationEvent !== "function")
+ return;
+
+ _orientationEvent = new DeviceOrientationEvent();
+ _orientationEvent.initDeviceOrientationEvent("deviceorientation", true, false, motion.orientation.alpha,
+ motion.orientation.beta, motion.orientation.gamma, true);
+ }
+ else {
+ _orientationEvent = motion.orientation;
}
- _lockScreen(_isLockScreenOn());
+ _orientation.exec(_orientationEvent);
+ });
+ }
+};
- _pageVisibility = _bind("visibilitychange", frame.contentWindow);
+module.exports = _self;
- widgetDocument.addEventListener = function (event, callback, useCapture) {
- switch (event) {
- case "visibilitychange":
- _pageVisibility.add(callback, useCapture);
- break;
+});
+define('ripple/platform', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _current,
+ db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _console = require('ripple/console'),
+ app = require('ripple/app'),
+ event = require('ripple/event'),
+ spec = require('ripple/platform/spec'),
+ _self;
- default:
- add.apply(widgetDocument, arguments);
- break;
- }
- };
+function _getRequestedPlatform() {
+ var requestedPlatform = null,
+ enableRippleArg = utils.queryString().enableripple,
+ platform;
- widgetDocument.removeEventListener = function (event, callback, useCapture) {
- _pageVisibility.remove(callback, useCapture);
- remove.apply(widgetDocument, arguments);
- };
+ if (enableRippleArg) {
+ enableRippleArg = enableRippleArg.split('-');
+ platform = spec.get(enableRippleArg[0], enableRippleArg[1]);
+ if (platform) {
+ requestedPlatform = { name: platform.id, version: platform.version };
+ }
+ }
- event.on("LockScreenChanged", function (on) {
- if (_isComWinSHow() === false) {
- _lockScreen(on);
- }
- else {
- if (on === true) {
- ui.hideOverlay("communication-window");
- _lockScreen(on);
- }
- else {
- _lockScreen(on);
- ui.showOverlay("communication-window");
- }
- }
- });
+ return requestedPlatform;
+}
- event.on("CommWinShow", function (status) {
- _ComWinShow = status;
- if (_isLockScreenOn() === true) {
- if (status === false) {
- _lockScreen(true);
- }
- else {
- jQuery("#lock-screen-window").hide();
- }
- }
+function _validatePlatform(platform, defaultPlatform) {
+ if (!platform ||
+ !spec[platform.name] ||
+ !spec[platform.name][platform.version] ||
+ (spec[platform.name][platform.version] && !spec[platform.name][platform.version].objects)) {
+ return defaultPlatform;
+ }
+ return platform;
+}
+
+function _getPlatform() {
+ return require('ripple/platform/' + _current.name + "/" + _current.version + "/spec");
+}
+
+function _getCurrentPlatform() {
+ var uriParams, platform = {};
+
+ uriParams = utils.getURIParams(document.documentURI);
+ if (uriParams && uriParams.platform) {
+ var platformName = uriParams.platform.split("-")[0], platformVersion;
+
+ if (platformName === "mobile" || platformName === "tizen") {
+ platformName = "tizen";
+ platformVersion = "2.0";
+ }
+ else {
+ platformName = "ivi";
+ platformVersion = "3.0";
+ }
+ platform.name = platformName;
+ platform.version = platformVersion;
+
+ return platform;
+ }
+
+ return undefined;
+}
+
+_self = {
+ initialize: function () {
+ var firstAvailablePlatform = utils.map(this.getList(), function (platform) {
+ return utils.map(platform, function (details, version) {
+ return {name: details.id, version: version};
+ })[0];
+ })[0];
+
+ _current = _getRequestedPlatform() || _getCurrentPlatform() ||
+ db.retrieveObject("api-key") || firstAvailablePlatform;
+ _current = _validatePlatform(_current, firstAvailablePlatform);
+
+ db.saveObject("api-key", _current);
+
+ _console.prefix = _current.name;
+ },
+
+ getList: function () {
+ var platformList = {};
+ utils.forEach(spec, function (platform, platformKey) {
+ utils.forEach(platform, function (version, versionKey) {
+ platformList[platformKey] = platformList[platformKey] || {};
+ platformList[platformKey][versionKey] = {
+ "id": version.id,
+ "name": version.name,
+ "type": version.type,
+ "text": require('ripple/platform/' + platformKey + "/" + versionKey + "/spec").version
+ };
});
+ });
- event.on("visibilitychange", function (hidden) {
- widgetDocument.hidden = hidden;
- widgetDocument.visibilityState = hidden ? widgetDocument.PAGE_HIDDEN : widgetDocument.PAGE_VISIBLE;
- _pageVisibility.exec();
+ return platformList;
+ },
+
+ getPersistencePrefix: function (id) {
+ return _getPlatform().persistencePrefix + (id || app.getInfo().id) + "-";
+ },
+
+ current: function () {
+ return _getPlatform();
+ },
+
+ changeEnvironment: function (platform, deviceId, callback) {
+ var save = jWorkflow.order(function (prev, baton) {
+ baton.take();
+ db.saveObject("api-key", platform, null, baton.pass);
+ }).andThen(function (prev, baton) {
+ baton.take();
+ db.save("device-key", deviceId, null, baton.pass);
+ }).andThen(function (prev, baton) {
+ //remove the persisted value for the layout
+ baton.take();
+ db.save("layout", null, null, baton.pass);
+ }).andThen(function () {
+ event.trigger("PlatformChangedEvent", [], true);
+ _console.prefix = null;
+ _console.log("Emulator :: loading platform " + platform.name);
});
+
+ save.start(callback);
+ }
+};
+
+module.exports = _self;
+
+});
+define('ripple/hwKeyEmulator', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ _self;
+
+function _HWKeyEvent(keyName) {
+ var doc = document.getElementById('document').contentDocument,
+ event;
+
+ event = doc.createEvent('Event');
+ event.initEvent("tizenhwkey", true, false);
+ event.__defineGetter__("keyName", function () {
+ return keyName;
+ });
+ doc.dispatchEvent(event);
+}
+
+
+_self = {
+ init: function (win, doc) {
+ event.clear("tizenhwkeyEvent");
+ event.on("tizenhwkeyEvent", function (keyName) {
+ _HWKeyEvent(keyName);
});
}
};
};
});
-define('ripple/event', function (require, exports, module) {
+define('ripple/documentEventListener', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- _listeners = {};
-
-function _on(eventType, listener, scope, once) {
- if (!eventType) {
- throw "eventType must be truthy";
- }
- _listeners[eventType] = _listeners[eventType] || [];
- _listeners[eventType].push({
- func: listener,
- scope: scope,
- once: !!once
- });
-}
-
-function _deleteEventHandler(eventType, listenerFunc, scope) {
- var i, listeners;
- if (!eventType) {
- throw "eventType must be truthy";
- }
+var event = require('ripple/event'),
+ constants = require('ripple/constants'),
+ deviceSettings = require('ripple/deviceSettings'),
+ ui = require('ripple/ui'),
+ _self,
+ _ComWinShow = false;
- listeners = _listeners[eventType];
+function _bind(name, win) {
+ var _listeners = [];
- // only delete once
- for (i = 0; i < listeners.length; i++) {
- if (listeners[i].func === listenerFunc) {
- listeners.splice(i, 1);
- break;
+ return {
+ add: function (callback, useCapture) {
+ // ignore non-function
+ if (typeof callback === "function") {
+ // ignore useCapture as we could not handle it
+ if (!useCapture) {
+ if (!_listeners.some(function (listener) {
+ return (listener === callback);
+ })) {
+ _listeners.push(callback);
+ }
+ }
+ }
+ },
+ exec: function (arg) {
+ _listeners.forEach(function (listener) {
+ listener.apply(win, arg);
+ });
+ },
+ remove: function (callback, useCapture) {
+ // ignore non-function
+ if (typeof callback === "function") {
+ // ignore useCapture as we do not add them into _listeners
+ if (!useCapture) {
+ _listeners = _listeners.filter(function (listener) {
+ return (listener !== callback);
+ });
+ }
+ }
}
- }
+ };
}
-function _trigger(listener, args, sync) {
- try {
- if (sync) {
- listener.func.apply(listener.scope, args);
- }
- else {
- setTimeout(function () {
- listener.func.apply(listener.scope, args);
- }, 1);
- }
- }
- catch (e) {
- exception.handle(e);
- }
+function _isComWinSHow() {
+ return _ComWinShow;
}
-module.exports = {
- on: function (eventType, listener, scope) {
- _on(eventType, listener, scope, false);
- },
+_self = {
+ mask: function (frame, doc) {
+ /*
+ * The current issue is that "document.addEventListener(visibilitychange, function(){...})"
+ * does not work if it is invoked in the document.DOMContentLoaded listeners, for example, at
+ * JQuery(document).ready function.
- once: function (eventType, listener, scope) {
- _on(eventType, listener, scope, true);
- },
-
- trigger: function (eventType, args, sync) {
- args = args || [];
- sync = sync || false;
-
- var listeners = _listeners[eventType];
-
- if (listeners) {
- listeners.forEach(function (listener) {
- _trigger(listener, args, sync);
- });
-
- _listeners[eventType] = listeners.filter(function (listener) {
- return !listener.once;
- });
- }
- },
-
- eventHasSubscriber: function (eventType) {
- return !!_listeners[eventType];
- },
-
- getEventSubscribers: function (eventType) {
- return utils.copy(_listeners[eventType]) || [];
- },
-
- clear: function (eventType) {
- if (eventType) {
- delete _listeners[eventType];
- }
- },
-
- deleteEventHandler: function (eventType, listener, scope) {
- _deleteEventHandler(eventType, listener, scope);
- }
-};
-
-});
-define('ripple/exception', function (require, exports, module) {
-/*
- * Copyright 2011 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 _console = require('ripple/console');
-
-function _getStack(depth) {
- var caller,
- stack = "",
- count = 0;
-
- try {
- caller = arguments.callee.caller.arguments.callee.caller;
-
- while (count <= depth && caller) {
- stack += "function: " + caller.toString().match(/function\s?(.*)\{/)[1] + "\n";
- caller = caller.arguments.callee.caller;
- count++;
- }
- } catch (e) {
- stack = "failed to determine stack trace (" + (e.name || e.type) + " :: " + e.message + ")";
- }
-
- return stack;
-}
+ * The reason is that window.DOMContentLoaded is fired after the document.DOMContentLoaded.
+ * Currently we have not found a proper event to override the document.addEventListener.
+ * The beforeload is fine for window.addEventListener, while does not work for document.addEventListener
+ * because the contentDocument will be reset after loading.
+ */
+ frame.addEventListener("DOMContentLoaded", function () {
+ var widgetDocument = doc,
+ _pageVisibility,
+ add = widgetDocument.addEventListener,
+ remove = widgetDocument.removeEventListener;
-module.exports = {
+ widgetDocument.PAGE_HIDDEN = "hidden";
+ widgetDocument.PAGE_VISIBLE = "visible";
+ widgetDocument.PAGE_PREVIEW = "preview";
- types: {
- Application: "Application",
- ArgumentLength: "ArgumentLength",
- ArgumentType: "ArgumentType",
- Argument: "Argument",
- NotificationType: "NotificationType",
- NotificationStateType: "NotificationStateType",
- DomObjectNotFound: "DomObjectNotFound",
- LayoutType: "LayoutType",
- OrientationType: "OrientationType",
- DeviceNotFound: "DeviceNotFound",
- tinyHipposMaskedException: "tinyHipposMaskedException",
- Geo: "Geo",
- Accelerometer: "Accelerometer",
- MethodNotImplemented: "MethodNotImplemented",
- InvalidState: "InvalidState",
- ApplicationState: "ApplicationState"
- },
+ function _lockScreen(on) {
+ var hidden = on;
- handle: function handle(exception, reThrow) {
- reThrow = reThrow || false;
+ if (on) {
+ ui.showOverlay("lock-screen-window", function (background) {});
+ } else {
+ ui.hideOverlay("lock-screen-window", function (background) {});
+ }
- var eMsg = exception.message || "exception caught!",
- msg = eMsg + "\n\n" + (exception.stack || "*no stack provided*") + "\n\n";
+ event.trigger("visibilitychange", [hidden]);
+ }
- _console.error(msg);
+ function _isLockScreenOn() {
+ return deviceSettings.retrieve("Config.lockScreen");
+ }
- if (reThrow) {
- throw exception;
- }
- },
+ _lockScreen(_isLockScreenOn());
- raise: function raise(exceptionType, message, customExceptionObject) {
- var obj = customExceptionObject || {
- type: "",
- message: "",
+ _pageVisibility = _bind("visibilitychange", frame.contentWindow);
- toString: function () {
- var result = this.name + ': "' + this.message + '"';
+ widgetDocument.addEventListener = function (event, callback, useCapture) {
+ switch (event) {
+ case "visibilitychange":
+ _pageVisibility.add(callback, useCapture);
+ break;
- if (this.stack) {
- result += "\n" + this.stack;
- }
- return result;
+ default:
+ add.apply(widgetDocument, arguments);
+ break;
}
};
- message = message || "";
+ widgetDocument.removeEventListener = function (event, callback, useCapture) {
+ _pageVisibility.remove(callback, useCapture);
+ remove.apply(widgetDocument, arguments);
+ };
- obj.name = exceptionType;
- obj.type = exceptionType;
- // TODO: include the exception objects original message if exists
- obj.message = message;
- obj.stack = _getStack(5);
+ event.on("LockScreenChanged", function (on) {
+ if (_isComWinSHow() === false) {
+ _lockScreen(on);
+ }
+ else {
+ if (on === true) {
+ ui.hideOverlay("communication-window");
+ _lockScreen(on);
+ }
+ else {
+ _lockScreen(on);
+ ui.showOverlay("communication-window");
+ }
+ }
+ });
- throw obj;
- },
+ event.on("CommWinShow", function (status) {
+ _ComWinShow = status;
+ if (_isLockScreenOn() === true) {
+ if (status === false) {
+ _lockScreen(true);
+ }
+ else {
+ jQuery("#lock-screen-window").hide();
+ }
+ }
+ });
- throwMaskedException: function throwMaskedException(exceptionType, message, customExceptionObject) {
- try {
- this.raise.apply(this, arguments);
- } catch (e) {
- this.handle(e);
- }
- this.raise(this.types.tinyHipposMaskedException, "tinyhippos terminated your script due to exception");
+ event.on("visibilitychange", function (hidden) {
+ widgetDocument.hidden = hidden;
+ widgetDocument.visibilityState = hidden ? widgetDocument.PAGE_HIDDEN : widgetDocument.PAGE_VISIBLE;
+ _pageVisibility.exec();
+ });
+ });
}
-
};
+module.exports = _self;
+
});
-define('ripple/fileSystem', function (require, exports, module) {
+define('ripple/honeypot', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- db = require('ripple/db'),
- exception = require('ripple/exception'),
- event = require('ripple/event'),
- _console = require('ripple/console'),
- utils = require('ripple/utils'),
- _fileSystemPaths = {
- "photos": { "uri": "" },
- "videos": { "uri": "" },
- "music": { "uri": "" },
- "downloads": { "uri": "" },
- "widgethome": { "uri": "" }
- },
- _fileSystemRegex = {
- "photos": { "virtualPathRegex": /^\/virtual\/photos\//i },
- "videos": { "virtualPathRegex": /^\/virtual\/videos\//i },
- "music": { "virtualPathRegex": /^\/virtual\/music\//i },
- "downloads": { "virtualPathRegex": /^\/virtual\/downloads\//i },
- "widgethome": { "virtualPathRegex": /^\/virtual\/widgethome\//i }
- },
- _overrides = {};
-module.exports = {
- initialize: function () {
- _fileSystemPaths = db.retrieveObject(constants.FILESYSTEM.PERSISTENCE_KEY) || _fileSystemPaths;
- _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
- },
+var noop = function () {};
- getURI: function getURI(origURI) {
- var newURI = origURI,
- found = false;
+module.exports = {
+ monitor: function (context, target) {
- if (_overrides[origURI]) {
- return _overrides[origURI];
- }
+ var setup = function (get, set) {
+ set = set || noop;
- utils.forEach(_fileSystemPaths, function (value, key) {
- if (found) {
- return;
- }
+ context.__defineGetter__(target, noop);
+ context.__defineSetter__(target, function (value) {
+ context.__defineGetter__(target, get);
+ set(value);
+ });
+ };
- var uri = value.uri.replace(/\/$/, "");
- if (origURI.match(_fileSystemRegex[key].virtualPathRegex)) {
- newURI = origURI.replace(_fileSystemRegex[key].virtualPathRegex, uri + "/");
- found = true;
+ return {
+ andReturn: function (value) {
+ setup(function () {
+ return value;
+ });
+ },
+ andRun: function (get, set) {
+ setup(get, set);
}
- });
-
- return newURI;
- },
-
- exists: function (path) {
- try {
- var scrubbedUri = this.getURI(path),
- xhr = new XMLHttpRequest();
-
- xhr.open("GET", scrubbedUri, false);
- xhr.send();
-
- //HACK: this should return maybe for 403
- return xhr.status !== 404;
- }
- catch (e) {
- exception.handle(e);
- _console.log("failed to check if [" + path + "] exists");
- return false;
- }
- },
-
-
- getFileSystemPaths: function getFileSystemPaths() {
- return utils.copy(_fileSystemPaths);
- },
-
- updateFileSystemPaths: function updateFileSystemPaths(filePathsObject) {
- _fileSystemPaths = utils.copy(filePathsObject);
- _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname;
- db.saveObject(constants.FILESYSTEM.PERSISTENCE_KEY, filePathsObject);
- },
-
- override : function (from, to) {
- _overrides[from] = to;
+ };
}
};
});
-define('ripple/fs', function (require, exports, module) {
+define('ripple/bootstrap', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- event = require('ripple/event'),
+var _bound,
_console = require('ripple/console'),
- _self, _fs;
+ utils = require('ripple/utils'),
+ ui = require('ripple/ui'),
+ db = require('ripple/db'),
+ _CURRENT_URL = "current-url",
+ resizer = require('ripple/resizer'),
+ platform = require('ripple/platform');
-function _map(array, callback) {
- var map = [], i;
- for (i = 0; i < array.length; i++) {
- map[i] = callback(array[i], i);
- }
- return map;
+var _srcChangedObserver = new WebKitMutationObserver(function (mutations) {
+ utils.forEach(mutations, function (mutation) {
+ _bindObjectsToFrame(mutation.target);
+ });
+ });
+
+function _observeIframeAdded(doc) {
+ doc._iframeAddedObserver.observe(doc, {childList: true, subtree: true});
}
-function _resolveLocalFileSystemURL(path, success, error) {
- return (window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL)(path, success, error);
+function _bindObjects(win, doc) {
+ if (!win.tinyHippos) {
+ require('ripple/emulatorBridge').link(win, doc);
+ /// require('ripple/platform/tizen/2.0/touchEvent').mask(win, doc);
+ require('ripple/touchEventEmulator').mask(win, doc);
+ require('ripple/hwKeyEmulator').init(win, doc);
+ require('ripple/documentEventListener').mask(win, doc);
+ require('ripple/deviceMotionEmulator').init(win, doc);
+ require('ripple/resizer').init(win, doc);
+ win.addEventListener("DOMContentLoaded", function () {
+ var iframes = $(this.document).find("iframe");
+ // Observe iframe added event so that we can bind objects to newly added iframes
+ if (!this.document._iframeAddedObserver) {
+ this.document._iframeAddedObserver = new WebKitMutationObserver(function (mutations) {
+ utils.forEach(mutations, function (mutation) {
+ for (var i in mutation.addedNodes) {
+ var node = mutation.addedNodes[i];
+ if (node.tagName && (node.tagName.toUpperCase() === "IFRAME")) {
+ _bindObjectsToFrame(node);
+ }
+ }
+ });
+ });
+ _observeIframeAdded(this.document);
+ }
+ iframes.each(function () {
+ _bindObjectsToFrame(this);
+ });
+
+ });
+ win.frameElement._bound = true;
+ }
}
-function _blobBuilder() {
- var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder;
- return new BlobBuilder();
+function _beforeLoad() {
+ this._bound = false;
+ _bindObjects(this.contentWindow, this.contentDocument);
+ this._intervalId = window.setInterval(function () {
+ if (this._bound) {
+ window.clearInterval(this._intervalId);
+ } else {
+ _bindObjects(this.contentWindow, this.contentDocument);
+ }
+ }.bind(this), 1);
}
-function _error(e) {
- var msg = '';
+function _bindObjectsToFrame(frame) {
+ _srcChangedObserver.observe(frame, {attributes: true, attributeFilter: ["src"]});
+ frame.addEventListener("beforeload", _beforeLoad);
+ // beforeload event of an iframe will not be triggered unless we detach and
+ // then attach the iframe to the dom tree
+ var parentNode = frame.parentNode;
+ var nextNode = frame.nextNode;
+ if (parentNode) {
+ // Disable iframe added observer to avoid infinite loop of binding objects
+ if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
+ frame.ownerDocument._iframeAddedObserver.disconnect();
+ }
+ parentNode.removeChild(frame);
+ if (nextNode)
+ nextNode.insertBefore(frame);
+ else
+ parentNode.appendChild(frame);
- switch (e.code) {
- case FileError.QUOTA_EXCEEDED_ERR:
- msg = 'QUOTA_EXCEEDED_ERR';
- break;
- case FileError.NOT_FOUND_ERR:
- msg = 'NOT_FOUND_ERR';
- break;
- case FileError.SECURITY_ERR:
- msg = 'SECURITY_ERR';
- break;
- case FileError.INVALID_MODIFICATION_ERR:
- msg = 'INVALID_MODIFICATION_ERR';
- break;
- case FileError.INVALID_STATE_ERR:
- msg = 'INVALID_STATE_ERR';
- break;
- default:
- msg = 'Unknown Error';
- break;
+ if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
+ _observeIframeAdded(frame.ownerDocument);
+ }
}
-
- _console.log('FileSystem error: ' + msg);
}
-_self = {
- initialize: function (prev, baton) {
- try {
- var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+function _createFrame(src) {
+ var frame = document.createElement("iframe");
+ frame.setAttribute("id", "document");
+ frame.src = src;
- if (requestFileSystem) {
- baton.take();
- }
+ if (ui.registered("omnibar")) {
+ _bindObjectsToFrame(frame);
+ }
- requestFileSystem(window.TEMPORARY, constants.FS_SIZE, function (fs) {
- _fs = fs;
- event.trigger("FileSystemInitialized", null, true);
- baton.pass();
- }, _error);
- }
- catch (e) {
- console.log("File System Not Available");
+ return frame;
+}
+
+function _cleanBody() {
+ require('ripple/utils').forEach(document.body.children, function (child) {
+ if (child && child.id && !child.id.match(/ui|tooltip|bus/)) {
+ document.body.removeChild(child);
}
- },
- ls: function (path, success, error) {
- path = path || "/";
+ document.body.removeAttribute("style");
+ document.body.removeAttribute("id");
+ document.body.removeAttribute("class");
+ });
+}
- _fs.root.getDirectory(path, {}, function (dirEntry) {
- var dirReader = dirEntry.createReader();
- dirReader.readEntries(function (entries) {
- success(_map(entries, function (entry, index) {
- return entry;
- }));
- }, error);
- }, error);
- },
+function reload() {
+ window.tinyHipposReload = true;
+ location.reload();
+}
- rm: function (path, success, error, options) {
- options = options || {};
+function _post(src) {
+ var event = require('ripple/event'),
+ frame = _createFrame(src);
- _fs.root[options.recursive ? "getDirectory" : "getFile"](path, {create: false}, function (entry) {
- entry[options.recursive ? "removeRecursively" : "remove"](function () {
- success();
- }, error);
- }, error);
- },
+ _console.log("Initialization Finished (Make it so.)");
- rmdir: function (path, success, error, options) {
- options = options || {};
+ frame.onload = function () {
+ var bootLoader = document.querySelector("#emulator-booting"),
+ id,
+ iframe = document.getElementById('document'),
+ viewportTagFound = false,
+ viewportTagContent = {},
+ viewportTagStr = "",
+ tagProperties = [],
+ propertyKey ="",
+ propertyValue = "",
+ curViewPortWidth = "",
+ curViewPortHeight = "",
+ layout = db.retrieve("layout") || "portrait",
+ preLayout = "";
- _fs.root.getDirectory(path, {create: false}, function (entry) {
- entry.remove(function () {
- success();
- }, error);
- }, error);
- },
+ if (bootLoader) {
+ document.querySelector("#ui").removeChild(bootLoader);
+ }
- mkdir: function (path, success, error) {
- _fs.root.getDirectory(path, {create: true}, function (dirEntry) {
- success(dirEntry);
- }, error);
- },
+ // Workaround to enforce the content of iframe to rerender when scrolling
+ document.getElementById('document').contentWindow.onscroll = function() {
+ jQuery("#device-maskmask").show();
+ setTimeout(function() {
+ jQuery("#device-maskmask").hide();
+ }, 50);
+ }
- mv: function (from, to, success, error) {
- var path = to.replace(/^\//, "").split("/"),
- fileName = path.splice(path.length - 1, 1).toString();
+ event.trigger("TinyHipposLoaded");
+ _cleanBody();
+ id = window.setInterval(_cleanBody, 20);
- _self.stat(from, function (entry) {
- _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
- entry.moveTo(dest, fileName, function (finalDestination) {
- success(finalDestination);
- }, error);
- }, error);
- }, error);
- },
+ window.setTimeout(function () {
+ window.clearInterval(id);
+ }, 1200);
- touch: function (path, success, error) {
- _fs.root.getFile(path, {create: true}, function (fileEntry) {
- success(fileEntry);
- }, error);
- },
+ // Clean data for different app
+ if (db.retrieve("current-url") !== db.retrieve("previous-url")) {
+ db.remove("viewport_width");
+ db.remove("viewport_height");
+ db.remove("viewportTag");
+ db.remove("prelayout");
+ }
- cp: function (from, to, success, error) {
- var path = to.replace(/^\//, "").split("/"),
- fileName = path.splice(path.length - 1, 1).toString();
+ curViewPortWidth = db.retrieve("viewport_width");
+ curViewPortHeight = db.retrieve("viewport_height");
+ preLayout = db.retrieve("prelayout") || "portrait";
+ db.save("previous-url", db.retrieve("current-url"));
- _self.stat(from, function (entry) {
- _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
- entry.copyTo(dest, fileName, function (finalDestination) {
- success(finalDestination);
- }, error);
- }, error);
- }, error);
- },
+ if (iframe.contentDocument.getElementsByName('viewport')[0] !== undefined) {
+ viewportTagStr = iframe.contentDocument.getElementsByName('viewport')[0].getAttribute("content");
+ viewportTagStr = viewportTagStr.replace(/\s/g, '');
+ tagProperties = viewportTagStr.split(",");
- stat: function (path, success, error) {
- var url = "filesystem:" + utils.location().origin + "/temporary/" + path;
- _resolveLocalFileSystemURL(url, function (entry) {
- success(entry);
- }, error);
- },
+ for (var i in tagProperties) {
+ propertyKey = tagProperties[i].split("=")[0];
+ propertyValue = tagProperties[i].split("=")[1];
+ viewportTagContent[propertyKey] = propertyValue;
+ }
+ viewportTagFound = true;
+ }
- write: function (path, contents, success, error, options) {
- options = options || {};
+ // if viewport tag found (width, height)
+ if (viewportTagFound && ((viewportTagContent['width'] !== undefined) || (viewportTagContent['height'] !== undefined))) {
+ if ((viewportTagContent['width'] !== undefined)) {
+ if (curViewPortWidth !== viewportTagContent['width']) {
+ db.saveObject("viewportTag", viewportTagContent);
+ if (layout !== preLayout) {
+ db.save("prelayout", layout);
+ resizer.changeLayoutType(layout);
+ event.trigger("LayoutChanged", [layout], true);
+ frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
+ } else {
+ resizer.changeLayoutType(layout);
+ }
+ }
+ } else {
+ if (curViewPortHeight !== viewportTagContent['height']) {
+ db.saveObject("viewportTag", viewportTagContent);
+ if (layout !== preLayout) {
+ db.save("prelayout", layout);
+ resizer.changeLayoutType(layout);
+ event.trigger("LayoutChanged", [layout], true);
+ frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
+ } else {
+ resizer.changeLayoutType(layout);
+ }
+ }
+ }
+ } else {
+ // Set layout to portrait if no viewport tag detected
+ resizer.changeLayoutType('portrait');
+ event.trigger("LayoutChanged", ['portrait'], true);
+ }
- function write(entry) {
- entry.createWriter(function (fileWriter) {
- var bb = _blobBuilder();
+ if (ui.registered("omnibar")) {
+ //reset the onload function so that when navigating we can destroy
+ //the iframe and create a new one so we can reinject the platform by
+ //calling post again.
+ frame.onload = function () {
+ var url = frame.contentWindow.location.href;
+ document.getElementById("viewport-container").removeChild(frame);
+ event.trigger("FrameHistoryChange", [url]);
+ _console.log("-----------------------------------------------------------");
+ _console.log("Pay no attention to that man behind the curtain.");
+ _console.log("Environment Warning up again (Set main batteries to auto-fire cycle)");
+ _post(url);
+ };
+ }
+ };
- fileWriter.onwriteend = function (progressEvent) {
- success(entry);
- };
- fileWriter.onerror = error;
+ // append frame
+ document.getElementById("viewport-container").appendChild(frame);
- if (options.mode === "append") {
- fileWriter.seek(fileWriter.length);
- }
+ delete tinyHippos.boot;
+}
- bb.append(contents);
- fileWriter.write(bb.getBlob('text/plain'));
- }, error);
- }
+function _bootstrap() {
+ // TODO: figure this out for web and ext
+ //_console.log("-----------------------------------------------------------");
+ //_console.log("There be dragons above here!");
+ _console.log("Web Simulator :: Environment Warming Up (Tea. Earl Gray. Hot.)");
- _self.stat(path, function (entry) {
- if (options.mode === "append") {
- write(entry);
- } else {
- _self.rm(path, function () {
- _self.touch(path, write, error);
- }, error);
- }
- }, function (e) {
- if (e.code === FileError.NOT_FOUND_ERR) {
- _self.touch(path, write, error);
- } else {
- error(e);
- }
- });
- },
+ window.tinyHippos = require('ripple');
- read: function (path, success, error) {
- _self.stat(path, function (entry) {
- entry.file(function (file) {
- var reader = new FileReader();
+ tinyHippos.boot(function () {
+ var uri = ui.registered('omnibar') ?
+ db.retrieve(_CURRENT_URL) || "about:blank" :
+ document.documentURI.replace(/enableripple=[^&]*[&]?/i, "").replace(/[\?&]*$/, "");
- reader.onloadend = function (progressEvent) {
- success(progressEvent.target.result);
- };
- reader.onerror = error;
+ _post(uri);
+ delete tinyHippos.boot;
+ });
+}
- reader.readAsText(file);
- }, error);
- }, error);
+module.exports = {
+ bootstrap: _bootstrap,
+ inject: function (frameWindow, frameDocument) {
+ _bindObjects(frameWindow, frameDocument);
}
};
-module.exports = _self;
-
});
-define('ripple/geo', function (require, exports, module) {
+define('ripple/appcache', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- exception = require('ripple/exception'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- _positionInfo = {
- "latitude": 39.968362,
- "longitude": 116.410186,
- "altitude": 50,
- "accuracy": 150,
- "altitudeAccuracy": 80,
- "heading": 0,
- "speed": 0,
- "cellID": 1130433
- },
- self;
-
-function _serialize(settings) {
- var tempSettings = utils.copy(settings);
- tempSettings.position.timeStamp = "new Date(" + tempSettings.position.timeStamp.getTime() + ")";
- return tempSettings;
-}
-
-function _validatePositionInfo(pInfo) {
- return (pInfo &&
- !(isNaN(pInfo.latitude) ||
- isNaN(pInfo.longitude) ||
- isNaN(pInfo.altitude) ||
- isNaN(pInfo.accuracy) ||
- isNaN(pInfo.altitudeAccuracy) ||
- isNaN(pInfo.heading) ||
- isNaN(pInfo.speed) ||
- isNaN(pInfo.cellID))) ? true : false;
-}
-
-self = module.exports = {
+module.exports = {
initialize: function () {
- var settings = db.retrieveObject("geosettings");
- if (settings) {
- utils.forEach(_positionInfo, function (value, key) {
- _positionInfo[key] = parseFloat(settings.position[key] || value);
- });
-
- self.timeout = settings.timeout;
- self.delay = settings.delay || 0;
-
- }
- },
-
- getPositionInfo: function () {
- var pi = utils.copy(_positionInfo);
- pi.timeStamp = new Date();
-
- return pi;
- },
-
- updatePositionInfo: function (newPositionInfo, delay, timeout) {
- if (!_validatePositionInfo(newPositionInfo)) {
- exception.raise(exception.types.Geo, "invalid positionInfo object");
- }
-
- _positionInfo = utils.copy(newPositionInfo);
- _positionInfo.timeStamp = new Date();
-
- self.delay = delay || 0;
- self.timeout = timeout;
-
- db.saveObject("geosettings", _serialize({
- position: _positionInfo,
- delay: self.delay,
- timeout: self.timeout
- }));
-
- event.trigger("PositionInfoUpdatedEvent", [_positionInfo]);
- },
-
- timeout: false,
- delay: 0,
- map: {}
+ window.addEventListener('load', function (e) {
+ window.applicationCache.addEventListener('updateready', function (e) {
+ if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
+ window.applicationCache.swapCache();
+ window.location.reload();
+ }
+ }, false);
+ }, false);
+ }
};
});
-define('ripple/honeypot', function (require, exports, module) {
+define('ripple/app', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var _data = {},
+ utils = require('ripple/utils'),
+ _self;
-var noop = function () {};
+_self = {
+ setInfo: function (info) {
+ if (!info) {
+ _data = {};
+ }
+ _data = info;
+ },
-module.exports = {
- monitor: function (context, target) {
+ getInfo: function () {
+ return utils.copy(_data);
+ },
- var setup = function (get, set) {
- set = set || noop;
+ isPreferenceReadOnly: function (key) {
+ return (_data.preferences &&
+ _data.preferences[key] &&
+ _data.preferences[key].readonly &&
+ _data.preferences[key].readonly === true);
+ },
- context.__defineGetter__(target, noop);
- context.__defineSetter__(target, function (value) {
- context.__defineGetter__(target, get);
- set(value);
- });
- };
+ validateVersion: function (configValidationObject) {
+ // TODO: WTF figure this out, platform is empty object when require at require time
+ // could be that the new platform _getBuilder code dies when called, beforre it is initialized
+ var spec = require('ripple/platform').current();
+ if (typeof spec.config.validateVersion === "function" && configValidationObject) {
+ return spec.config.validateVersion(configValidationObject);
+ }
- return {
- andReturn: function (value) {
- setup(function () {
- return value;
- });
- },
- andRun: function (get, set) {
- setup(get, set);
- }
- };
+ return true;
+ },
+
+ saveInfo: function (configValidationObject) {
+ var spec = require('ripple/platform').current(),
+ info = null;
+ if (typeof spec.config.extractInfo === "function") {
+ info = spec.config.extractInfo(configValidationObject);
+ }
+
+ if (info) {
+ _self.setInfo(info);
+ }
}
+
};
+module.exports = _self;
+
});
-define('ripple/hwKeyEmulator', function (require, exports, module) {
+define('ripple/deviceSettings', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+/* DeviceSettings
+ * A per object store for a platform's settings.
+ * For example, RadioInfo object in WAC has isRadioEnabled that can be true/false
+ * setting => {key: {key1: "test"}}
+ */
+var _PERSISTENCE_KEY = "devicesettings",
+ db = require('ripple/db'),
+ platform = require('ripple/platform'),
+ _currentDeviceSettings = {},
+ _self;
-var event = require('ripple/event'),
- _self;
+function _default(key) {
+ var keys = key.split("."),
+ defaults = platform.current().device;
+ if (keys.length === 1)
+ return defaults[key];
+ return keys.length === 2 &&
+ defaults[keys[0]] &&
+ defaults[keys[0]][keys[1]] &&
+ defaults[keys[0]][keys[1]].control ?
+ defaults[keys[0]][keys[1]].control.value : undefined;
+}
-function _HWKeyEvent(keyName) {
- var doc = document.getElementById('document').contentDocument,
- event;
+_self = {
+ initialize: function () {
+ // TODO: remove deprecated DeviceSettings from persisted ones.
+ _currentDeviceSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
+ },
+ register: function (key, obj) {
+ _currentDeviceSettings[key] = obj;
+ },
- event = doc.createEvent('Event');
- event.initEvent("tizenhwkey", true, false);
- event.__defineGetter__("keyName", function () {
- return keyName;
- });
- doc.dispatchEvent(event);
-}
+ persist: function (key, obj) {
+ if (key) {
+ _currentDeviceSettings[key] = obj;
+ }
+ db.saveObject(_PERSISTENCE_KEY, _currentDeviceSettings);
+ },
+ retrieve: function (key) {
+ return _currentDeviceSettings.hasOwnProperty(key) ?
+ _currentDeviceSettings[key] : _default(key);
+ },
-_self = {
- init: function (win, doc) {
- event.clear("tizenhwkeyEvent");
- event.on("tizenhwkeyEvent", function (keyName) {
- _HWKeyEvent(keyName);
- });
+ retrieveAsInt: function (key) {
+ return parseInt(_self.retrieve(key), 10);
+ },
+
+ retrieveAsBoolean: function (key) {
+ return !!_self.retrieve(key);
}
};
module.exports = _self;
});
-define('ripple/notifications', function (require, exports, module) {
+define('ripple/touchEventEmulator', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- exception = require('ripple/exception'),
+var emulatorBridge = require('ripple/emulatorBridge'),
utils = require('ripple/utils'),
- event = require('ripple/event');
-
-function _validateAndInitNType(nType) {
- nType = nType || "normal";
-
- if (nType !== "normal" && nType !== "error") {
- exception.raise(exception.types.NotificationType, "Unknown Notification Type == " + nType + ",when dealing with Console notification.");
- }
+ _isMouseDown, self;
- return nType;
+// NOTE: missing view, detail, touches, targetTouches, scale and rotation
+function _initTouchEvent(type, canBubble, cancelable, eventData) {
+ var touchEvent = emulatorBridge.document().createEvent("Event");
+ touchEvent.initEvent(type, canBubble, cancelable);
+ utils.mixin(eventData, touchEvent);
+ return touchEvent;
}
-function _processNotification(nType, stateType, message) {
- nType = _validateAndInitNType(nType);
- message = message || "";
-
- var display,
- displayText,
- className,
- notificationIcon,
- box = document.getElementById(constants.NOTIFICATIONS.MAIN_CONTAINER_CLASS),
- msgBox = document.getElementById(constants.NOTIFICATIONS.MESSAGE_TEXT_CONTAINER_CLASS);
-
- className = "ui-widget";
-
- switch (stateType) {
+function _raiseTouchEvent(mouseEvent) {
+ var type = "",
+ simulatedEvent,
+ touchObj,
+ eventData;
- case constants.NOTIFICATIONS.STATE_TYPES.CLOSE:
- display = "display: none;"; //need to do this better.
- displayText = "";
+ switch (mouseEvent.type) {
+ case "mousedown":
+ type = "touchstart";
+ _isMouseDown = true;
break;
-
- case constants.NOTIFICATIONS.STATE_TYPES.OPEN:
- display = "display: block;"; //need to do this better.
- displayText = message;
- if (nType === "error") {
- displayText = "Oh Snap!\n\n" + displayText;
- className += " ui-state-error ui-corner-all";
- notificationIcon = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>';
- }
- else {
- className += " ui-state-highlight ui-corner-all";
- notificationIcon = '<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>';
+ case "mousemove":
+ if (!_isMouseDown) {
+ return;
}
+ type = "touchmove";
+ break;
+ case "mouseup":
+ type = "touchend";
+ _isMouseDown = false;
break;
-
default:
- exception.raise(exception.types.NotificationStateType, "Unknown StateType == " + stateType.toString());
+ return;
}
- msgBox.innerHTML = notificationIcon + displayText;
- box.setAttribute("class", className);
- box.setAttribute("style", display);
+ touchObj = {
+ clientX: mouseEvent.pageX,
+ clientY: mouseEvent.pageY,
+ identifier: "",
+ pageX: mouseEvent.pageX,
+ pageY: mouseEvent.pageY,
+ screenX: mouseEvent.pageX,
+ screenY: mouseEvent.pageY,
+ target: mouseEvent.target
+ };
-}
+ eventData = {
+ altKey: mouseEvent.altKey,
+ ctrlKey: mouseEvent.ctrlKey,
+ shiftKey: mouseEvent.shiftKey,
+ metaKey: mouseEvent.metaKey,
+ changedTouches: [touchObj],
+ targetTouches: [touchObj],
+ touches: [touchObj]
+ };
-module.exports = {
- openNotification: function (nType, msg) {
- _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.OPEN, msg);
- },
+ utils.mixin(touchObj, eventData);
- closeNotification: function (nType) {
- _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.CLOSE);
+ simulatedEvent = _initTouchEvent(type, true, true, eventData);
+
+ mouseEvent.target.dispatchEvent(simulatedEvent);
+
+ if (typeof mouseEvent.target["on" + type] === "function") {
+ mouseEvent.target["on" + type].apply(mouseEvent.target, [simulatedEvent]);
}
-};
+}
-});
-define('ripple/omgwtf', function (require, exports, module) {
-/*
- * Copyright 2011 Research In Motion Limited.
+function _marshalEvents(win, doc) {
+ utils.forEach(["mousedown", "mousemove", "mouseup"],
+ function (event) {
+ doc.addEventListener(event, _raiseTouchEvent, true);
+ });
+
+ //win.Node.prototype.ontouchstart = null;
+ //win.Node.prototype.ontouchend = null;
+ //win.Node.prototype.ontouchmove = null;
+}
+
+self = module.exports = {
+ mask: function (win, doc) {
+ _marshalEvents(win, doc);
+ }
+};
+
+});
+define('ripple/constants', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- db = require('ripple/db'),
- _loaded = false,
- _self;
-
-function _delay(action) {
- window.setTimeout(function () {
- if (!_loaded) {
- if (jQuery(".first-run-window").is(":visible")) {
- _delay(action);
- } else {
- action();
- }
- }
- }, 10000);
-}
+module.exports = {
+ "API_URL": "http://api.tinyhippos.com",
-function _hide() {
- jQuery(".error-window").css({display: 'none'});
- jQuery(".error-dialog").css({display: 'none'});
-}
+ "RELEASE_VERSION": "simulator-release-version",
-function _show() {
- jQuery(".error-window").css({display: 'block'});
+ "SERVICES": {
+ "GOOGLE_MAPS_URI": "http://maps.google.com/maps/api/staticmap?size=476x476&maptype=roadmap",
+ "GOOGLE_MAPS_API_KEY": "ABQIAAAA-CaPZHXR-0Tzhui_h6gpjhSE_2rGlnYiB7L-ZGVwgaut5s7OYRSlBAaHCzBuZf2_23_vrCOfPxXHjA"
+ },
- jQuery(".error-dialog").css({
- display: 'block',
- left: (jQuery(document).width() / 2) - 277 + "px"
- });
+ "FS_SIZE": 1024 * 1024 * 10,
- jQuery("#error-wait").click(function () {
- _hide();
- _delay(_show);
- });
+ "COMMON": {
+ "APPLICATION_STATE": "ui-application-state-",
+ "PREFIX": "tinyhippos-",
+ "DEVICE_CONTAINER" : "device-container",
+ "MENU_BUTTON" : "menu-button",
+ "BACK_BUTTON" : "back-button",
+ "HTML_CONTAINER" : "document",
+ "INFO_SECTION": "information-sub-container",
+ "ORIENTATION_SELECT_PORTRAIT_ID" : "layout-portrait",
+ "ORIENTATION_SELECT_LANDSCAPE_ID" : "layout-landscape",
+ "PLATFORM_SELECT_ID": "platform-select",
+ "DEVICE_SELECT_ID": "device-select",
+ "STORAGE_TABLE_BODY_CLASS": "preferences-list-body",
+ "STORAGE_COUNT_CONTAINER_ID": "preferences-count",
+ "GEO_MAP_CONTAINER_ID": "geo-map",
+ "FILESYSTEM_UPDATE_BUTTON_ID_WITH_HASH": "#update-filesystem-button",
+ "USER_AGENT_DEFAULT": "default",
+ "APPLICATIONS_CONTAINER_ID": "widget-applications-content",
+ "STORAGE_CLEAR_BUTTON_ID": "preferences-clear-button",
+ "AJAX_LOADER_CONTAINER_CLASS": ".loader",
+ "IRRELEVANT_CLASS": "irrelevant",
+ "MULTIMEDIA_VOLUME_SLIDER_ID": "media-volume",
+ "MULTIMEDIA_VOLUME_FIELD_ID": "media-volume-value",
+ "MULTIMEDIA_AUDIO_STATE_FIELD_ID": "media-audio-state",
+ "MULTIMEDIA_AUDIO_PLAYING_FIELD_ID": "multimedia-isaudioplaying",
+ "MULTIMEDIA_AUDIO_PROGRESS_ID": "media-audio-progress",
+ "MULTIMEDIA_AUDIO_FILE_FIELD_ID": "media-audio-file",
+ "MULTIMEDIA_VIDEO_STATE_FIELD_ID": "media-video-state",
+ "MULTIMEDIA_VIDEO_PLAYING_FIELD_ID": "multimedia-isvideoplaying",
+ "MULTIMEDIA_VIDEO_PROGRESS_ID": "media-video-progress",
+ "MULTIMEDIA_VIDEO_FILE_FIELD_ID": "media-video-file",
+ "EXTENSION_URL_CONTAINER": "extension-url",
+ "SECURITY_LEVEL": "security-level"
+ },
+ "LAUNCHING_HISTORY": "application-launching-history",
- jQuery("#error-panic").click(function () {
- db.removeAll(null, function () {
- window.tinyHipposReload = true;
- localStorage.clear();
- location.reload();
- });
- });
-}
+ "FILESYSTEM": {
+ "PERSISTENCE_KEY": "filesystem",
+ "INPUT_PREFIX_ID": "#panel-filesystem-"
+ },
-_delay(_show);
+ "PLATFORM": {
+ "DEFAULT": {
+ "name": "tizen",
+ "version": "1.0"
+ }
+ },
-_self = {
- initialize: function (previous, baton) {
- event.on("TinyHipposLoaded", function () {
- _loaded = true;
- });
+ "DEVICE": {
+ "SAVED_KEY": "device-key"
},
- show: _show,
- hide: _hide
-};
-module.exports = _self;
+ "BATTERY": {
+ "TIME": "charging-time",
+ "VOLUME": "battery-volume",
+ "CHARGING": "is-charging"
+ },
-});
-define('ripple/platform/builder', function (require, exports, module) {
-/*
- * Copyright 2011 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.
- */
+ "TOUCHEVENT": {
+ "OPTION": "touch_option",
+ "ALTKEY": "touch_altKey",
+ "METAKEY": "touch_metaKey",
+ "CTRLKEY": "touch_ctrlKey",
+ "SHIFTKEY": "touch_shiftKey",
+ "CANVAS": "touch_canvas"
+ },
-var utils = require('ripple/utils'),
- app = require('ripple/app');
+ "ENCAPSULATOR": {
+ "DEFAULT_HEIGHT": 684,
+ "DEFAULT_WIDTH": 480,
+ "LAYOUT": "layout",
+ "DISPLAY_LAYOUT": {
+ "LANDSCAPE": "landscape",
+ "PORTRAIT": "portrait"
+ },
+ "ZOOMING": "screen-zooming"
+ },
-function _objectFactory(context, objects/*, allowed*/) {
- utils.forEach(objects, function (obj, key) {
- var result = {}, objFeatures = {}, rst, f, widgetFeatures;
+ "GEO": {
+ "OPTIONS" : {
+ "LATITUDE" : "geo-latitude",
+ "LONGITUDE" : "geo-longitude",
+ "ALTITUDE" : "geo-altitude",
+ "CELL_ID" : "geo-cellid",
+ "ACCURACY" : "geo-accuracy",
+ "ALTITUDE_ACCURACY" : "geo-altitudeaccuracy",
+ "HEADING" : "geo-heading",
+ "SPEED" : "geo-speed",
+ "TIME_STAMP" : "geo-timestamp",
+ "DELAY" : "geo-delay",
+ "DELAY_LABEL" : "geo-delay-label",
+ "HEADING_LABEL" : "geo-heading-label",
+ "HEADING_MAP_LABEL" : "geo-map-direction-label",
+ "IMAGE" : "geo-map-img",
+ "MAP_CONTAINER" : "geo-map-container",
+ "TIMEOUT" : "geo-timeout",
+ "GPXFILE": "geo-gpxfile",
+ "GPXGO": "geo-gpx-go",
+ "GPXMULTIPLIER": "geo-gpxmultiplier-select",
+ "GPXREPLAYSTATUS": "geo-gpxreplaystatus"
+ },
+ "MAP_ZOOM_MAX": 18,
+ "MAP_ZOOM_MIN": 0,
+ "MAP_ZOOM_LEVEL_CONTAINER": "geo-map-zoomlevel-value",
+ "MAP_ZOOM_KEY": "geo-map-zoom-key",
+ "GPXGO_LABELS": {
-// if (allowed(obj)) {
- result = obj.path ? require('ripple/platform/' + obj.path) : {};
- if (typeof result === "function" && obj.handleSubfeatures && obj.handleSubfeatures === true) {
- rst = new result();
- if (obj.feature) {
- objFeatures = obj.feature.split('|');
- if (rst.handleSubFeatures) {
- widgetFeatures = app.getInfo().features; // features in config.xml
- f = {};
- utils.forEach(objFeatures, function (o) {
- if (widgetFeatures && !!widgetFeatures[o]) {
- f[widgetFeatures[o].id] = widgetFeatures[o];
- }
- });
- rst.handleSubFeatures(f);
- delete rst.handleSubFeatures;
- }
- }
- result = rst;
+ "GO": "Go",
+ "STOP": "Stop"
}
-// }
+ },
- if (obj.children) {
- _objectFactory(result, obj.children/*, allowed*/);
+ "PUSH": {
+ "OPTIONS" : {
+ "PAYLOAD" : "push-text"
}
+ },
- context.__defineGetter__(key, function () {
- return result;
- });
- // inject into the context if it is allowed or it has children that were allowed
-// if (allowed(obj) || utils.count(result)) {
-// context[key] = result;
-// }
-// else {
-// if (context.hasOwnProperty(key))
-// console.log("delete " + key);
-// delete context[key];
-// }
- });
-}
+ "TELEPHONY": {
+ "CALL_LIST_KEY": "telephony-call-list-key"
+ },
-module.exports = {
- build: function (objects) {
- return {
- into: function (sandbox) {
-/* var features = utils.copy(app.getInfo().features);
- allowed = function (obj) {
- var contains = function (requirements) {
- return requirements.split('|').some(function (feature) {
- return !!features[feature];
- });
- };
- //object is allowed if:
- // 1. it has no feature requirement
- // 2. the config file doesn't exist (features collection is null)
- // 3. the feature exists in the defined features
- return !obj.feature || !features || (features && contains(obj.feature));
- };
-*/
+ "PIM": {
+ "ADDRESS_LIST_KEY": "pim-address-list-key",
+ "CALENDAR_LIST_KEY": "pim-calendar-list-key"
+ },
- _objectFactory(sandbox, objects/*, allowed*/);
- }
- };
- }
-};
+ "CAMERA": {
+ "WINDOW_ANIMATION": "images/tizen-wave.gif",
+ "WARNING_TEXT": "The runtime simulated saving the camera file to {file}. If you need to access this file in your application, please copy a file to the saved location"
+ },
-});
-define('ripple/platform/cordova/2.0.0/JavaPluginManager', function (require, exports, module) {
-module.exports = {
- exec: function () {
- throw "this really shouldn't be called. like ever!";
+ "AUDIOPLAYER" : {
+ "WARNING_TEXT": "The runtime simulated saving the audio file to {file}. If you need to access this file in your application, please copy a file to the saved location"
},
- resume: function () {
- throw "this shouldn't be called";
+
+ "API_APPLICATION": {
+ "NO_APPLICATIONS_MESSAGE": "No applications available for your platform"
},
- pause: function () {
- throw "this shouldn't be called";
+
+ "NOTIFICATIONS": {
+ "MESSAGE_CONTAINER_CLASS": "notification-message-div",
+ "MAIN_CONTAINER_CLASS": "panel-notification",
+ "CLOSE_BUTTON_CLASS": "panel-notification-closebtn",
+ "MESSAGE_TEXT_CONTAINER_CLASS": "panel-notification-text",
+ "CSS_PREFIX": "panel-notification-",
+ "STATE_TYPES": {
+ "OPEN": 1,
+ "CLOSE": 2
+ }
},
- destroy: function () {
- throw "this shouldn't be called";
- }
-};
-});
-define('ripple/platform/cordova/2.0.0/MediaError', function (require, exports, module) {
-/*
- * Copyright 2011 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 MediaError = function (code, msg) {
- this.code = (code !== undefined ? code : null);
- this.message = msg || "";
-};
+ "CSS_PREFIX": {
+ "IRRELEVANT" : "irrelevant"
+ },
-MediaError.MEDIA_ERR_NONE_ACTIVE = 0;
-MediaError.MEDIA_ERR_ABORTED = 1;
-MediaError.MEDIA_ERR_NETWORK = 2;
-MediaError.MEDIA_ERR_DECODE = 3;
-MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
+ "STORAGE": {
+ "PAIR_DELIMETER" : ",",
+ "KEY_VALUE_DELIMETER" : "|"
+ },
-module.exports = MediaError;
+ "REGEX": {
+ "GEO" : /^geo-/,
+ "URL": /^((https?|ftp|gopher|telnet|file|notes|ms-help):((\/\/)|(\\\\))+[\w\d:#@%\/;$()~_?\+-=\\\.&]*)$/,
+ //"Email": /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
+ "EMAIL": /^([^@\s]+)@((?:[\-a-z0-9]+\.)+[a-z]{2,})$/,
+ "WC3_DTF": /^((\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)|(\d{4})-(\d\d)|(\d\d\d\d))$/,
+ "LOCAL_URI": /^https?:\/\/(127\.0\.0\.1|localhost)|^file:\/\//,
+ "EXTERNAL_URI": /(?:(?:[a-zA-Z0-9\/;\?&=:\-_\$\+!\*'\(\|\\~\[\]#%\.](?!www))+(?:\.[Cc]om|\.[Ee]du|\.[gG]ov|\.[Ii]nt|\.[Mm]il|\.[Nn]et|\.[Oo]rg|\.[Bb]iz|\.[Ii]nfo|\.[Nn]ame|\.[Pp]ro|\.[Aa]ero|\.[cC]oop|\.[mM]useum|\.[Cc]at|\.[Jj]obs|\.[Tt]ravel|\.[Aa]rpa|\.[Mm]obi|\.[Aa]c|\.[Aa]d|\.[aA]e|\.[aA]f|\.[aA]g|\.[aA]i|\.[aA]l|\.[aA]m|\.[aA]n|\.[aA]o|\.[aA]q|\.[aA]r|\.[aA]s|\.[aA]t|\.[aA]u|\.[aA]w|\.[aA]z|\.[aA]x|\.[bB]a|\.[bB]b|\.[bB]d|\.[bB]e|\.[bB]f|\.[bB]g|\.[bB]h|\.[bB]i|\.[bB]j|\.[bB]m|\.[bB]n|\.[bB]o|\.[bB]r|\.[bB]s|\.[bB]t|\.[bB]v|\.[bB]w|\.[bB]y|\.[bB]z|\.[cC]a|\.[cC]c|\.[cC]d|\.[cC]f|\.[cC]g|\.[cC]h|\.[cC]i|\.[cC]k|\.[cC]l|\.[cC]m|\.[cC]n|\.[cC]o|\.[cC]r|\.[cC]s|\.[cC]u|\.[cC]v|\.[cC]x|\.[cC]y|\.[cC]z|\.[dD]e|\.[dD]j|\.[dD]k|\.[dD]m|\.[dD]o|\.[dD]z|\.[eE]c|\.[eE]e|\.[eE]g|\.[eE]h|\.[eE]r|\.[eE]s|\.[eE]t|\.[eE]u|\.[fF]i|\.[fF]j|\.[fF]k|\.[fF]m|\.[fF]o|\.[fF]r|\.[gG]a|\.[gG]b|\.[gG]d|\.[gG]e|\.[gG]f|\.[gG]g|\.[gG]h|\.[gG]i|\.[gG]l|\.[gG]m|\.[gG]n|\.[gG]p|\.[gG]q|\.[gG]r|\.[gG]s|\.[gG]t|\.[gG]u|\.[gG]w|\.[gG]y|\.[hH]k|\.[hH]m|\.[hH]n|\.[hH]r|\.[hH]t^[ml]?|\.[hH]u|\.[iI]d|\.[iI]e|\.[iI]l|\.[iI]m|\.[iI]n|\.[iI]o|\.[iI]q|\.[iI]r|\.[iI]s|\.[iI]t|\.[jJ]e|\.[jJ]m|\.[jJ]o|\.[jJ]p|\.[kK]e|\.[kK]g|\.[kK]h|\.[kK]i|\.[kK]m|\.[kK]n|\.[kK]p|\.[kK]r|\.[kK]w|\.[kK]y|\.[kK]z|\.[lL]a|\.[lL]b|\.[lL]c|\.[lL]i|\.[lL]k|\.[lL]r|\.[lL]s|\.[lL]t|\.[lL]u|\.[lL]v|\.[lL]y|\.[mM]a|\.[mM]c|\.[mM]d|\.[mM]g|\.[mM]h|\.[mM]k|\.[mM]l|\.[mM]m|\.[mM]n|\.[mM]o|\.[mM]p|\.[mM]q|\.[mM]r|\.[mM]s|\.[mM]t|\.[mM]u|\.[mM]v|\.[mM]w|\.[mM]x|\.[mM]y|\.[mM]z|\.[nN]a|\.[nN]c|\.[nN]e|\.[nN]f|\.[nN]g|\.[nN]i|\.[nN]l|\.[nN]o|\.[nN]p|\.[nN]r|\.[nN]u|\.[nN]z|\.[oO]m|\.[pP]a|\.[pP]e|\.[pP]f|\.[pP]g|\.[pP]h|\.[pP]k|\.[pP]l|\.[pP]m|\.[pP]n|\.[pP]r|\.[pP]s|\.[pP]t|\.[pP]w|\.[pP]y|\.[qP]a|\.[rR]e|\.[rR]o|\.[rR]u|\.[rR]w|\.[sS]a|\.[sS]b|\.[sS]c|\.[sS]d|\.[sS]e|\.[sS]g|\.[sS]h|\.[Ss]i|\.[sS]j|\.[sS]k|\.[sS]l|\.[sS]m|\.[sS]n|\.[sS]o|\.[sS]r|\.[sS]t|\.[sS]v[^c]|\.[sS]y|\.[sS]z|\.[tT]c|\.[tT]d|\.[tT]f|\.[tT]g|\.[tT]h|\.[tT]j|\.[tT]k|\.[tT]l|\.[tT]m|\.[tT]n|\.[tT]o|\.[tT]p|\.[tT]r|\.[tT]t|\.[tT]v|\.[tT]w|\.[tT]z|\.[uU]a|\.[uU]g|\.[uU]k|\.[uU]m|\.[uU]s|\.[uU]y|\.[uU]z|\.[vV]a|\.[vV]c|\.[vV]e|\.[vV]g|\.[vV]i|\.[vV]n|\.[vV]u|\.[wW]f|\.[wW]s|\.[yY]e|\.[yY]t|\.[yY]u|\.[zZ]a|\.[zZ]m|\.[zZ]w))/
+ },
-});
-define('ripple/platform/cordova/2.0.0/bridge/accelerometer', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- _success,
- _error,
- _current = {x: 0, y: 0, z: 0, timestamp: (new Date()).getTime()},
- _interval;
+ "CONFIG": {
+ "SUCCESS_CSS": {
+ "true": "ui-text-pass",
+ "false": "ui-text-fail",
+ "missing": "ui-text-missing"
+ }
+ },
-event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
- _current.x = accelerometerInfo.accelerationIncludingGravity.x;
- _current.y = accelerometerInfo.accelerationIncludingGravity.y;
- _current.z = accelerometerInfo.accelerationIncludingGravity.z;
- _current.timestamp = (new Date()).getTime();
-});
+ "SETTINGS": {
+ "TOOLTIPS_TOGGLE_DIV": "#settings-toggletooltips",
+ "TOOLTIPS_KEY": "tool-tips-key"
+ },
-module.exports = {
- start: function (success, error, args) {
- _success = success;
- _error = error;
- // Possible HACK? update the timestamp of the last data to something current
- _interval = window.setInterval(function () {
- _current.timestamp = (new Date()).getTime();
- _success(_current);
- }, 50);
+ "PANEL": {
+ "PANEL_CONFIG_ENABLE": "panel-config-enable"
},
- stop: function () {
- _success = null;
- _error = null;
- window.clearInterval(_interval);
- }
-};
+ "UI": {
+ "JQUERY_UI_BUTTON_CLASSES": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",
+ "JQUERY_UI_INPUT_CLASSES": "ui-state-default ui-corner-all",
+ "PANEL_TABLE_CLASS": "panel-table",
+ "RIGHT_RANGE_LABEL_CLASS": "range-label",
+ "LEFT_RANGE_LABEL_CLASS": "range-label-left",
+ "TEXT_LABEL_CLASS": "ui-text-label",
+ "SCREEN_PPI": 96
+ },
-});
-define('ripple/platform/cordova/2.0.0/bridge/app', function (require, exports, module) {
-/*
- * Copyright 2011 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 camera = require('ripple/ui/plugins/camera'),
- event = require('ripple/event');
+ "MULTIMEDIA": {
+ "AUDIO_STATES": {
+ "OPENED": "opened",
+ "STOPPED": "stopped",
+ "PAUSED": "paused",
+ "PLAYING": "playing",
+ "COMPLETED": "completed"
+ }
+ },
-module.exports = {
- show: function (success, error, args) {
- return success && success();
- }
-};
+ "LANG": {
+ "ISO6392_LIST": ["abk", "ace", "ach", "ada", "ady", "aar", "afh", "afr", "afa", "ain", "aka", "akk", "alb/sqi", "gsw", "ale", "alg", "tut", "amh", "anp", "apa", "ara", "arg", "arp", "arw", "arm/hye", "rup", "art", "asm", "ast", "ath", "aus", "map", "ava", "ave", "awa", "aym", "aze", "ban", "bat", "bal", "bam", "bai", "bad", "bnt", "bas", "bak", "baq/eus", "btk", "bej", "bel", "bem", "ben", "ber", "bho", "bih", "bik", "byn", "bin", "bis", "zbl", "nob", "bos", "bra", "bre", "bug", "bul", "bua", "bur/mya", "cad", "spa", "cat", "cau", "ceb", "cel", "cai", "khm", "chg", "cmc", "cha", "che", "chr", "nya", "chy", "chb", "chi/zho", "chn", "chp", "cho", "zha", "chu", "chk", "chv", "nwc", "syc", "rar", "cop", "cor", "cos", "cre", "mus", "crp", "cpe", "cpf", "cpp", "crh", "hrv", "cus", "cze/ces", "dak", "dan", "dar", "del", "div", "zza", "din", "doi", "dgr", "dra", "dua", "dut/nld", "dum", "dyu", "dzo", "frs", "efi", "egy", "eka", "elx", "eng", "enm", "ang", "myv", "epo", "est", "ewe", "ewo", "fan", "fat", "fao", "fij", "fil", "fin", "fiu", "fon", "fre/fra", "frm", "fro", "fur", "ful", "gaa", "gla", "car", "glg", "lug", "gay", "gba", "gez", "geo/kat", "ger/deu", "nds", "gmh", "goh", "gem", "kik", "gil", "gon", "gor", "got", "grb", "grc", "gre/ell", "kal", "grn", "guj", "gwi", "hai", "hat", "hau", "haw", "heb", "her", "hil", "him", "hin", "hmo", "hit", "hmn", "hun", "hup", "iba", "ice/isl", "ido", "ibo", "ijo", "ilo", "arc", "smn", "inc", "ine", "ind", "inh", "ina", "ile", "iku", "ipk", "ira", "gle", "mga", "sga", "iro", "ita", "jpn", "jav", "kac", "jrb", "jpr", "kbd", "kab", "xal", "kam", "kan", "kau", "pam", "kaa", "krc", "krl", "kar", "kas", "csb", "kaw", "kaz", "kha", "khi", "kho", "kmb", "kin", "kir", "tlh", "kom", "kon", "kok", "kor", "kos", "kpe", "kro", "kua", "kum", "kur", "kru", "kut", "lad", "lah", "lam", "day", "lao", "lat", "lav", "ltz", "lez", "lim", "lin", "lit", "jbo", "dsb", "loz", "lub", "lua", "lui", "smj", "lun", "luo", "lus", "mac/mkd", "mad", "mag", "mai", "mak", "mlg", "may/msa", "mal", "mlt", "mnc", "mdr", "man", "mni", "mno", "glv", "mao/mri", "arn", "mar", "chm", "mah", "mwr", "mas", "myn", "men", "mic", "min", "mwl", "moh", "mdf", "rum/ron", "mkh", "lol", "mon", "mos", "mul", "mun", "nqo", "nah", "nau", "nav", "nde", "nbl", "ndo", "nap", "new", "nep", "nia", "nic", "ssa", "niu", "zxx", "nog", "non", "nai", "frr", "sme", "nso", "nor", "nno", "nub", "iii", "nym", "nyn", "nyo", "nzi", "oci", "pro", "oji", "ori", "orm", "osa", "oss", "oto", "pal", "pau", "pli", "pag", "pan", "pap", "paa", "pus", "per/fas", "peo", "phi", "phn", "pon", "pol", "por", "pra", "que", "raj", "rap", "qaa-qtz", "roa", "roh", "rom", "run", "rus", "sal", "sam", "smi", "smo", "sad", "sag", "san", "sat", "srd", "sas", "sco", "sel", "sem", "srp", "srr", "shn", "sna", "scn", "sid", "sgn", "bla", "snd", "sin", "sit", "sio", "sms", "den", "sla", "slo/slk", "slv", "sog", "som", "son", "snk", "wen", "sot", "sai", "alt", "sma", "srn", "suk", "sux", "sun", "sus", "swa", "ssw", "swe", "syr", "tgl", "tah", "tai", "tgk", "tmh", "tam", "tat", "tel", "ter", "tet", "tha", "tib/bod", "tig", "tir", "tem", "tiv", "tli", "tpi", "tkl", "tog", "ton", "tsi", "tso", "tsn", "tum", "tup", "tur", "ota", "tuk", "tvl", "tyv", "twi", "udm", "uga", "uig", "ukr", "umb", "mis", "und", "hsb", "urd", "uzb", "vai", "ven", "vie", "vol", "vot", "wak", "wln", "war", "was", "wel/cym", "fry", "wal", "wol", "xho", "sah", "yao", "yap", "yid", "yor", "ypk", "znd", "zap", "zen", "zul", "zun"]
+ },
-});
-define('ripple/platform/cordova/2.0.0/bridge/camera', function (require, exports, module) {
-/*
- * Copyright 2011 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 camera = require('ripple/ui/plugins/camera'),
- event = require('ripple/event');
+ "XHR": {
+ "PROXY_DISABLED_BUTTON": "settings-xhrproxy-disabled"
+ },
-module.exports = {
- takePicture: function (success, error, args) {
- event.once("captured-image", function (uri, file) {
- success(uri);
- });
- camera.show();
+ "PLATFORMS": {
+ "WAC": {
+ "APPLICATIONS": [
+ "ALARM",
+ "BROWSER",
+ "CALCULATOR",
+ "CALENDAR",
+ "CAMERA",
+ "CONTACTS",
+ "FILES",
+ "GAMES",
+ "MAIL",
+ "MEDIAPLAYER",
+ "MESSAGING",
+ "PHONECALL",
+ "PICTURES",
+ "PROG_MANAGER",
+ "SETTINGS",
+ "TASKS",
+ "WIDGET_MANAGER"
+ ],
+ "DEVICE": {
+ "WIDGET_ENGINE_NAME": "Generic",
+ "WIDGET_ENGINE_PROVIDER": "tinyHippos",
+ "WIDGET_ENGINE_VERSION": "x.x"
+ }
+ }
},
- cleanup: function (success, error, args) {
- success();
+
+ "POWER_RESOURCE": {
+ "SCREEN": {
+ "NAME": "SCREEN",
+ "STATE": {
+ "SCREEN_OFF": {
+ "NAME": "SCREEN_OFF",
+ "MIN": 0,
+ "MAX": 0,
+ "VALUE": 0
+ },
+ "SCREEN_DIM": {
+ "NAME": "SCREEN_DIM",
+ "MIN": 0,
+ "MAX": 0.2,
+ "VALUE": 0.15
+ },
+ "SCREEN_NORMAL": {
+ "NAME": "SCREEN_NORMAL",
+ "MIN": 0.2,
+ "MAX": 1,
+ "VALUE": 0.8
+ },
+ "SCREEN_BRIGHT": {
+ "NAME": "SCREEN_BRIGHT",
+ "MIN": 1,
+ "MAX": 1,
+ "VALUE": 1
+ }
+ }
+ },
+ "CPU": {
+ "NAME": "CPU",
+ "STATE": {
+ "CPU_AWAKE": {
+ "NAME": "CPU_AWAKE",
+ "DEFAULT_VALUE" : 0.5
+ }
+ }
+ }
}
};
});
-define('ripple/platform/cordova/2.0.0/bridge/capture', function (require, exports, module) {
+define('ripple/ui/plugins/tooltip', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var camera = require('ripple/ui/plugins/camera'),
- event = require('ripple/event');
+var utils = require('ripple/utils'),
+ _options = {
+ track: true,
+ delay: 0,
+ showURL: false,
+ fade: 250,
+ extraClass: "ui-state-highlight ui-corner-all"
+ };
module.exports = {
- captureImage: function (success, error, args) {
- event.once("captured-image", function (uri, file) {
- file.fullPath = uri;
- success([file]);
- });
- camera.show();
- }
-};
+ create: function (element, message) {
+ var options = utils.copy(_options);
-});
-define('ripple/platform/cordova/2.0.0/bridge/compass', function (require, exports, module) {
-/*
- * Copyright 2011 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 geo = require('ripple/geo');
+ options.bodyHandler = function () {
+ return message;
+ };
-module.exports = {
- getHeading: function (success, error, args) {
- // TODO: build facility to trigger onError() from emulator
- // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
- success({
- magneticHeading: geo.getPositionInfo().heading,
- trueHeading: geo.getPositionInfo().heading,
- headingAccuracy: 100,
- timestamp: new Date().getSeconds()
- });
+ return jQuery(element).tooltip(options);
},
- stopHeading: function () {
- //do nothing
- }
-};
-
-});
-define('ripple/platform/cordova/2.0.0/bridge/console', function (require, exports, module) {
-/*
- * Copyright 2011 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.
- */
+ toggle: function () {
+ jQuery.tooltip.block();
+ return this.isOff();
+ },
-module.exports = {
- log: function (win, fail, args) {
- console.log(args[0]);
+ isOff: function () {
+ return jQuery.tooltip.blocked;
}
};
});
-define('ripple/platform/cordova/2.0.0/bridge/contacts', function (require, exports, module) {
+define('ripple/ui/plugins/call', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
+var event = require('ripple/event'),
utils = require('ripple/utils'),
- _self;
-
-function _default() {
- return [{
- "name": {formatted: "Brent Lintner"},
- "displayName": "Brent Lintner",
- "emails": [{type: "work", value: "brent@tinyhippos.com", pref: false}]
- }, {
- "name": {formatted: "PJ Lowe"},
- "displayName": "PJ Lowe",
- "emails": [{type: "work", value: "pj@tinyhippos.com", pref: false}]
- }, {
- "name": {formatted: "Dan Silivestru"},
- "displayName": "Dan Silivestru",
- "emails": [{type: "work", value: "dan@tinyhippos.com", pref: false}]
- }, {
- "name": {formatted: "Gord Tanner"},
- "displayName": "Gord Tanner",
- "emails": [{type: "work", value: "gord@tinyhippos.com", pref: true}]
- }, {
- "name": {formatted: "Mark McArdle"},
- "displayName": "Mark McArdle",
- "emails": [{type: "work", value: "mark@tinyhippos.com", pref: false}]
- }].map(function (obj) {
- obj.id = Math.uuid(undefined, 16);
- return navigator.contacts.create(obj);
- });
-}
+ db = require('ripple/db'),
+ _exception = {
+ "unknown": "Unknown",
+ "network": "Network",
+ "unreachable": "Unreachable",
+ "no-answer": "No Answer",
+ "bad-number": "Bad Number",
+ "number-not-in-use": "Number Not In Use",
+ "media": "Media",
+ "no-sim": "No Sim Card",
+ "account-down": "Account Down",
+ "credit-down": "Credit Down",
+ "barred": "Barred",
+ "network-busy": "Network Busy",
+ "network-down": "Network Down"
+ },
+ _status = {
+ IDLE: 0,
+ DIALED: 1,
+ PLACED: 2,
+ INPROGRESS: 3,
+ },
+ _statusInfo = [
+ "Waiting...;Waiting", // IDLE
+ "Calling... ;Incomming call from simulator", // DIALED
+ "Incomming call from ;Calling simulator", // PLACED
+ "In conversation with ;In conversation with simulator" // INPROGRESS
+ ],
+ _data = {
+ status: _status.IDLE,
+ isInException: false,
+ isAutoAccept: false,
+ autoAcceptTimerId: null,
+ conversationStartTime: null
+ },
+ _contactMap = {
+ "861012345678": "Guest"
+ },
+ _CONTACT_KEY = "tizen1-contact",
+ _RECORDING_KEY = "tizen1-call-recording",
+ _RECORDING_PATH = "music/",
+ _record = {},
+ _conversationSeconds = 0,
+ _conversationTimer,
+ _callingEffectTimer;
-function _get() {
- return db.retrieveObject("cordova-contacts") || _default();
-}
+function _initContacts() {
+ var data = db.retrieveObject(_CONTACT_KEY),
+ contactsSelect = document.getElementById("call-local-phone-number"),
+ displayName = null, number = null, index = 0, i;
+
+ contactsSelect.innerHTML = "";
-function _save(contacts) {
- db.saveObject("cordova-contacts", contacts);
-}
+ utils.forEach(data, function (addrBook) {
+ utils.forEach(addrBook._contacts, function (contact) {
+ if (contact.name && contact.name && contact.phoneNumbers &&
+ contact.phoneNumbers.length > 0) {
+ displayName = contact.name.firstName + ' ' + contact.name.lastName;
+ number = contact.phoneNumbers[0].number;
+ _contactMap[number] = displayName;
-function _filtered(compare, options) {
- // this could be done a lot better..
- var found = false;
- if (!options.filter || options.filter === "") {
- found = true;
- } else if (typeof compare === "string" &&
- compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
- found = true;
- } else if (typeof compare === "object" || compare instanceof Array) {
- utils.forEach(compare, function (value) {
- if (!found) {
- found = _filtered(value, options);
+ contactsSelect.appendChild(utils.createElement("option", {
+ "innerText": displayName + ':' + number,
+ "value": index
+ }));
+ index++;
}
});
+ });
+
+ if (displayName === null && number === null) {
+ for (i in _contactMap) {
+ displayName = _contactMap[i];
+ number = i;
+ contactsSelect.appendChild(utils.createElement("option", {
+ "innerText": displayName + ':' + number,
+ "value": index
+ }));
+ }
}
- return found;
}
-_self = {
- search: function (success, error, args) {
- var fields = args[0],
- options = args[1],
- foundContacts = [],
- tempContact = navigator.contacts.create(),
- contacts = _get();
-
- options = options || {};
+function _initEventWatchers() {
+ event.on("DialerLaunched", function (remoteParty) {
+ var localContact = document.getElementById("call-local-phone-number");
- // handle special case of ["*"] to return all fields
- if (fields.length === 1 && fields[0] === "*") {
- fields = utils.map(tempContact, function (v, k) {
- return k;
- });
+ if (_data.status !== _status.IDLE) {
+ return;
}
- if (fields.length > 0) {
- contacts.forEach(function (contact, index) {
- var newContact = navigator.contacts.create(contact);
+ localContact.appendChild(utils.createElement("option", {
+ "innerText": remoteParty.displayName,
+ "value": remoteParty.remoteParty,
+ "selected": "selected"
+ }));
+ _localCall();
+ });
+}
- if (options && (!_filtered(contact, options))) {
- return;
- }
+function _initExceptionTypes() {
+ utils.forEach(_exception, function (value, key) {
+ document.getElementById("call-exception-type").appendChild(utils.createElement("option", {
+ "innerText": value,
+ "value": key
+ }));
+ });
+}
- utils.forEach(newContact, function (value, prop) {
- if (typeof newContact[prop] !== "function" && prop !== "id" &&
- !fields.some(function (field) {
- return field === prop;
- })) {
- delete newContact[prop];
- }
- });
+function _initRecord() {
+ var localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
+ localPartStringList = localPartString.split(":"),
+ displayName;
- foundContacts.push(newContact);
- });
- }
+ if (localPartStringList.length > 1) {
+ displayName = localPartStringList[0];
+ }
+ else {
+ displayName = localPartString;
+ }
- // TODO: don't loop over entire db just to slice the array
- if (options.multiple === false) {
- foundContacts = foundContacts.splice(0, 1);
- }
- success(foundContacts);
- },
+ _record = {};
+ _record.serviceId = (new Date()).getTime() || 0;
+ _record.callParticipants = [{
+ id: localPartString + ':' + displayName,
+ displayName: displayName,
+ contactRef: null
+ }];
+ _record.forwardedFrom = null;
+ _record.startTime = new Date();
+ _record.recording = [];
+}
- save: function (success, error, args) {
- var contacts = _get(),
- contact = args[0],
- index;
- if (!contact.id) {
- contact.id = Math.uuid(undefined, 16);
- contacts.push(contact);
- } else {
- index = contacts.reduce(function (result, value, index) {
- return value.id === contact.id ? index : result;
- }, -1);
+function updateConvTime() {
+ var timeObj = new Date(1970, 0, 1),
+ timeString;
- if (index >= 0) {
- utils.mixin(contact, contacts[index]);
- contact = contacts[index];
- } else {
- contact = null;
- }
- }
+ timeObj.setSeconds(_conversationSeconds);
+ timeString = timeObj.toTimeString().substr(0, 8);
+ jQuery("#ConvTimeString").text(timeString);
+ jQuery("#ConvTimeString2").text(timeString);
+ _conversationSeconds = _conversationSeconds + 1;
+}
- _save(contacts);
- if (success) {
- success(contact);
- }
- },
- remove: function (success, error, args) {
- var contacts = _get(),
- id = args[0],
- toDelete = contacts.reduce(function (result, current, index) {
- return current.id === id ? index : result;
- }, -1);
+function CallingEffect() {
+ var color = jQuery("#callingString").css('color');
+ if (color === "rgb(255, 255, 255)") {
+ jQuery("#callingString").css('color', "black");
+ jQuery("#callingString2").css('color', "black");
+ }
+ else {
+ jQuery("#callingString").css('color', "white");
+ jQuery("#callingString2").css('color', "white");
+ }
+}
- if (toDelete >= 0) {
- contacts.splice(toDelete, 1);
- _save(contacts);
- if (success) {
- success();
- }
- } else {
- error({code: 3, message: "could not find contact with id (" + id + ")"}); // PENDING_OPERATION_ERROR
- }
+
+function _transferStatus() {
+ var statusStringList = _statusInfo[_data.status].split(";"),
+ localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
+ localPartStringList = localPartString.split(":"),
+ localNumber = localPartStringList[0],
+ localName = _contactMap[localNumber] || localNumber;
+ jQuery("#status-text").show();
+ jQuery("#remote-status-text").show();
+ jQuery("#call-status").show();
+ jQuery("#remote-call-status").show();
+ jQuery("#remotePartyName").html(localName);
+ jQuery("#call-local-call").show();
+ window.clearInterval(_callingEffectTimer);
+
+ switch (_data.status) {
+ case _status.DIALED: // local call
+ jQuery("#call-remote-text").html("Accept");
+ jQuery("#end-remote-text").html("Reject");
+ jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
+ "<span id='callingString' style='font-size: 14px;'> " + statusStringList[0] +
+ "</span><br><br><br><button id='call-local-end-d' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
+ jQuery("#call-local-end-d").bind("click", _localEnd);
+ jQuery("#remote-call-status").html("<span style='font-size: 20px;'>Simulator Bot</span><br>" +
+ "<span id='callingString2' style='font-size: 12px;'> Incoming call...</span>" +
+ "<br><br><br><button id='call-remote-decline-d' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button> " +
+ "<button id='call-remote-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px; background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
+ jQuery("#call-remote-answer-d").bind("click", _remoteCall);
+ jQuery("#call-remote-decline-d").bind("click", _remoteEnd);
+ _callingEffectTimer = window.setInterval(CallingEffect, 800);
+ break;
+ case _status.PLACED: // Remote Call
+ jQuery("#call-local-text").html("Accept");
+ jQuery("#end-local-text").html("Reject");
+ jQuery("#call-status").html(statusStringList[0] + localName);
+ jQuery("#remote-call-status").html(statusStringList[1]);
+ jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Bot</span><br>" +
+ "<span id='callingString' style='font-size: 14px;'> Calling..." +
+ "</span><br><br><br><button id='call-remote-end-d' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
+ jQuery("#call-remote-end-d").bind("click", _remoteEnd);
+ jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
+ "<span id='callingString2' style='font-size: 14px;'> Incoming call...</span>" +
+ "<br><br><br><button id='call-local-decline-d' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button> " +
+ "<button id='call-local-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px;" +
+ " background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
+ jQuery("#call-local-answer-d").bind("click", _localCall);
+ jQuery("#call-local-decline-d").bind("click", _localEnd);
+ _callingEffectTimer = window.setInterval(CallingEffect, 800);
+ break;
+ case _status.INPROGRESS:
+ jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
+ "<span id='ConvTimeString' style='font-size: 14px;'>" + "00:00:00" +
+ "</span><br><br><br><button id='call-local-end-d-c' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
+ jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Robot</span><br>" +
+ "<span id='ConvTimeString2' style='font-size: 14px;'>" + "00:00:00" +
+ "</span><br><br><br><button id='call-remote-end-d-c' class='ui-corner-all' style='padding:2px;" +
+ " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
+ jQuery("#call-local-end-d-c").bind("click", _localEnd);
+ jQuery("#call-remote-end-d-c").bind("click", _remoteEnd);
+ _conversationTimer = window.setInterval(updateConvTime, 1000);
+ jQuery("#call-remote-text").html("Call");
+ jQuery("#end-remote-text").html("End");
+ jQuery("#call-local-text").html("Call");
+ jQuery("#end-local-text").html("End");
+ break;
+ default:
+ jQuery("#call-status").html(statusStringList[0]);
+ jQuery("#call-status").html("default");
+ jQuery("#remote-call-status").html(statusStringList[1]);
+ jQuery("#remote-call-status").html("default");
+ jQuery("#call-remote-text").html("Call");
+ jQuery("#end-remote-text").html("End");
+ jQuery("#call-local-text").html("Call");
+ jQuery("#end-local-text").html("End");
+ return;
}
-};
+}
-module.exports = _self;
+function _startCall() {
+ _data.conversationStartTime = new Date();
+ event.trigger("CallInProgress", [true]);
+ _data.status = _status.INPROGRESS;
+ //_transferStatus();
+}
-});
-define('ripple/platform/cordova/2.0.0/bridge/device', function (require, exports, module) {
-/*
- * Copyright 2011 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 devices = require('ripple/devices');
+function _endCall(callEndReason) {
+ if (_data.autoAcceptTimerId) {
+ var path = _RECORDING_PATH + _record.serviceId + ".mp3";
-module.exports = {
- getDeviceInfo: function (success, fail, args) {
- var device = devices.getCurrentDevice();
+ _record.recording.push(path);
+ db.saveObject(_RECORDING_KEY, path);
- success({
- available: true,
- platform: device.osName,
- version: device.osVersion,
- name: device.name,
- uuid: device.uuid,
- cordova: "2.0.0"
- });
+ clearTimeout(_data.autoAcceptTimerId);
+ _data.autoAcceptTimerId = null;
}
-};
-});
-define('ripple/platform/cordova/2.0.0/bridge/file', function (require, exports, module) {
-// HACK: fs keeps a reference to the last-used FileSystem requested via requestFileSystem
-// this is a hack because if you keep switching between TEMPORARY vs. PERSISTENT file systems requested,
-// and run Cordova File API methods, no parameter is passed into exec specifying the underlying File System.
-// This should be fixed in Cordova!
-var fs,
- topCordova = require('ripple/platform/cordova/2.0.0/spec'),
- rlfsu;
+ _record.duration = _data.conversationStartTime ? ((new Date()) - _data.conversationStartTime) : 0;
+ _data.conversationStartTime = null;
+
+ _record.endReason = callEndReason;
-function cleanPath(path) {
- while (path[0] && path[0] === '/') {
- path = path.substr(1);
+ if (_data.status === _status.PLACED) {
+ _record.direction = "missed-new";
}
- return path;
-}
-module.exports = {
- requestFileSystem: function (win, fail, args) {
- // HACK: may not be webkit
- var rfs = window.webkitRequestFileSystem,
- type = args[0],
- size = args[1];
-
- // HACK: assume any FS requested over a gig in size will throw an error
- if (size > (1024 * 1024 * 1024 /* gigabyte */)) {
- if (fail) fail(FileError.QUOTA_EXCEEDED_ERR);
- } else {
- return rfs(type, size, function (effes) {
- fs = effes;
- win(effes);
- }, fail);
- }
- },
- resolveLocalFileSystemURI: function (win, fail, args) {
- var uri = args[0],
- fulluri = fs.root.toURL();
+ event.trigger("CallRecorded", [_record]);
+ event.trigger("CallInProgress", [false]);
- // HACK: iOS-specific bs right here. See lib/ios/plugin/ios/Entry.js in cordova.js for details
- // Cordova badly needs a unified File System abstraction.
- if (uri.indexOf("file://localhost") === 0) {
- uri = uri.substr(16);
- }
- uri = cleanPath(uri);
+ _data.status = _status.IDLE;
+ _transferStatus();
+ _record = {};
- fulluri += uri;
+ _conversationSeconds = 0;
+ window.clearInterval(_conversationTimer);
+ jQuery("#call-status").hide();
+ jQuery("#remote-call-status").hide();
- return window.webkitResolveLocalFileSystemURL(fulluri, function (entry) {
- if (win) win(entry);
- }, function (error) {
- if (fail) fail(error.code);
- });
- },
- getFile: function (win, fail, args) {
- var path = args[0],
- filename = args[1],
- options = args[2],
- file = '';
+ jQuery("#status-text").hide();
+ jQuery("#remote-status-text").hide();
+}
- path = cleanPath(path);
- filename = cleanPath(filename);
+function _localCall() {
+ if (_data.isInException) {
+ return;
+ }
- if (path) {
- file = path + '/';
+ switch (_data.status) {
+ case _status.IDLE: //local call
+ _data.status = _status.DIALED;
+ _initRecord();
+ _record.direction = "dialed";
+ break;
+ case _status.PLACED:
+ _data.status = _status.INPROGRESS;
+ _record.direction = "received";
+ if (_data.autoAcceptTimerId) {
+ clearTimeout(_data.autoAcceptTimerId);
+ _data.autoAcceptTimerId = null;
}
- file += filename;
+ _startCall();
+ break;
+ default:
+ return;
+ }
- fs.root.getFile(file, options, function (entry) {
- if (win) win(entry);
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- remove: function (win, fail, args) {
- var file = args[0];
- window.webkitResolveLocalFileSystemURL(fs.root.toURL() + file, function (entry) {
- entry.remove(function () {
- if (win) win();
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, fail);
- },
- readEntries: function (win, fail, args) {
- var root = fs.root.toURL(),
- path = args[0],
- reader;
+ _transferStatus();
- path = cleanPath(path);
- path = root + path;
+ if (_data.isInException) {
+ _endCall(document.getElementById("call-exception-type").value);
+ }
+}
- window.webkitResolveLocalFileSystemURL(path, function (entry) {
- reader = entry.createReader();
- reader.readEntries(function (entries) {
- if (win) win(entries);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- getDirectory: function (win, fail, args) {
- var path = args[0],
- filename = args[1],
- options = args[2],
- file = '';
+function _localEnd() {
+ switch (_data.status) {
+ case _status.DIALED: // Local Cancel
+ case _status.INPROGRESS: // Local End
+ _endCall("local");
+ break;
+ case _status.PLACED:
+ _record.direction = "missed-new";
+ _endCall("local");
+ break;
+ default:
+ return;
+ }
+}
- path = cleanPath(path);
- filename = cleanPath(filename);
+function _remoteCall() {
+ if (_data.isInException) {
+ return;
+ }
- if (path) {
- file = path + '/';
+ switch (_data.status) {
+ case _status.IDLE: // Remote Call
+ _data.status = _status.PLACED;
+ _initRecord();
+ if (_data.isAutoAccept) {
+ _data.autoAcceptTimerId = setTimeout(_localCall, 2000);
}
- file += filename;
-
- fs.root.getDirectory(file, options, function (entry) {
- if (win) win(entry);
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- removeRecursively: function (win, fail, args) {
- var root = fs.root.toURL(),
- path = args[0];
-
- path = cleanPath(path);
-
- window.webkitResolveLocalFileSystemURL(root + path, function (dirEntry) {
- dirEntry.removeRecursively(function () {
- if (win) win();
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- getFileMetadata: function (win, fail, args) {
- var path = args[0],
- root = fs.root.toURL();
-
- path = cleanPath(path);
-
- window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
- entry.file(function (file) {
- if (win) win(file);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- getMetadata: function (win, fail, args) {
- var path = args[0],
- root = fs.root.toURL();
-
- path = cleanPath(path);
-
- window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
- entry.getMetadata(function (data) {
- if (win) win(data);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- getParent: function (win, fail, args) {
- var path = args[0],
- root = fs.root.toURL();
-
- path = cleanPath(path);
-
- window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
- entry.getParent(function (dirEntry) {
- if (win) win(dirEntry);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- copyTo: function (win, fail, args) {
- var src = args[0],
- parent = args[1],
- name = args[2],
- root = fs.root.toURL();
-
- parent = cleanPath(parent);
- src = cleanPath(src);
-
- rlfsu = window.webkitResolveLocalFileSystemURL;
- // get the directoryentry that we will copy TO
- rlfsu(root + parent, function (parentDirToCopyTo) {
- rlfsu(root + src, function (sourceDir) {
- sourceDir.copyTo(parentDirToCopyTo, name, function (newEntry) {
- if (win) win(newEntry);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- moveTo: function (win, fail, args) {
- var src = args[0],
- parent = args[1],
- name = args[2],
- root = fs.root.toURL();
-
- parent = cleanPath(parent);
- src = cleanPath(src);
-
- rlfsu = window.webkitResolveLocalFileSystemURL;
- // get the directoryentry that we will move TO
- rlfsu(root + parent, function (parentDirToMoveTo) {
- rlfsu(root + src, function (sourceDir) {
- sourceDir.moveTo(parentDirToMoveTo, name, function (newEntry) {
- if (win) win(newEntry);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- write: function (win, fail, args) {
- var file = args[0],
- text = args[1],
- position = args[2],
- sourcepath,
- BB = window.BlobBuilder || window.WebKitBlobBuilder,
- bb = new BB();
-
- // Format source path
- sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
- sourcepath = cleanPath(sourcepath);
-
- // Create a blob for the text to be written
- bb.append(text);
-
- // Get the FileEntry, create if necessary
- fs.root.getFile(sourcepath, {create: true}, function (entry) {
- // Create a FileWriter for this entry
- entry.createWriter(function (writer) {
- writer.onwriteend = function (progressEvt) {
- if (win) win(progressEvt.total);
- };
- writer.onerror = function (err) {
- if (fail) fail(err.code);
- };
-
- if (position && position > 0) {
- writer.seek(position);
- }
- writer.write(bb.getBlob('text/plain'));
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- readAsText: function (win, fail, args) {
- var path = args[0],
- encoding = args[1],
- FileReader = topCordova.nativeMethods.FileReader,
- fr = new window.FileReader();
-
- // Set up FileReader events
- fr.onerror = function (err) {
- if (fail) fail(err.code);
- };
- fr.onload = function (evt) {
- if (win) win(evt.target.result);
- };
-
- path = cleanPath(path);
-
- fs.root.getFile(path, {create: false}, function (entry) {
- entry.file(function (blob) {
- fr.readAsText(blob, encoding);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- readAsDataURL: function (win, fail, args) {
- var path = args[0],
- FileReader = topCordova.nativeMethods.FileReader,
- fr = new window.FileReader();
-
- // Set up FileReader events
- fr.onerror = function (err) {
- if (fail) fail(err.code);
- };
- fr.onload = function (evt) {
- if (win) win(evt.target.result);
- };
-
- path = cleanPath(path);
-
- fs.root.getFile(path, {create: false}, function (entry) {
- entry.file(function (blob) {
- fr.readAsDataURL(blob);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
- },
- truncate: function (win, fail, args) {
- var file = args[0],
- position = args[1],
- sourcepath;
-
- // Format source path
- sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
- sourcepath = cleanPath(sourcepath);
+ break;
+ case _status.DIALED: // Remote Answer
+ _startCall();
+ break;
+ default:
+ return;
+ }
- // Get the FileEntry, create if necessary
- fs.root.getFile(sourcepath, {create: false}, function (entry) {
- // Create a FileWriter for this entry
- entry.createWriter(function (writer) {
- writer.onwriteend = function (progressEvt) {
- if (win) win(progressEvt.target.length);
- };
- writer.onerror = function (err) {
- if (fail) fail(err.code);
- };
+ _transferStatus();
- writer.truncate(position);
- }, function (err) {
- if (fail) fail(err.code);
- });
- }, function (err) {
- if (fail) fail(err.code);
- });
+ if (_data.isInException) {
+ _endCall(document.getElementById("call-exception-type").value);
}
-};
+}
-});
-define('ripple/platform/cordova/2.0.0/bridge/geolocation', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- geo = require('ripple/geo'),
- utils = require('ripple/utils'),
- PositionError = require('ripple/platform/w3c/1.0/PositionError'),
- _watches = {},
- _current = {
- "latitude": 43.465187,
- "longitude": -80.522372,
- "altitude": 100,
- "accuracy": 150,
- "altitudeAccuracy": 80,
- "heading": 0,
- "velocity": 0,
- },
- _error;
+function _remoteEnd() {
+ switch (_data.status) {
+ case _status.DIALED: // Remote Reject
+ _endCall("rejected");
+ break;
+ case _status.INPROGRESS: // Remote End
+ _endCall("remote");
+ break;
+ case _status.PLACED: // Remote Cancel
+ _record.direction = "missed-new";
+ _endCall("remote");
+ break;
+ default:
+ return;
+ }
+}
-function _getCurrentPosition(win, fail) {
- if (geo.timeout) {
- if (fail) {
- var positionError = new PositionError();
+function _leaveMessage() {
+ if (!this.checked && _data.autoAcceptTimerId) {
+ clearTimeout(_data.autoAcceptTimerId);
+ _data.autoAcceptTimerId = null;
+ }
+ _data.isAutoAccept = this.checked;
+}
- positionError.code = PositionError.TIMEOUT;
- positionError.message = "postion timed out";
- fail(positionError);
+function _exceptionStatus() {
+ _data.isInException = this.checked;
+ if (_data.isInException && (_data.status !== _status.IDLE)) {
+ if (_data.status === _status.RECEIVED) { // Remote Cancel
+ _record.direction = "missed-new";
+ _record.duration = 0;
}
- }
- else {
- win(geo.getPositionInfo());
+ _endCall(document.getElementById("call-exception-type").value);
}
}
-event.on("PositionInfoUpdatedEvent", function (pi) {
- _current.latitude = pi.latitude;
- _current.longitude = pi.longitude;
- _current.altitude = pi.altitude;
- _current.accuracy = pi.accuracy;
- _current.altitudeAccuracy = pi.altitudeAccuracy;
- _current.heading = pi.heading;
- _current.velocity = pi.speed;
- utils.forEach(_watches, function (watch) {
- try {
- _getCurrentPosition(watch.win, watch.fail);
- } catch (e) {
- console.log(e);
- }
- });
-});
+function _updateRemotePartyName() {
+ jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
+}
-module.exports = {
- getLocation: function (success, error, args) {
- _getCurrentPosition(success, error);
- },
- addWatch: function (success, error, args) {
- _watches[args[0]] = {
- win: success,
- fail: error
- };
- _getCurrentPosition(success, error);
+module.exports = {
+ panel: {
+ domId: "call-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Call",
+ display: true
},
+ initialize: function () {
+ jQuery("#call-local-call").bind("click", _localCall);
+ jQuery("#call-local-end").bind("click", _localEnd);
+ jQuery("#call-remote-call").bind("click", _remoteCall);
+ jQuery("#call-remote-end").bind("click", _remoteEnd);
+ jQuery("#recording-status").bind("click", _leaveMessage);
+ jQuery("#call-exception-status").bind("click", _exceptionStatus);
+ jQuery("#call-exception-type").bind("click", null);
- clearWatch: function (id) {
- delete _watches[id];
+ _initEventWatchers();
+ _initContacts();
+ jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
+ jQuery("#call-local-phone-number").bind("change", _updateRemotePartyName);
+ _initExceptionTypes();
}
};
});
-define('ripple/platform/cordova/2.0.0/bridge/media', function (require, exports, module) {
+define('ripple/ui/plugins/omnibar', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var audioObjects = {},
- noop = function () {};
-
-function createAudio(id, src, error) {
- var a = new Audio();
- a.addEventListener("error", function (e) {
- error(new window.MediaError(1, e.toString()));
- });
- a.addEventListener("durationchange", function () {
- //HACK: I don't like this but best way for us to update the duration
- cordova.require("cordova/plugin/Media").onStatus(id, 2, this.duration);
- });
- a.src = src;
+var emulatorBridge = require('ripple/emulatorBridge'),
+ platform = require('ripple/platform'),
+ db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ devices = require('ripple/devices'),
+ constants = require('ripple/constants'),
+ _event = require('ripple/event'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ histories = [];
- return a;
+function _omnibar() {
+ return document.querySelector(".omni-bar input");
}
-module.exports = {
- create: function (success, error, args) {
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+function _persist(url) {
+ db.save("current-url", url);
+}
- var id = args[0],
- src = args[1];
+function _persistRoot(url) {
+ db.save("root-url", url);
+}
- error = error || noop;
- success = success || noop;
+function _currentURL() {
+ return db.retrieve("current-url") || "about:blank";
+}
- audioObjects[id] = createAudio(id, src, error);
- success();
- },
- startPlayingAudio: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+function _rootURL() {
+ return db.retrieve("root-url") || "about:blank";
+}
- var id = args[0],
- audio = audioObjects[id];
+function _reload() {
+ _event.trigger("ApplicationLoad", null);
+ emulatorBridge.window().location.reload();
+}
- if (args.length === 1) {
- error("Media source argument not found");
- return;
+function _loadApplication() {
+ var omnibar = _omnibar(),
+ xhr;
+ if (omnibar.value.trim() !== "") {
+ if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
+ xhr = new XMLHttpRequest();
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.responseText !== '') {
+ _persist(omnibar.value);
+ _persistRoot(omnibar.value);
+ emulatorBridge.window().location.assign(omnibar.value);
+ } else {
+ alert("File doesn't exist!");
+ return;
+ }
+ }
+ };
+ xhr.open('GET', omnibar.value, true);
+ xhr.send(null);
+ } else {
+ omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
+ _persist(omnibar.value);
+ _persistRoot(omnibar.value);
+ emulatorBridge.window().location.assign(omnibar.value);
}
+ _addHistory(omnibar.value);
+ }
+ _event.trigger("ApplicationLoad", null);
+}
- if (audio) {
- audio.pause();
- audioObjects[id] = undefined;
- }
+function _hideHistory() {
+ $("#app-launching-history").hide("slide", {direction: "up"}, "fast");
+ $("#overlayBackground-transparent").hide();
+}
- audio = audioObjects[id] = createAudio(id, args[1], error);
- audio.play();
+function _makeHistoryItems() {
+ histories = db.retrieveObject(constants.LAUNCHING_HISTORY);
+ if (histories === undefined) {
+ histories = [];
+ }
+ $("#app-launching-history").empty();
+ histories.reverse();
+ histories.forEach(function (item) {
+ $("#app-launching-history").append('<div class="app-launching-history-item">' + item + '</div>');
+ });
- success();
- },
- stopPlayingAudio: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+ if (histories.length === 0) {
+ $("#app-launching-history").append('<div class="app-launching-history-item-empty">History empty</div>');
+ }
- var id = args[0],
- audio = audioObjects[id];
+ $(".app-launching-history-item").unbind('click');
+ $(".app-launching-history-item").bind("click", function () {
+ $(".omni-bar input").val(histories[$(this).index()]);
+ _loadApplication();
+ _hideHistory();
+ });
+}
- if (!audio) {
- error("Audio Object has not been initialized");
- return;
- }
- audio.pause();
- audioObjects[id] = undefined;
+function _showHistory() {
+ _makeHistoryItems();
+ $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
+ $("#app-launching-history").show("slide", {direction: "up"}, "fast");
+ $(window).bind('resize', function () {
+ $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
+ $("#overlayBackground-transparent").css("width", $(window).width());
+ $("#overlayBackground-transparent").css("height", $(window).height());
+ });
- success();
- },
- seekToAudio: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+ $("#history-background-overlay").show();
+ $("#overlayBackground-transparent").css("width", $(window).width());
+ $("#overlayBackground-transparent").css("height", $(window).height());
+ $("#overlayBackground-transparent").show();
+ $("#overlayBackground-transparent").unbind('click');
+ $("#overlayBackground-transparent").bind("click", function () {
+ _hideHistory();
+ });
+}
- var id = args[0],
- audio = audioObjects[id];
- if (!audio) {
- error("Audio Object has not been initialized");
- return;
- } else if (args.length === 1) {
- error("Media seek time argument not found");
- return;
- } else {
- try {
- audio.currentTime = args[1];
- } catch (e) {
- error("Error seeking audio: " + e);
+function _addHistory(uri) {
+ var i = 0, thehistories = db.retrieveObject(constants.LAUNCHING_HISTORY);
+ if (thehistories !== undefined) {
+ for (i; i < thehistories.length; i++) {
+ if (uri === thehistories[i]) {
+ return;
}
}
-
- success();
- },
- pausePlayingAudio: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
+ if (thehistories.length >= 20) {
+ thehistories.reverse();
+ thehistories.pop();
+ thehistories.reverse();
}
+ } else {
+ thehistories = [];
+ }
+ thehistories.push(uri);
+ db.saveObject(constants.LAUNCHING_HISTORY, thehistories);
+}
- var id = args[0],
- audio = audioObjects[id];
+_event.on("FrameHistoryChange", function (url) {
+ _omnibar().value = url;
+ _persist(url);
+ _persistRoot(url);
+});
- if (!audio) {
- error("Audio Object has not been initialized");
- return;
- }
+module.exports = {
+ initialize: function () {
+ var omnibar = _omnibar(), loc, tmp,
+ url, filename, matching, deviceId,
+ xhr, uriParams, platformName, platformVersion, newUrl;
- audio.pause();
- success();
- },
- getCurrentPositionAudio: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+ jQuery(".logo, .beta, .left, .right, .left-panel-collapse, .right-panel-collapse").css({
+ "marginTop": "35px"
+ });
- var id = args[0],
- audio = audioObjects[id];
+ jQuery("#settings-xhr-proxy").parent().parent().hide();
- if (!audio) {
- error("Audio Object has not been initialized");
- return;
- }
+ $(".omni-bar").show();
- success(audio.currentTime);
- },
- getDuration: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
+ uriParams = utils.getURIParams(document.documentURI);
+ if (uriParams.url !== undefined) {
+ url = uriParams.url;
+ if (url.match(/^\.[\.]?/) !== null) {
+ loc = document.location;
+ filename = loc.pathname.replace(/^.*[\\\/]/, '');
+ matching = new RegExp(filename, "g");
+ tmp = loc.protocol + "//" + loc.hostname + loc.pathname.replace(matching, "") + url;
+ url = tmp;
+ }
+ _persist(url);
+ _persistRoot(url);
+ require('ripple/widgetConfig').initialize();
+ require('ripple/ui/plugins/widgetConfig').initialize();
}
- var id = args[0],
- audio = audioObjects[id];
+ omnibar.value = _currentURL();
- if (!audio) {
- error("Audio Object has not been initialized");
- return;
- }
+ omnibar.addEventListener("keydown", function (event) {
+ if (event.keyCode === '13' || event.keyCode === 13 || event.keyCode === '0' || event.keyCode === 0) { // enter or return
+ if (omnibar.value.trim() !== "") {
+ if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
+ xhr = new XMLHttpRequest();
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.responseText !== '') {
+ _persist(omnibar.value);
+ _persistRoot(omnibar.value);
+ emulatorBridge.window().location.assign(omnibar.value);
+ } else {
+ alert("File doesn't exist!");
+ return;
+ }
+ }
+ };
+ xhr.open('GET', omnibar.value, true);
+ xhr.send(null);
+ } else {
+ //default the protocal if not provided
+ omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
+ _persist(omnibar.value);
+ _persistRoot(omnibar.value);
+ emulatorBridge.window().location.assign(omnibar.value);
+ }
+ _event.trigger("ApplicationLoad", null);
+ _addHistory(omnibar.value);
+ }
+ }
+ });
- success(audio.duration);
- },
- startRecordingAudio: function (success, error, args) {
- error = error || noop;
- error("Not supported");
- },
- stopRecordingAudio: function (success, error, args) {
- error = error || noop;
- error("Not supported");
- },
- release: function (success, error, args) {
- error = error || noop;
- success = success || noop;
- if (!args.length) {
- error("Media Object id was not sent in arguments");
- return;
- }
+ window.addEventListener("keydown", function (event) {
+ var hasMetaOrAltPressed = (event.metaKey || event.ctrlKey),
+ key = parseInt(event.keyCode, 10);
- var id = args[0],
- audio = audioObjects[id];
+ if (key === 82 && hasMetaOrAltPressed) { // cmd/ctrl + r
+ event.preventDefault();
+ _reload();
+ }
- if (audio) {
- audioObjects[id] = undefined;
- audio.src = undefined;
- //delete audio;
- }
+ if (key === 116) { // F5
+ event.preventDefault();
+ _reload();
+ }
+ });
- success();
+ document.getElementById("history-reload").addEventListener("click", _reload);
+ $("#options-button-history").bind("click", function () {
+ _showHistory();
+ });
+ tooltip.create("#history-reload", "Reload Application");
+ tooltip.create("#options-button-history", "History");
+ tooltip.create("#options-button-config-window", "Configuration");
+ tooltip.create("#options-button-panels", "Panel Settings");
+ tooltip.create("#options-button-about", "About");
+ },
+ currentURL: function () {
+ return _currentURL();
+ },
+ rootURL: function () {
+ return _rootURL();
}
};
});
-define('ripple/platform/cordova/2.0.0/bridge/network', function (require, exports, module) {
+define('ripple/ui/plugins/fileSystem', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var deviceSettings = require('ripple/deviceSettings'),
- event = require('ripple/event'),
- _success;
-
-event.on("ConnectionChanged", function () {
- return _success && _success(deviceSettings.retrieve("NetworkStatus.connectionType"));
-});
+var utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ fileSystem = require('ripple/fileSystem'),
+ fileSystemPaths = fileSystem.getFileSystemPaths();
module.exports = {
- getConnectionInfo: function (success, fail, args) {
- _success = success;
- success(deviceSettings.retrieve("NetworkStatus.connectionType"));
+ panel: {
+ domId: "filsystem-container",
+ collapsed: true,
+ pane: "left"
+ },
+ initialize: function () {
+ var fileSystemPaths = fileSystem.getFileSystemPaths();
+
+ utils.forEach(fileSystemPaths, function (value, key) {
+ utils.bindAutoSaveEvent(jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val(value.uri), function () {
+ value.uri = jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val();
+ fileSystem.updateFileSystemPaths(fileSystemPaths);
+ });
+ });
}
};
});
-define('ripple/platform/cordova/2.0.0/bridge/notification', function (require, exports, module) {
+define('ripple/ui/plugins/notifications', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var notifications = require('ripple/notifications'),
- _console = require('ripple/console'),
- goodVibrations = require('ripple/ui/plugins/goodVibrations');
-module.exports = {
- alert: function (success, error, args) {
- notifications.openNotification("normal", args[0]);
- return success && success();
- },
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ _notificationUIStack,
+ _notificationTemplate = "";
- confirm: function (success, error, args) {
- throw "Not Implemented";
- },
+function _remove(id) {
+ delete _notificationUIStack[id];
+ db.saveObject("posted-notifications", _notificationUIStack);
+ event.trigger("refreshNotificationStack", [], true);
+ _render();
+}
- activityStart: function (success, error, args) {
- },
+function _removeAll() {
+ _notificationUIStack = {};
+ db.saveObject("posted-notifications", _notificationUIStack);
+ event.trigger("refreshNotificationStack", [], true);
+ $("#notification-box").empty();
+ $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
+ $("#remove-all-notifications-btn").hide();
+}
- activityStop: function (success, error, args) {
- },
+function _render() {
+ var notificationHTML = "",
+ htmlContent = "";
- progressStart: function (success, error, args) {
- },
+ utils.forEach(_notificationUIStack, function (item) {
+ notificationHTML = _notificationTemplate.replace(/#id/g, item.id)
+ .replace(/#title/g, item.title)
+ .replace(/#content/, item.content ? item.content : "")
+ .replace(/#type/, item.type)
+ .replace(/#statusType/, item.statusType)
+ .replace(/#postedTime/, item.postedTime)
+ .replace(/#iconPath/, item.iconPath ? item.iconPath : "")
+ .replace(/#subIconPath/, item.subIconPath ? item.subIconPath : "")
+ .replace(/#number/, item.number ? item.number : "")
+ .replace(/#detailInfo/, item.detailInfo ? item.detailInfo.join() : "")
+ .replace(/#backgroundImagePath/, item.backgroundImagePath ? item.backgroundImagePath : "")
+ .replace(/#thumbnails/, item.thumbnails ? item.thumbnails.join() : "")
+ .replace(/#soundPath/, item.soundPath ? item.soundPath : "")
+ .replace(/#vibration/, item.vibration !== undefined ? (item.vibration === true ? "true" : "false") : "")
+ .replace(/#appControl/, item.appControl ? item.appControl : "")
+ .replace(/#appId/, item.appId ? item.appId : "")
+ .replace(/#progressType/g, item.progressType ? item.progressType: "")
+ .replace(/#progressValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue.toString() + "%" : "")
+ .replace(/#progressBarValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue : 0)
+ .replace(/#progress2Value/, (item.statusType === "PROGRESS" && item.progressType === "BYTE" && item.progressValue) ? item.progressValue.toString() + " byte(s)" : "")
+ .replace(/#displayBar/g, (item.statusType !== "PROGRESS" || item.progressType !== "PERCENTAGE") ? "none" : "")
+ .replace(/#display2Bar/g, (item.statusType !== "PROGRESS" || item.progressType !== "BYTE") ? "none" : "");
+ htmlContent += notificationHTML;
+ });
- vibrate: function (success, error, args) {
- var ms = args[0] || 500;
- goodVibrations.vibrateDevice(ms);
- },
+ $("#notification-box").accordion("destroy");
+ $("#notification-box").html(htmlContent).accordion({
+ active : false,
+ collapsible : true,
+ autoHeight : false
+ });
- beep: function (success, error, args) {
- for (var i = args[0]; i > 0; i--) {
- _console.log("beep!");
- }
- notifications.openNotification("normal", "BEEP x " + args[0]);
+ $("#notification-box .progress-bar").each(function (index, item) {
+ $(item).width(this.id);
+ });
+ if (utils.count(_notificationUIStack) !== 0) {
+ $("#remove-all-notifications-btn").show();
+ } else {
+ $("#remove-all-notifications-btn").hide();
}
-};
-
-});
-define('ripple/platform/cordova/2.0.0/bridge', function (require, exports, module) {
-/*
- * Copyright 2011 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 _prompt = require('ripple/ui/plugins/exec-dialog');
+ $("." + "remove-notification-btn").bind("click", function () {
+ _remove(this.id);
+ });
+}
module.exports = {
- exec: function (success, fail, service, action, args) {
- var emulator = {
- "App": require('ripple/platform/cordova/2.0.0/bridge/app'),
- "Accelerometer": require('ripple/platform/cordova/2.0.0/bridge/accelerometer'),
- "Compass": require('ripple/platform/cordova/2.0.0/bridge/compass'),
- "Camera": require('ripple/platform/cordova/2.0.0/bridge/camera'),
- "Capture": require('ripple/platform/cordova/2.0.0/bridge/capture'),
- "Contacts": require('ripple/platform/cordova/2.0.0/bridge/contacts'),
- "Debug Console": require('ripple/platform/cordova/2.0.0/bridge/console'),
- "Device": require('ripple/platform/cordova/2.0.0/bridge/device'),
- "File": require('ripple/platform/cordova/2.0.0/bridge/file'),
- "Geolocation": require('ripple/platform/cordova/2.0.0/bridge/geolocation'),
- "Media": require('ripple/platform/cordova/2.0.0/bridge/media'),
- "Network Status": require('ripple/platform/cordova/2.0.0/bridge/network'),
- "NetworkStatus": require('ripple/platform/cordova/2.0.0/bridge/network'),
- "Notification": require('ripple/platform/cordova/2.0.0/bridge/notification')
- };
-
- try {
- emulator[service][action](success, fail, args);
- }
- catch (e) {
- console.log("missing exec:" + service + "." + action);
- console.log(args);
- console.log(e);
- console.log(e.stack);
- //TODO: this should really not log the above lines, but they are very nice for development right now
- _prompt.show(service, action, success, fail);
+ panel: {
+ domId: "notification-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Notification",
+ display: true
+ },
+ initialize: function () {
+ _notificationTemplate = $("#notification-template").html();
+ $("#notification-box").empty();
+ _notificationUIStack = db.retrieveObject("posted-notifications") || {};
+ if (utils.count(_notificationUIStack) === 0) {
+ $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
}
- }
-};
+ else
+ _render();
+ $("#remove-all-notifications-btn").bind("click", _removeAll);
-});
-define('ripple/platform/cordova/2.0.0/logger', function (require, exports, module) {
-module.exports = {
- log: function (msg) {
- console.log(msg);
+ event.on("refreshNotificationUI", function () {
+ _notificationUIStack = db.retrieveObject("posted-notifications");
+ _render();
+ });
}
};
});
-define('ripple/platform/cordova/2.0.0/spec/config', function (require, exports, module) {
+define('ripple/ui/plugins/messaging', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants');
+var event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ _type = {
+ sms: "SMS",
+ mms: "MMS",
+ email: "E-mail"
+ },
+ _filename_suffix = 0,
+ _attachments = [];
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
- (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));
+function _getAttachmentFileName() {
+ return "attach" + _filename_suffix + ".txt";
+}
- return valid;
+module.exports = {
+ panel: {
+ domId: "messaging-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Messaging",
+ display: true
},
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
- }
+ initialize: function () {
+ document.getElementById("messaging-send")
+ .addEventListener("click", function () {
+ var number = document.getElementById("messaging-sms-number").value,
+ text = document.getElementById("messaging-text").value,
+ type = document.getElementById("messaging-type").value,
+ message = {
+ type: type,
+ body: text,
+ from: number,
+ time: new Date(),
+ attachments: _attachments
+ };
- var widgetInfo = {};
+ event.trigger("MessageReceived", [message]);
+
+ _attachments = [];
+/* TODO: add back when attachment is finished
+ document.getElementById("messaging-attachments").innerHTML = "";
+*/
+ _filename_suffix = 0;
+ }, false);
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+/* TODO: add back when attachment is finished
+ document.getElementById("messaging-attach")
+ .addEventListener("click", function () {
+ var attachedFile, attachedFileCheckbox, attachedFileName;
+ if (_filename_suffix > 0)
+ return;
+ _attachments.push({filename: _getAttachmentFileName(), content: document.getElementById("messaging-attachment-content").value});
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:gap": {
- attributeName: "xmlns:gap",
- required: true,
- type: "list",
- listValues: ["http://phonegap.com/ns/1.0"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["floating", "fullscreen"]
- }
- },
- children: {
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "short": {
- attributeName: "short",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- email: {
- attributeName: "email",
- type: "regex",
- required: false,
- regex: constants.REGEX.EMAIL
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- encoding: {
- attributeName: "encoding",
- type: "string",
- required: false
- },
- type: {
- attributeName: "type",
- type: "string",
- required: false
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "list",
- required: true,
- listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
- "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
- "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
- "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
- "http://api.phonegap.com/1.0/storage"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- }
- },
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "string",
- required: true
- },
- value: {
- type: "string",
- attributeName: "value",
- required: false
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
- }
+ attachedFile = document.getElementById("messaging-attachments").insertRow(0);
+ attachedFileName = attachedFile.insertCell(0);
+ attachedFileCheckbox = attachedFile.insertCell(1);
+ attachedFileName.innerHTML = _attachments[_filename_suffix].filename;
+// attachedFileCheckbox.innerHTML = '<input type="checkbox" value="' + _filename_suffix + '">';
+
+ document.getElementById("messaging-attachment-content").value = "";
+ _filename_suffix++;
+ }, false);
+
+ document.getElementById("messaging-detach")
+ .addEventListener("click", function () {
+ _attachments = [];
+ document.getElementById("messaging-attachments").innerHTML = "";
+ _filename_suffix = 0;
+ }, false);
+*/
+ event.on("OutsideMessageReceived", function (message) {
+ var numRecipients = 0,
+ i = 0,
+ recipients = [],
+ recipientsStatus = {},
+ strRecipients = document.getElementById("messaging-recipients").value;
+
+ recipientsStatus.id = message.id;
+ recipientsStatus.msg = message.msg;
+ for (i in message.to) {
+ recipientsStatus[message.to[i]] = true;
+ recipients.push(message.to[i]);
}
- }
+ for (i in message.cc) {
+ recipientsStatus[message.cc[i]] = true;
+ recipients.push(message.cc[i]);
+ }
+ for (i in message.bcc) {
+ recipientsStatus[message.bcc[i]] = true;
+ recipients.push(message.bcc[i]);
+ }
+ numRecipients = recipients.length;
+ strRecipients = recipients.join(",");
+ event.trigger("MessageSent", [recipientsStatus]);
+ document.getElementById("messaging-received").innerHTML = "" + numRecipients + " recipient(s)" + " delivered";
+ document.getElementById("messaging-recipients").value = strRecipients;
+ document.getElementById("received-message-box").value = message.body;
+ });
+
+ document.getElementById("messaging-clear")
+ .addEventListener("click", function () {
+ document.getElementById("received-message-box").value = "";
+ document.getElementById("messaging-received").innerHTML = "";
+ }, false);
+
+ utils.forEach(_type, function (msgTypeText, msgType) {
+ var typeNode = utils.createElement("option", {
+ "innerText": msgTypeText,
+ "value": msgType
+ });
+
+ document.getElementById("messaging-type").appendChild(typeNode);
+ });
}
};
});
-define('ripple/platform/cordova/2.0.0/spec/device', function (require, exports, module) {
+define('ripple/ui/plugins/audioPlayer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
+var event = require('ripple/event'),
+ constants = require('ripple/constants'),
+ audioObj = document.getElementById("multimedia-audio"),
+ audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);
module.exports = {
- "NetworkStatus": {
- "connectionType": {
- "name": "Connection Type",
- "control": {
- "type": "select",
- "value": "ethernet"
- },
- "options": {
- "unknown": "UNKNOWN",
- "ethernet": "ETHERNET",
- "wifi": "WIFI",
- "2g": "CELL_2G",
- "3g": "CELL_3G",
- "4g": "CELL_4G",
- "none": "none"
- },
- "callback": function (setting) {
- var connected = setting !== "none";
- require('ripple/bus').send("network", connected);
- }
- },
- "lag": {
- "name": "Lag the network",
- "control": {
- type: "checkbox",
- value: false
- },
- "callback": function (setting) {
- require('ripple/bus').send("lag", setting);
- }
- },
+ initialize: function () {
+ var audioObj = document.getElementById("multimedia-audio"),
+ audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);
+
+ if (audioObj) {
+ event.on("MultimediaVolumeChanged", function (volume) {
+ audioObj.volume = parseFloat(volume / 10);
+ });
+
+ audioObj.addEventListener("timeupdate", function () {
+ var s = parseInt(audioObj.currentTime % 60, 10),
+ m = parseInt((audioObj.currentTime / 60) % 60, 10);
+
+ audioProgress.innerText = ((m > 9) ? m : "0" + m) + ':' + ((s > 9) ? s : "0" + s);
+ }, false);
+
+ event.on("MultimediaAudioStateChanged", function (state) {
+ document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_STATE_FIELD_ID).innerText = state;
+ document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_FILE_FIELD_ID).innerText = audioObj.getAttribute("src");
+ });
+ }
}
};
});
-define('ripple/platform/cordova/2.0.0/spec/events', function (require, exports, module) {
+define('ripple/ui/plugins/settings', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function _fires(name, data) {
- return function () {
- cordova.fireDocumentEvent(name, data);
- };
+var db = require('ripple/db'),
+ constants = require('ripple/constants'),
+ KEY = constants.XHR.PROXY_DISABLED_BUTTON; // TODO: one settings object for all
+
+function _saveAndReload(key, value) {
+ jWorkflow.order(function (prev, baton) {
+ baton.take();
+ db.save(key, value, null, baton.pass);
+ }).start(function () {
+ window.tinyHipposReload = true;
+ location.reload();
+ });
+}
+
+function _initialize(prev, baton) {
+ var select = document.getElementById("settings-xhr-proxy"),
+ about = require('ripple/ui/plugins/about-dialog');
+
+ select.value = String(db.retrieve(KEY));
+ select.addEventListener("change", function () {
+ _saveAndReload(KEY, this.value);
+ }, false);
+
+ $("#options-menu-about").click(function () {
+ about.show();
+ });
+ // TODO: reload here?
}
module.exports = {
- "deviceready": {
- callback: _fires("deviceready")
- },
- "backbutton": {
- callback: _fires("backbutton")
- },
- "menubutton": {
- callback: _fires("menubutton")
- },
- "pause": {
- callback: _fires("pause")
- },
- "resume": {
- callback: _fires("resume")
- },
- "searchbutton": {
- callback: _fires("searchbutton")
- },
- "online": {
- callback: _fires("online")
+ panel: {
+ domId: "settings-container",
+ collapsed: true,
+ pane: "right"
},
- "offline": {
- callback: _fires("offline")
- }
+ initialize: _initialize
};
});
-define('ripple/platform/cordova/2.0.0/spec/ui', function (require, exports, module) {
+define('ripple/ui/plugins/widgetConfig', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- plugins: [
- "accelerometer",
- "deviceSettings",
- "geoView",
- "widgetConfig",
- "platformEvents"
- ]
-};
-
-});
-define('ripple/platform/cordova/2.0.0/spec', function (require, exports, module) {
-function loadWebworks(win, device) {
- var builder = require('ripple/platform/builder'),
- platform = device.id === "Playbook" || device.id === "Colt" ? "tablet" : "handset",
- webworks = require('ripple/platform/webworks.' + platform + '/2.0.0/spec');
-
- builder.build(webworks.objects).into(win);
- builder.build(webworks.objects).into(window);
-}
+var constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ platform = require('ripple/platform'),
+ widgetConfig = require('ripple/widgetConfig');
-module.exports = {
- id: "cordova",
- version: "2.0.0",
- name: "Apache Cordova",
- type: "platform",
- nativeMethods: {},
+function _buildConfigAccordionNode(node, accordionContainer, counter) {
+ var nodeDiv, nodeTitleH3, nodeContentDiv, tableString, attribute, child, result,
+ tableClass, nameClass, attributeNameClass, messageClass, nameId, messageId, attributeName, attributeValue, attributeMessage,
+ helpText = {},
+ nodeCounter = 0,
+ attributeCounter = 0,
+ moreNodes = node.validationResult,
+ createTooltip = function (value, index) {
+ tooltip.create("#" + index, value);
+ };
- config: require('ripple/platform/cordova/2.0.0/spec/config'),
- device: require('ripple/platform/cordova/2.0.0/spec/device'),
- ui: require('ripple/platform/cordova/2.0.0/spec/ui'),
- events: require('ripple/platform/cordova/2.0.0/spec/events'),
+ while (moreNodes) {
+ result = node.validationResult[nodeCounter];
- initialize: function (win) {
- var honeypot = require('ripple/honeypot'),
- devices = require('ripple/devices'),
- device = devices.getCurrentDevice(),
- bridge = require('ripple/platform/cordova/2.0.0/bridge'),
- cordova,
- topCordova = window.top.require('ripple/platform/cordova/2.0.0/spec'),
- get = function () {
- return cordova;
- },
- set = function (orig) {
- if (cordova) {
- return;
- }
+ if (!result) {
+ // this should never happen
+ return;
+ }
- cordova = orig;
+ // the container of the entire accordion block
+ nodeDiv = utils.createElement("div", {
+ "id": "config-accordion-node-content-" + counter + "-" + nodeCounter,
+ "class": "ui-corner-all"
+ });
- cordova.define.remove("cordova/exec");
- cordova.define("cordova/exec", function (require, exports, module) {
- module.exports = bridge.exec;
- });
+ // the header bar of the accordion block
+ nodeTitleH3 = utils.createElement("h3", {
+ "id": "config-accordion-node-title-" + counter + "-" + nodeCounter,
+ "class": "config-accordion-node-title"
+ });
- cordova.UsePolling = true;
+ nodeTitleH3.appendChild(utils.createElement("a", {
+ href: "#",
+ innerText: node.nodeName,
+ "class": constants.CONFIG.SUCCESS_CSS[(result.valid === undefined) ? "missing" : result.valid.toString()]
+ }));
+ nodeDiv.appendChild(nodeTitleH3);
- //do nothing here as we will just call the callbacks ourselves
- cordova.define.remove("cordova/plugin/android/polling");
- cordova.define("cordova/plugin/android/polling", function (require, exports, module) {
- module.exports = function () {};
- });
+ if (node.helpText) {
+ helpText[nodeTitleH3.id] = node.helpText;
+ }
- var builder = cordova.require('cordova/builder'),
- allTheThings = window,
- base = cordova.require('cordova/common'),
- iosPlugin;
+ nodeContentDiv = utils.createElement("div");
- //HACK: Overwrite all the things, handles when cordova.js executes before we start booting
- builder.build(base.objects).intoAndClobber(allTheThings);
- cordova.require('cordova/channel').onNativeReady.fire();
- // DIRTY HACK: once cordova is cleaned up, we do not
- // need this.
- // reference issue: https://issues.apache.org/jira/browse/CB-1013
- try {
- iosPlugin = cordova.require('cordova/plugin/ios/device');
- bridge.exec(function (info) {
- iosPlugin.setInfo(info);
- }, null, 'Device', 'getDeviceInfo', []);
- } catch (e) {
- cordova.require('cordova/channel').onCordovaInfoReady.fire();
- }
- };
+ // display node value (add tool tip if exists)
+ if (node.type || (!node.type && result && result.value)) {
+ nodeContentDiv.appendChild(utils.createElement("div", {
+ "id": "config-accordion-node-content-value-" + counter + "-" + nodeCounter,
+ "class": "config-accordion-node-content-value",
+ "innerHTML": "<span>Value:</span>" + (result.value || "")
+ }));
- if (window.FileReader && !topCordova.nativeMethods.FileReader) {
- topCordova.nativeMethods.FileReader = window.FileReader;
+ if (node.helpValueText) {
+ helpText["config-accordion-node-content-value-" + counter + "-" + nodeCounter] = node.helpValueText;
+ }
}
- if (device.manufacturer === "Research In Motion") {
- loadWebworks(win, device);
+ // display node message if failed validation
+ if (result && result.message) {
+ nodeContentDiv.appendChild(utils.createElement("div", {
+ "id": "config-accordion-node-content-value-message-" + counter + "-" + nodeCounter,
+ "class": "config-accordion-node-content-value-message ui-text-fail",
+ "innerHTML": "<span>Message:</span>" + result.message
+ }));
}
- honeypot.monitor(win, "cordova").andRun(get, set);
- },
+ // display node attributes with name, value, message if failed validation
+ if (result.attributes) {
+ nodeContentDiv.appendChild(utils.createElement("div", {
+ "id": "config-accordion-node-content-attributes-title-" + counter + "-" + nodeCounter,
+ "class": "config-accordion-node-content-attributes-title",
+ "innerHTML": "Attributes..."
+ }));
- objects: {
- MediaError: {
- path: "cordova/2.0.0/MediaError"
- },
- org: {
- children: {
- apache: {
- children: {
- cordova: {
- children: {
- Logger: {
- path: "cordova/2.0.0/logger"
- },
- JavaPluginManager: {
- path: "cordova/2.0.0/JavaPluginManager"
- }
- }
- }
+ tableClass = "preferences-table";
+ nameClass = "config-attributes-name-value";
+ attributeNameClass = "ui-text-label";
+ messageClass = "config-attributes-message";
+
+ tableString = '<table class="' + tableClass + ' ui-widget-content">';
+ for (attribute in result.attributes) {
+ if (result.attributes.hasOwnProperty(attribute)) {
+ nameId = "config-accordion-node-content-attributes-table-name-" + counter + "-" + nodeCounter + "-" + attributeCounter;
+ messageId = "config-accordion-node-content-attributes-table-message-" + counter + "-" + nodeCounter + "-" + attributeCounter;
+ attributeName = result.attributes[attribute].attributeName;
+ attributeValue = result.attributes[attribute].value || " ";
+ attributeMessage = result.attributes[attribute].message || null;
+
+ tableString += '<tr class="' + nameClass + '" id="' + nameId + '">' +
+ '<td class="' + attributeNameClass + '">' + attributeName + '</td>' +
+ '<td>' + attributeValue + '</td></tr>';
+
+ if (node.attributes[attributeName].helpText) {
+ helpText[nameId] = node.attributes[attributeName].helpText;
+ }
+
+ if (attributeMessage !== null) {
+ tableString += "<tr class=" + messageClass + " id=" + messageId + "><td colspan=\"2\">" +
+ attributeMessage + "</td></tr>";
}
+ attributeCounter++;
}
}
+ tableString += "</table>";
+
+ nodeContentDiv.innerHTML += tableString;
+ }
+
+
+ nodeDiv.appendChild(nodeContentDiv);
+ accordionContainer.appendChild(nodeDiv);
+
+ utils.forEach(helpText, createTooltip);
+
+ nodeCounter ++;
+
+ if (!node.validationResult[nodeCounter]) {
+ nodeCounter = 0;
+ moreNodes = false;
+ }
+ }
+
+ if (node.children) {
+ for (child in node.children) {
+ if (node.children.hasOwnProperty(child)) {
+ counter ++;
+ _buildConfigAccordionNode(node.children[child], accordionContainer, counter);
+ }
}
}
-};
+}
+
+function _initializeConfigResultsView(results) {
+ try {
+ var rootNode,
+ accordionContainer = document.getElementById("widget-config");
+
+ accordionContainer.innerHTML = "";
+ if (!results) {
+ accordionContainer.appendChild(utils.createElement("div", {
+ "class": "config-accordion-node-title " + constants.CONFIG.SUCCESS_CSS["false"],
+ "innerHTML": "Expected to find a configuration file for your application, but none is present. Please create" +
+ " a configuration file with the following name in the root directory of your application: " +
+ platform.current().fileName
+ }));
+ return;
+ }
+ rootNode = results[results.rootElement];
+
+ _buildConfigAccordionNode(rootNode, accordionContainer, 0);
+
+ jQuery(function () {
+ var stop = false;
+ jQuery("#widget-config h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#widget-config").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ });
+ } catch (e) {
+ exception.handle(e, true);
+ }
+}
+
+event.on("FrameHistoryChange", function () {
+ module.exports.initialize();
});
-define('ripple/platform/ivi/3.0/VehiclePanelEngine', function (require, exports, module) {
+module.exports = {
+ panel: {
+ domId: "config-container",
+ collapsed: true,
+ pane: "right",
+ titleName: "Application Configuration",
+ display: true
+ },
+ initialize: function () {
+ var results = widgetConfig.getValidationResults();
+ _initializeConfigResultsView(results);
+ }
+};
+
+});
+define('ripple/ui/plugins/layout', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var utils = require('ripple/utils'),
+var constants = require('ripple/constants'),
db = require('ripple/db'),
- dbinit = require('ripple/platform/ivi/3.0/dbinit'),
- _vehicleMapStack = {},
- _databaseName = "ivi-vehicle-database",
- VehiclePanelEngine;
-
-function _save (data) {
- db.saveObject(_databaseName, data);
-}
-
-function _get () {
- var database = db.retrieveObject(_databaseName);
+ resizer = require('ripple/resizer'),
+ devices = require('ripple/devices'),
+ event = require('ripple/event');
- if (!database) {
- db.saveObject(_databaseName, dbinit.Vehicle);
- database = db.retrieveObject(_databaseName);
- }
+function _initializeLayout(prev, baton) {
+ var layout = db.retrieve("layout"),
+ orientation = db.retrieve("deviceOrientation") || "portrait",
+ layoutLandscape = document.getElementById(constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID),
+ layoutPortrait = document.getElementById(constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID),
+ currentDevice = devices.getCurrentDevice(),
+ defaultOrientation = currentDevice ? currentDevice.defaultOrientation : null,
+ layoutTypeChanged = false;
- return database;
-}
+ jQuery("#" + constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID).bind("click", function () {
+ layoutLandscape.setAttribute("class", "layout-selected");
+ layoutPortrait.setAttribute("class", "layout-not-selected");
+ resizer.rotateDevice("landscape");
+ event.trigger("OrientationChanged", ["landscape"], true);
+ });
-VehiclePanelEngine = function () {
- var _CONFIGURATION = "configuration", _AUTO = "auto",
- _database,
- _configuration, _currentConfiguration,
- _supported, _settings, _autoRunning;
+ jQuery("#" + constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID).bind("click", function () {
+ layoutLandscape.setAttribute("class", "layout-not-selected");
+ layoutPortrait.setAttribute("class", "layout-selected");
+ resizer.rotateDevice("portrait");
+ event.trigger("OrientationChanged", ["portrait"], true);
+ });
- function _init () {
- _database = _get();
+ jQuery("#" + constants.COMMON.MENU_BUTTON).bind("click", function () {
+ event.trigger("HardwareKey", [1]);
+ });
- _settings = _database.settingData;
+ jQuery("#" + constants.COMMON.BACK_BUTTON).bind("click", function () {
+ event.trigger("HardwareKey", [0]);
+ });
- _configuration = _database.configurationData;
- _currentConfiguration = _database.currentConfiguration;
+ if (!layout) {
+ layout = defaultOrientation || "portrait";
+ layoutTypeChanged = true;
+ resizer.changeLayoutType(layout);
+ }
- _supported = _database.supported;
+ //Hide the orientation buttons that we don't need for this device
+ if (!currentDevice.viewPort.landscape) {
+ layoutLandscape.setAttribute("style", "display:none");
+ }
- _autoRunning = _database.autoRunningData;
+ if (!currentDevice.viewPort.portrait) {
+ layoutPortrait.setAttribute("style", "display:none");
}
- this.saveData = function (supported, currentConfiguration, configuration, settings, autoRunning) {
- _database.supported = supported;
- _database.currentConfiguration = currentConfiguration;
- _database.settingData = settings;
- _database.configurationData[currentConfiguration] = configuration;
- _database.autoRunningData[0] = autoRunning;
+ if (layout && layout === "portrait") {
+ layoutLandscape.setAttribute("class", "layout-not-selected");
+ layoutPortrait.setAttribute("class", "layout-selected");
+ }
+ else if (layout && layout === "landscape") {
+ layoutLandscape.setAttribute("class", "layout-selected");
+ layoutPortrait.setAttribute("class", "layout-not-selected");
+ }
- _save(_database);
- };
+ if (!layoutTypeChanged) {
+ resizer.resize(currentDevice);
+ }
- function _formatVehicleDB (map, db) {
- var formatSettings = {},
- VehicleMap = map, vehicleData = db,
- property, name, item, i = 0;
+ if (orientation === "portrait") {
+ layoutLandscape.setAttribute("class", "layout-not-selected");
+ layoutPortrait.setAttribute("class", "layout-selected");
+ } else {
+ layoutLandscape.setAttribute("class", "layout-selected");
+ layoutPortrait.setAttribute("class", "layout-not-selected");
+ }
+ resizer.rotateDevice(orientation);
+}
- for (property in VehicleMap) {
- name = property.split("-")[0];
- item = property.split("-")[1];
+module.exports = {
+ initialize: _initializeLayout
+};
- if (!formatSettings[name]) {
- formatSettings[name] = {};
- }
+});
+define('ripple/ui/plugins/devices', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ db = require('ripple/db'),
+ resizer = require('ripple/resizer');
- formatSettings[name][item] = utils.copy(VehicleMap[property]);
- formatSettings[name][item].value = vehicleData[i];
+function _getTextZooming(zooming) {
+ return zooming + '%';
+}
- i++;
- }
+module.exports = {
+ panel: {
+ domId: "devices-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Orientation and Zooming",
+ display: true
+ },
- return formatSettings;
- }
+ initialize: function () {
+ var zooming = document.getElementById(constants.ENCAPSULATOR.ZOOMING);
+ function updateZoomingValues() {
+ var zoomingText, scaleFactor;
- /**
- * get
- * @return {Object}
- */
- this.getConfiguration = function () {
- var configuration = {}, i, j, dataIndex, tempArray,
- configurationMap = _vehicleMapStack.vehicleConfigurationMap,
- configurationData = _configuration;
+ zoomingText = _getTextZooming(zooming.value);
+ jQuery('#screen-zooming-label').html(zoomingText);
- for (j = 0; j < configurationData.length; j++) {
- dataIndex = _CONFIGURATION + j;
- configuration[dataIndex] = {};
+ // Zooming device skin
+ scaleFactor = zooming.value / 100;
+ resizer.scaleDevice(scaleFactor);
+ }
- for (i = 0; i < configurationMap.length; i++) {
- tempArray = configurationMap[i].split("-");
+ function initializeValues() {
+ var zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING);
- if (!configuration[dataIndex][tempArray[0]]) {
- configuration[dataIndex][tempArray[0]] = {};
- }
- configuration[dataIndex][tempArray[0]][tempArray[1]] = configurationData[j][i];
+ if (!zoomingValue) {
+ zoomingValue = 100;
}
+ jQuery("#" + constants.ENCAPSULATOR.ZOOMING).val(zoomingValue);
+ updateZoomingValues();
}
- return configuration;
- };
+ jQuery("#" + constants.ENCAPSULATOR.ZOOMING).bind("change", function () {
+ updateZoomingValues();
+ db.save(constants.ENCAPSULATOR.ZOOMING, zooming.value);
+ });
- /**
- * get
- * @return {String}
- */
- this.getCurrentConfiguration = function () {
- return _CONFIGURATION + _currentConfiguration;
- };
+ initializeValues();
+ }
+};
- /**
- * get
- * @return {Array}
- */
- this.getProperties = function () {
- return _vehicleMapStack.vehicleProperties;
- };
-
- /**
- * get supported vehicle properties name.
- * @return {Array}
- */
- this.getSupported = function () {
- return _supported;
- };
-
- /**
- * get property unit.
- * @param property
- * @param item
- * @return {String}
- */
- this.getPropertyUnit = function (property, item) {
- var unitKey = property + "-" + item,
- propertyUnitMap = _vehicleMapStack.vehiclePropertyUnitsMap;
-
- return !propertyUnitMap[unitKey] ? "" : "(" + propertyUnitMap[unitKey] + ")";
- };
-
- this.getPropertyRange = function (property, item) {
- var rangeKey = property + "-" + item,
- propertyRangeMap = _vehicleMapStack.vehiclePropertyRangeMap;
-
- return !propertyRangeMap[rangeKey] ? false : propertyRangeMap[rangeKey];
- };
-
- /**
- * get
- * @param property
- * @param item
- * @return {*}
- */
- this.getPropertyConstant = function (property, item) {
- var propertyConstants = _vehicleMapStack.vehiclePropertyConstantsMap;
-
- return !propertyConstants[property] ? null : propertyConstants[property][item];
- };
-
- this.getSettings = function () {
- return _formatVehicleDB(_vehicleMapStack.vehicleSettingMap, _settings);
- };
-
- this.getAutoRunning = function () {
- var autoRunning = {}, i,
- autoRunningMap = _vehicleMapStack.vehicleAutoRunningMap,
- autoRunningData = _autoRunning;
-
- for (i = 0; i < _autoRunning.length; i++) {
- autoRunning[_AUTO + i] = _formatVehicleDB(autoRunningMap, autoRunningData[i]);
- }
- return autoRunning;
- };
-
- _init();
-};
-
-//can support all properties.
-_vehicleMapStack.vehicleProperties = [
- "VehicleSpeed", "EngineSpeed", "VehiclePowerMode", "TripMeter",
- "Acceleration", "Transmission", "CruiseControlStatus", "WheelBrake",
- "LightStatus", "InteriorLightStatus", "Horn", "Fuel", "EngineOil",
- "Location", "ExteriorBrightness", "Temperature", "RainSensor",
- "WindshieldWiper", "HVAC", "WindowStatus", "Sunroof", "ConvertibleRoof",
- "VehicleId", "Size", "FuelInfo", "VehicleType", "Doors",
- "TransmissionGearType", "WheelInformation", "Odometer", "Fluid", "Battery",
- "TirePressure", "TireTemperature", "SecurityAlert", "ParkingBrake",
- "ParkingLight", "HazardLight", "AntilockBrakingSystem", "TractionControlSystem",
- "VehicleTopSpeedLimit", "AirbagStatus", "DoorStatus", "SeatBeltStatus",
- "OccupantStatus", "ObstacleDistance", "NightMode", "DrivingMode",
- "TurnSignal", "ButtonEvent"
-];
-
-//Vehicle Configuration
-_vehicleMapStack.vehicleConfigurationMap = [
- "VehicleId-WMI", "VehicleId-VIN",
- "Size-width", "Size-height", "Size-length",
- "FuelInfo-type", "FuelInfo-refuelPosition",
- "VehicleType-type",
- "Doors-doorsPerRow",
- "TransmissionGearType-transmissionGearType",
- "WheelInformation-frontWheelRadius", "WheelInformation-rearWheelRadius", "WheelInformation-wheelTrack", "WheelInformation-ABS"
-];
-
-//all ranged attributes' min. max and step.
-_vehicleMapStack.vehiclePropertyRangeMap = {
- "VehicleSpeed-vehicleSpeed": [0, 400, 1],
- "EngineSpeed-engineSpeed": [0, 10000, 20],
- "Acceleration-x": [0, 200, 1],
- "Acceleration-y": [0, 200, 1],
- "Acceleration-z": [0, 200, 1],
- "Fuel-level": [0, 100, 1],
- "Fuel-range": [0, 1000, 1],
- "Fuel-instantConsumption": [0, 100, 1],
- "Fuel-instantEconomy": [0, 100, 1],
- "Fuel-averageEconomy": [0, 100, 1],
- "EngineOil-remaining": [0, 100, 1],
- "EngineOil-temperature": [0, 100, 1],
- "EngineOil-pressure": [0, 1000, 1],
- "Location-latitude": [-180, 180, 1],
- "Location-longitude": [-19, 90, 1],
- "Location-altitude": [0, 100, 1],
- "Location-direction": [0, 360, 1],
- "ExteriorBrightness-exteriorBrightness": [0, 100, 1],
- "Temperature-interior": [-5, 35, 1],
- "Temperature-exterior": [-40, 60, 1],
- "Odometer-odometer": [0, 10000, 10],
- "CruiseControlStatus-speed": [1, 100, 1],
- "HVAC-targetTemperature": [0, 35, 7],
- "Sunroof-openness": [0, 100, 1],
- "Sunroof-tilt": [0, 100, 1],
- "ConvertibleRoof-openness": [0, 100, 1],
- "WindowStatus-openness": [0, 100, 1],
- "VehicleTopSpeedLimit-vehicleTopSpeedLimit": [0, 400, 1],
- "ObstacleDistance-obstacleDistance": [0, 120, 1],
- "Fluid-transmission": [0, 100, 1],
- "Fluid-brake": [0, 100, 1],
- "Fluid-washer": [0, 100, 1],
- "Battery-voltage": [0, 12, 1],
- "Battery-current": [0, 200, 1],
- "TirePressure-leftFront": [0, 500, 1],
- "TirePressure-rightFront": [0, 500, 1],
- "TirePressure-leftRear": [0, 500, 1],
- "TirePressure-rightRear": [0, 500, 1],
- "TireTemperature-leftFront": [0, 60, 1],
- "TireTemperature-rightFront": [0, 60, 1],
- "TireTemperature-leftRear": [0, 60, 1],
- "TireTemperature-rightRear": [0, 60, 1],
- "TurnSignal-turnSignal": [0, 100, 1],
- "ButtonEvent-buttonEvent": [0, 100, 1]
-};
-
-//simulate car running attributes' controller-types.
-_vehicleMapStack.vehicleAutoRunningMap = {
- "VehicleSpeed-vehicleSpeed": {
- "type": "range"
- },
- "EngineSpeed-engineSpeed": {
- "type": "range"
- },
- "VehiclePowerMode-vehiclePowerMode": {
- "type": "select",
- "options": [{"OFF": 0},{"ACCESSORY1": 1},{"ACCESSORY2": 2},{"RUN": 3}]
- },
- "TripMeter-tripMeters": {
- "type": "text"
- },
- "Acceleration-x": {
- "type": "range"
- },
- "Acceleration-y": {
- "type": "range"
- },
- "Acceleration-z": {
- "type": "range"
- },
- "Fuel-level": {
- "type": "range"
- },
- "Fuel-range": {
- "type": "range"
- },
- "Fuel-instantConsumption": {
- "type": "range"
- },
- "Fuel-instantEconomy": {
- "type": "range"
- },
- "Fuel-averageEconomy": {
- "type": "range"
- },
- "EngineOil-remaining": {
- "type": "range"
- },
- "EngineOil-temperature": {
- "type": "range"
- },
- "EngineOil-pressure": {
- "type": "range"
- },
- "Location-latitude": {
- "type": "range"
- },
- "Location-longitude": {
- "type": "range"
- },
- "Location-altitude": {
- "type": "range"
- },
- "Location-direction": {
- "type": "range"
- },
- "ExteriorBrightness-exteriorBrightness": {
- "type": "range"
- },
- "Temperature-interior": {
- "type": "range"
- },
- "Temperature-exterior": {
- "type": "range"
- },
- "RainSensor-rainSensor": {
- "type": "select",
- "options": [{"No Rain": 0},{"Rain 1": 1},{"Rain 2": 2},{"Rain 3": 3},{"Rain 4": 4},{"Rain 5": 5},
- {"Rain 6": 6},{"Rain 7": 7},{"Rain 8": 8},{"Rain 9": 9},{"Heaviest": 10}]
- },
- "Odometer-odometer": {
- "type": "range"
- },
- "TurnSignal-turnSignal": {
- "type": "range"
- },
- "ButtonEvent-buttonEvent": {
- "type": "range"
- }
-};
-
-//Vehicle Setting attributes' controller-types.
-_vehicleMapStack.vehicleSettingMap = {
- "Transmission-gearPosition": {
- "type": "select",
- "options": [{"NEUTRAL": 0},{"FIRST": 1},{"SECOND": 2},{"THIRD": 3}, {"FORTH": 4},{"FIFTH": 5},
- {"SIXTH": 6},{"SEVENTH": 7}, {"EIGHTH": 8},{"NINTH": 9},{"TENTH": 10},{"CVT": 64},
- {"REVERSE": 128},{"PARK": 255}]
- },
- "Transmission-mode": {
- "type": "select",
- "options": [{"NORMAL": 0},{"SPORT": 1},{"ECONOMY": 2}, {"OEMCUSTOM1": 3},{"OEMCUSTOM2": 4}]
- },
- "CruiseControlStatus-activated": {
- "type": "radio",
- "options": [{"Active": true}, {"Inactive": false}]
- },
- "CruiseControlStatus-speed": {
- "type": "range"
- },
- "WheelBrake-engaged": {
- "type": "radio",
- "options": [{"Engaged": true}, {"Disengaged": false}]
- },
- "LightStatus-head": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-rightTurn": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-leftTurn": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-brake": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-fog": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-hazard": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-parking": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "LightStatus-highBeam": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "InteriorLightStatus-passenger": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "InteriorLightStatus-driver": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "InteriorLightStatus-center": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "Horn-on": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "WindshieldWiper-windshieldWiper": {
- "type": "select",
- "options": [{"OFF": 0},{"SLOWEST": 1},{"FASTEST": 5},{"AUTO": 10}]
- },
- "HVAC-airflowDirection": {
- "type": "select",
- "options": [{"FRONTPANEL": 0},{"FLOORDUCT": 1},{"FRONT": 0x02}, {"DEFROSTER": 0x04}]
- },
- "HVAC-fanSpeed": {
- "type": "select",
- "options": [{"0": 0},{"1": 1},{"2": 2},{"3": 3},{"4": 4},{"5": 5}, {"6": 6},{"7": 7}]
- },
- "HVAC-targetTemperature": {
- "type": "range"
- },
- "HVAC-airConditioning": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "HVAC-airRecirculation": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "HVAC-heater": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "HVAC-steeringWheelHeater": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "HVAC-seatHeater": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "HVAC-seatCooler": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "Sunroof-openness": {
- "type": "range"
- },
- "Sunroof-tilt": {
- "type": "range"
- },
- "ConvertibleRoof-openness": {
- "type": "range"
- },
- "SecurityAlert-securityAlert": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "ParkingBrake-parkingBrake": {
- "type": "radio",
- "options": [{"Engaged": true}, {"Disengaged": false}]
- },
- "ParkingLight-parkingLight": {
- "type": "radio",
- "options": [{"Engaged": true}, {"Disengaged": false}]
- },
- "HazardLight-hazardLight": {
- "type": "radio",
- "options": [{"Engaged": true}, {"Disengaged": false}]
- },
- "AntilockBrakingSystem-antilockBrakingSystem": {
- "type": "radio",
- "options":[{"Engaged": true}, {"Idle": false}]
- },
- "TractionControlSystem-tractionControlSystem": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "VehicleTopSpeedLimit-vehicleTopSpeedLimit": {
- "type": "range"
- },
- "WindowStatus-openness": {
- "type": "range"
- },
- "WindowStatus-defrost": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "AirbagStatus-airbagStatus": {
- "type": "select",
- "options": [{"INACTIVE": 0},{"ACTIVE": 1},{"DEPLOYED": 2}]
- },
- "DoorStatus-doorStatus": {
- "type": "select",
- "options": [{"CLOSED": 0},{"OPEN": 1},{"AJAR": 2}]
- },
- "DoorStatus-doorLockStatus": {
- "type": "radio",
- "options": [{"Locked": true}, {"Unlocked": false}]
- },
- "DoorStatus-childLockStatus": {
- "type": "radio",
- "options": [{"On": true}, {"Off": false}]
- },
- "SeatBeltStatus-seatBeltStatus": {
- "type": "radio",
- "options": [{"Fasten": true}, {"Unfastened": false}]
- },
- "OccupantStatus-occupantStatus": {
- "type": "select",
- "options": [{"VACANT": 0},{"CHILD": 1},{"ADULT": 2}]
- },
- "ObstacleDistance-obstacleDistance": {
- "type": "range"
- },
- "NightMode-nightMode": {
- "type": "radio",
- "options": [{"Night": true}, {"Day": false}]
- },
- "DrivingMode-drivingMode": {
- "type": "select",
- "options": [{"Not Driving": 0},{"Driving": 1}]
- },
- "Fluid-transmission": {
- "type": "range"
- },
- "Fluid-brake": {
- "type": "range"
- },
- "Fluid-washer": {
- "type": "range"
- },
- "Battery-voltage": {
- "type": "range"
- },
- "Battery-current": {
- "type": "range"
- },
- "TirePressure-leftFront": {
- "type": "range"
- },
- "TirePressure-rightFront": {
- "type": "range"
- },
- "TirePressure-leftRear": {
- "type": "range"
- },
- "TirePressure-rightRear": {
- "type": "range"
- },
- "TireTemperature-leftFront": {
- "type": "range"
- },
- "TireTemperature-rightFront": {
- "type": "range"
- },
- "TireTemperature-leftRear": {
- "type": "range"
- },
- "TireTemperature-rightRear": {
- "type": "range"
- }
-};
-
-//attributes units
-_vehicleMapStack.vehiclePropertyUnitsMap = {
- "VehicleSpeed-vehicleSpeed": "kph",
- "EngineSpeed-engineSpeed": "rpm",
- "TripMeter-tripMeters": "[m,...]",
- "CruiseControlStatus-speed": "kph",
- "Fuel-level": "%",
- "Fuel-instantConsumption": "ml/s",
- "Fuel-instantEconomy": "km/l",
- "Fuel-averageEconomy": "km/l",
- "EngineOil-remaining": "%",
- "EngineOil-temperature": "C",
- "EngineOil-pressure": "kpa",
- "ExteriorBrightness-exteriorBrightness": "lux",
- "Temperature-interior": "C",
- "Temperature-exterior": "C",
- "HVAC-targetTemperature": "C",
- "Sunroof-openness": "%",
- "Sunroof-tilt": "%",
- "ConvertibleRoof-openness": "%",
- "WindowStatus-openness": "%",
- "ObstacleDistance-obstacleDistance": "m",
- "Size-width": "mm",
- "Size-height": "mm",
- "Size-length": "mm",
- "WheelInformation-frontWheelRadius": "mm",
- "WheelInformation-rearWheelRadius": "mm",
- "WheelInformation-wheelTrack": "mm",
- "Odometer-odometer": "km",
- "Fluid-transmission": "%",
- "Fluid-brake": "%",
- "Fluid-washer": "%",
- "Battery-voltage": "V",
- "Battery-current": "A",
- "TirePressure-leftFront": "kpa",
- "TirePressure-rightFront": "kpa",
- "TirePressure-leftRear": "kpa",
- "TirePressure-rightRear": "kpa",
- "TireTemperature-leftFront": "C",
- "TireTemperature-rightFront": "C",
- "TireTemperature-leftRear": "C",
- "TireTemperature-rightRear": "C",
- "VehicleTopSpeedLimit-vehicleTopSpeedLimit": "kph"
-};
-
-//key and value of select types in attributes
-_vehicleMapStack.vehiclePropertyConstantsMap = {
- "FuelInfo": {
- "type": {
- "val0": "GASOLINE",
- "val1": "HIGH_OCTANE",
- "val2": "DIESEL",
- "val3": "ELECTRIC",
- "val4": "HYDROGEN"
- },
- "refuelPosition": {
- "val0": "LEFT",
- "val1": "RIGHT",
- "val2": "FRONT",
- "val3": "REAR"
- }
- },
- "VehicleType": {
- "type": {
- "val0": "SEDAN",
- "val1": "COUPE",
- "val2": "CABRIOLE",
- "val3": "ROADSTER",
- "val4": "SUV",
- "val5": "TRUCK"
- }
- },
- "TransmissionGearType": {
- "transmissionGearType": {
- "val0": "AUTO",
- "val1": "MANUAL",
- "val2": "CV"
- }
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": {
- "val0": "OFF",
- "val1": "ACCESSORY1",
- "val2": "ACCESSORY2",
- "val3": "RUN"
- }
- }
-};
-
-exports.VehiclePanelEngine = new VehiclePanelEngine();
});
-define('ripple/platform/ivi/3.0/WebAPIError', function (require, exports, module) {
+define('ripple/ui/plugins/storage', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ platform = require('ripple/platform'),
+ utils = require('ripple/utils'),
+ app = require('ripple/app'),
+ db = require('ripple/db');
-var errorcode = require('ripple/platform/ivi/3.0/errorcode');
+function _updatePreferencesView() {
+ var node = document.getElementById(constants.COMMON.STORAGE_TABLE_BODY_CLASS),
+ countTitle = document.getElementById(constants.COMMON.STORAGE_COUNT_CONTAINER_ID);
-var msg = {
- 1: "Permission denied.",
- 2: "Unsupported property.",
- 3: "Timeout.",
- 10: "Unknown."
-},
- errType = {
- 1: "PermissionDeniedError",
- 2: "PropertyUnavailableError",
- 3: "TimeoutError",
- 10: "UnknownError"
-};
+ // TODO: convert to appendChild
+ if (node) {
+ db.retrieveAll(platform.getPersistencePrefix(), function (results) {
+ var str = "",
+ counter = 0;
-module.exports = function (code, message, name) {
- var _code, _message, _name;
+ utils.forEach(results, function (value, key) {
+ // TODO: based of current platform
+ if (app.isPreferenceReadOnly(key)) {
+ str += '<tr class="ui-text-highlight">';
+ } else {
+ str += '<tr>';
+ }
+ str += '<td>' + key + '</td><td>' + value + "</td></tr>";
+ counter ++;
+ });
- if (typeof code !== 'number') {
- _code = errorcode.UNKNOWN;
- _message = msg[_code];
- _name = errType[_code];
- } else {
- _code = code;
- if (typeof message === 'string') {
- _message = message;
- } else {
- _message = msg[_code];
- }
- if (typeof name === 'string') {
- _name = name;
- } else {
- _name = errType[_code];
- }
+ node.innerHTML = str;
+ countTitle.innerHTML = counter.toString();
+
+ if (counter === 0) {
+ jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).addClass(constants.CSS_PREFIX.IRRELEVANT);
+ }
+ else {
+ jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).removeClass(constants.CSS_PREFIX.IRRELEVANT);
+ }
+ });
}
+}
- this.__defineGetter__("code", function () {
- return _code;
- });
- this.__defineGetter__("message", function () {
- return _message;
- });
- this.__defineGetter__("name", function () {
- return _name;
- });
+module.exports = {
+ panel: {
+ domId: "preferences",
+ collapsed: true,
+ pane: "left"
+ },
+ initialize: function () {
+ jQuery("#preferences-clear-button").bind("click", function () {
+ db.removeAll(platform.getPersistencePrefix());
+ });
+
+ event.on("StorageUpdatedEvent", function () {
+ _updatePreferencesView();
+ });
+
+ _updatePreferencesView();
+ }
};
});
-define('ripple/platform/ivi/3.0/WebAPIException', function (require, exports, module) {
+define('ripple/ui/plugins/messagePort', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2014 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var errorcode = require('ripple/platform/ivi/3.0/errorcode');
-
-var msg = {
- 1: "Permission denied.",
- 2: "Unsupported property.",
- 3: "Timeout.",
- 10: "Unknown."
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ exception = require('ripple/exception'),
+ dbinit = require('ripple/platform/tizen/2.0/dbinit'),
+ _messagePortGlobal = {
+ localMessagePorts: {}
},
- errType = {
- 1: "PermissionDeniedError",
- 2: "PropertyUnavailableError",
- 3: "TimeoutError",
- 10: "UnknownError"
- };
+ _db = null;
-module.exports = function (code, message, name) {
- var g, c, _code, _message, _name;
+function _initMessagePortDatabase() {
+ _db = dbinit.MessagePort;
- for (c in errorcode) {
- g = errorcode.__lookupGetter__(c);
- if (g) {
- this.__defineGetter__(c, g);
- }
+ db.saveObject("tizen-messageport", _db);
+}
+
+function _initializeMessagePortPanel() {
+ var stop = false;
+
+ _makeRemoteApplicationsHtml();
+ _sendingRemoteMessage();
+ _setSameCertificate();
+
+ try {
+ jQuery("#messagePort-remote-applications h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = true;
+ }
+ });
+ jQuery("#messagePort-remote-applications").accordion("destroy").accordion({
+ header: "> div > h3",
+ active: false,
+ collapsible: true,
+ autoHeight: false
+ });
+ } catch (e) {
+ exception.handle(e, true);
}
+}
- if (typeof code !== 'number') {
- _code = errorcode.UNKNOWN;
- _message = msg[_code];
- _name = errType[_code];
- } else {
- _code = code;
- if (typeof message === 'string') {
- _message = message;
- } else {
- _message = msg[_code];
- }
- if (typeof name === 'string') {
- _name = name;
- } else {
- _name = errType[_code];
- }
+function _addLocalMessagePortOptions(messagePortName) {
+ var htmlTemplate = '<option value="#messagePortName">#messagePortName</option>',
+ option = '', appId, portSelector = [], sendSelector = [];
+
+ for (appId in _db) {
+ portSelector.push("#" + appId + "-local-port");
+ sendSelector.push("#" + appId + "-send");
}
- this.__defineGetter__("code", function () {
- return _code;
- });
- this.__defineGetter__("message", function () {
- return _message;
- });
- this.__defineGetter__("name", function () {
- return _name;
- });
-};
+ option += htmlTemplate.replace(/#messagePortName/g, messagePortName);
-});
-define('ripple/platform/ivi/3.0/dbinit', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ jQuery(portSelector.join(",")).append(option);
+ jQuery(portSelector.join(",")).removeAttr("disabled");
+ jQuery(sendSelector.join(",")).removeAttr("disabled");
+}
-var exception = require('ripple/exception'),
- DBBuilder,
- _data = {
- dbBuilder: null
- },
- _self = {};
+function _makeRemoteApplicationsHtml() {
+ var htmlTemplate = jQuery("#messagePort-remote-template").html(),
+ portHtmlTemplate = '<h3><span style="font-weight: bold;">#isTrustedIcon</span> #messagePortName</h3>' +
+ '<div class="#portContainterAddr" style="border: 1px solid #DCDCDC; height: 10em; overflow: auto; border-radius: 8px;"></div>',
+ appId, appName, portName, abbr, isTrusted, html = '', portHtml, tabSelectors = [];
-function _initialize() {
- _data.dbBuilder = new DBBuilder();
+ for (appId in _db) {
+ appName = _db[appId].name;
- _data.dbBuilder.register("Vehicle", "dbvehicle.json");
-}
+ portHtml = '';
+ for (portName in _db[appId].ports) {
+ isTrusted = _db[appId].ports[portName];
+ abbr = portName.replace(/\s+/g, "");
-DBBuilder = function () {
- var self;
+ portHtml += portHtmlTemplate.replace(/#messagePortName/g, portName)
+ .replace(/#RemoteApplicationId/g, appId)
+ .replace(/#isTrustedIcon/g, isTrusted ? "Ⓣ" : "◯")
+ .replace(/#portContainterAddr/g, abbr);
+ }
- // private
- function formatString(str) {
- return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, "");
+ tabSelectors.push("#" + appId + "-operations");
+
+ html += htmlTemplate.replace(/#RemoteApplicationId/g, appId)
+ .replace(/#RemoteApplicationName/g, appName)
+ .replace(/#RemoteApplicationPortHtml/g, portHtml);
}
- // private
- function formatHex(str) {
- return str.replace(/,(0x[0-9a-fA-F]+?),/g, ',"$1",');
+ jQuery("#messagePort-remote-applications").html(html);
+
+ jQuery(tabSelectors.join(",")).tabs();
+}
+
+function _sendingRemoteMessage() {
+ var appId, sendSelector = [], clearSelector = [];
+
+ for (appId in _db) {
+ sendSelector.push("#" + appId + "-send");
+ clearSelector.push("#" + appId + "-clear");
}
- // public
- function register(type, dbFile, Extension) {
- _data[type] = Extension ? new Extension() : {};
+ jQuery(sendSelector.join(",")).bind("click", function () {
+ var appId = this.id.replace("-send", ""),
+ key = jQuery("#" + appId + "-key").val(),
+ value = jQuery("#" + appId + "-value").val(),
+ data, remotePort, errorHtml,
+ messagePortName = jQuery("#" + appId + "-local-port").val(),
+ certificate = _db[appId].certificate;
- if (!dbFile)
+ data = [{
+ key: key,
+ value: value
+ }];
+ remotePort = {
+ appId: appId,
+ messagePortName: messagePortName,
+ isTrusted: false
+ };
+ jQuery("#" + appId + "-key").val("");
+ jQuery("#" + appId + "-value").val("");
+
+ if (!certificate && _messagePortGlobal.localMessagePorts[messagePortName]) {
+ errorHtml = 'Access Denied: "' + messagePortName + '" is a trusted port ' +
+ 'and the target application is signed with the different certification ' +
+ 'from this application.';
+ jQuery("#" + appId + "-access").html(errorHtml);
+ jQuery("#" + appId + "-access").show();
+ window.setTimeout(function () {
+ jQuery("#" + appId + "-access").hide();
+ }, 5000);
return;
+ }
- _self.__defineGetter__(type, function () {
- var fnInit;
+ event.trigger("LocalMessagePortReceived", [data, remotePort, false]);
+ });
- if (!_data[type].db) {
- fnInit = _data[type].initdb || initdb;
- _data[type].db = fnInit(dbFile);
- }
+ jQuery(clearSelector.join(",")).bind("click", function () {
+ var appId = this.id.replace("-clear", "");
- return _data[type].db;
- });
+ jQuery("#" + appId + "-key").val("");
+ jQuery("#" + appId + "-value").val("");
+ });
+}
+
+function _setSameCertificate(){
+ var appId, certificateSelector = [];
+
+ for (appId in _db) {
+ certificateSelector.push("#" + appId + "-isTrusted");
}
- function initdb(dbFile) {
- var xmlHttp, res;
+ jQuery(certificateSelector.join(",")).bind("change", function () {
+ var appId = this.id.replace("-isTrusted", "");
- try {
- xmlHttp = new XMLHttpRequest();
- xmlHttp.open("GET", "dbsamples/" + dbFile, false);
- xmlHttp.send();
- } catch (e) {
- exception.handle(e);
- }
+ _db[appId].certificate = this.checked ? true : false;
- if (!xmlHttp.responseText) {
- return null;
- }
+ db.saveObject("tizen-messageport", _db);
+ });
+}
- res = formatHex(formatString(xmlHttp.responseText));
+function _showRequestMessagePort(id, messagePortName, isTrusted, isRemote, appId) {
+ var htmlTemplate, port, html, remoteKey;
- return JSON.parse(res);
+ htmlTemplate = '<h3><span style="font-weight: bold;">#isTrustedIcon</span> #messagePortName</h3>';
+
+ if (isRemote) {
+ remoteKey = messagePortName + " (=>" + appId + ")";
+ html = htmlTemplate.replace("#messagePortName", remoteKey)
+ .replace("#isTrustedIcon", isTrusted ? "Ⓣ" : "◯");
+ } else {
+ remoteKey = messagePortName;
+ html = htmlTemplate.replace("#messagePortName", remoteKey)
+ .replace("#isTrustedIcon", isTrusted ? "Ⓣ" : "◯");
}
- self = {
- register: register,
- initdb: initdb
- };
+ if (port === undefined) {
+ jQuery(id).append(html);
- return self;
-};
+ if (!isRemote) {
+ _addLocalMessagePortOptions(remoteKey);
+ }
+ }
+}
-_initialize();
+/**
+ * receive sending message from current application and show content
+ * @param remoteMessagePort
+ * @param data
+ * @param localMessagePort
+ * @private
+ */
+function _receiveMessage(remoteMessagePort, data, localMessagePort) {
+ var htmlTemplate, header, footer, html = '', i, appId, messagePortName, selector,
+ remotePort;
-module.exports = _self;
+ appId = remoteMessagePort.appId;
+ messagePortName = remoteMessagePort.messagePortName;
-});
-define('ripple/platform/ivi/3.0/errorcode', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ selector = "#" + appId + "-receiving ." + messagePortName.replace(/\s+/g, "");
-var _self = {};
+ header = '<table class="preferences-table" style="border-bottom: 1px dashed #DCDCDC; width: 100%;">';
+ htmlTemplate = '<tr><td><label class="ui-text-label">Key:</label></td><td>#Key</td></tr>' +
+ '<tr><td><label class="ui-text-label">Value:</label></td><td>#Value</td></tr>';
+ footer = '</table>';
-_self.__defineGetter__("PERMISSION_DENIED", function () {
- return 1;
-});
+ for (i = 0; i < data.length; i++) {
+ html += header +
+ htmlTemplate.replace("#Key", data[i].key).replace("#Value", data[i].value) +
+ footer;
+ }
-_self.__defineGetter__("PROPERTY_UNAVAILABLE", function () {
- return 2;
+ jQuery(selector).html(html);
+
+ if (!localMessagePort) return;
+
+ remotePort = {
+ appId: appId,
+ messagePortName: localMessagePort.messagePortName,
+ isTrusted: localMessagePort.isTrusted
+ };
+
+ event.trigger("LocalMessagePortReceived", [_db[appId]["reply"], remotePort, true]);
+}
+
+//show requested local message port
+event.on("LocalMessagePortAdded", function (messagePortName, isTrusted) {
+ _showRequestMessagePort("#current-app-local-port", messagePortName, isTrusted, false);
});
-_self.__defineGetter__("TIMEOUT", function () {
- return 3;
+//show requested remote message port
+event.on("RemoteMessagePortAdded", function (appId, messagePortName, isTrusted) {
+ _showRequestMessagePort("#current-app-remote-port", messagePortName, isTrusted, true, appId);
});
-_self.__defineGetter__("UNKNOWN", function () {
- return 10;
+//show sending message content
+event.on("RemoteMessagePortSent", function (remoteMessagePort, data, localMessagePort) {
+ _receiveMessage(remoteMessagePort, data, localMessagePort);
});
-module.exports = _self;
+module.exports = {
+ panel: {
+ domId: "messagePort-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Message Port",
+ display: true
+ },
+ initialize: function () {
+ _initMessagePortDatabase();
+ _initializeMessagePortPanel();
+ }
+};
});
-define('ripple/platform/ivi/3.0/spec/btdevices', function (require, exports, module) {
+define('ripple/ui/plugins/platform', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var constants = require('ripple/constants'),
+ utils = require('ripple/utils'),
+ devices = require('ripple/devices'),
+ platform = require('ripple/platform'),
+ db = require('ripple/db');
-module.exports = {
- "22:33:44:12:34:56": {
- "name": "Tizen Phone",
- "address": "22:33:44:12:34:56",
- "deviceClass": {
- "major": 0x02,
- "majorName": "PHONE",
- "minor": 0x03,
- "minorName": "PHONE_SMARTPHONE",
- "services": [0x0080],
- "servicesName": ["OBJECT_TRANSFER"]
- },
- "isTrusted": false,
- "services": {
- "5bce9431-6c75-32ab-afe0-2ec108a30860" : {
- "name": "Data Exchange",
- "uuid": "5bce9431-6c75-32ab-afe0-2ec108a30860",
- "protocol": "RFCOMM"
- },
- "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
- "name": "Data Transfer",
- "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
- "protocol": "RFCOMM"
- }
- }
- },
- "22:33:44:12:34:88": {
- "name": "Keyboard",
- "address": "22:33:44:12:34:88",
- "deviceClass": {
- "major": 0x05,
- "majorName": "PERIPHERAL",
- "minor": 0x10,
- "minorName": "PERIPHERAL_KEYBOARD",
- "services": [0x0080],
- "servicesName": ["OBJECT_TRANSFER"]
- },
- "isTrusted": true,
- "services": {
- "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
- "name": "Data Exchange",
- "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
- "protocol": "RFCOMM"
- }
- }
- },
- "22:33:44:88:34:58": {
- "name": "Tizen Laptop",
- "address": "22:33:44:88:34:58",
- "deviceClass": {
- "major": 0x01,
- "majorName": "COMPUTER",
- "minor": 0x03,
- "minorName": "COMPUTER_LAPTOP",
- "services": [0x0080],
- "servicesName": ["OBJECT_TRANSFER"]
- },
- "isTrusted": true,
- "services": {
- "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
- "name": "Data Exchange",
- "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
- "protocol": "RFCOMM"
- }
+function _updatePlatformDeviceSelect(platformID, currentDeviceKey) {
+ var devicesSelect = document.getElementById(constants.COMMON.DEVICE_SELECT_ID),
+ listOfSortedDevices = devices.getDevicesForPlatform(platformID)
+ .sort(function (a, b) {
+ return (a.screen.width * a.screen.height) < (b.screen.width * b.screen.height) ? -1 : ((a.screen.width * a.screen.height) > (b.screen.width * b.screen.height) ? 1 : 0);
+ });
+ db.remove("viewport_width");
+ db.remove("viewport_height");
+ db.remove("viewportTag");
+
+ devicesSelect.innerHTML = "";
+ listOfSortedDevices.forEach(function (dev) {
+ var deviceNode = utils.createElement("option", {
+ "innerText": dev.name,
+ "value": dev.id
+ });
+
+ if (currentDeviceKey && deviceNode.value === currentDeviceKey) {
+ deviceNode.selected = true;
}
+
+ devicesSelect.appendChild(deviceNode);
+ });
+
+ if (platformID === "ivi") {
+ jQuery("#configuration-window-save-btn").hide();
+ jQuery("#configuration-window-load-btn").hide();
+
+ jQuery("#item_container :nth-child(2)").hide();
+ jQuery("#item_container :nth-child(3)").hide();
+
+ //jQuery("#hwkeys-panel").hide();
+ }
+ else {
+ jQuery("#configuration-window-save-btn").show();
+ jQuery("#configuration-window-load-btn").show();
+
+ jQuery("#item_container :nth-child(2)").show();
+ jQuery("#item_container :nth-child(3)").show();
+
+ //jQuery("#hwkeys-panel").show();
+ }
+}
+
+function checkResolutionSize(evt) {
+ var query_str, id_str, len;
+ query_str = "#resolution-custom-" + evt.data.msg;
+ id_str = "custom_" + evt.data.msg;
+ len = jQuery(query_str).val();
+ if (len >= 200 && len <= 2000) {
+ db.save(id_str, len);
+ } else {
+ jQuery(query_str).val(db.retrieve(id_str));
+ }
+}
+
+module.exports = {
+ initialize: function () {
+ var currentPlatform = platform.current().id,
+ currentVersion = platform.current().version,
+ platformList = platform.getList(),
+ platformSelect = document.getElementById(constants.COMMON.PLATFORM_SELECT_ID),
+ versionSelect = document.getElementById("version-select"),
+ currentDeviceKey = devices.getCurrentDevice().id,
+ platformNode, versionNode;
+
+ jQuery("#platform-select").bind("change", function () {
+ var newPlatform = jQuery(this).val(),
+ newDevice = jQuery("#device-select").val();
+
+ jQuery(versionSelect).children("option").remove();
+ utils.forEach(platformList, function (platform) {
+ utils.forEach(platform, function (version, versionNumber) {
+ if (newPlatform === version.id) {
+ versionSelect.appendChild(utils.createElement("option", {
+ "innerText": version.text,
+ "value": versionNumber
+ }));
+ }
+ });
+ });
+ _updatePlatformDeviceSelect(newPlatform, newDevice);
+
+ });
+
+ jQuery("#device-select").bind("focus", function () {
+ $('input:radio[name="resolution-type"][value="predefined"]').click();
+ });
+ jQuery("#resolution-custom-width").bind("focus", function () {
+ $('input:radio[name="resolution-type"][value="custom"]').click();
+ });
+ jQuery("#resolution-custom-height").bind("focus", function () {
+ $('input:radio[name="resolution-type"][value="custom"]').click();
+ });
+ jQuery("#resolution-custom-width").bind("change", {msg: "width"}, checkResolutionSize);
+ jQuery("#resolution-custom-height").bind("change", {msg: "height"}, checkResolutionSize);
+
+ utils.forEach(platformList, function (platform, platformKey) {
+ platformNode = utils.createElement("option", {
+ "innerText": platformKey === "tizen" ? "mobile": platformKey,
+ "value": platformKey
+ });
+
+ utils.forEach(platform, function (version, versionNumber) {
+ versionNode = utils.createElement("option", {
+ "innerText": version.text,
+ "value": versionNumber
+ });
+
+ if (currentPlatform && version.id === currentPlatform) {
+ versionSelect.appendChild(versionNode);
+ if (currentVersion && currentVersion === versionNumber) {
+ platformNode.selected = true;
+ versionNode.selected = true;
+ }
+ }
+ });
+ platformSelect.appendChild(platformNode);
+ });
+
+ _updatePlatformDeviceSelect(currentPlatform, currentDeviceKey);
}
};
});
-define('ripple/platform/ivi/3.0/spec/config', function (require, exports, module) {
+define('ripple/ui/plugins/geoView', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
- * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
+var constants = require('ripple/constants'),
+ geo = require('ripple/geo'),
db = require('ripple/db'),
- constants = require('ripple/constants');
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ platform = require('ripple/platform'),
+ markers,
+ _gpsMapZoomLevel,
+ _routePoints = [],
+ _routes = [],
+ _routeMarkers,
+ _lineLayer,
+ _drawLineTimeout,
+ _playFrequency = 0,
+ _originalNavigator = window.navigator,
+ _locationSharing = false;
+ _playState = {'play': false, 'replay': false};
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- // no xmlns:JIL in wac 2.0 spec
- valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
+function _initTimeZone() {
+ var allTZ, dbTZ, node = jQuery("#time-locale-select"),
+ timezone = require('ripple/platform/tizen/2.0/timezone_info'),
+ alarms, time;
- return valid;
- },
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
+ function triggerAlarm() {
+ time = new Date();
+ alarms = db.retrieveObject("tizen1.0-db-alarms");
+ if (alarms !== null) {
+ utils.forEach(alarms, function (obj) {
+ if (obj.id !== undefined) {
+ event.trigger("CheckAlarm", [obj.id]);
+ }
+ });
}
+ }
+ window.setInterval(triggerAlarm, 1000);
- var widgetInfo = {},
- configFeatures,
- configPreferences,
- preferenceName,
- platform, rst, i, j,
- settingRst = {
- 'screen-orientation': 'portrait',
- 'context-menu': 'enable',
- 'background-support': 'disable',
- encryption: 'disable',
- 'install-location': 'auto',
- 'hwkey-event': 'enable'
- };
+ allTZ = timezone.getAllTimezone();
+ utils.forEach(allTZ, function (tz) {
+ node.append(utils.createElement("option", {
+ "value": tz,
+ "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
+ }));
+ });
+ dbTZ = db.retrieve("tizen-timezone");
+ if (timezone.isValidTimezone(dbTZ)) {
+ node.val(dbTZ);
+ } else {
+ db.save("tizen-timezone", node.val());
+ }
+ node.bind("change", function () {
+ db.save("tizen-timezone", node.val());
+ });
+}
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
- if (configValidationObject.widget.children.application.validationResult[0].valid) {
- widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
- widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
- }
+function _updateGpsMap() {
+ var positionInfo = geo.getPositionInfo(),
+ mapContainer = document.getElementById(constants.GEO.OPTIONS.MAP_CONTAINER);
- widgetInfo.features = {};
+ if (mapContainer && jQuery(mapContainer).is(':visible')) {
+ geo.map.setCenter(new OpenLayers.LonLat(positionInfo.longitude, positionInfo.latitude).transform(
+ new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel, true);
+ }
- if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
- rst = configValidationObject.widget.children.setting.validationResult;
- // the first one has higher priority per platform implementation
- for (i = rst.length -1 ; i >= 0; i--) {
- if (rst[i].valid === true) {
- for (j in rst[i].attributes) {
- if (rst[i].attributes[j].value !== undefined) {
- settingRst[j] = rst[i].attributes[j].value;
- }
- }
- }
- }
- db.save("layout", settingRst["screen-orientation"]);
+ if (_lineLayer) {
+ geo.map.removeLayer(_lineLayer);
+ geo.map.addLayer(_lineLayer);
+ }
+}
+
+function _updateGpsMapZoom(goUp) {
+ if (goUp && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) {
+ _gpsMapZoomLevel++;
+ }
+ else if (!goUp && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN) {
+ _gpsMapZoomLevel--;
+ }
+
+ _updateGpsMap();
+ db.save(constants.GEO.MAP_ZOOM_KEY, _gpsMapZoomLevel);
+}
+
+function _getTextHeading(heading) {
+ if (heading >= 337.5 || (heading >= 0 && heading <= 22.5)) {
+ return 'N';
+ }
+
+ if (heading >= 22.5 && heading <= 67.5) {
+ return 'NE';
+ }
+
+ if (heading >= 67.5 && heading <= 112.5) {
+ return 'E';
+ }
+ if (heading >= 112.5 && heading <= 157.5) {
+ return 'SE';
+ }
+
+ if (heading >= 157.5 && heading <= 202.5) {
+ return 'S';
+ }
+
+ if (heading >= 202.5 && heading <= 247.5) {
+ return 'SW';
+ }
+
+ if (heading >= 247.5 && heading <= 292.5) {
+ return 'W';
+ }
+
+ if (heading >= 292.5 && heading <= 337.5) {
+ return 'NW';
+ }
+}
+
+function _updateRoutes() {
+ var i, j, k, lon_step, lat_step;
+ _routes = [];
+
+ for (i = 0; i < _routePoints.length - 1; i++) {
+ lon_step = (_routePoints[i + 1].lonlat.lon - _routePoints[i].lonlat.lon) / 50;
+ lat_step = (_routePoints[i + 1].lonlat.lat - _routePoints[i].lonlat.lat) / 50;
+
+ _routes.push(new OpenLayers.LonLat(_routePoints[i].lonlat.lon, _routePoints[i].lonlat.lat));
+ for (j = 1, k = _routes.length; j < 50; j++, k++) {
+ _routes.push(new OpenLayers.LonLat(_routes[k - 1].lon + lon_step, _routes[k - 1].lat + lat_step));
}
+ }
+ _routes.push(new OpenLayers.LonLat(
+ _routePoints[_routePoints.length - 1].lonlat.lon,
+ _routePoints[_routePoints.length - 1].lonlat.lat)
+ );
+}
- configFeatures = configValidationObject.widget.children.feature.validationResult;
- utils.forEach(configFeatures, function (f) {
- if (f.valid === true) {
- var feature = {id: f.attributes.name.value,
- required: f.attributes.required.valid};
- widgetInfo.features[feature.id] = feature;
- }
+function _drawLine(array) {
+ var GEO_OPTIONS = constants.GEO.OPTIONS,
+ latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
+ longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
+ lonlat = new OpenLayers.LonLat(array[0].lon, array[0].lat).transform(
+ new OpenLayers.Projection("EPSG:900913"),
+ new OpenLayers.Projection("EPSG:4326")
+ ),
+ points = new Array(
+ new OpenLayers.Geometry.Point(array[0].lon, array[0].lat),
+ new OpenLayers.Geometry.Point(array[1].lon, array[1].lat)
+ ),
+ line = new OpenLayers.Geometry.LineString(points),
+ style = {
+ strokeColor: '#0000ff',
+ strokeOpacity: 1,
+ strokeWidth: 3
+ },
+ lineFeature = new OpenLayers.Feature.Vector(line, null, style);
+
+ if (!_lineLayer) {
+ _lineLayer = new OpenLayers.Layer.Vector("Line Layer");
+ geo.map.addLayer(_lineLayer);
+ }
+
+ _lineLayer.addFeatures([lineFeature]);
+ longitude.value = lonlat.lon;
+ latitude.value = lonlat.lat;
+
+ if (_playFrequency % 10 === 0) {
+ geo.map.panTo(new OpenLayers.LonLat(array[0].lon, array[0].lat), _gpsMapZoomLevel);
+ }
+ _playFrequency++;
+}
+
+function clearRoute() {
+ if (!_playState.play) {
+ _routePoints.forEach(function (item) {
+ _routeMarkers.removeMarker(item.marker);
});
+ _routePoints = [];
+ _routes = [];
+ _lineLayer.removeFeatures(_lineLayer.features);
+ }
+}
- widgetInfo.preferences = {};
+function setRoute() {
+ var clickHandler = new OpenLayers.Handler.Click(
+ this,
+ {
+ click: function (e) {
+ if (geo.map.calculateBounds(null, 1) === null) {
+ geo.map.zoomTo(geo.map.zoom);
+ }
+ var location = geo.map.getLonLatFromViewPortPx(e.xy),
+ size = new OpenLayers.Size(21, 25),
+ offset = new OpenLayers.Pixel(-(size.w / 2), -size.h),
+ icon = new OpenLayers.Icon('images/map_marker.png', size, offset),
+ marker = new OpenLayers.Marker(new OpenLayers.LonLat(location.lon, location.lat), icon);
- configPreferences = configValidationObject.widget.children.preference.validationResult;
+ geo.map.addLayer(_routeMarkers);
+ _routeMarkers.addMarker(marker);
+ _routePoints.push({
+ lonlat : location,
+ marker : marker
+ });
+ }
+ },
+ {double: true}
+ );
+ clickHandler.dblclick = function () {
+ _updateRoutes();
+ this.deactivate();
+ };
- platform = require('ripple/platform');
- utils.forEach(configPreferences, function (preference) {
- preferenceName = preference.attributes.name.value;
- if (preferenceName) {
- widgetInfo.preferences[preferenceName] = {
- "key": preferenceName,
- "value": preference.attributes.value.value || "",
- "readonly": preference.attributes.readonly.value === "true"
- };
+ if (!_playState.play) {
+ clickHandler.setMap(geo.map);
+ clickHandler.activate();
+ }
+}
- db.save(preferenceName,
- widgetInfo.preferences[preferenceName].value,
- platform.getPersistencePrefix(widgetInfo.id));
+function playRoute() {
+ var speed = document.getElementById("play-route-speed"),
+ getPlaySpeed = function () {
+ return 20 / speed.value * 1000 / 50;
+ },
+ draw = function () {
+ if (_routes.length <= 1) {
+ window.clearTimeout(_drawLineTimeout);
+ geo.map.panTo(new OpenLayers.LonLat(
+ _routePoints[_routePoints.length - 1].lonlat.lon,
+ _routePoints[_routePoints.length - 1].lonlat.lat),
+ _gpsMapZoomLevel);
+ _playState.play = false;
+ _playState.replay = true;
+ document.getElementById('play-btn-icon').src = "images/play.png";
+ } else {
+ _drawLine(_routes);
+ _routes.splice(0, 1);
+ _drawLineTimeout = window.setTimeout(draw, getPlaySpeed());
}
- });
+ };
- return widgetInfo;
+ if (!_playState.play && _routes.length !== 0) {
+ if (_lineLayer && _playState.replay) {
+ _lineLayer.removeFeatures(_lineLayer.features);
+ _updateRoutes();
+ }
+ draw();
+ _playState.play = true;
+ document.getElementById('play-btn-icon').src = "images/pause.png";
+ } else if (_playState.play) {
+ window.clearTimeout(_drawLineTimeout);
+ _playState.play = false;
+ _playState.replay = false;
+ document.getElementById('play-btn-icon').src = "images/play.png";
+ }
+}
+
+function skipTo(position) {
+ if (_routes.length !== 0) {
+ var index = (position === 'start' ? 0 : _routePoints.length - 1);
+ window.clearTimeout(_drawLineTimeout);
+ _lineLayer.removeFeatures(_lineLayer.features);
+ geo.map.panTo(new OpenLayers.LonLat(_routePoints[index].lonlat.lon, _routePoints[index].lonlat.lat), _gpsMapZoomLevel);
+ _routes = [];
+ _updateRoutes();
+ _playFrequency = 0;
+ _playState.play = false;
+ _playState.replay = false;
+ document.getElementById('play-btn-icon').src = "images/play.png";
+ }
+}
+
+module.exports = {
+ panel: {
+ domId: "gps-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Geolocation",
+ display: true
},
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:tizen": {
- attributeName: "xmlns:tizen",
- required: false,
- type: "list",
- listValues: ["http://tizen.org/ns/widgets"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
- },
- defaultlocale: {
- attributeName: "defaultlocale",
- required: false,
- type: "iso-language"
- }
+ initialize: function () {
+ var GEO_OPTIONS = constants.GEO.OPTIONS,
+ positionInfo = geo.getPositionInfo(),
+ positionEvent = "PositionInfoUpdatedEvent",
+ latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
+ longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
+ altitude = document.getElementById(GEO_OPTIONS.ALTITUDE),
+ accuracy = document.getElementById(GEO_OPTIONS.ACCURACY),
+ altitudeAccuracy = document.getElementById(GEO_OPTIONS.ALTITUDE_ACCURACY),
+ heading = document.getElementById(GEO_OPTIONS.HEADING),
+ speed = document.getElementById(GEO_OPTIONS.SPEED),
+ cellID = document.getElementById(GEO_OPTIONS.CELL_ID),
+ delay = document.getElementById(GEO_OPTIONS.DELAY),
+ delayLabel = document.getElementById(GEO_OPTIONS.DELAY_LABEL),
+ headingLabel = document.getElementById(GEO_OPTIONS.HEADING_LABEL),
+ headingMapLabel = document.getElementById(GEO_OPTIONS.HEADING_MAP_LABEL),
+ timeout = document.getElementById(GEO_OPTIONS.TIMEOUT),
+ gpxMultiplier = document.getElementById(GEO_OPTIONS.GPXMULTIPLIER),
+ gpxReplayStatus = document.getElementById(GEO_OPTIONS.GPXREPLAYSTATUS),
+ gpxGo = $(document.getElementById(GEO_OPTIONS.GPXGO)).find("span")[0],
+ mapContainer = document.getElementById(GEO_OPTIONS.MAP_CONTAINER),
+ map = null,
+ track = [],
+ _replayingGpxFile = false,
+ _haltGpxReplay = false;
+
+ function updateGeo() {
+ if (parseFloat(latitude.value) > 90)
+ latitude.value = 90;
+ else if (parseFloat(latitude.value) < -90)
+ latitude.value = -90;
+
+ if (parseFloat(longitude.value) > 180)
+ longitude.value = 180;
+ else if (parseFloat(longitude.value) < -180)
+ longitude.value = -180;
+
+ geo.updatePositionInfo({
+ latitude: parseFloat(latitude.value),
+ longitude: parseFloat(longitude.value),
+ altitude: parseInt(altitude.value, 10),
+ accuracy: parseInt(accuracy.value, 10),
+ altitudeAccuracy: parseInt(altitudeAccuracy.value, 10),
+ heading: heading.value ? parseFloat(heading.value) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
+ speed: speed.value ? parseInt(speed.value, 10) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
+ cellID: cellID.value,
+ timeStamp: new Date()
},
- children: {
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- "short": {
- attributeName: "short",
- required: false,
- type: "string"
+ delay.value,
+ timeout.checked);
+ }
+
+ function updateHeadingValues() {
+ var headingDeg = parseFloat(heading.value),
+ headingText = _getTextHeading(parseFloat(heading.value));
+
+ headingLabel.innerText = headingText;
+ headingMapLabel.innerHTML = headingText + "</br>" + headingDeg + "°";
+ }
+
+ function updateValsFromMap() {
+ var center = geo.map.getCenter().transform(
+ new OpenLayers.Projection("EPSG:900913"),
+ new OpenLayers.Projection("EPSG:4326"));
+ longitude.value = center.lon;
+ latitude.value = center.lat;
+ updateGeo();
+ }
+
+ function initializeValues() {
+ latitude.value = positionInfo.latitude;
+ longitude.value = positionInfo.longitude;
+ altitude.value = positionInfo.altitude;
+ accuracy.value = positionInfo.accuracy;
+ altitudeAccuracy.value = positionInfo.altitudeAccuracy;
+ cellID.value = positionInfo.cellID;
+ delay.value = document.getElementById(GEO_OPTIONS.DELAY_LABEL).innerText = geo.delay || 0;
+ if (geo.timeout) {
+ timeout.checked = true;
+ }
+ updateHeadingValues();
+ }
+
+ function initMap() {
+ var marker, clickHandler;
+ // override image location so we don't have to include image assets
+ OpenLayers.ImgPath = 'http://openlayers.org/api/img/';
+
+ // init map
+ geo.map = new OpenLayers.Map(mapContainer, { controls: [] });
+
+ // add controls and OSM map layer
+ geo.map.addLayer(new OpenLayers.Layer.OSM());
+ geo.map.addControl(new OpenLayers.Control.Navigation());
+
+ // override behaviour of click to pan and double click to zoom in
+ clickHandler = new OpenLayers.Handler.Click(
+ this,
+ {
+ click: function (e) {
+ if (geo.map.calculateBounds(null, 1) === null) {
+ geo.map.zoomTo(geo.map.zoom);
}
+ var location = geo.map.getLonLatFromViewPortPx(e.xy);
+ geo.map.panTo(new OpenLayers.LonLat(location.lon, location.lat), _gpsMapZoomLevel);
},
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
+
+ dblclick: function () {
+ _updateGpsMapZoom(true);
}
},
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
+ {double: true}
+ );
+
+ // add click handler to map
+ clickHandler.setMap(geo.map);
+ clickHandler.activate();
+
+ // update long and lat when map is panned
+ geo.map.events.register("moveend", map, function () {
+ updateValsFromMap();
+ });
+ geo.map.events.register("zoomend", map, function (obj) {
+ if ((obj.object.zoom > _gpsMapZoomLevel && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) ||
+ (obj.object.zoom < _gpsMapZoomLevel && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN)) {
+ _gpsMapZoomLevel = obj.object.zoom;
+ }
+ });
+
+ markers = new OpenLayers.Layer.Markers("markers");
+ _routeMarkers = new OpenLayers.Layer.Markers("markers");
+ geo.map.addLayer(markers);
+
+ event.on("ApplicationState", function (obj) {
+ if (obj && obj[0].id === 'gps-container' && obj.hasClass('ui-box-open')) {
+ _updateGpsMap();
+
+ // Update the position if user accept location sharing
+ if (_locationSharing === false) {
+ _originalNavigator.geolocation.getCurrentPosition(function(geoPosition) {
+ geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
+ new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
+ _locationSharing = true;
+ });
}
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- required: false,
- type: "regex",
- regex: constants.REGEX.URL
- },
- email: {
- attributeName: "email",
- required: false,
- type: "regex",
- regex: constants.REGEX.EMAIL
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
+
+ // Simulator is loaded with geo panel folded, now it's the first time it's unfolded
+ if (!marker) {
+ // Only when the geo panel is unfolded, getCenter() will go well
+ marker = new OpenLayers.Marker(geo.map.getCenter(),
+ new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
+ markers.addMarker(marker);
+
+ navigator.geolocation.getCurrentPosition(function (geoPosition) {
+ geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
+ new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
+ });
}
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
+ }
+ });
+ _updateGpsMap();
+
+ // Simulator is loaded with geo panel unfolded
+ if (mapContainer && jQuery(mapContainer).is(':visible')) {
+ marker = new OpenLayers.Marker(geo.map.getCenter(),
+ new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
+ markers.addMarker(marker);
+
+ navigator.geolocation.getCurrentPosition(function (geoPosition) {
+ geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
+ new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
+ _locationSharing = true;
+ });
+ }
+
+ geo.map.events.register("move", map, function () {
+ markers.clearMarkers();
+ marker = new OpenLayers.Marker(geo.map.getCenter(),
+ new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
+ markers.addMarker(marker);
+ });
+ }
+
+ function loadGpxFile(win, fail, args) {
+ var reader = new FileReader(),
+ file = args[0],
+ _xml,
+ t,
+ att,
+ lastAtt,
+ _ele,
+ _timestamp,
+ _lastTimestamp,
+ _useTimestamp = new Date().getTime(),
+ _tempTimestamp,
+ _tempPosition,
+ _lastPosition,
+ _useLastTimestamp,
+ _heading = 0,
+ _speed = 0,
+ _dist = 0,
+ navUtils = new utils.navHelper();
+
+ reader.onload = function (e) {
+ _xml = e.target.result;
+ t = $(_xml).find('trkpt');
+
+ track = [];
+
+ utils.forEach(t, function (p, i) {
+ if (!isNaN(i)) {
+ att = t[i].attributes;
+ lastAtt = t[i - 1] ? t[i - 1].attributes : {};
+ _ele = $(t[i]).find("ele")[0];
+ _timestamp = $(t[i]).find("time")[0];
+ _lastTimestamp = $(t[i - 1]).find("time")[0];
+
+ if (_timestamp) {
+ //files recorded with endomondo and others have timestamps, this is not a route plan but a record of a track
+ _useTimestamp = new Date(_timestamp.innerText).getTime();
}
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
+
+ if (t[i - 1]) {
+ _dist = navUtils.getDistance(att["lat"].value, att["lon"].value, lastAtt["lat"].value, lastAtt["lon"].value);
+
+ if (_lastTimestamp) {
+ _useLastTimestamp = new Date(_lastTimestamp.innerText).getTime();
+ }
+ else {
+ //routes from YOURS come in as tracks (rather than routes under the GPX schema), but with no timestamps. This is a route.
+ _useLastTimestamp = _useTimestamp;
+ _useTimestamp += Math.round(_dist / 22.2222 * 1000); //80km/h in m/s
+ }
+
+ _heading = navUtils.getHeading(lastAtt["lat"].value, lastAtt["lon"].value, att["lat"].value, att["lon"].value);
+ _speed = (_dist / ((_useTimestamp - _useLastTimestamp) / 1000)).toFixed(2);
+
+ if (!_lastTimestamp) {
+ //on YOURS routes, make sure we have at least one update a second
+ _tempTimestamp = _useLastTimestamp;
+
+ while (_useTimestamp - _tempTimestamp > 1000) {
+ _tempTimestamp += 1000;
+ _lastPosition = track[track.length - 1].coords;
+ _tempPosition = navUtils.simulateTravel(_lastPosition.latitude, _lastPosition.longitude, _heading, _speed);
+ track.push({
+ coords: {
+ latitude: _tempPosition.latitude,
+ longitude: _tempPosition.longitude,
+ altitude: _ele ? _ele.innerText : 0,
+ accuracy: 150,
+ altitudeAccuracy: 80,
+ heading: _heading,
+ speed: _speed
+ },
+ timestamp: _tempTimestamp
+ });
}
}
}
+
+ track.push({
+ coords: {
+ latitude: att["lat"].value,
+ longitude: att["lon"].value,
+ altitude: _ele ? _ele.innerText : 0,
+ accuracy: 150,
+ altitudeAccuracy: 80,
+ heading: _heading,
+ speed: _speed
+ },
+ timestamp: _useTimestamp
+ });
}
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- encoding: {
- attributeName: "encoding",
- required: false,
- type: "string"
- },
- type: {
- attributeName: "type",
- required: false,
- type: "string"
- }
- }
- },
- setting: {
- nodeName: "tizen:setting",
- required: false,
- occurrence: 0,
- attributes: {
- 'screen-orientation': {
- attributeName: "screen-orientation",
- required: false,
- type: "list",
- listValues: ['portrait', 'landscape', 'auto']
- },
- 'context-menu': {
- attributeName: "context-menu",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'background-support': {
- attributeName: "background-support",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'encryption': {
- attributeName: "encryption",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'install-location': {
- attributeName: "install-location",
- required: false,
- type: "list",
- listValues: ['auto', 'internal-only', 'perfer-external']
- },
- 'hwkey-event': {
- attributeName: "hwkey-event",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- }
+ });
+ };
+ reader.onerror = function (e) {
+ fail(e);
+ };
+ reader.readAsText(file.target.files[0], "UTF-8");
+ }
+
+ function replayGpxTrack() {
+ if (_replayingGpxFile) {
+ _haltGpxReplay = true;
+ gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
+ }
+ else {
+ if (track.length > 0) {
+ _haltGpxReplay = false;
+ gpxGo.innerText = constants.GEO.GPXGO_LABELS.STOP;
+
+ latitude.value = track[0].coords.latitude;
+ longitude.value = track[0].coords.longitude;
+ altitude.value = track[0].coords.altitude;
+ accuracy.value = track[0].coords.accuracy;
+ altitudeAccuracy.value = track[0].coords.altitudeAccuracy;
+ heading.value = track[0].coords.heading;
+ speed.value = track[0].coords.speed;
+
+ updateGeo();
+ updateHeadingValues();
+ _triggerEvent();
+
+ moveNextGpxTrack(1);
+ }
+ }
+ }
+
+ function moveNextGpxTrack(i)
+ {
+ if (_haltGpxReplay) {
+ _replayingGpxFile = false;
+ _haltGpxReplay = false;
+ console.log("Ripple :: User interrupted replay of GPX file (Aye Captain, answers All Stop.)");
+ }
+ else {
+ _replayingGpxFile = true;
+ var _timeMultiplier = !isNaN(gpxMultiplier.value) ? gpxMultiplier.value : 1,
+ _step = 0,
+ _interval = 0;
+
+ while (_interval < 250) {
+ _step++;
+ if ((i + _step) >= track.length) { break; }
+ _interval = (track[i + _step].timestamp - track[i].timestamp) / _timeMultiplier;
+ }
+
+ gpxReplayStatus.textContent = (_interval / 1000).toFixed(2) + "s (" + (_interval / 1000 * _timeMultiplier).toFixed(2) + "s realtime), " + (i + 1) + " of " + track.length + " (stepping " + _step + " at " + _timeMultiplier + "x)";
+
+ setTimeout(function () {
+ latitude.value = track[i].coords.latitude;
+ longitude.value = track[i].coords.longitude;
+ altitude.value = track[i].coords.altitude;
+ accuracy.value = track[i].coords.accuracy;
+ altitudeAccuracy.value = track[i].coords.altitudeAccuracy;
+ heading.value = track[i].coords.heading;
+ speed.value = track[i].coords.speed;
+
+ updateGeo();
+ updateHeadingValues();
+ _triggerEvent();
+
+ if (track[i + _step]) {
+ moveNextGpxTrack(i + _step);
}
- },
- application: {
- nodeName: "tizen:application",
- required: true,
- occurrence: 1,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- },
- required_version: {
- attributeName: "required_version",
- required: true,
- type: "list",
- listValues: ['1.0', '2.0', '2.1', '2.2']
- },
- package: {
- attributeName: "package",
- required: false,
- type: "string"
+ else {
+ if (i < track.length - 1) {
+ moveNextGpxTrack(track.length - 1);
}
- }
- },
- "tizen:content": {
- nodeName: "tizen:content",
- required: false,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
+ else {
+ _replayingGpxFile = false;
+ gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
+ console.log("Ripple :: Finished replaying GPX file (Arriving at our destination, assuming standard orbit Captain.)");
}
}
- },
- control: {
- nodeName: "tizen:app-control",
- required: false,
- occurrence: 0,
- children: {
- src: {
- nodeName: "tizen:src",
- required: true,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- operation: {
- nodeName: "tizen:operation",
- required: true,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- uri: {
- nodeName: "tizen:uri",
- required: false,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- mime: {
- nodeName: "tizen:mime",
- required: false,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- }
- }
- },
- "app-widget": {
- nodeName: "tizen:app-widget",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- },
- primary: {
- attributeName: "primary",
- required: true,
- type: "list",
- listValues: ['true', 'false']
- },
- "auto-launch": {
- attributeName: "auto-launch",
- required: false,
- type: "list",
- listValues: ['true', 'false']
- },
- "update-period": {
- attributeName: "update-period",
- required: false,
- type: "integer"
- }
- },
- children: {
- "box-label": {
- nodeName: "tizen:box-label",
- required: true,
- occurence: 1
- },
- "box-icon": {
- nodeName: "tizen:box-icon",
- required: true,
- occurence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- }
- }
- },
- "box-content": {
- nodeName: "tizen:box-content",
- required: true,
- occurence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- "mouse-event": {
- attributeName: "mouse-event",
- required: false,
- type: "string"
- },
- "touch-event": {
- attributeName: "touch-event",
- required: false,
- type: "string"
- }
- },
- children: {
- "box-size": {
- nodeName: "tizen:box-size",
- required: false,
- occurence: 1,
- attributes: {
- "preview": {
- attributeName: "preview",
- required: false,
- type: "string"
- }
- }
- },
- pd: {
- nodeName: "tizen:pd",
- required: false,
- occurence: 1,
- attributes: {
- "src": {
- attributeName: "src",
- required: true,
- type: "string"
- },
- "width": {
- attributeName: "width",
- required: true,
- type: "integer"
- },
- "height": {
- attributeName: "height",
- required: true,
- type: "integer"
- }
- }
- }
- }
- }
- }
- },
- account: {
- nodeName: "tizen:account",
- required: false,
- occurrence: 0,
- attributes: {
- "multiple-account-support": {
- attributeName: "multiple-account-support",
- required: true,
- type: "list",
- listValues: ['true', 'false']
- }
- },
- children: {
- icon: {
- nodeName: "tizen:icon",
- required: false,
- occurence: 1,
- attributes: {
- section: {
- attributeName: "section",
- required: true,
- type: "string"
- }
- }
- },
- "display-name": {
- nodeName: "tizen:display-name",
- required: false,
- occurence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "string"
- }
- }
- },
- capability: {
- nodeName: "capability",
- required: false,
- occurence: 1
- }
- }
- },
- feature: {
- nodeName: "tizen:privilege",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/TR/battery-status/",
- "http://www.w3.org/TR/geolocation-API/",
- "http://www.w3.org/TR/touch-events/",
- "http://www.w3.org/TR/vibration/",
- "http://tizen.org/privilege/vehicle",
- "http://tizen.org/privilege/tizen"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- },
- children: {
- param: {
- nodeName: "param",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string"
- },
- value: {
- attributeName: "value",
- required: true,
- type: "string"
- }
- }
- }
- }
- },
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string"
- },
- value: {
- type: "string",
- required: false,
- attributeName: "value"
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
- }
+ }, _interval);
}
}
- }
-};
-});
-define('ripple/platform/ivi/3.0/spec/dbvehicle', function (require, exports, module) {
-module.exports = {
- "supported": ["VehicleSpeed", "EngineSpeed", "VehiclePowerMode", "TripMeter",
- "Acceleration", "Transmission", "CruiseControlStatus", "WheelBrake",
- "LightStatus", "InteriorLightStatus", "Horn", "Fuel", "EngineOil",
- "Location", "ExteriorBrightness", "Temperature", "RainSensor",
- "WindshieldWiper", "HVAC", "WindowStatus", "Sunroof", "ConvertibleRoof",
- "VehicleId", "Size", "FuelInfo", "VehicleType", "Doors",
- "TransmissionGearType", "WheelInformation", "Odometer", "Fluid", "Battery",
- "TirePressure", "TireTemperature", "SecurityAlert", "ParkingBrake",
- "ParkingLight", "HazardLight", "AntilockBrakingSystem", "TractionControlSystem",
- "VehicleTopSpeedLimit", "AirbagStatus", "DoorStatus", "SeatBeltStatus",
- "OccupantStatus", "ObstacleDistance", "NightMode", "DrivingMode"],
- "newestHistory": null,
- "currentConfiguration": 0,
- "configurationData": [
- [
- "AFA", //VehicleId => WMI
- "21D1M2883N342FFG7", //VehicleId => VIN
- 2096, //Size => width
- 1860, //Size => height
- 4779, //Size => length
- 0, //FuelInfo => type
- 0, //FuelInfo => refuelPosition
- 0, //VehicleType => type
- [2, 2], //Doors => doorsPerRow
- 0, //TransmissionGearType => transmissionGearType
- 1953, //WheelInformation => frontWheelRadius
- 2000, //WheelInformation => rearWheelRadius
- 1465, //WheelInformation => wheelTrack
- true //WheelInformation => ABS
- ],
- [
- "KMH", "21D1M2888N342FFL7", /**/2125, 1961, 4901, /**/4, 3, /**/4, /**/[2, 2], /**/2,
- /**/1964, 2000, 1470, true
- ]
- ],
- "settingData": [
- 0, //Transmission-gearPosition
- 0, //Transmission-mode
- true, //CruiseControlStatus-activated
- 0, //CruiseControlStatus-speed
- true, //WheelBrake-engaged
- true, //LightStatus-head
- false, //LightStatus-rightTurn
- false, //LightStatus-leftTurn
- false, //LightStatus-brake
- false, //LightStatus-fog
- false, //LightStatus-hazard
- false, //LightStatus-parking
- false, //LightStatus-highBeam
- false, //InteriorLightStatus-passenger
- false, //InteriorLightStatus-driver
- false, //InteriorLightStatus-center
- false, //Horn-horn
- 0, //WindshieldWiper-windshieldWiper
- 0x04, //HVAC-airflowDirection
- 0, //HVAC-airflowDirection
- 0, //HVAC-targetTemperature
- false, //HVAC-airConditioning
- false, //HVAC-airRecirculation
- false, //HVAC-heater
- false, //HVAC-steeringWheelHeater
- false, //HVAC-seatHeater
- false, //HVAC-seatCooler
- 0, //Sunroof-openness
- 0, //Sunroof-tilt
- 0, //ConvertibleRoof-openness
- true, //SecurityAlert-securityAlert
- true, //ParkingBrake-parkingBrake
- true, //ParkingLight-parkingLight
- true, //HazardLight-hazardLight
- true, //AntilockBrakingSystem-antilockBrakingSystem
- true, //TractionControlSystem-TractionControlSystem
- 120, //VehicleTopSpeedLimit-VehicleTopSpeedLimit
- 0, //WindowStatus-openness
- true, //WindowStatus-defrost
- 2, //AirbagStatus-airbagStatus
- 0, //DoorStatus-doorStatus
- true, //DoorStatus-doorLockStatus
- true, //DoorStatus-childLockStatus
- false, //SeatBeltStatus-seatBeltStatus
- 0, //OccupantStatus-occupantStatus
- 10, //ObstacleDistance-obstacleDistance
- false, //NightMode-nightMode
- 0, //DrivingMode-drivingMode
- 0, //Fluid-transmission
- 0, //Fluid-brake
- 0, //Fluid-washer
- 220, //Battery-voltage
- 0.5, //Battery-current
- 0, //TirePressure-leftFront
- 0, //TirePressure-rightFront
- 0, //TirePressure-leftRear
- 0, //TirePressure-rightRear
- 0, //TireTemperature-leftFront
- 0, //TireTemperature-rightFront
- 0, //TireTemperature-leftRear
- 0 //TireTemperature-rightRear
- ],
- "autoRunningData": [
- [
- 0, //VehicleSpeed => vehicleSpeed
- 0, //EngineSpeed => engineSpeed
- 1, //VehiclePowerMode => vehiclePowerMode
- [23, 7876, 124, 4577], //TripMeter => tripMeters
- 0, //Acceleration => x
- 0, //Acceleration => y
- 0, //Acceleration => z
- 87, //Fuel => level
- 251, //Fuel => range
- 250, //Fuel => instantConsumption
- 85, //Fuel => instantEconomy
- 15, //Fuel => averageEconomy
- 0, //EngineOil => remaining
- 0, //EngineOil => temperature
- 0, //EngineOil => pressure
- 0, //Location => latitude
- 0, //Location => longitude
- 0, //Location => altitude
- 0, //Location => direction
- 0, //ExteriorBrightness => exteriorBrightness
- 0, //Temperature => interior
- 0, //Temperature => exterior
- 2, //RainSensor => rainSensor
- 15000 //Odometer => odometer
- ],
- [
- 60, /**/2500, /**/0, /**/[23, 7876, 124, 4577, 10], /**/10, 10, 10, /**/80, 251, 59, 87, 15,
- /**/150, 10, 59, /**/-15, -89, 16, 69, /**/456, /**/45, 45, /**/10, /**/1213
- ],
- [
- 120, /**/2800, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 20, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ],
- [
- 180, /**/3200, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 40, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ],
- [
- 200, /**/3500, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 60, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ],
- [
- 300, /**/3900, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 80, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ],
- [
- 240, /**/3600, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 70, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ],
- [
- 100, /**/2600, /**/1, /**/[23, 7876, 124, 4577, 25], /**/120, 120, 120, /**/65, 251, 59, 87, 15,
- /**/78, 30, 54, /**/-97, -54, 124, 65, /**/45, /**/67, 45, /**/9, /**/250
- ]
- ]
-};
+ // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
+ if (platform.current().id === 'phonegap' ||
+ platform.current().id === 'webworks' ||
+ platform.current().id === 'cordova') {
+ // make the fields visible
+ jQuery("#geo-cellid-container").hide();
+ jQuery("#geo-heading-container").show();
+ jQuery("#geo-speed-container").show();
+ }
+ else {
+ jQuery("#geo-cellid-container").show();
+ jQuery("#geo-heading-container").hide();
+ jQuery("#geo-speed-container").hide();
+ }
-});
-define('ripple/platform/ivi/3.0/spec/device', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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 event = require('ripple/event'),
- utils = require('ripple/utils'),
- StorageTypeTable = {
- "UNKNOWN": "UNKNOWN",
- "INTERNAL": "INTERNAL",
- "MMC": "MMC",
- "USB_HOST": "USB_HOST"
- },
- NetworkTypeTable = {
- "NONE": "NONE",
- "2G": "2G",
- "2.5G": "2.5G",
- "3G": "3G",
- "4G": "4G",
- "WIFI": "WIFI",
- "ETHERNET": "ETHERNET",
- "UNKNOWN": "UNKNOWN"
- },
- LocaleTable = {
- "eng_USA": "eng_USA",
- "eng_CAN": "eng_CAN",
- "deu_DEU": "deu_DEU",
- "jpn_JPN": "jpn_JPN",
- "zho_CHN": "zho_CHN",
- "UNKNOWN": "UNKNOWN"
- },
- SimStateTable = {
- "ABSENT": "ABSENT",
- "INITIALIZING": "INITIALIZING",
- "READY": "READY",
- "PIN_REQUIRED": "PIN_REQUIRED",
- "PUK_REQUIRED":"PUK_REQUIRED",
- "NETWORK_LOCKED": "NETWORK_LOCKED",
- "SIM_LOCKED": "SIM_LOCKED",
- "UNKNOWN": "UNKNOWN"
- };
+ _gpsMapZoomLevel = db.retrieve(constants.GEO.MAP_ZOOM_KEY) || 14;
-function deviceStatusEventTrigger(setting) {
- event.trigger("DeviceStatusChanged", [setting]);
-}
+ jQuery("#geo-map-zoom-decrease").bind("click", function () {
+ _updateGpsMapZoom(false);
+ });
-module.exports = {
- "Config": {
- "vibratingMode": {
- "name": "Vibrator",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("VibratingModeChanged", [setting]);
- }
- },
- "lockScreen": {
- "name": "Lock Screen",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "callback": function (setting) {
- event.trigger("LockScreenChanged", [setting]);
- }
- }
- },
- "DEVICE_ORIENTATION": {
- "status": {
- "name": "Status",
- "control": {
- "type": "label",
- "innertext": "PORTRAIT_PRIMARY",
- "value": "PORTRAIT_PRIMARY"
- },
- "event": "LayoutChanged"
- },
- "isAutoRotation": {
- "name": "Is Auto Rotation",
- "control": {
- "type": "label",
- "value": false
- }
- }
- },
- "CPU": {
- "load": {
- "name": "Load",
- "control": {
- "type": "number",
- "value": 0.1
- },
- "event": "CpuLoadChanged",
- "callback": function (setting) {
- if (setting > 1) setting = 1;
- if (setting < 0) setting = 0;
- event.trigger("CpuLoadChanged", [setting]);
- }
- }
- },
- "STORAGE": {
- "type": {
- "name": "Type",
- "control": {
- "type": "select",
- "value": StorageTypeTable["INTERNAL"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(StorageTypeTable, function (key, value) {
- optionList[key] = StorageTypeTable[value];
- });
+ jQuery("#geo-map-zoom-increase").bind("click", function () {
+ _updateGpsMapZoom(true);
+ });
- return optionList;
- }())
- },
- "capacity": {
- "name": "Capacity(bytes)",
- "control": {
- "type": "label",
- "value": 16000000000
- }
- },
- "availableCapacity": {
- "name": "AvailableCapacity(bytes)",
- "control": {
- "type": "number",
- "value": 12000000000
- },
- "callback": function (setting) {
- event.trigger("AvailCapacityChanged", [setting]);
- }
- },
- "isRemovable": {
- "name": "IsRemovable",
- "control": {
- "type": "checkbox",
- "value": true
- }
- }
- },
- "BUILD": {
- "model": {
- "name": "Model",
- "control": {
- "type": "label",
- "innertext": "tizen-2.2 build",
- "value": "tizen-2.2 build"
- }
- },
- "manufacturer": {
- "name": "Manufacturer",
- "control": {
- "type": "label",
- "innertext": "Tizen",
- "value": "Tizen"
- }
- },
- "buildVersion": {
- "name": "Build Version",
- "control": {
- "type": "label",
- "innertext": "TIZEN_WEB_SIMULATOR_000001",
- "value": "TIZEN_WEB_SIMULATOR_000001"
- }
- }
- },
- "LOCALE": {
- "language": {
- "name": "Language",
- "control": {
- "type": "select",
- "value": LocaleTable["eng_USA"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(LocaleTable, function (key, value) {
- optionList[key] = LocaleTable[value];
- });
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LATITUDE), updateGeo);
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LONGITUDE), updateGeo);
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE), updateGeo);
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ACCURACY), updateGeo);
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE_ACCURACY), updateGeo);
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.CELL_ID), updateGeo);
- return optionList;
- }())
- },
- "country": {
- "name": "Country",
- "control": {
- "type": "select",
- "value": LocaleTable["eng_USA"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(LocaleTable, function (key, value) {
- optionList[key] = LocaleTable[value];
- });
+ jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
+ jQuery("#play-route-speed").bind("change", function () {
+ jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
+ });
+ jQuery("#clear-route-btn").bind("click", function () {
+ clearRoute();
+ });
+ jQuery("#set-route-btn").bind("click", function () {
+ setRoute();
+ });
+ jQuery("#play-route-btn").bind("click", function () {
+ playRoute();
+ });
+ jQuery("#back-route-btn").bind("click", function () {
+ skipTo("start");
+ });
+ jQuery("#forward-route-btn").bind("click", function () {
+ skipTo("end");
+ });
- return optionList;
- }())
- }
- },
- "DISPLAY": {
- "resolutionWidth": {
- "name": "Resolution Width(pixels)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "resolutionHeight": {
- "name": "Resolution Height(pixels)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "dotsPerInchWidth": {
- "name": "DPI-X",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "dotsPerInchHeight": {
- "name": "DPI-Y",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "physicalWidth": {
- "name": "Physical Width(millimeters)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "physicalHeight": {
- "name": "Physical Height(millimeters)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "brightness": {
- "name": "Brightness",
- "control": {
- "type": "number",
- "value": 1
- },
- "event": "DisplayBrightnessChanged",
- "callback": function (setting) {
- if (setting > 1) setting = 1;
- if (setting < 0) setting = 0;
- event.trigger("DisplayBrightnessChanged", [setting]);
- }
+ jQuery("#" + GEO_OPTIONS.DELAY).bind("change", function () {
+ updateGeo();
+ delayLabel.innerText = delay.value;
+ });
+ jQuery("#" + GEO_OPTIONS.TIMEOUT).bind("click", function () {
+ updateGeo();
+ });
+ jQuery("#" + GEO_OPTIONS.GPXFILE).bind("change", function (a) {
+ loadGpxFile(null, null, [a]);
+ });
+ jQuery("#" + GEO_OPTIONS.GPXGO).bind("click", function () {
+ replayGpxTrack();
+ });
+
+ // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
+ if (platform.current().id === 'phonegap' || platform.current().id === 'webworks' || platform.current().id === 'cordova') {
+ jQuery("#" + GEO_OPTIONS.HEADING).bind("change", function () {
+ updateGeo();
+ updateHeadingValues();
+ });
+
+ utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.SPEED), updateGeo);
+ heading.value = positionInfo.heading;
+ speed.value = positionInfo.speed;
}
- },
- "NETWORK": {
- "networkType": {
- "name": "Network Type",
- "control" : {
- "type": "select",
- "value": NetworkTypeTable["NONE"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(NetworkTypeTable, function (key, value) {
- optionList[key] = NetworkTypeTable[value];
- });
- return optionList;
- }())
+ initMap();
+ if (navigator.onLine === false) {
+ jQuery("#disable_geo_panel").show();
}
- },
- "WIFI_NETWORK": {
- "status": {
- "name": "Status",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "event": "WiFiNetworkStatusChanged",
- "callback": function (setting) {
- event.trigger("WiFiNetworkStatusChanged", [setting]);
- }
- },
- "ssid": {
- "name": "SSID",
- "control": {
- "type": "text",
- "value": "Tizen WiFi"
- }
- },
- "ipAddress": {
- "name": "IP Address",
- "control": {
- "type": "text",
- "value": "192.168.0.1"
- }
- },
- "ipv6Address": {
- "name": "IPv6 Address",
- "control": {
- "type": "text",
- "value": "2001:db8:85a3:0:0:0:70:7334"
- }
- },
- "signalStrength": {
- "name": "Signal Strength",
- "control": {
- "type": "select",
- "value": 0
- },
- "options": (function () {
- var i,
- optionList = {};
+ jQuery(window).bind("online", function () {
+ jQuery("#disable_geo_panel").hide();
+ console.log("ONLINE");
+ });
+ jQuery(window).bind("offline", function () {
+ jQuery("#disable_geo_panel").show();
+ console.log("OFFLINE");
+ });
- for (i = 0; i <= 10; i++) {
- optionList[i] = i;
- }
+ initializeValues();
+ _initTimeZone();
- return optionList;
- }())
- }
- },
- "CELLULAR_NETWORK": {
- "status": {
- "name": "Status",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "CellularNetworkStatusChanged",
- "callback": function (setting) {
- event.trigger("CellularNetworkStatusChanged", [setting]);
- }
- },
- "apn": {
- "name": "APN",
- "control": {
- "type": "text",
- "value": "Tizen"
- }
- },
- "ipAddress": {
- "name": "IP Address",
- "control": {
- "type": "text",
- "value": "10.0.2.16"
- }
- },
- "ipv6Address": {
- "name": "IPv6 Address",
- "control": {
- "type": "text",
- "value": "2001:db8:85a3:0:0:0:70:7334"
- }
- },
- "mcc": {
- "name": "MCC",
- "control": {
- "type": "number",
- "value": 460
- }
- },
- "mnc": {
- "name": "MNC",
- "control": {
- "type": "number",
- "value": 0
- }
- },
- "cellId": {
- "name": "Cell ID",
- "control": {
- "type": "number",
- "value": 0
- }
- },
- "lac": {
- "name": "LAC",
- "control": {
- "type": "number",
- "value": 0
- }
- },
- "isRoaming": {
- "name": "Roaming",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "isFlightMode": {
- "name": "Flight Mode",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "callback": function (setting) {
- event.trigger("FlightModeChanged", [setting]);
- }
- },
- "imei": {
- "name": "IMEI",
- "control": {
- "type": "text",
- "value": "012417005203000"
- }
- }
- },
- "SIM": {
- "state": {
- "name": "State",
- "control": {
- "type": "select",
- "value": SimStateTable["READY"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(SimStateTable, function (key, value) {
- optionList[key] = SimStateTable[value];
- });
+ event.on(positionEvent, function () {
+ _updateGpsMap();
+ });
- return optionList;
- }())
- },
- "operatorName": {
- "name": "Operator Name",
- "control": {
- "type": "text",
- "value": "Tizen"
- }
- },
- "msisdn": {
- "name": "MSISDN",
- "control": {
- "type": "text",
- "value": "088123456789"
- }
- },
- "iccid": {
- "name": "ICCID",
- "control": {
- "type": "text",
- "value": "123000MFSSYYGXXXXXXP"
- }
- },
- "mcc": {
- "name": "MCC",
- "control": {
- "type": "number",
- "value": 460
- }
- },
- "mnc": {
- "name": "MNC",
- "control": {
- "type": "number",
- "value": 0
- }
- },
- "msin": {
- "name": "MSIN",
- "control": {
- "type": "text",
- "value": "H1 H2 H3 S 12345"
- }
- },
- "spn": {
- "name": "SPN",
- "control": {
- "type": "text",
- "value": "TizenSPN"
- }
- }
- },
- "PERIPHERAL": {
- "isVideoOutputOn": {
- "name": "Video Output",
- "control": {
- "type": "checkbox",
- "value": false
- }
+ _triggerEvent();
+
+ function _triggerEvent() {
+ event.trigger(positionEvent, [{
+ latitude: latitude.value,
+ longitude: longitude.value,
+ altitude: altitude.value,
+ accuracy: accuracy.value,
+ altitudeAccuracy: altitudeAccuracy.value,
+ heading: heading ? heading.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
+ speed: speed ? speed.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
+ cellID: cellID.value,
+ timeStamp: new Date()
+ }]);
}
}
};
});
-define('ripple/platform/ivi/3.0/spec/sensor', function (require, exports, module) {
+define('ripple/ui/plugins/goodVibrations', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
-
-function sensorStatusEventTrigger(setting) {
- event.trigger("SensorStatusChanged", [setting]);
-}
+var constants = require('ripple/constants');
module.exports = {
- "Accelerometer": {
- "resolution": 0.039239998906850815,
- "minDelay": 20,
- "range": 20.051639556884766,
- "name": "Accelerometer",
- "type": "Accelerometer"
- },
- "MagneticField": {
- "x": {
- "name": "X",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-xChanged", [setting]);
- }
- },
+ vibrateDevice: function (milliseconds) {
+ var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
+ x, times;
- "y": {
- "name": "Y",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-yChanged", [setting]);
- }
- },
+ times = Math.floor(milliseconds / 100);
- "z": {
- "name": "Z",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-zChanged", [setting]);
- }
- },
+ for (x = 1; x <= times; x++) {
+ node.animate({ left: -10 }, 5)
+ .animate({ left: 0 }, 1)
+ .animate({ left: 10 }, 5)
+ .animate({ left: 0 }, 1);
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "MagneticField",
- "type": "MagneticField"
- },
- "Rotation": {
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "Rotation",
- "type": "Rotation"
+ node.animate({ top: -10 }, 5)
+ .animate({ top: 0 }, 1)
+ .animate({ top: 10 }, 5)
+ .animate({ top: 0 }, 1);
+ }
},
- "Orientation": {
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "Orientation",
- "type": "Orientation"
+ shakeDevice: function (times) {
+ var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
+ x;
+
+ for (x = 1; x <= times; x++) {
+ node.animate({ left: -25 }, 50)
+ .animate({ left: 0 }, 30)
+ .animate({ left: 25 }, 50)
+ .animate({ left: 0 }, 30);
+ }
}
};
});
-define('ripple/platform/ivi/3.0/spec/ui', function (require, exports, module) {
+define('ripple/ui/plugins/time', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- plugins: [
- "vehicle"
- ]
-};
-});
-define('ripple/platform/ivi/3.0/spec/vehicledb', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 _init() {
+ var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ allTZ, dbTZ, node = jQuery("#time-locale-select"),
+ timezone = require('ripple/platform/tizen/2.0/timezone_info'),
+ event = require('ripple/event'),
+ alarms, time;
-module.exports = {
- supported: ["VehicleSpeed", "EngineSpeed", "VehiclePowerMode", "TripMeter",
- "Acceleration", "Transmission", "CruiseControlStatus", "WheelBrake",
- "LightStatus", "InteriorLightStatus", "Horn", "Fuel", "EngineOil",
- "Location", "ExteriorBrightness", "Temperature", "RainSensor",
- "WindshieldWiper", "HVAC", "WindowStatus", "Sunroof", "ConvertibleRoof",
- "VehicleId", "Size", "FuelInfo", "VehicleType", "Doors",
- "TransmissionGearType", "WheelInformation", "Odometer", "Fluid", "Battery",
- "TirePressure", "TireTemperature", "SecurityAlert", "ParkingBrake",
- "ParkingLight", "HazardLight", "AntilockBrakingSystem", "TractionControlSystem",
- "VehicleTopSpeedLimit", "AirbagStatus", "DoorStatus", "SeatBeltStatus",
- "OccupantStatus", "ObstacleDistance"],
- config: {
- "current": "Car1",
- "Car1": {
- "VehicleId": {
- "WMI": "AFA",
- "VIN": "21D1M2883N342FFG7"
- },
- "Size": {
- "width": 2096,
- "height": 1860,
- "length": 4779
- },
- "FuelInfo": {
- "type": 0,
- "refuelPosition": 0
- },
- "VehicleType": {
- "type": 0
- },
- "Doors": {
- "doorsPerRow": [2,2]
- },
- "TransmissionGearType": {
- "transmissionGearType": 0
- },
- "WheelInformation": {
- "frontWheelRadius": 1953,
- "rearWheelRadius": 2000,
- "wheelTrack": 1465,
- "ABS": true
- }
- },
- "Car2": {
- "VehicleId": {
- "WMI": "KMH",
- "VIN": "21D1M2888N342FFL7"
- },
- "Size": {
- "width": 2125,
- "height": 1961,
- "length": 4901
- },
- "FuelInfo": {
- "type": 4,
- "refuelPosition": 3
- },
- "VehicleType": {
- "type": 4
- },
- "Doors": {
- "doorsPerRow": [2,2]
- },
- "TransmissionGearType": {
- "transmissionGearType": 2
- },
- "WheelInformation": {
- "frontWheelRadius": 1964,
- "rearWheelRadius": 2000,
- "wheelTrack": 1470,
- "ABS": true
- }
- }
- },
- stopSet: {
- "Fluid": {
- "transmission": {
- "type": "text",
- "title": "unsigned short (0-100 percentage)",
- "default": 100
- },
- "brake": {
- "type": "text",
- "title": "unsigned short (0-100 percentage)",
- "default": 100
- },
- "washer": {
- "type": "text",
- "title": "unsigned short (0-100 percentage)",
- "default": 100
- }
- },
- "Battery": {
- "voltage": {
- "type": "text",
- "title": "double",
- "default": 11.5
- },
- "current": {
- "type": "text",
- "title": "double",
- "default": 10.4
- }
- },
- "TirePressure": {
- "leftFront": {
- "type": "text",
- "title": "double (kpa)",
- "default": 100.5
- },
- "rightFront": {
- "type": "text",
- "title": "double (kpa)",
- "default": 120.3
- },
- "leftRear": {
- "type": "text",
- "title": "double (kpa)",
- "default": 200.6
- },
- "rightRear": {
- "type": "text",
- "title": "double (kpa)",
- "default": 600.5
- }
- },
- "TireTemperature": {
- "leftFront": {
- "type": "text",
- "title": "double (celcius)",
- "default": 88.5
- },
- "rightFront": {
- "type": "text",
- "title": "double (celcius)",
- "default": 52.1
- },
- "leftRear": {
- "type": "text",
- "title": "double (celcius)",
- "default": 70.6
- },
- "rightRear": {
- "type": "text",
- "title": "double (celcius)",
- "default": 96.5
- }
- }
- },
- enabledSet: {
- "Transmission": {
- "gearPosition": {
- "type": "select",
- "options": [{"NEUTRAL":0},{"FIRST":1},{"SECOND":2},{"THIRD":3},
- {"FORTH":4},{"FIFTH":5},{"SIXTH":6},{"SEVENTH":7},
- {"EIGHTH":8},{"NINTH":9},{"TENTH":10},{"CVT":64},
- {"REVERSE":128},{"PARK":255}],
- "default": 255
- },
- "mode": {
- "type": "select",
- "options": [{"NORMAL":0},{"SPORT":1},{"ECONOMY":2},
- {"OEMCUSTOM1":3},{"OEMCUSTOM2":4}],
- "default": 0
- }
- },
- "CruiseControlStatus": {
- "activated": {
- "type": "radio",
- "options": ["active","inactive"],
- "default": true
- },
- "speed": {
- "type": "text",
- "title": "unsigned short (kph)",
- "default": 100
- }
- },
- "WheelBrake": {
- "engaged": {
- "type": "radio",
- "options": ["engaged","disengaged"],
- "default": true
- }
- },
- "LightStatus": {
- "head": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "rightTurn": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "leftTurn": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "brake": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "fog": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "hazard": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "parking": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "highBeam": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- }
- },
- "InteriorLightStatus": {
- "passenger": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "driver": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "center": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- }
- },
- "Horn": {
- "horn": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- }
- },
- "WindshieldWiper": {
- "windshieldWiper": {
- "type": "select",
- "options": [{"OFF":0},{"SLOWEST":1},{"FASTEST":5},{"AUTO":10}],
- "default": 0
- }
- },
- "HVAC": {
- "airflowDirection": {
- "type": "select",
- "options": [{"FRONTPANEL":0},{"FLOORDUCT":1},{"FRONT":0x02},
- {"DEFROSTER":0x04}],
- "default": 0
- },
- "fanSpeed": {
- "type": "select",
- "options": [{"0":0},{"1":1},{"2":2},{"3":3},{"4":4},{"5":5},
- {"6":6},{"7":7}],
- "default": 1
- },
- "targetTemperature": {
- "type": "text",
- "title": "unsigned short (celcius)",
- "default": 21
- },
- "airConditioning": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "airRecirculation": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "heater": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "defrost-window": {
- "type": "text",
- "title": "unsigned short",
- "default": 1
- },
- "defrost-defrost": {
- "type": "radio",
- "options": ["yes","no"],
- "default": true
- },
- "steeringWheelHeater": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "seatHeater": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- },
- "seatCooler": {
- "type": "radio",
- "options": ["on","off"],
- "default": false
- }
- },
- "Sunroof": {
- "openness": {
- "type": "text",
- "title": "unsigned short (percentage)",
- "default": 50
- },
- "tilt": {
- "type": "text",
- "title": "unsigned short (percentage)",
- "default": 50
- }
- },
- "ConvertibleRoof": {
- "openness": {
- "type": "text",
- "title": "unsigned short (percentage)",
- "default": 50
- }
- },
- "SecurityAlert": {
- "securityAlert": {
- "type": "radio",
- "options": ["on","off"],
- "default": true
- }
- },
- "ParkingBrake": {
- "parkingBrake": {
- "type": "radio",
- "options": ["engaged","disengaged"],
- "default": true
- }
- },
- "ParkingLight": {
- "parkingLight": {
- "type": "radio",
- "options": ["engaged","disengaged"],
- "default": true
- }
- },
- "HazardLight": {
- "hazardLight": {
- "type": "radio",
- "options": ["engaged","disengaged"],
- "default": true
- }
- },
- "AntilockBrakingSystem": {
- "securityAlert": {
- "type": "radio",
- "options": ["engaged","idle"],
- "default": true
- }
- },
- "TractionControlSystem": {
- "tractionControlSystem": {
- "type": "radio",
- "options": ["on","off"],
- "default": true
- }
- },
- "VehicleTopSpeedLimit": {
- "vehicleTopSpeedLimit": {
- "type": "text",
- "title": "unsigned short (km/h)",
- "default": 150
- }
- },
- "WindowStatus": {
- "WindowStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- }
- },
- "AirbagStatus": {
- "airbagStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- }
- },
- "DoorStatus": {
- "airbagStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- }
- },
- "SeatBeltStatus": {
- "doorStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- },
- "doorLockStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- },
- "childLockStatus": {
- "type": "radio",
- "options": ["on","off"],
- "default": true
- }
- },
- "OccupantStatus": {
- "occupantStatus": {
- "type": "text",
- "title": "dictionary",
- "default": null
- }
- },
- "ObstacleDistance": {
- "obstacleDistance": {
- "type": "text",
- "title": "dictionary",
- "default": null
- }
- }
- },
- properties: ["VehicleSpeed", "EngineSpeed", "VehiclePowerMode", "TripMeter",
- "Acceleration", "Transmission", "CruiseControlStatus", "WheelBrake",
- "LightStatus", "InteriorLightStatus", "Horn", "Fuel", "EngineOil",
- "Location", "ExteriorBrightness", "Temperature", "RainSensor",
- "WindshieldWiper", "HVAC", "WindowStatus", "Sunroof", "ConvertibleRoof",
- "VehicleId", "Size", "FuelInfo", "VehicleType", "Doors",
- "TransmissionGearType", "WheelInformation", "Odometer", "Fluid", "Battery",
- "TirePressure", "TireTemperature", "SecurityAlert", "ParkingBrake",
- "ParkingLight", "HazardLight", "AntilockBrakingSystem", "TractionControlSystem",
- "VehicleTopSpeedLimit", "AirbagStatus", "DoorStatus", "SeatBeltStatus",
- "OccupantStatus", "ObstacleDistance"],
- dataCount: 9,
- now: "1384408800000",
- historyCount: 0,
- history: {
- },
- zone: {
- "ZONE_None": 0,
- "ZONE_Front": 1,
- "ZONE_Middle": 0x10,
- "ZONE_Right": 0x100,
- "ZONE_Left": 0x1000,
- "ZONE_Rear": 0x10000,
- "ZONE_Center": 0x10000
- },
- data: {
- "1384408800000": { //2013-11-14 14:00:00
- "VehicleSpeed" : {
- "vehicleSpeed": 0
- },
- "EngineSpeed" : {
- "engineSpeed": 0
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 1
- },
- "TripMeter": {
- "tripMeters": [23, 7876, 124, 4577]
- },
- "Acceleration": {
- "x": 0,
- "y": 0,
- "z": 0
- },
- "Fuel": {
- "level": 87,
- "range": 251,
- "instantConsumption": 250,
- "instantEconomy": 85,
- "averageEconomy": 15
- },
- "EngineOil": {
- "remaining": 0,
- "temperature": 0,
- "pressure": 0
- },
- "Location": {
- "latitude": 0,
- "longitude": 0,
- "altitude": 0,
- "direction": 0
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 0
- },
- "Temperature": {
- "interior": 0,
- "exterior": 0
- },
- "RainSensor": {
- "rainSensor": 2
- },
- "Odometer": {
- "odometer": 333
- }
- },
- "1384401600000": { //2013-11-14 12:00:00
- "VehicleSpeed" : {
- "vehicleSpeed": 60
- },
- "EngineSpeed" : {
- "engineSpeed": 2500
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 0
- },
- "TripMeter": {
- "tripMeters": [100, 1000, 1500]
- },
- "Acceleration": {
- "x": 10,
- "y": 10,
- "z": 10
- },
- "Fuel": {
- "level": 100,
- "range": 105,
- "instantConsumption": 59,
- "instantEconomy": 87,
- "averageEconomy": 15
- },
- "EngineOil": {
- "remaining": 150,
- "temperature": 560,
- "pressure": 59
- },
- "Location": {
- "latitude": -15,
- "longitude": -89,
- "altitude": 16,
- "direction": 69
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 456
- },
- "Temperature": {
- "interior": 45,
- "exterior": 45
- },
- "RainSensor": {
- "rainSensor": 10
- },
- "Odometer": {
- "odometer": 1213
- }
- },
- "1384402500000": { //2013-11-14 12:15:00
- "VehicleSpeed" : {
- "vehicleSpeed": 120
- },
- "EngineSpeed" : {
- "engineSpeed": 2800
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 1
- },
- "TripMeter": {
- "tripMeters": [100, 1000]
- },
- "Acceleration": {
- "x": 1002,
- "y": 1045,
- "z": 1036
- },
- "Fuel": {
- "level": 100,
- "range": 254,
- "instantConsumption": 59,
- "instantEconomy": 87,
- "averageEconomy": 15
- },
- "EngineOil": {
- "remaining": 78,
- "temperature": 546,
- "pressure": 54
- },
- "Location": {
- "latitude": -97,
- "longitude": -54,
- "altitude": 124,
- "direction": 65
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 45
- },
- "Temperature": {
- "interior": 67,
- "exterior": 45
- },
- "RainSensor": {
- "rainSensor": 9
- },
- "Odometer": {
- "odometer": 250
- }
- },
- "1384403400000": { //2013-11-14 12:30:00
- "VehicleSpeed" : {
- "vehicleSpeed": 180
- },
- "EngineSpeed" : {
- "engineSpeed": 3100
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 2
- },
- "TripMeter": {
- "tripMeters": [100, 1000, 1500]
- },
- "Acceleration": {
- "x": 1234,
- "y": 45,
- "z": 67
- },
- "Fuel": {
- "level": 34,
- "range": 67,
- "instantConsumption": 97,
- "instantEconomy": 123,
- "averageEconomy": 56
- },
- "EngineOil": {
- "remaining": 155,
- "temperature": 960,
- "pressure": 78
- },
- "Location": {
- "latitude": 58,
- "longitude": -89,
- "altitude": 123,
- "direction": 69
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 768
- },
- "Temperature": {
- "interior": 45,
- "exterior": 98
- },
- "RainSensor": {
- "rainSensor": 8
- },
- "Odometer": {
- "odometer": 360
- }
- },
- "1384404300000": { //2013-11-14 12:45:00
- "VehicleSpeed" : {
- "vehicleSpeed": 240
- },
- "EngineSpeed" : {
- "engineSpeed": 3400
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 3
- },
- "TripMeter": {
- "tripMeters": [100, 15]
- },
- "Acceleration": {
- "x": 789,
- "y": 234,
- "z": 1200
- },
- "Fuel": {
- "level": 58,
- "range": 78,
- "instantConsumption": 123,
- "instantEconomy": 56,
- "averageEconomy": 31
- },
- "EngineOil": {
- "remaining": 54,
- "temperature": 963,
- "pressure": 210
- },
- "Location": {
- "latitude": -15,
- "longitude": 32,
- "altitude": 16,
- "direction": 23
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 234
- },
- "Temperature": {
- "interior": 76,
- "exterior": 45
- },
- "RainSensor": {
- "rainSensor": 7
- },
- "Odometer": {
- "odometer": 38
- }
- },
- "1384405200000": { //2013-11-14 13:00:00
- "VehicleSpeed" : {
- "vehicleSpeed": 280
- },
- "EngineSpeed" : {
- "engineSpeed": 3700
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 0
- },
- "TripMeter": {
- "tripMeters": [1245, 1000]
- },
- "Acceleration": {
- "x": 400,
- "y": 10,
- "z": 600
- },
- "Fuel": {
- "level": 120,
- "range": 130,
- "instantConsumption": 140,
- "instantEconomy": 145,
- "averageEconomy": 47
- },
- "EngineOil": {
- "remaining": 56,
- "temperature": 78,
- "pressure": 54
- },
- "Location": {
- "latitude": -15,
- "longitude": 12,
- "altitude": 16,
- "direction": 69
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 45
- },
- "Temperature": {
- "interior": 45,
- "exterior": 58
- },
- "RainSensor": {
- "rainSensor": 6
- },
- "Odometer": {
- "odometer": 1314
- }
- },
- "1384406100000": { //2013-11-14 13:15:00
- "VehicleSpeed" : {
- "vehicleSpeed": 320
- },
- "EngineSpeed" : {
- "engineSpeed": 4000
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 1
- },
- "TripMeter": {
- "tripMeters": [90, 100, 1000]
- },
- "Acceleration": {
- "x": 850,
- "y": 853,
- "z": 956
- },
- "Fuel": {
- "level": 78,
- "range": 99,
- "instantConsumption": 98,
- "instantEconomy": 125,
- "averageEconomy": 157
- },
- "EngineOil": {
- "remaining": 89,
- "temperature": 1001,
- "pressure": 12
- },
- "Location": {
- "latitude": 46,
- "longitude": -89,
- "altitude": 16,
- "direction": 69
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 432
- },
- "Temperature": {
- "interior": 45,
- "exterior": 21
- },
- "RainSensor": {
- "rainSensor": 5
- },
- "Odometer": {
- "odometer": 521
- }
- },
- "1384407000000": { //2013-11-14 13:30:00
- "VehicleSpeed" : {
- "vehicleSpeed": 220
- },
- "EngineSpeed" : {
- "engineSpeed": 3200
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 3
- },
- "TripMeter": {
- "tripMeters": [55]
- },
- "Acceleration": {
- "x": 777,
- "y": 7878,
- "z": 521
- },
- "Fuel": {
- "level": 58,
- "range": 96,
- "instantConsumption": 230,
- "instantEconomy": 237,
- "averageEconomy": 245
- },
- "EngineOil": {
- "remaining": 12,
- "temperature": 521,
- "pressure": 16
- },
- "Location": {
- "latitude": -15,
- "longitude": -89,
- "altitude": 16,
- "direction": 86
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 123
- },
- "Temperature": {
- "interior": 45,
- "exterior": 12
- },
- "RainSensor": {
- "rainSensor": 4
- },
- "Odometer": {
- "odometer": 2
- }
- },
- "1384407900000": { //2013-11-14 13:45:00
- "VehicleSpeed" : {
- "vehicleSpeed": 100
- },
- "EngineSpeed" : {
- "engineSpeed": 2600
- },
- "VehiclePowerMode": {
- "vehiclePowerMode": 2
- },
- "TripMeter": {
- "tripMeters": [1030, 1012]
- },
- "Acceleration": {
- "x": 888,
- "y": 666,
- "z": 444
- },
- "Fuel": {
- "level": 132,
- "range": 145,
- "instantConsumption": 87,
- "instantEconomy": 169,
- "averageEconomy": 91
- },
- "EngineOil": {
- "remaining": 66,
- "temperature": 1314,
- "pressure": 88
- },
- "Location": {
- "latitude": -15,
- "longitude": -89,
- "altitude": 789,
- "direction": 69
- },
- "ExteriorBrightness": {
- "exteriorBrightness": 768
- },
- "Temperature": {
- "interior": 0,
- "exterior": 45
- },
- "RainSensor": {
- "rainSensor": 3
- },
- "Odometer": {
- "odometer": 66
- }
+ function triggerAlarm() {
+ time = new Date();
+ alarms = db.retrieveObject("tizen1.0-db-alarms");
+ if (alarms !== null) {
+ utils.forEach(alarms, function (obj) {
+ if (obj.id !== undefined) {
+ event.trigger("CheckAlarm", [obj.id]);
+ }
+ });
}
}
+ window.setInterval(triggerAlarm, 1000);
+
+ allTZ = timezone.getAllTimezone();
+ utils.forEach(allTZ, function (tz) {
+ node.append(utils.createElement("option", {
+ "value": tz,
+ "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
+ }));
+ });
+ dbTZ = db.retrieve("tizen-timezone");
+ if (timezone.isValidTimezone(dbTZ)) {
+ node.val(dbTZ);
+ } else {
+ db.save("tizen-timezone", node.val());
+ }
+ node.bind("change", function () {
+ db.save("tizen-timezone", node.val());
+ });
+/* FIXME: Node "trigger-alarm-id" will be removed from Time panel
+ * due to "time" panel will changed to "time zone" panel(PTSDK-875)
+
+ event.on("SendTriggerAppId", function (applicationId) {
+ if (timeId !== undefined)
+ clearTimeout(timeId);
+ triggerNode.empty();
+ triggerNode.append(utils.createElement("p", {
+ "innerHTML": applicationId + " is triggered"
+ }));
+ triggerNode.show();
+ timeId = setTimeout("jQuery('#trigger-alarm-id').empty();", 10000);// Comments will disappear after 10s
+ });
+*/
+}
+
+module.exports = {
+ panel: {
+ domId: "time-container",
+ collapsed: true,
+ pane: "right",
+ titleName: "Time",
+ display: true
+ },
+ initialize: _init
};
});
-define('ripple/platform/ivi/3.0/spec', function (require, exports, module) {
+define('ripple/ui/plugins/multimedia', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
+ volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);
module.exports = {
+ panel: {
+ domId: "multimedia-container",
+ collapsed: true,
+ pane: "left"
+ },
+ initialize: function () {
+ var volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
+ volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);
- id: "ivi",
- version: "3.0",
- name: "IVI",
-
- persistencePrefix: "ivi3-",
+ event.on("MultimediaVolumeChanged", function (volume) {
+ volumeField.innerText = volume > 9 ? volume : "0" + volume;
+ if (volume.value !== volume) {
+ volume.value = volume;
+ }
+ });
- config: require('ripple/platform/ivi/3.0/spec/config'),
- ui: require('ripple/platform/ivi/3.0/spec/ui'),
- device: require('ripple/platform/ivi/3.0/spec/device'),
- sensor: require('ripple/platform/ivi/3.0/spec/sensor'),
- DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
- DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),
+ volume.addEventListener('change', function () {
+ event.trigger("MultimediaVolumeChanged", [this.value], true);
+ }, false);
- objects: {
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- SensorConnection: {
- path: "w3c/1.0/SensorConnection"
- },
- navigator: {
- path: "tizen/2.0/navigator",
- children: {
- geolocation: {
- path: "wac/2.0/geolocation"
- }
- }
- },
- tizen: {
- children: {
- vehicle: {
- path: "ivi/3.0/vehicle",
- feature: "http://tizen.org/privilege/vehicle",
- handleSubfeatures: true
- }
- }
- }
+ event.on("MultimediaAudioStateChanged", function updateIsAudioPlaying(state) {
+ document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PLAYING_FIELD_ID).innerHTML = state === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
+ });
}
};
});
-define('ripple/platform/ivi/3.0/typecast', function (require, exports, module) {
+define('ripple/ui/plugins/exec-dialog', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 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.
* limitations under the License.
*/
-var typedef = require('ripple/platform/ivi/3.0/typedef'),
- errorcode = require('ripple/platform/ivi/3.0/errorcode'),
- WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
- TypeCoerce = require('ripple/platform/ivi/3.0/typecoerce'),
- _self = {};
-
-function _cast(pattern, obj, isDuplicate) {
- var tc, tcFunc;
-
- if (pattern === null)
- return;
-
- tc = new TypeCoerce(pattern);
- tcFunc = isDuplicate ? tc.copy : tc.cast;
-
- if ((obj = tcFunc(obj)) === null) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
-
- return obj;
-}
-
-function _castType(pattern) {
- /*
- * Type cast for each known type. The function name is the exact name of the
- * corresponding type.
- *
- * obj
- * Variable to be casted
- *
- * aux
- * Auxiliary descriptor of obj. It can be any one or combination of below
- * strings, or ignored in most cases.
- *
- * "?" Nullable types
- * "[]" Array
- * "+" Deep copy
- *
- * Return
- * Casted or duplicated object.
- */
-
- return function (obj, aux) {
- var type, isNullable, isDuplicate;
-
- aux = aux ? String(aux) : "";
- type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
- isNullable = (aux.indexOf("?") !== -1);
- isDuplicate = (aux.indexOf("+") !== -1);
-
- if (isNullable && ((obj === null) || (obj === undefined))) {
- return obj;
- }
+function exec(func) {
+ return function () {
+ var val = $("#exec-response").val();
- return _cast(type, obj, isDuplicate);
+ //TODO: handle multiple args
+ func.apply(null, val ? [JSON.parse(val)] : []);
+ $("#exec-dialog").dialog("close");
};
}
-function _castConstructor(name) {
- var constructors, hook, vtc, isOverloaded, castConstructor;
+module.exports = {
+ initialize: function () {
+ $("#exec-dialog").dialog({
+ autoOpen: false,
+ modal: true,
+ title: "I Haz Cheeseburger?!?!",
+ width: 500,
+ position: 'center'
+ }).hide();
- /*
- * Type cast for constructor. The function name is the exact name of the
- * object type.
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- */
+ $("#exec-success").button();
+ $("#exec-fail").button();
+ },
- function castUnique(argv) {
- _cast(constructors, argv, false);
+ show: function (service, action, success, fail) {
+ console.log(service);
+ console.log(action);
+ $("#exec-service").text(service);
+ $("#exec-action").text(action);
+ $("#exec-dialog").dialog("open");
+ $("#exec-success").unbind().bind('click', exec(success));
+ $("#exec-fail").unbind().bind('click', exec(fail));
}
+};
- /*
- * Type cast for overloaded constructors. The function name is the exact
- * name of the object type.
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- *
- * scope
- * 'this' of the original constructor.
- *
- * voc
- * Array of overloaded constructors callback
- */
-
- function castOverload(argv, scope, voc) {
- var iOverload;
-
- if (!vtc) {
- vtc = [];
- constructors.forEach(function (c) {
- vtc.push((c === null) ? null : new TypeCoerce(c));
- });
- }
-
- vtc.some(function (tc, index) {
- if (tc && (tc.cast(argv) === null))
- return false;
-
- iOverload = index;
- return true;
- });
-
- if (iOverload === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+});
+define('ripple/ui/plugins/camera', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- return (voc && voc[iOverload].apply(scope, argv));
- }
+var ui = require('ripple/ui'),
+ event = require('ripple/event'),
+ video = document.getElementById('camera-video'),
+ upload = document.getElementById('picture-upload'),
+ select = document.getElementById('select-file'),
+ take = document.getElementById('take-file'),
+ pic = document.getElementById("camera-image");
- constructors = typedef.constructor[name];
- if (name in _self) {
- hook = _self[name];
- }
+select.addEventListener('click', function () {
+ upload.click();
+});
- isOverloaded = (Object.prototype.toString.call(constructors) ===
- "[object Array]");
- castConstructor = isOverloaded ? castOverload : castUnique;
+upload.addEventListener('change', function () {
+ pic.src = window.webkitURL.createObjectURL(upload.files[0]);
+ take.style.display = "inline";
+});
- return function (argv, scope) {
- if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
- return (hook && hook.apply(this, arguments));
- }
+take.addEventListener('click', function () {
+ console.log("captured-image: " + pic.src);
+ event.trigger('captured-image', [pic.src, upload.files[0]]);
+ module.exports.hide();
+});
- if (!(scope instanceof argv.callee)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
+module.exports = {
+ show: function () {
+ ui.showOverlay("camera-window");
+ if (pic.src) {
+ take.style.display = "inline";
}
-
- castConstructor.apply(this, arguments);
- };
-}
-
-function _castInterface(name) {
- var interface, hook;
-
- interface = typedef.interface[name];
-
- if (name in _self) {
- hook = _self[name];
- }
-
- /*
- * Type cast for each known method of interface. The function name is the
- * exact name of the corresponding interface.
- *
- * method
- * String of method name
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- *
- * isDuplicate
- * A boolean value to indicate whether arguments will be copied or not.
- */
-
- return function (method, argv, isDuplicate) {
- if ((typeof method !== "string") || (typeof argv !== "object")) {
- return (hook && hook.apply(this, arguments));
+ else {
+ take.style.display = "none";
}
-
- _cast(interface[method], argv, isDuplicate);
- };
-}
-
-(function () {
- var i;
-
- for (i in typedef) {
- _self[i] = _castType(typedef[i]);
- }
-
- for (i in typedef.constructor) {
- _self[i] = _castConstructor(i);
- typedef[i]._constructor = i;
- }
-
- for (i in typedef.interface) {
- _self[i] = _castInterface(i);
+ },
+ hide: function () {
+ ui.hideOverlay("camera-window");
}
-}());
-
-module.exports = _self;
+};
});
-define('ripple/platform/ivi/3.0/typecoerce', function (require, exports, module) {
+define('ripple/ui/plugins/network', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/ivi/3.0/typedef'),
- _self;
-
-_self = function (pattern) {
- var typeCoerce, typeOfPattern;
-
- // private
- function getExtendedType(val) {
- var type = Object.prototype.toString.call(val), attr;
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ deviceSettings = require('ripple/deviceSettings'),
+ //dbinit = require('ripple/platform/tizen/2.0/dbinit'),
+ _NFC_TAG = "tizen1.0-nfc-tag",
+ _NFC_PEER = "tizen1.0-nfc-peer",
+ _NFC_OUTPUT_MESSAGE = "tizen1.0-nfc-output-message",
+ _powered = false,
+ _isConnected = false,
+ _tagNDEF = {
+ type: "GENERIC_TARGET",
+ isSupportedNDEF: true,
+ ndefSize: 3,
+ ndefs: [{
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID001",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID002",
+ payload: "This is 2nd payload"
+ }]
+ },
+ {
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID003",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID004",
+ payload: "This is 2nd payload"
+ }]
+ },
+ {
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID005",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID006",
+ payload: "This is 2nd payload"
+ }]
+ }]
+ },
+ _tagRaw = {
+ type: "GENERIC_TARGET",
+ isSupportedNDEF: false,
+ rawData : ""
+ },
+ _peerNDEF = {
+ ndef: {
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID001",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID002",
+ payload: "This is 2nd payload"
+ }]
+ }
+ },
+ btNodes,
+ _btDeviceTemplate = "",
+ _btSimulatedDevs = {},
+ _btBluetoothDB;
- switch (type) {
- case "[object Array]":
- if ((typeof val[0] === "string") && (val[0].length > 0)) {
- type = "enum";
- } else {
- type = "Union";
- }
- return type;
+function elementEnableDisableSetting(prop) {
+ jQuery("#nfc-attach-msg").text("\xa0");
+ jQuery("#nfc-peer-send-msg").text("\xa0");
+ if (prop && prop.power !== undefined && prop.power !== null) {
+ if (!prop.power) {
+ $("#nfc-type").removeAttr("disabled");
+ }
+ }
+ if (prop && prop.connectedState !== undefined && prop.connectedState !== null) {
+ if (prop.connectedState) {
+ $("#nfc-type").attr("disabled", "disabled");
+ $("#nfc-tag-type-text").text($("#nfc-tag-type option:selected").text());
+ $("#nfc-tag-type").hide();
+ $("#nfc-tag-type-text").show();
+ $("#nfc-tag-NDEF-support-text").text($("#nfc-tag-NDEF-support option:selected").text());
+ $("#nfc-tag-NDEF-support").hide();
+ $("#nfc-tag-NDEF-support-text").show();
+ $("#nfc-raw-data").attr("disabled", "disabled");
+ } else {
+ $("#nfc-type").removeAttr("disabled");
+ $("#nfc-tag-type").show();
+ $("#nfc-tag-type-text").hide();
+ $("#nfc-tag-NDEF-support").show();
+ $("#nfc-tag-NDEF-support-text").hide();
+ $("#nfc-raw-data").removeAttr("disabled");
+ }
+ }
+}
- case "[object Object]":
- if ("_dictionary" in val) {
- return "dictionary";
- }
+function _initializeElements() {
+ jQuery(function () {
+ var stop = false,
+ wifiRadio = $("#wifi-radio"),
+ isSupportNDEF, type;
- type = "Object";
+ // initialize main menus
+ wifiRadio.buttonset();
- for (attr in val) {
- if (attr === "0") {
- type = "Arguments";
- } else if (val[attr] === "Callback") {
- type = "Callback";
- }
- break;
- }
+ $("#cellular-radio").buttonset();
+ $("#nfc-radio").buttonset();
+ $("#bluetooth-radio").buttonset();
+ $("#bearer-radio").buttonset();
- return type;
+ $("#wifi-radio1").prop('checked', false);
+ $("#wifi-radio2").prop('checked', false);
+ if (deviceSettings.retrieve("WIFI_NETWORK.status") === true) {
+ $("#wifi-radio1").prop('checked', true);
+ $("#wifi-radio1-label").css({'color': '#000000'});
+ $("#wifi-radio2-label").css({'color': '#bbbbbb'});
}
+ else {
+ $("#wifi-radio2").prop('checked', true);
+ $("#wifi-radio1-label").css({'color': '#bbbbbb'});
+ $("#wifi-radio2-label").css({'color': '#222222'});
+ }
+ $("#wifi-radio1").button("refresh");
+ $("#wifi-radio2").button("refresh");
- switch (val) {
- case "Callback":
- type = "Function";
- break;
-
- case "TZDate":
- case "any":
- case "byte":
- case "float":
- case "long":
- case "long long":
- case "octet":
- case "short":
- case "unsigned long":
- case "unsigned long long":
- case "unsigned short":
- type = val;
- break;
-
- case "double":
- type = "float";
- break;
+ $("#cellular-radio1").prop('checked', false);
+ $("#cellular-radio2").prop('checked', false);
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === true) {
+ $("#cellular-radio1").prop('checked', true);
+ $("#cellular-radio1-label").css({'color': '#000000'});
+ $("#cellular-radio2-label").css({'color': '#bbbbbb'});
+ }
+ else {
+ $("#cellular-radio2").prop('checked', true);
+ $("#cellular-radio1-label").css({'color': '#bbbbbb'});
+ $("#cellular-radio2-label").css({'color': '#222222'});
+ }
- default: // Derivative type name: e.g., "AbstractFilter"
- type = "";
- break;
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
+ $("#cellular-radio1").prop('disabled', true);
+ $("#cellular-radio2").prop('disabled', true);
+ $("#panel_flight_mode_notice").show();
+ }
+ else {
+ $("#cellular-radio1").prop('disabled', false);
+ $("#cellular-radio2").prop('disabled', false);
+ $("#panel_flight_mode_notice").hide();
}
- return type;
- }
+ $("#cellular-radio1").button("refresh");
+ $("#cellular-radio2").button("refresh");
- function getType(val, isPattern) {
- var type = Object.prototype.toString.call(val);
+ $("#bearer-radio2").prop('checked', true);
+ $("#bearer-radio2").button("refresh");
- switch (type) {
- case "[object Array]":
- type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
- "Array";
- break;
+ $("#wifi-radio1").click(function () {
+ $("#wifi-radio1-label").css({'color': '#000000'});
+ $("#wifi-radio2-label").css({'color': '#bbbbbb'});
+ deviceSettings.persist("WIFI_NETWORK.status", true);
+ event.trigger("WiFiNetworkStatusChanged", [true]);
+ });
- case "[object Arguments]":
- type = "Arguments";
- break;
+ $("#wifi-radio2").click(function () {
+ $("#wifi-radio1-label").css({'color': '#bbbbbb'});
+ $("#wifi-radio2-label").css({'color': '#222222'});
+ deviceSettings.persist("WIFI_NETWORK.status", false);
+ event.trigger("WiFiNetworkStatusChanged", [false]);
+ });
- case "[object Boolean]":
- type = "boolean";
- break;
+ $("#cellular-radio1").click(function () {
+ $("#cellular-radio1-label").css({'color': '#000000'});
+ $("#cellular-radio2-label").css({'color': '#bbbbbb'});
+ deviceSettings.persist("CELLULAR_NETWORK.status", true);
+ event.trigger("CellularNetworkStatusChanged", [true]);
+ });
- case "[object Date]":
- type = "Date";
- break;
+ $("#cellular-radio2").click(function () {
+ $("#cellular-radio1-label").css({'color': '#bbbbbb'});
+ $("#cellular-radio2-label").css({'color': '#222222'});
+ deviceSettings.persist("CELLULAR_NETWORK.status", false);
+ event.trigger("CellularNetworkStatusChanged", [false]);
+ });
- case "[object Function]":
- type = "Function";
- break;
+ $("#nfc-radio1-label").css({'color': '#bbbbbb'});
+ $("#nfc-radio2-label").css({'color': '#222222'});
- case "[object Number]":
- type = "Number";
- break;
+ $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
+ $("#bluetooth-radio2-label").css({'color': '#222222'});
- case "[object Object]":
- type = isPattern ? getExtendedType(val) : "Object";
- break;
+ $("#bearer-radio1-label").css({'color': '#bbbbbb'});
+ $("#bearer-radio2-label").css({'color': '#222222'});
- case "[object String]":
- type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
- break;
- }
+ $("#nfc-radio1").click(function () {
+ $("#nfc-radio2-label").css({'color': '#bbbbbb'});
+ $("#nfc-radio1-label").css({'color': '#222222'});
+ $("#nfc-main-container").show();
+ });
- return type;
- }
+ $("#nfc-radio2").click(function () {
+ $("#nfc-radio1-label").css({'color': '#bbbbbb'});
+ $("#nfc-radio2-label").css({'color': '#222222'});
+ $("#nfc-main-container").hide();
+ });
- function isConstructed(obj) {
- if (!("_constructor" in pattern))
- return true;
+ $("#bluetooth-radio1").click(function () {
+ $("#bluetooth-radio2-label").css({'color': '#bbbbbb'});
+ $("#bluetooth-radio1-label").css({'color': '#222222'});
+ $("#bluetooth-main-container").show();
+ });
- if (obj instanceof window.tizen[pattern._constructor])
- return true;
+ $("#bluetooth-radio2").click(function () {
+ $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
+ $("#bluetooth-radio2-label").css({'color': '#222222'});
+ $("#bluetooth-main-container").hide();
+ });
- return false;
- }
+ $("#bearer-radio1").click(function () {
+ $("#bearer-radio2-label").css({'color': '#bbbbbb'});
+ $("#bearer-radio1-label").css({'color': '#222222'});
+ $("#bearer-main-container").show();
+ });
- function toInteger(x) {
- return (x < 0) ? Math.ceil(x) : Math.floor(x);
- }
+ $("#bearer-radio2").click(function () {
+ $("#bearer-radio1-label").css({'color': '#bbbbbb'});
+ $("#bearer-radio2-label").css({'color': '#222222'});
+ $("#bearer-main-container").hide();
+ });
- function modulo(a, b) {
- return (a - Math.floor(a / b) * b);
- }
+ // initialize nfc
+ jQuery("nfc-tag-ndef-container h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#nfc-tag-ndef-container").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ jQuery("nfc-nfcpeer h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#nfc-nfcpeer").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ jQuery("#nfc-tag-NDEF-support").bind("change", function () {
+ isSupportNDEF = jQuery("#nfc-tag-NDEF-support").val();
+ if (isSupportNDEF === "Yes") {
+ jQuery("#nfc-tag-ndef-container").fadeIn();
+ jQuery("#nfc-tag-raw-container").hide();
+ } else {
+ jQuery("#nfc-tag-ndef-container").hide();
+ jQuery("#nfc-tag-raw-container").fadeIn();
+ }
+ });
+ jQuery("#nfc-type").bind("change", function () {
+ type = jQuery("#nfc-type").val();
+ if (type === "Tag") {
+ jQuery("#nfc-nfctag").fadeIn();
+ jQuery("#nfc-nfcpeer").hide();
+ } else {
+ jQuery("#nfc-nfctag").hide();
+ jQuery("#nfc-nfcpeer").fadeIn();
+ }
+ elementEnableDisableSetting();
+ });
+ jQuery("#nfc-power").bind("change", function () {
+ var status;
+ status = jQuery("#nfc-power").val() === "On" ? true : false;
+ if (status)
+ jQuery("#nfc").show();
+ event.trigger("nfc-power-setting", [status]);
+ });
+ jQuery("#nfc-attach").bind("click", function () {
+ var type, isAttached;
+ isAttached = jQuery("#nfc-attach").children().text() === "Attach" ? true : false;
+ jQuery("#nfc-attach-msg").text("\xa0");
- function toInt(x, bits) {
- var p;
+ if (!_powered && isAttached) {
+ jQuery("#nfc-attach-msg").text("Power:Off, attach won't work");
+ return;
+ }
+ type = jQuery("#nfc-type").val();
+ event.trigger("nfc-attach-setting", [type, isAttached]);
+ });
+ jQuery("#nfc-peer-send").bind("click", function () {
+ jQuery("#nfc-peer-send-msg").text("\xa0");
+ if (!_isConnected) {
+ jQuery("#nfc-peer-send-msg").text("Disconnected. Send won't work");
+ return;
+ }
+ db.saveObject(_NFC_PEER, _peerNDEF);
+ event.trigger("nfc-peer-sending-ndef", []);
+ });
- x = Number(x);
+ // Initialize network bearer selection
+ $("#bearer-cellular-radio1").prop('checked', true);
+ $("#bearer-unknown-radio2").prop('checked', true);
+ $("#bearer-cellular-radio1").button("refresh");
+ $("#bearer-unknown-radio2").button("refresh");
- if (isNaN(x) || !isFinite(x))
- return null;
+ $("#bearer-cellular-radio2").click(function () {
+ $("#bearer-cellular button").click();
+ });
- p = Math.pow(2, bits);
- x = modulo(toInteger(x), p);
+ $("#bearer-unknown-radio2").click(function () {
+ $("#bearer-unknown button").click();
+ });
+ });
+}
- return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
- }
+function _btRender() {
+ var devicesHTML, btHtmlContent = "";
- function toUInt(x, bits) {
- x = Number(x);
-
- if (isNaN(x) || !isFinite(x))
- return null;
-
- return modulo(toInteger(x), Math.pow(2, bits));
- }
-
- function toInt8(x) {
- return toInt(x, 8);
- }
-
- function toInt16(x) {
- return toInt(x, 16);
- }
+ utils.forEach(_btSimulatedDevs, function (item) {
+ var uuidsHTML = "", firstService = null;
- function toInt32(x) {
- return toInt(x, 32);
- }
+ utils.forEach(item.services, function (s, index) {
+ if (!firstService) {
+ firstService = s;
+ }
+ uuidsHTML += '<option value="' + index + '">' + s.name + '</option>';
+ });
- function toInt64(x) {
- return toInt(x, 64);
- }
+ devicesHTML = _btDeviceTemplate.replace(/#name/g, item.name)
+ .replace(/#address/g, item.address)
+ .replace(/#class-major/, item.deviceClass.majorName)
+ .replace(/#class-minor/, item.deviceClass.minorName)
+ .replace(/#class-service/, item.deviceClass.servicesName.join(","))
+ .replace(/#bonded/, "No")
+ .replace(/#trusted/, item.isTrusted ? "Yes" : "No")
+ .replace(/#connected/, "No")
+ .replace(/#uuids/, uuidsHTML)
+ .replace(/#service-uuid/, firstService.uuid)
+ .replace(/#service-protocol/, firstService.protocol)
+ .replace(/#service-state/, firstService.state || "CLOSED")
+ .replace(/#id/g, item.address.replace(/:/g, ""));
- function toUInt8(x) {
- return toUInt(x, 8);
- }
+ btHtmlContent += devicesHTML;
+ });
- function toUInt16(x) {
- return toUInt(x, 16);
- }
+ $("#network-bt-box").accordion("destroy");
+ $("#network-bt-box").html(btHtmlContent).accordion({
+ active : false,
+ collapsible : true,
+ autoHeight : false
+ });
+}
- function toUInt32(x) {
- return toUInt(x, 32);
- }
+function _btRemove(index) {
+ delete _btSimulatedDevs[index];
+ db.saveObject("bt-simulated-devices", _btSimulatedDevs);
+ event.trigger("bt-simulated-devices-changed", []);
+ _btRender();
+}
- function toUInt64(x) {
- return toUInt(x, 64);
+function _bearerRelease(type, idBearer, evNetworkDisconnected) {
+ if ($("#bearer-row-" + idBearer).length > 0) {
+ $("tr[id='bearer-row-" + idBearer + "']").remove();
}
- // public
- function cast(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
-
- typeMap = {
- "Arguments": function () {
- var i, isNullable, ret;
-
- for (i in pattern) {
- if (i === "_optional")
- continue;
+ event.trigger(evNetworkDisconnected);
- isNullable = !!(pattern._optional && pattern._optional[i]);
+ $("#bearer-" + type + " tr:even").css("background-color", "white");
+ $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
+}
- if (i > obj.length - 1) {
- if (!isNullable) {
- return null;
- }
- break;
- }
+module.exports = {
+ panel: {
+ domId: "network-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Network Management",
+ display: true
+ },
+ initialize: function () {
+ _initializeElements();
- if (!isNullable || (obj[i] !== null)) {
- ret = _self(pattern[i]).cast(obj[i]);
- if (ret === null) {
- return null;
+ // Events for nfc module
+ event.on("nfc-power-changed", function (status) {
+ _powered = status;
+ if (_powered === true) {
+ $("#nfc-power").val("On");
+ } else {
+ $("#nfc-power").val("Off");
+ }
+ elementEnableDisableSetting({power: status});
+ });
+ event.on("nfc-connectedState-changed", function (state) {
+ var i, type, isSupportedNDEF, str, bytes = [];
+ _isConnected = state;
+ elementEnableDisableSetting({connectedState: state});
+ type = jQuery("#nfc-type").val();
+ if (state) {
+ jQuery("#nfc-attach").children().text("Detach");
+ jQuery("#nfc-tag-connection").text("Connected");
+ jQuery("#nfc-peer-connection").text("Connected");
+ if (type === "Tag") {
+ isSupportedNDEF = jQuery("#nfc-tag-NDEF-support").val() === "Yes" ? true : false;
+ if (isSupportedNDEF) {
+ _tagNDEF.type = jQuery("#nfc-tag-type").val();
+ db.saveObject(_NFC_TAG, _tagNDEF);
+ } else {
+ _tagRaw.type = jQuery("#nfc-tag-type").val();
+ str = jQuery("#nfc-raw-data").val();
+ for (i = 0; i < str.length; i++) {
+ bytes.push(str.charCodeAt(i));
}
- obj[i] = ret;
+ _tagRaw.rawData = bytes;
+ db.saveObject(_NFC_TAG, _tagRaw);
}
+ event.trigger("nfc-tag-send", [true]);
+ } else {
+ event.trigger("nfc-peer-send", [true]);
}
-
- return obj;
- },
-
- "Array": function () {
- var elementType, i, ret;
-
- if (typeOfObj !== typeOfPattern) {
- return null;
- }
-
- elementType = _self(pattern[0]);
- for (i in obj) {
- ret = elementType.cast(obj[i]);
- if (ret === null) {
- return null;
- }
- obj[i] = ret;
+ } else {
+ jQuery("#nfc-attach").children().text("Attach");
+ jQuery("#nfc-tag-connection").text("Disconnected");
+ jQuery("#nfc-peer-connection").text("Disconnected");
+ jQuery("#nfc-output").text("");
+ jQuery("#nfc-output-table").hide();
+ if (type === "Tag") {
+ event.trigger("nfc-tag-send", [false]);
+ } else {
+ event.trigger("nfc-peer-send", [false]);
}
+ }
+ });
+ event.on("nfc-output-msg", function () {
+ var msg;
+ msg = db.retrieve(_NFC_OUTPUT_MESSAGE);
+ jQuery("#nfc-output").text(msg);
+ jQuery("#nfc-output-table").show();
+ });
- return obj;
- },
+ // Events for bluetooth module
+ event.on("bluetoothPowerState", function (state) {
+ if (state) {
+ $("#bluetooth-radio1").click();
+ } else {
+ $("#bluetooth-radio2").click();
+ }
+ });
+ event.on("bt-adapter-name-changed", function (name) {
+ $("#bt-adapter-name").text(name);
+ });
+ event.on("bt-adapter-power-changed", function (state) {
+ if (state) {
+ $("#bt-adapter-power").text("On");
+ } else {
+ $("#bt-adapter-power").text("Off");
+ }
+ });
+ event.on("bt-adapter-visible-changed", function (state) {
+ if (state) {
+ $("#bt-adapter-visible").text("On");
+ } else {
+ $("#bt-adapter-visible").text("Off");
+ }
+ });
+ event.on("bt-device-bonded-changed", function (addr, isBonded) {
+ var str = "No";
+ if (isBonded) {
+ str = "Yes";
+ }
+ jQuery("#bonded-" + addr.replace(/:/g, "")).html(str);
+ });
+ event.on("bt-device-connected-changed", function (addr, isConnected) {
+ var str = "No";
+ if (isConnected) {
+ str = "Yes";
+ }
+ jQuery("#connected-" + addr.replace(/:/g, "")).html(str);
+ });
+ event.on("bt-service-state-changed", function (addr, uuid, state) {
+ var str = "CLOSED";
+ if (state) {
+ str = "OPEN";
+ }
+ _btSimulatedDevs[addr].services[uuid].state = str;
+ jQuery("#service-state-" + addr.replace(/:/g, "")).html(str);
+ });
+ event.on("bt-service-write-msg", function (addr, uuid, data) {
+ var msg = "", uuidNow;
+ utils.forEach(data, function (char) {
+ msg += String.fromCharCode(char);
+ });
+ uuidNow = jQuery("#network-bt-uuid-" + addr.replace(/:/g, "")).html();
+ if (uuidNow === uuid) {
+ jQuery("#service-receive-textarea-" + addr.replace(/:/g, "")).html(msg);
+ }
+ });
- "Callback": function () {
- var attr;
+ // Event for network bearer selection module
+ event.on("NetworkRequest", function (networkType, domainName) {
+ var type = networkType.toLowerCase(), name, idBearer,
+ evNetworkOpened = "NO_" + networkType + "_" + domainName,
+ evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
- if (typeOfObj !== "Object") {
- return null;
- }
+ if (!$("#bearer-" + type + "-radio1").prop("checked")) {
+ event.trigger(evNetworkOpened, [false]);
+ event.trigger(evNetworkDisconnected);
- for (attr in pattern) {
- if (attr in obj) {
- obj[attr] = _self(pattern[attr]).cast(obj[attr]);
- if (obj[attr] === null) {
- return null;
- }
- }
- }
+ return;
+ }
- return obj;
- },
+ name = domainName.replace(/\./, "");
+ idBearer = type + '-' + name;
- "DOMString": function () {
- switch (typeOfObj) {
- case "DOMString":
- case "Date":
- case "Number":
- case "boolean":
- obj = String(obj);
- break;
+ if ($("#bearer-row-" + idBearer).length <= 0) {
+ $("#bearer-" + type).append("<tr id='bearer-row-" + idBearer + "'>" +
+ "<td> <lable class='ui-text-label'>" + domainName + "</label></td>" +
+ "<td><button id='bearer-btn-" + idBearer + "'>X</button>  </td>" +
+ "</tr>");
- default:
- if ((obj === null) || (obj === undefined)) {
- obj = String(obj);
- } else {
- obj = null;
- }
- break;
- }
+ $("#bearer-btn-" + idBearer).click(function () {
+ _bearerRelease(type, idBearer, evNetworkDisconnected);
+ });
- return obj;
- },
+ $("#bearer-" + type + " tr:even").css("background-color", "white");
+ $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
+ }
- "Date": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
+ event.trigger(evNetworkOpened, [true]);
+ });
- "Function": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
+ event.on("NetworkRelease", function (networkType, domainName) {
+ var type = networkType.toLowerCase(),
+ name = domainName.replace(/\./, ""),
+ idBearer = type + '-' + name,
+ evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
- "Object": function () {
- var ret, attr, i;
+ _bearerRelease(type, idBearer, evNetworkDisconnected);
+ });
- if (typeOfObj !== typeOfPattern) {
- if ((obj === null) || (obj === undefined)) {
- return null;
- }
- if (!("_derived" in pattern)) {
- return null;
- }
- }
+ // Update UI for Flight Mode changing
+ event.on("FlightModeChanged", function (value) {
+ if (value === true) {
+ $("#cellular-radio1").prop('disabled', true);
+ $("#cellular-radio2").prop('disabled', true);
+ $("#panel_flight_mode_notice").show();
+ }
+ else {
+ $("#cellular-radio1").prop('disabled', false);
+ $("#cellular-radio2").prop('disabled', false);
+ $("#panel_flight_mode_notice").hide();
+ }
- if (!isConstructed(obj)) {
- return null;
- }
+ $("#cellular-radio1").button("refresh");
+ $("#cellular-radio2").button("refresh");
+ });
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ $("#bt-adapter-name").text(db.retrieveObject("tizen1-db-bluetooth_adapter-name") || "Tizen BT Adapter");
+ _btDeviceTemplate = $("#network-bt-template").html();
+ $("#network-bt-box").empty();
+ btNodes = jQuery("#network-bt-device-select");
+ btNodes.html("");
- case "_derived":
- for (i in pattern._derived) {
- ret = _self(pattern._derived[i]).cast(obj);
- if (ret !== null)
- break;
- }
- if (ret === null) {
- return null;
- }
- break;
+ //_btBluetoothDB = dbinit.Bluetooth;
+ _btBluetoothDB = db.retrieveObject("bt-simulated-devices");
+ utils.forEach(_btBluetoothDB, function (item, index) {
+ btNodes.append(utils.createElement("option", {
+ "value": index,
+ "innerText": item.name
+ }));
+ });
- default:
- if (!pattern._optional || !pattern._optional[attr] ||
- (obj[attr] !== undefined) &&
- (obj[attr] !== null)) {
- ret = _self(pattern[attr]).cast(obj[attr]);
- if (ret === null) {
- return null;
- }
- obj[attr] = ret;
- }
- break;
- }
- }
+ jQuery("#network-bt-nearby-btn").click(function () {
+ var index;
+ index = jQuery("#network-bt-device-select").val();
+ if (_btSimulatedDevs[index]) {
+ return;
+ }
+ _btSimulatedDevs[index] = _btBluetoothDB[index];
+ db.saveObject("bt-simulated-devices", _btSimulatedDevs);
+ event.trigger("bt-simulated-devices-changed", []);
+ _btRender();
+ });
+ $(".network-bt-remove-btn").live("click", function () {
+ _btRemove(this.id);
+ });
+ $(".network-bt-send-btn").live("click", function () {
+ var msg = jQuery("#service-transfer-textarea-" + this.id.replace(/:/g, "")).val(),
+ uuid = jQuery("#network-bt-uuid-" + this.id.replace(/:/g, "")).html();
+ event.trigger("bt-service-rawdata-received", [this.id, uuid, msg]);
+ });
+ $(".network-bt-service-select").live("change", function () {
+ var uuid = this.children[this.selectedIndex].value,
+ index = this.id,
+ addr,
+ service;
+ addr = index.replace(/:/g, "");
+ service = _btSimulatedDevs[index].services[uuid];
+ jQuery("#network-bt-uuid-" + index.replace(/:/g, "")).html(service.uuid);
+ jQuery("#network-bt-protocol-" + index.replace(/:/g, "")).html(service.protocol);
+ jQuery("#service-state-" + index.replace(/:/g, "")).html(service.state || "CLOSED");
+ jQuery("#service-transfer-textarea-" + addr).val("");
+ jQuery("#service-receive-textarea-" + addr).html("");
+ });
- return obj;
- },
+ //Default "Tizen Phone" is nearby
+ //_btSimulatedDevs["00:02:60:00:05:63"] = _btBluetoothDB["00:02:60:00:05:63"];
+ for (var address in _btBluetoothDB) {
+ _btSimulatedDevs[address] = _btBluetoothDB[address];
+ break;
+ }
- "TZDate": function () {
- if (typeOfObj !== "Object") {
- return null;
- }
- return (obj instanceof window.tizen.TZDate) ? obj : null;
- },
+ db.saveObject("bt-simulated-devices", _btSimulatedDevs);
+ _btRender();
+ }
+};
- "Union": function () {
- var ret, i;
+});
+define('ripple/ui/plugins/download', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- for (i in pattern) {
- ret = _self(pattern[i]).cast(obj);
- if (ret !== null)
- break;
- }
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ _data = {
+ DB_DOWNLOAD_KEY : "tizen1-db-download",
+ resources : []
+ },
+ _cleanInputs, intervalId,
+ _downloads;
- return ret;
- },
+function _get() {
+ _downloads = [
+ {id: "0001", url : "http://tizen.org/small_file.zip", size : "5", speed : "1.0", estimatedTime : "5", MIMEType : "application/zip"},
+ {id: "0002", url : "http://tizen.org/big_file.zip", size : "20", speed : "1.0", estimatedTime : "20", MIMEType : "application/zip"},
+ {id: "0003", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-hq.png", size : "3937596", speed : "1968798", estimatedTime : "2", MIMEType : "image/png"},
+ {id: "0004", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-lq.png", size : "589", speed : "589", estimatedTime : "1", MIMEType : "image/png"}
+ ];
+ _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
+ if (db.retrieveObject(_data.DB_DOWNLOAD_KEY) && db.retrieveObject(_data.DB_DOWNLOAD_KEY).length === 0) {
+ _data.resources = _downloads;
+ } else {
+ _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
+ }
+ _save();
+}
- "any": function () {
- return obj;
- },
+function _save() {
+ db.saveObject(_data.DB_DOWNLOAD_KEY, _data.resources);
+ event.trigger('downloadResourceChanged');
+}
- "boolean": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
+function checkURL(url) {
+ var rg = new RegExp("((^http)|(^https)|(^ftp)):\/\/()+");
+ return rg.test(url);
+}
- "byte": function () {
- return toInt8(obj);
- },
+function loadResources() {
+ var installed = document.getElementById("download-resource"), node, i;
+ installed.innerHTML = "";
+ for (i in _data.resources) {
+ node = utils.createElement("option", {
+ "innerText": _data.resources[i].url,
+ "value": _data.resources[i].id
+ });
+ installed.appendChild(node);
+ }
+ _cleanInputs();
+}
- "dictionary": function () {
- var attr, ret;
+function _displayInfo(text) {
+ var info = document.getElementById("download-error");
+ info.innerHTML = text;
+ if (intervalId) {
+ clearTimeout(intervalId);
+ }
+ intervalId = setTimeout(clearDisplayInfo, 5000);
+}
- if (typeOfObj !== "Object") {
- return null;
- }
+function clearDisplayInfo() {
+ document.getElementById('download-error').innerHTML = '';
+}
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- ret = _self(pattern._dictionary).cast(obj);
- if (ret === null) {
- return null;
- }
- }
- break;
+function _cleanInputs() {
+ document.getElementById("download-url").value = "";
+ document.getElementById("download-size").value = "";
+ document.getElementById("download-speed").value = "";
+ document.getElementById("download-time").innerText = "0";
+ document.getElementById("download-MIMEType").value = "";
+}
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- ret = _self(pattern[attr]).cast(obj[attr]);
- if (ret === null) {
- return null;
- }
- obj[attr] = ret;
- }
- break;
- }
- }
+function checkProperties(optionType, url, size, speed, time, MIMEType) {
+ var back = true;
+ if (url === "" || size === "" || speed === "" || time === "" || MIMEType === "") {
+ _displayInfo(optionType + " failed, empty input.");
+ back = false;
+ }
+ if (!checkURL(url)) {
+ _displayInfo(optionType + " failed, 'URL' is invalid.");
+ back = false;
+ }
+ if (size <= 0 || speed <= 0) {
+ _displayInfo(optionType + " failed, invalid input.");
+ back = false;
+ }
+ return back;
+}
- return obj;
- },
+function showUpdateNotification() {
+ var url = document.getElementById("download-url").value,
+ size = document.getElementById("download-size").value,
+ speed = document.getElementById("download-speed").value,
+ MIMEType = document.getElementById("download-MIMEType").value,
+ isValid = true;
+ if (url === "" || size === "" || speed === "" || MIMEType === "" || !checkURL(url) || size <= 0 || speed <= 0) {
+ isValid = false;
+ }
+ if (isValid) {
+ _displayInfo("Resource changed, please Add or Update the content.");
+ }
+}
- "enum": function () {
- var i;
+function _adding() {
+ var id, time, url, size, speed, MIMEType, object, i, isValid;
+ url = document.getElementById("download-url").value;
+ size = document.getElementById("download-size").value;
+ speed = document.getElementById("download-speed").value;
+ MIMEType = document.getElementById("download-MIMEType").value;
+ time = size / speed;
+ id = Math.uuid(null, 16);
- obj = String(obj).trim();
- for (i in pattern) {
- if (obj === pattern[i]) {
- return obj;
- }
- }
+ isValid = checkProperties("Add", url, size, speed, time, MIMEType);
+ if (!isValid)
+ return;
+ if (_data.resources.length !== 0) {
+ for (i in _data.resources) {
+ if (url === _data.resources[i].url) {
+ _displayInfo("Add failed, the download resource is already available.");
+ return;
+ }
+ }
+ }
+ document.getElementById("download-time").innerText = Math.round(time * 100) / 100;
+ object = {'id': id, 'url': url, 'size': size, 'speed': speed, 'estimatedTime': time, MIMEType: MIMEType};
+ _data.resources.push(object);
+ _save();
+ loadResources();
+}
- return null;
- },
+function _update() {
+ var id, time, url, size, speed, MIMEType, i, isExist = false, isValid;
- "float": function () {
- var f = parseFloat(obj, 10);
+ id = document.getElementById("download-resource").value;
+ url = document.getElementById("download-url").value;
+ size = document.getElementById("download-size").value;
+ speed = document.getElementById("download-speed").value;
+ MIMEType = document.getElementById("download-MIMEType").value;
+ time = size / speed;
- return (isNaN(f) ? null : f);
- },
+ if (_data.resources.length === 0) {
+ _displayInfo("Update failed, there is no download resource now.");
+ return;
+ }
+ isValid = checkProperties("Update", url, size, speed, time, MIMEType);
+ if (!isValid)
+ return;
+ for (i in _data.resources) {
+ if (_data.resources[i].url === url) {
+ isExist = true;
+ _data.resources[i] = {id: id, url : url, size : size, speed : speed, estimatedTime: time, MIMEType: MIMEType};
+ loadResources();
+ _save();
+ break;
+ }
+ }
+ if (!isExist)
+ _displayInfo("Update failed, the download resource doesn't exist.");
+}
- "long": function () {
- return toInt32(obj);
- },
+function _delete() {
+ var i, id;
+ id = document.getElementById("download-resource").value;
+ if (id) {
+ for (i in _data.resources) {
+ if (_data.resources[i].id === id) {
+ _data.resources.splice(i, 1);
+ _save();
+ loadResources();
+ }
+ }
+ }
+}
- "long long": function () {
- return toInt64(obj);
- },
+function _showAppDetail(id) {
+ var i;
+ for (i in _data.resources) {
+ if (id === _data.resources[i].id) {
+ document.getElementById("download-time").innerText = Math.round(_data.resources[i].estimatedTime * 100) / 100;
+ jQuery("#download-url").val(_data.resources[i].url);
+ jQuery("#download-size").val(_data.resources[i].size);
+ jQuery("#download-speed").val(_data.resources[i].speed);
+ jQuery("#download-MIMEType").val(_data.resources[i].MIMEType);
+ }
+ }
+}
- "octet": function () {
- return toUInt8(obj);
- },
+function _changeAppData() {
+ var id = jQuery("#download-resource").val();
+ _showAppDetail(id);
+}
+function changeValue() {
+ var size = document.getElementById("download-size").value,
+ speed = document.getElementById("download-speed").value;
+ if (size > 0 && speed > 0) {
+ document.getElementById("download-time").innerText = Math.round(size / speed * 100) / 100;
+ } else {
+ document.getElementById("download-time").innerText = "";
+ }
+}
+function checkInputValue(input) {
+ if (input.value === "" || input.value <= 0) {
+ input.style['border-color'] = 'red';
+ _displayInfo("Invalided value.");
+ } else {
+ if (input.style['border-color']) {
+ input.style.removeProperty('border-color');
+ }
+ changeValue();
+ //showUpdateNotification();
+ }
+}
+module.exports = {
+ panel: {
+ domId: "download-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Download",
+ display: true
+ },
+ initialize: function () {
+ _get();
+ loadResources();
- "short": function () {
- return toInt16(obj);
- },
+ document.getElementById("download-add").addEventListener("click", _adding, false);
+ document.getElementById("download-update").addEventListener("click", _update, false);
+ document.getElementById("download-delete").addEventListener("click", _delete, false);
- "unsigned long": function () {
- return toUInt32(obj);
- },
+ jQuery("#download-resource").bind("focus change", function () {
+ var url = document.getElementById("download-url"),
+ size = document.getElementById("download-size"),
+ speed = document.getElementById("download-speed"),
+ MIMEType = document.getElementById("download-MIMEType");
+ if (url.style['border-color']) {
+ url.style.removeProperty('border-color');
+ }
+ if (MIMEType.style['border-color']) {
+ MIMEType.style.removeProperty('border-color');
+ }
+ if (size.value > 0 && size.style['border-color']) {
+ size.style.removeProperty('border-color');
+ }
+ if (speed.value > 0 && speed.style['border-color']) {
+ speed.style.removeProperty('border-color');
+ }
+ _changeAppData();
+ });
+ jQuery("#download-speed").bind("blur", function () {
+ changeValue();
+ });
+ jQuery("#download-size").bind("blur", function () {
+ changeValue();
+ });
+ jQuery("#download-speed").bind("change", function () {
+ checkInputValue(this);
+ });
+ jQuery("#download-size").bind("change", function () {
+ checkInputValue(this);
+ });
+ jQuery("#download-speed").bind("change", function () {
+ checkInputValue(this);
+ });
+ jQuery("#download-url").bind("change", function () {
+ if (this.style['border-color']) {
+ this.style.removeProperty('border-color');
+ }
+ if (this.value && checkURL(this.value)) {
+ //showUpdateNotification();
+ } else {
+ _displayInfo("Invalided URL.");
+ this.style['border-color'] = 'red';
+ }
+ });
+ }
+};
- "unsigned long long": function () {
- return toUInt64(obj);
- },
+});
+define('ripple/ui/plugins/tooltips', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+// Class: UI.Tooltips
+// Purpose: build tooltips for UI
+// See here for Tooltip Options
+// http://jquery.bassistance.de/tooltip/demo/
+var utils = require('ripple/utils'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ constants = require('ripple/constants'),
+ db = require('ripple/db'),
+ utils = require('ripple/utils');
- "unsigned short": function () {
- return toUInt16(obj);
- },
+function _updateButtonText() {
+ document.querySelector("#settings-toggletooltips > span")
+ .innerHTML = "Turn " + (tooltip.isOff() ? "On" : "Off");
+}
- "": function () {
- return _self(t[pattern]).cast(obj);
- }
- };
+module.exports = {
+ initialize: function () {
+ var saved = db.retrieve(constants.SETTINGS.TOOLTIPS_KEY);
- return typeMap[typeOfPattern]();
- }
+ // blarg, tooltips are always enabled so if its saved to false disable it
+ if (!tooltip.isOff() && (saved === "false" || saved === false)) {
+ tooltip.toggle();
+ }
- function copy(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
+ _updateButtonText();
- typeMap = {
- "Arguments": function () {
- var i, isNullable, ret = [];
+ jQuery(constants.SETTINGS.TOOLTIPS_TOGGLE_DIV).click(function () {
+ db.save(constants.SETTINGS.TOOLTIPS_KEY, !tooltip.toggle());
+ _updateButtonText();
+ });
+ }
+};
- for (i in pattern) {
- if (i === "_optional")
- continue;
+});
+define('ripple/ui/plugins/deviceSettings', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ constants = require('ripple/constants'),
+ deviceSettings = require('ripple/deviceSettings'),
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ platform = require('ripple/platform'),
+ db = require('ripple/db'),
+ _CONST = {
+ "CONTENT_CONTAINER_ID": "devicesettings-content-container",
+ "UKNOWN_CONTROL_MESSAGE": "Unknown device control type"
+ },
+ _contentContainer,
+ _network_contentContainer,
+ DBNETWORKSETTING_KEY = "tizen2-preFlightModeNetworksetting",
+ _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;
- isNullable = !!(pattern._optional && pattern._optional[i]);
+function _retrieveDeviceInfo(key) {
+ var layout, rtn, deviceInfo = require('ripple/devices').getCurrentDevice();
- if (i > obj.length - 1) {
- if (!isNullable) {
- return null;
- }
- break;
- }
+ switch (key) {
+ case "Device.model":
+ return deviceInfo.model;
+ case "Device.version":
+ return deviceInfo.firmware;
+ case "Device.vendor":
+ return deviceInfo.manufacturer;
+ case "DISPLAY.resolutionHeight":
+ return deviceInfo.screen.height;
+ case "DISPLAY.resolutionWidth":
+ return deviceInfo.screen.width;
+ case "DISPLAY.pixelAspectRatio":
+ return (deviceInfo.screen.width / deviceInfo.screen.height).toFixed(2);
- if (!isNullable || (obj[i] !== null)) {
- ret[i] = _self(pattern[i]).copy(obj[i]);
- if (ret[i] === null) {
- return null;
- }
- }
- }
+ case "DISPLAY.physicalWidth":
+ return Number((deviceInfo.screen.width / deviceInfo.ppi).toFixed(2));
+ case "DISPLAY.physicalHeight":
+ return Number((deviceInfo.screen.height / deviceInfo.ppi).toFixed(2));
+ case "DISPLAY.dpiY":
+ case "DISPLAY.dotsPerInchHeight":
+ return deviceInfo.ppi;
+ case "DISPLAY.dpiX":
+ case "DISPLAY.dotsPerInchWidth":
+ return deviceInfo.ppi;
+ case "OperatingSystem.version":
+ return deviceInfo.osVersion;
+ case "OperatingSystem.name":
+ return deviceInfo.osName;
+ case "OperatingSystem.vendor":
+ return deviceInfo.manufacturer;
+ case "DEVICE_ORIENTATION.status":
+ layout = db.retrieve("layout");
+ if (layout === null || layout === undefined) {
+ layout = deviceInfo.defaultOrientation || "portrait";
+ }
+ if (layout === "portrait") {
+ return "PORTRAIT_PRIMARY";
+ } else {
+ return "LANDSCAPE_PRIMARY";
+ }
+ break;
+ case "WIFI_NETWORK.status":
+ case "CELLULAR_NETWORK.status":
+ rtn = deviceSettings.retrieve(key);
+ if (rtn === true) {
+ return "ON";
+ } else {
+ return "OFF";
+ }
+ break;
+ case "CPU.load":
+ rtn = deviceSettings.retrieve(key);
+ if (rtn > 1) {
+ rtn = 1;
+ deviceSettings.persist(key, rtn);
+ }
+ if (rtn < 0) {
+ rtn = 0;
+ deviceSettings.persist(key, rtn);
+ }
+ return rtn;
+ case "DISPLAY.brightness":
+ rtn = deviceSettings.retrieve(key);
+ if (rtn > 1) {
+ rtn = 1;
+ deviceSettings.persist("DISPLAY.brightness", rtn);
+ }
+ if (rtn < 0) {
+ rtn = 0;
+ deviceSettings.persist("DISPLAY.brightness", rtn);
+ }
+ return rtn;
+ case "BUILD.manufacturer":
+ return deviceInfo.manufacturer;
+ default:
+ return deviceSettings.retrieve(key);
+ }
+}
- for (i in ret) {
- obj[i] = ret[i];
- }
+function _retrieveSettingName(type) {
- return obj;
- },
+ switch (type) {
+ case "CellularHardware":
+ return "Cellular Hardware";
+ case "CellularNetwork":
+ return "Cellular Network";
+ case "MemoryUnit":
+ return "Memory Unit";
+ case "OperatingSystem":
+ return "Operating System";
+ case "WebRuntime":
+ return "Web Runtime";
+ case "WiFiHardware":
+ return "WiFi Hardware";
+ case "WiFiNetwork":
+ return "WiFi Network";
+ default:
+ return type;
+ }
+}
- "Array": function () {
- var arr = [], elementType, i;
+function _appendSettingNode(labelNode, inputNode, label) {
+ var frag = document.createDocumentFragment(),
+ rowNode = frag.appendChild(utils.createElement("tr")),
+ tempTdNode;
- if (typeOfObj !== typeOfPattern) {
- return null;
- }
+ rowNode.appendChild(utils.createElement("td"))
+ .appendChild(labelNode);
- elementType = _self(pattern[0]);
- for (i in obj) {
- if (obj[i]) {
- arr[i] = elementType.copy(obj[i]);
- if (arr[i] === null)
- return null;
- }
- }
+ tempTdNode = rowNode.appendChild(utils.createElement("td"));
- return arr;
- },
+ if (label) {
+ tempTdNode.appendChild(label);
+ }
- "Callback": function () {
- var ret = {}, attr;
+ tempTdNode.appendChild(inputNode);
- if (typeOfObj !== "Object") {
- return null;
- }
+ return frag;
+}
- for (attr in pattern) {
- if (attr in obj) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- }
+function _getCurrentSetting(setting, settingType, key) {
+ var ret, savedSetting, fullKey;
+ fullKey = settingType + "." + key;
+ savedSetting = _retrieveDeviceInfo(fullKey);
+ if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
+ if (savedSetting === "ON") {
+ savedSetting = true;
+ } else {
+ savedSetting = false;
+ }
+ }
+ ret = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;
+ return ret;
+}
- return ret;
- },
+function _buildDOMNode(setting, settingType, key) {
+ var settingsNode, tagName, jNode,
+ fullKey = settingType + "." + key,
+ savedSetting = _retrieveDeviceInfo(fullKey),
+ // TODO: move this into Utils (isSet method)
+ currentSetting,
+ domNode,
+ domNodeLabel = null;
- "Object": function () {
- var ret = {}, attr, i, derived;
+ if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
+ if (savedSetting === "ON") {
+ savedSetting = true;
+ } else {
+ savedSetting = false;
+ }
+ }
+ currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;
- if (typeOfObj !== typeOfPattern) {
- if ((obj === null) || (obj === undefined)) {
- return null;
- }
- if (!("_derived" in pattern)) {
- return null;
- }
- }
+ switch (setting.control.type) {
+ case "text":
+ case "number":
+ case "range":
+ case "checkbox":
+ tagName = "input";
+ break;
+ case "textarea":
+ tagName = "textarea";
+ break;
+ case "select":
+ tagName = "select";
+ break;
+ case "label":
+ tagName = "label";
+ break;
+ default:
+ exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
+ }
- if (!isConstructed(obj)) {
- return null;
- }
- if ("_constructor" in pattern) {
- ret.__proto__ = window.tizen[pattern._constructor].prototype;
- }
+ settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);
+ settingsNode.setAttribute("id", "device-settings-" + settingType + "-" + key);
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ // TODO: this should really be part of utils.createControl? add element of type "range" with label?
+ if (setting.control.type === "range") {
+ domNodeLabel = utils.createElement("label", {
+ "class": constants.UI.LEFT_RANGE_LABEL_CLASS
+ });
+ }
- case "_derived":
- for (i in pattern._derived) {
- derived = _self(pattern._derived[i]).copy(obj);
- if (derived !== null)
- break;
- }
- if (derived === null) {
- return null;
- }
- for (attr in derived) {
- ret[attr] = derived[attr];
- }
- break;
+ domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": "configure-window-text-label"}), settingsNode, domNodeLabel);
- default:
- if (!pattern._optional || !pattern._optional[attr] ||
- (obj[attr] !== undefined) &&
- (obj[attr] !== null)) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- break;
- }
- }
+ jNode = jQuery(settingsNode);
+ if (tagName !== "label") {
+ jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);
+ }
- return ret;
- },
+ switch (setting.control.type) {
+ case "checkbox":
+ jNode.bind("click", function () {
+ var checked = this.checked ? true : false;
+ deviceSettings.persist(fullKey, checked);
+ if (typeof setting.callback === "function") {
+ setting.callback(checked);
+ }
+ });
- "Union": function () {
- var ret, i;
+ if (currentSetting === true) {
+ jNode.attr("checked", "checked");
+ }
- for (i in pattern) {
- ret = _self(pattern[i]).copy(obj);
- if (ret !== null)
- break;
- }
+ break;
- return ret;
- },
+ case "text":
+ case "textarea":
+ case "number":
+ jNode.val(currentSetting);
+ utils.bindAutoSaveEvent(jNode, function () {
+ if (setting.control.type === "number") {
+ deviceSettings.persist(fullKey, Number(jNode.val()));
+ } else {
+ deviceSettings.persist(fullKey, jNode.val());
+ }
- "dictionary": function () {
- var ret = {}, attr, base, i;
+ if (typeof setting.callback === "function") {
+ setting.callback(jNode.val());
+ }
+ });
+ break;
- if (typeOfObj !== "Object") {
- return null;
- }
+ case "label":
+ jNode.text(currentSetting);
+ break;
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- base = _self(pattern._dictionary).copy(obj);
- if (base === null) {
- return null;
- }
- for (i in base) {
- ret[i] = base[i];
- }
- }
- break;
+ case "select":
+ case "range":
+ if (setting.control.type === "select") {
+ utils.forEach(setting.options, function (value, option) {
+ jNode.append(utils.createElement("option", {
+ "value": option,
+ "innerText": value
+ }));
+ });
+ }
+ else {
+ if (domNodeLabel) {
+ domNodeLabel.innerText = currentSetting;
+ }
+ }
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- break;
- }
+ jNode.val(currentSetting)
+ .bind("change", function () {
+ if (setting.control.type === "range" && domNodeLabel) {
+ domNodeLabel.innerText = jQuery(this).val();
}
+ deviceSettings.persist(fullKey, jQuery(this).val());
- return ret;
- },
-
- "": function () {
- return _self(t[pattern]).copy(obj);
+ if (typeof setting.callback === "function") {
+ setting.callback(jQuery(this).val(), currentSetting);
+ }
}
- };
-
- return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
- cast(obj);
+ );
}
- function match(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
-
- typeMap = {
- "Array": function () {
- var elementType, i;
+ // TODO: Brent, do in DeviceSettings on load instead?
+ if (currentSetting !== setting.control.value) {
+ deviceSettings.register(fullKey, currentSetting);
+ }
- if (typeOfObj !== typeOfPattern)
- return false;
+ return domNode;
+}
- elementType = _self(pattern[0]);
- for (i in obj) {
- if (!elementType.match(obj[i])) {
- return false;
- }
- }
+function displayBrightnessCB(value) {
+ if (value > 1) value = 1;
+ if (value < 0) value = 0;
+ if (document.getElementById("device-settings-DISPLAY-brightness").value === value) {
+ return;
+ }
+ deviceSettings.persist("DISPLAY.brightness", Number(value));
+ document.getElementById("device-settings-DISPLAY-brightness").value = value;
+}
- return true;
- },
+function cpuLoadCB(value) {
+ if (value > 1) value = 1;
+ if (value < 0) value = 0;
+ if (document.getElementById("device-settings-CPU-load").value === value) {
+ return;
+ }
+ deviceSettings.persist("CPU.load", Number(value));
+ document.getElementById("device-settings-CPU-load").value = value;
+}
- "Callback": function () {
- var attr, isMatched = true;
+function availCapacityCB(value) {
+ var capacity = deviceSettings.retrieve("STORAGE.capacity");
+ if (Number(value) > Number(capacity)) value = capacity;
+ if (Number(value) < 0) value = 0;
+ deviceSettings.persist("STORAGE.availableCapacity", Number(value));
+ document.getElementById("device-settings-STORAGE-availableCapacity").value = Number(value);
+}
- if (typeOfObj !== "Object") {
- return false;
- }
+function wiFiNetworkStatusCB(value) {
+ document.getElementById("device-settings-WIFI_NETWORK-status").checked = value;
+}
- for (attr in pattern) {
- if (attr in obj) {
- isMatched = _self(pattern[attr]).match(obj[attr]);
- if (!isMatched) {
- break;
- }
- }
- }
+function flightModeChangedCB(value) {
+ var networkSettings = {};
+ if (value === true) {
+ networkSettings['wifiSetting'] = deviceSettings.retrieve("WIFI_NETWORK.status");
+ networkSettings['cellularSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
+ //networkSettings['bluetoothSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
+ //networkSettings['nfcSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
+ db.saveObject(DBNETWORKSETTING_KEY, networkSettings);
- return isMatched;
- },
+ deviceSettings.persist("CELLULAR_NETWORK.status", false);
+ deviceSettings.persist("WIFI_NETWORK.status", false);
+ event.trigger("nfc-power-setting", [false]);
+ event.trigger("bt-power-setting", [false]);
- "DOMString": function () {
- return (typeOfObj === typeOfPattern);
- },
+ document.getElementById("device-settings-WIFI_NETWORK-status").checked = false;
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = false;
+ $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'> (Disabled for Flight Mode)</span>");
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;
- "Date": function () {
- return (typeOfObj === typeOfPattern);
- },
+ } else {
+ networkSettings = db.retrieveObject(DBNETWORKSETTING_KEY)||{"wifiSetting": true, "cellularSetting": true};
+ deviceSettings.persist("WIFI_NETWORK.status", networkSettings['wifiSetting']);
+ deviceSettings.persist("CELLULAR_NETWORK.status", networkSettings['cellularSetting']);
+ document.getElementById("device-settings-WIFI_NETWORK-status").checked = networkSettings['wifiSetting'];
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = networkSettings['cellularSetting'];
+ $("#config_flight_mode_notice").remove();
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = false;
+ }
+}
- "Function": function () {
- return (typeOfObj === typeOfPattern);
- },
+function cellularNetworkStatusCB(value) {
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = value;
+}
- "Object": function () {
- var attr, isMatched = false, i;
+function layoutCB(value) {
+ if (value === 'portrait') {
+ deviceSettings.register("DEVICE_ORIENTATION.status", "PORTRAIT_PRIMARY");
+ document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "PORTRAIT_PRIMARY";
+ } else {
+ deviceSettings.register("DEVICE_ORIENTATION.status", "LANDSCAPE_PRIMARY");
+ document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "LANDSCAPE_PRIMARY";
+ }
+}
- if (typeOfObj !== typeOfPattern) {
- if ((obj === null) || (obj === undefined)) {
- return false;
- }
- if (!("_derived" in pattern)) {
- return false;
- }
- return false;
- }
+// goes through current platforms device settings
+// adds nodes to panel and binds respective events
+// talks to DeviceSettings for persistence
+module.exports = {
+ initialize: function () {
+ var settings, value;
+ _contentContainer = document.getElementById(_CONTAINER_ID);
+ _network_contentContainer = document.getElementById("networksettings-content-container");
- if (!isConstructed(obj)) {
- return false;
- }
+ settings = platform.current().device;
+ utils.forEach(settings, function (settingSection, settingType) {
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ var currentTableNode, currentTableNode2, settingNameNode, settingName = _retrieveSettingName(settingType);
- case "_derived":
- for (i in pattern._derived) {
- isMatched = _self(pattern._derived[i]).match(obj);
- if (isMatched)
- break;
- }
- break;
+ settingNameNode = utils.createElement("h3", { "innerText": settingName });
+ settingNameNode.setAttribute("class", "configure-window-session-title");
- default:
- if (pattern._optional && pattern._optional[attr]) {
- isMatched = ((obj[attr] === null) ||
- (obj[attr] === undefined) ||
- _self(pattern[attr]).match(obj[attr]));
- } else {
- isMatched = (obj[attr] !== undefined) &&
- _self(pattern[attr]).match(obj[attr]);
- }
- break;
- }
+ if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
+ _network_contentContainer.appendChild(settingNameNode);
+ currentTableNode2 = utils.createElement("table", {
+ "class": constants.UI.PANEL_TABLE_CLASS
+ });
+ currentTableNode2.setAttribute("class", "configure-window-panel-table");
+ _network_contentContainer.appendChild(currentTableNode2);
+ }
+ else {
+ _contentContainer.appendChild(settingNameNode);
+ currentTableNode = utils.createElement("table", {
+ "class": constants.UI.PANEL_TABLE_CLASS
+ });
+ currentTableNode.setAttribute("class", "configure-window-panel-table");
+ _contentContainer.appendChild(currentTableNode);
+ }
- if (!isMatched)
- break;
+ utils.forEach(settingSection, function (setting, key) {
+ if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
+ currentTableNode2.appendChild(_buildDOMNode(setting, settingType, key));
+ }
+ else {
+ currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
+ }
+ value = _getCurrentSetting(setting, settingType, key);
+ if (setting.callback) {
+ setting.callback(value);
}
+ });
+ });
- /*// Check if verbose attributes are present
- if (isMatched) {
- for (attr in obj) {
- if (pattern[attr] === undefined) {
- isMatched = false;
- break;
- }
- }
- }*/
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
+ $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'> (Disabled for Flight Mode)</span>");
+ document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;
+ }
- return isMatched;
- },
+ event.on("DisplayBrightnessChanged", displayBrightnessCB);
+ event.on("DisplayBrightnessChangedByPower", displayBrightnessCB);
+ event.on("CpuLoadChanged", cpuLoadCB);
+ event.on("AvailCapacityChanged", availCapacityCB);
+ event.on("CpuLoadChangedByPower", cpuLoadCB);
+ event.on("FlightModeChanged", flightModeChangedCB);
+ event.on("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
+ event.on("CellularNetworkStatusChanged", cellularNetworkStatusCB);
+ event.on("LayoutChanged", layoutCB);
+ },
+ terminate: function () {
+ event.deleteEventHandler("DisplayBrightnessChanged", displayBrightnessCB);
+ event.deleteEventHandler("DisplayBrightnessChangedByPower", displayBrightnessCB);
+ event.deleteEventHandler("CpuLoadChanged", cpuLoadCB);
+ event.deleteEventHandler("AvailCapacityChanged", availCapacityCB);
+ event.deleteEventHandler("FlightModeChanged", flightModeChangedCB);
+ event.deleteEventHandler("CpuLoadChangedByPower", cpuLoadCB);
+ event.deleteEventHandler("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
+ event.deleteEventHandler("CellularNetworkStatusChanged", cellularNetworkStatusCB);
+ event.deleteEventHandler("LayoutChanged", layoutCB);
+ }
+};
- "Union": function () {
- var isMatched, i;
+});
+define('ripple/ui/plugins/invoke', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ event = require('ripple/event');
- for (i in pattern) {
- isMatched = _self(pattern[i]).match(obj);
- if (isMatched)
- break;
+module.exports = {
+ panel: {
+ domId: "invoke-container",
+ collapsed: true,
+ pane: "left"
+ },
+ initialize: function () {
+ document.getElementById("invoke-send")
+ .addEventListener("click", function () {
+ var invokeInfo = {};
+
+ invokeInfo.uri = document.getElementById("invoke-uri-text").value;
+ invokeInfo.source = document.getElementById("invoke-source-text").value;
+ invokeInfo.target = document.getElementById("invoke-target-text").value;
+ invokeInfo.action = document.getElementById("invoke-action-text").value;
+ invokeInfo.type = document.getElementById("invoke-mime-type-text").value;
+ invokeInfo.extension = document.getElementById("invoke-extension-text").value;
+ invokeInfo.data = document.getElementById("invoke-data-text").value;
+ if (invokeInfo.data) {
+ invokeInfo.data = window.btoa(invokeInfo.data);
}
- return isMatched;
- },
+ event.trigger("AppInvoke", [invokeInfo]);
+ }, false);
+ }
+};
- "any": function () {
- return true;
- },
+});
+define('ripple/ui/plugins/touchEvent', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation
+ *
+ * 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.
+ */
- "boolean": function () {
- return (typeOfObj === typeOfPattern);
- },
+var event = require('ripple/event'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants'),
+ colors = ["red", "green", "magenta", "blue", "yellow"],
+ Point,
+ intervalId,
+ moveEvents = {},
+ currentIndex = 0,
+ enlargeRatio = 4;
- "byte": function () {
- return (obj === toInt8(obj));
- },
+function _exec(operation) {
+ var canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
+ cxt = canvas.getContext("2d"),
+ altKey = document.getElementById(constants.TOUCHEVENT.ALTKEY),
+ metaKey = document.getElementById(constants.TOUCHEVENT.METAKEY),
+ ctrlKey = document.getElementById(constants.TOUCHEVENT.CTRLKEY),
+ shiftKey = document.getElementById(constants.TOUCHEVENT.SHIFTKEY),
+ key, eventType;
- "dictionary": function () {
- var attr, isMatched = true;
+ if (operation === "start") {
+ altKey.disabled = 'disabled';
+ metaKey.disabled = 'disabled';
+ ctrlKey.disabled = 'disabled';
+ shiftKey.disabled = 'disabled';
+ clearInterval(intervalId);
+ currentIndex = 0;
+ eventType = "touchEvent";
+ } else if (operation === "cancel") {
+ altKey.disabled = '';
+ metaKey.disabled = '';
+ ctrlKey.disabled = '';
+ shiftKey.disabled = '';
+ altKey.checked = false;
+ metaKey.checked = false;
+ ctrlKey.checked = false;
+ shiftKey.checked = false;
+ cxt.clearRect(0, 0, canvas.width, canvas.height);
+ moveEvents = {};
+ eventType = "touchCancel";
+ }
- if (typeOfObj !== "Object") {
- return false;
- }
+ event.trigger(eventType, [{
+ data : moveEvents,
+ keys : [altKey.checked, metaKey.checked, ctrlKey.checked, shiftKey.checked]
+ }]);
+}
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- isMatched = _self(pattern._dictionary).match(obj);
- if (!isMatched)
- break;
- }
- break;
+Point = function (x, y, color, isDragging) {
+ var _self = {};
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- isMatched = _self(pattern[attr]).match(obj[attr]);
- if (!isMatched)
- break;
- }
- break;
- }
- }
+ _self.x = x;
+ _self.y = y;
+ _self.color = color;
+ _self.isDragging = isDragging;
- return isMatched;
- },
+ return _self;
+};
- "enum": function () {
- for (var i in pattern) {
- if (obj === pattern[i]) {
- return true;
- }
- }
+module.exports = {
+ panel: {
+ domId: "touchEvent-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Touch Event",
+ display: true
+ },
- return false;
- },
+ initialize: function () {
+ var deviceInfo = require('ripple/devices').getCurrentDevice(),
+ canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
+ button = document.getElementById(constants.TOUCHEVENT.OPTION),
+ cxt = canvas.getContext("2d"),
+ points = [],
+ paint = false,
+ currentPoint = {};
- "float": function () {
- return (typeOfObj === "Number");
- },
+ function drawPoints() {
+ var key, index, points = [], point;
- "long": function () {
- return (obj === toInt32(obj));
- },
+ for (key in moveEvents) {
+ points = moveEvents[key];
+ cxt.fillStyle = colors[key];
- "long long": function () {
- return (obj === toInt64(obj));
- },
+ for (index = 0; index < points.length; index++) {
+ point = points[index];
+ cxt.beginPath();
+ cxt.arc(point.offsetX, point.offsetY, 5, 0, 2 * Math.PI, 1);
+ cxt.fill();
+ }
+ }
+ }
- "octet": function () {
- return (obj === toUInt8(obj));
- },
+ function endDraw(event) {
+ if (paint) {
+ paint = false;
+ clearInterval(intervalId);
+ moveEvents[currentIndex].push(event);
+ drawPoints();
- "short": function () {
- return (obj === toInt16(obj));
- },
+ currentIndex++;
+ if (currentIndex === 5)
+ currentIndex = 0;
+ }
+ }
- "unsigned long": function () {
- return (obj === toUInt32(obj));
- },
+ canvas.addEventListener("mousedown", function (event) {
+ if (button.value === "Touch Cancel") {
+ button.value = "Touch Start";
+ _exec("cancel");
+ }
+ moveEvents[currentIndex] = [];
+ currentPoint = event;
+ moveEvents[currentIndex].push(event);
+ paint = true;
+ drawPoints();
+ intervalId = setInterval(function () {
+ moveEvents[currentIndex].push(currentPoint);
+ }, 100);
+ });
- "unsigned long long": function () {
- return (obj === toUInt64(obj));
- },
+ canvas.addEventListener("mousemove", function (event) {
+ if (paint) {
+ currentPoint = event;
+ drawPoints();
+ }
+ });
- "unsigned short": function () {
- return (obj === toUInt16(obj));
- },
+ canvas.addEventListener("mouseup", endDraw);
+ canvas.addEventListener("mouseout", endDraw);
+ canvas.addEventListener("mouseleave", endDraw);
- "Arguments": function () {
- return true;
- },
+ document.getElementById(constants.TOUCHEVENT.OPTION).addEventListener("click", function () {
+ if (!moveEvents[0])
+ return;
- "": function () {
- return _self(t[pattern]).match(obj);
+ if (this.value === "Touch Start") {
+ this.value = "Touch Cancel";
+ _exec("start");
+ } else if (this.value === "Touch Cancel") {
+ this.value = "Touch Start";
+ _exec("cancel");
}
- };
+ }, false);
- return typeMap[typeOfPattern]();
+ canvas.width = deviceInfo.screen.width / enlargeRatio;
+ canvas.height = deviceInfo.screen.height / enlargeRatio;
}
-
- typeOfPattern = getType(pattern, true);
-
- typeCoerce = {
- cast: cast,
- copy: copy,
- match: match
- };
-
- return typeCoerce;
};
-module.exports = _self;
-
});
-define('ripple/platform/ivi/3.0/typedef', function (require, exports, module) {
+define('ripple/ui/plugins/options', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var about = require('ripple/ui/plugins/about-dialog'),
+ settings = require('ripple/ui/plugins/settings-dialog'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ hide,
+ show;
-var _t, _c, _i;
+show = function () {
+ if (settings.value("remoteInspector")) {
+ $("#options-menu-build-warning").show();
+ tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
+ }
+ else {
+ $("#options-menu-build-warning").hide();
+ }
-/*
- * Primitive type definition
- */
+ $("#options-window").show();
+ $("#options-menu").show();
+};
-_t = {
- // Basic
- Callback: "Callback",
- DOMString: "",
- Date: new Date(),
- Function: function () {},
- TZDate: "TZDate",
- any: "any",
- boolean: false,
- byte: "byte",
- double: "double",
- float: "float",
- long: "long",
- octet: "octet",
- short: "short",
- long_long: "long long",
- unsigned_long: "unsigned long",
- unsigned_long_long: "unsigned long long",
- unsigned_short: "unsigned short"
+hide = function () {
+ $("#options-window").hide();
+ $("#options-menu").effect("fade", {}, 300);
};
-/*
- * Derivative type definition
- */
+module.exports = {
+ initialize: function () {
+ $("#options-menu").menu().hide();
+ $("#options-menu").bind("click", function (event) {
+ var target = $("#" + event.target.parentElement.id),
+ action;
+
+ if (target.hasClass("not-ready")) {
+ return;
+ }
+
+ switch (target.attr("id")) {
+ case "options-menu-build":
+ case "options-menu-launch":
+ case "options-menu-sign":
+ action = target.attr("id").split("-")[2];
+ if (!settings.can(action)) {
+ settings.show(action);
+ }
+ else {
+ settings.perform(action);
+ }
+ break;
+ case "options-menu-about":
+ about.show();
+ break;
+ case "options-menu-settings":
+ settings.show();
+ break;
+ default:
+ break;
+ }
+ hide();
+ });
+
+ $("#options-window").click(hide);
+
+ $("#options-button-about").bind("click", function (event) {
+ about.show();
+ });
+
+ hide();
+ }
+};
+});
+define('ripple/ui/plugins/geoDB', function (require, exports, module) {
/*
- * Object attributes
- * Contruct a prototype of an object. Specify a primitive type for each attribute.
- *
- * _optional
- * Optional attributes table, which consists of two types of attributes,
- *
- * nullable
- * Nullable attributes, marked as '?' in IDL.
- *
- * undefined
- * Array type attributes, that not definitely specified to be
- * initialized as an empty array, i.e., undefined-initialized array.
- *
- * _derived
- * Derived types, which used in two cases of definition,
+ * Copyright 2012 Intel Corporation.
*
- * Subtype list
- * An array consists of derived subtypes. It exists in the definition of
- * a base type.
+ * 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
*
- * Union types
- * An array consists of member types. It exists in the definition of
- * a union type.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * _dictionary
- * Dictionary type, which indicates that the object is a dictionary type.
- */
-
-/*
- * Vehicle
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-_t.SupportedPropertiesSuccessCallback = _t.Function;
-
-_t.VehiclePropertyErrorCallback = _t.Function;
-_t.VehiclePropertyCallback = _t.Function;
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
+ _GEO_OBJECTS = "tizen1.0-geocode-objects",
+ _geoList, _currentGeo, _saveID, _showGeoDetail;
-_t.VehiclePropertyListCallback = _t.Function;
+function _getGeo() {
+ var geoList = [],
+ data = db.retrieveObject(_GEO_OBJECTS);
-/*
- * VehicleSpeed
- */
-_t.VehicleSpeed = {
- vehicleSpeed: _t.unsigned_long
-};
+ utils.forEach(data, function (geo) {
+ geoList.push(geo);
+ });
+ return geoList;
+}
-/*
- * EngineSpeed
- */
-_t.EngineSpeed = {
- engineSpeed: _t.unsigned_long
-};
+function _saveGeo() {
+ db.saveObject(_GEO_OBJECTS, _geoList);
+}
-/*
- * VehiclePowerMode
- */
-_t.VehiclePowerMode = {
- vehiclePowerMode: _t.octet
-};
+function GeoEntry(addr, coord) {
+ var _self;
+ _self = {
+ address : addr || null,
+ coordinate : coord || null
+ };
+ return _self;
+}
-/*
- * TripMeters
- */
-_t.TripMeter = {
- tripMeters: [_t.unsigned_long]
-};
+function _updateGeoDBSelect() {
+ var geoDBSelect = document.getElementById("geo-select"),
+ geoNode, i;
-/*
- * Acceleration
- */
-_t.Acceleration = {
- x: _t.unsigned_long,
- y: _t.unsigned_long,
- z: _t.unsigned_long
-};
+ geoDBSelect.innerHTML = "";
+ for (i = 0; i < _geoList.length; i++) {
+ geoNode = utils.createElement("option", {
+ "innerText": "(" + _geoList[i].coordinate.latitude + ", " + _geoList[i].coordinate.longitude + ")",
+ "value": i
+ });
+ if (_currentGeo === Number(geoNode.value)) {
+ geoNode.selected = true;
+ _showGeoDetail(_geoList[_currentGeo].coordinate, _geoList[_currentGeo].address);
+ }
+ geoDBSelect.appendChild(geoNode);
+ }
+}
-/*
- * Transmission
- */
-_t.Transmission = {
- gearPosition: _t.octet,
- mode: _t.octet
-};
+function _showGeoDetail(coord, addr) {
+ jQuery("#geoDB-latitude").val(coord.latitude);
+ jQuery("#geoDB-longitude").val(coord.longitude);
+ jQuery("#geoDB-altitude").val(coord.altitude);
+ jQuery("#geoDB-accuracy").val(coord.accuracy);
+ jQuery("#geoDB-altitudeAccuracy").val(coord.altitudeAccuracy);
+ jQuery("#geoDB-heading").val(coord.heading);
+ jQuery("#geoDB-speed").val(coord.speed);
-/*
- * CruiseControlStatus
- */
-_t.CruiseControlStatus = {
- activated: _t.boolean,
- speed: _t.unsigned_short
-};
-/*
- * WheelBrake
- */
-_t.WheelBrake = {
- engaged: _t.boolean
-};
+ jQuery("#geoDB-country").val(addr.country);
+ jQuery("#geoDB-region").val(addr.region);
+ jQuery("#geoDB-county").val(addr.county);
+ jQuery("#geoDB-city").val(addr.city);
+ jQuery("#geoDB-street").val(addr.street);
+ jQuery("#geoDB-streetNumber").val(addr.streetNumber);
+ jQuery("#geoDB-premises").val(addr.premises);
+ jQuery("#geoDB-additionalInformation").val(addr.additionalInformation);
+ jQuery("#geoDB-postalCode").val(addr.postalCode);
+}
-/*
- * LightStatus
- */
-_t.LightStatus = {
- head: _t.boolean,
- rightTurn: _t.boolean,
- leftTurn: _t.boolean,
- brake: _t.boolean,
- fog: _t.boolean,
- hazard: _t.boolean,
- parking: _t.boolean,
- highBeam: _t.boolean
-};
+function _changeGeoData() {
+ var id = Number(jQuery("#geo-select").val());
+ _currentGeo = id;
+ _showGeoDetail(_geoList[id].coordinate, _geoList[id].address);
+}
-/*
- * InteriorLightStatus
- */
-_t.InteriorLightStatus = {
- passenger: _t.boolean,
- driver: _t.boolean,
- center: _t.boolean
-};
+function _triggerReadOnly(on) {
+ if (on === true) {
+ jQuery("#geoDB-table input").attr("readonly", "readonly");
+ jQuery("#geoDB-add").show();
+ jQuery("#geoDB-modify").show();
+ jQuery("#geoDB-delete").show();
+ jQuery("#geo-select").removeAttr("disabled");
+ jQuery("#geoDB-save").hide();
+ jQuery("#geoDB-cancel").hide();
+ } else {
+ jQuery("#geoDB-table input").removeAttr("readonly");
+ jQuery("#geoDB-add").hide();
+ jQuery("#geoDB-modify").hide();
+ jQuery("#geoDB-delete").hide();
+ jQuery("#geo-select").attr("disabled", "disabled");
+ jQuery("#geoDB-save").show();
+ jQuery("#geoDB-cancel").show();
+ }
+}
-/*
- * Horn
- */
-_t.Horn = {
- on: _t.boolean
-};
-
-/*
- * Fuel
- */
-_t.Fuel = {
- level: _t.unsigned_short,
- range: _t.unsigned_short,
- instantConsumption: _t.unsigned_short,
- instantEconomy: _t.unsigned_short,
- averageEconomy: _t.unsigned_short
-};
+function _addGeoData() {
+ _triggerReadOnly(false);
+ jQuery("#geoDB-table input").val("");
+ _saveID = _geoList.length;
+ jQuery("#geo-select").val("");
+}
+function _modifyGeoData() {
+ _triggerReadOnly(false);
+ _saveID = _currentGeo;
+}
+function _deleteGeoData() {
+ _geoList.splice(_currentGeo, 1);
+ _saveGeo();
+ _currentGeo = 0;
+ _updateGeoDBSelect();
+}
+function _saveGeoData() {
+ var entry;
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ country: jQuery("#geoDB-country").val(),
+ region: jQuery("#geoDB-region").val(),
+ county: jQuery("#geoDB-county").val(),
+ city: jQuery("#geoDB-city").val(),
+ street: jQuery("#geoDB-street").val(),
+ streetNumber: jQuery("#geoDB-streetNumber").val(),
+ premises: jQuery("#geoDB-premises").val(),
+ additionalInformation: jQuery("#geoDB-additionalInformation").val(),
+ postalCode: jQuery("#geoDB-postalCode").val()
+ }),
+ new lbs.GeoCoordinates({
+ latitude: parseFloat(jQuery("#geoDB-latitude").val()),
+ longitude: parseFloat(jQuery("#geoDB-longitude").val()),
+ altitude: parseFloat(jQuery("#geoDB-altitude").val()),
+ accuracy: parseFloat(jQuery("#geoDB-accuracy").val()),
+ altitudeAccuracy: parseFloat(jQuery("#geoDB-altitudeAccuracy").val()),
+ heading: parseFloat(jQuery("#geoDB-heading").val()),
+ speed: parseFloat(jQuery("#geoDB-speed").val())
+ }));
+ if (_saveID === _geoList.length)
+ _geoList.push(entry);
+ else
+ _geoList[_saveID] = entry;
+
+ _saveGeo();
+ _currentGeo = _saveID;
+ _updateGeoDBSelect();
+ _triggerReadOnly(true);
+}
-/*
- * EngineOil
- */
-_t.EngineOil = {
- remaining: _t.unsigned_short,
- temperature: _t.long,
- pressure: _t.unsigned_short
-};
+function _cancelGeoData() {
+ _triggerReadOnly(true);
+ _updateGeoDBSelect();
+}
-/*
- * Location
- */
-_t.Location = {
- latitude: _t.double,
- longitude: _t.double,
- altitude: _t.double,
- direction: _t.unsigned_short
-};
+module.exports = {
+ panel: {
+ domId: "geoDB-container",
+ collapsed: true,
+ pane: "right"
+ },
-/*
- * ExteriorBrightness
- */
-_t.ExteriorBrightness = {
- exteriorBrightness: _t.unsigned_long
-};
+ initialize: function () {
+ _currentGeo = 0; // set _geoList[0] as default value
+ _geoList = _getGeo();
+ _updateGeoDBSelect();
+ _triggerReadOnly(true);
-/*
- * Temperature
- */
-_t.Temperature = {
- interior: _t.short,
- exterior: _t.short
+ jQuery("#geo-select").bind("change", function () {
+ _changeGeoData();
+ });
+ jQuery("#geoDB-add").bind("click", function () {
+ _addGeoData();
+ });
+ jQuery("#geoDB-modify").bind("click", function () {
+ _modifyGeoData();
+ });
+ jQuery("#geoDB-delete").bind("click", function () {
+ _deleteGeoData();
+ });
+ jQuery("#geoDB-save").bind("click", function () {
+ _saveGeoData();
+ });
+ jQuery("#geoDB-cancel").bind("click", function () {
+ _cancelGeoData();
+ });
+ }
};
+});
+define('ripple/ui/plugins/nfc', function (require, exports, module) {
/*
- * RainSensor
+ * Copyright 2012 Intel Corporation
+ *
+ * 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.
*/
-_t.RainSensor = {
- rainSensor: _t.unsigned_short
-};
-/*
- * WindshieldWiper
- */
-_t.WindshieldWiper = {
- windshieldWiper: _t.unsigned_short
-};
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ _NFC_TAG = "tizen1.0-nfc-tag",
+ _NFC_PEER = "tizen1.0-nfc-peer",
+ _NFC_OUTPUT_MESSAGE = "tizen1.0-nfc-output-message",
+ powered = false,
+ polling = false,
+ isConnected = false,
+ _tagNDEF = {
+ type: "GENERIC_TARGET",
+ isSupportedNDEF: true,
+ ndefSize: 2,
+ ndefs: [{
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID001",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID002",
+ payload: "This is 2nd payload"
+ }]
+ },
+ {
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID001",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID002",
+ payload: "This is 2nd payload"
+ }]
+ }]
+ },
+ _tagRaw = {
+ type: "GENERIC_TARGET",
+ isSupportedNDEF: false,
+ rawData : ""
+ },
+ _peerNDEF = {
+ ndef: {
+ recordCount: 2,
+ records: [{
+ tnf: 1,
+ type: "TypeA",
+ id: "ID001",
+ payload: "This is 1st payload"
+ }, {
+ tnf: 1,
+ type: "TypeA",
+ id: "ID002",
+ payload: "This is 2nd payload"
+ }]
+ }
+ };
-/*
- * DefrostDictionary
- */
-_t.DefrostDictionary = {
- window: _t.unsigned_short,
- defrost: _t.boolean,
+function elementEnableDisableSetting(prop) {
+ jQuery("#nfc-attach-msg").text("\xa0");
+ jQuery("#nfc-peer-send-msg").text("\xa0");
+ if (prop && prop.power !== undefined && prop.power !== null) {
+ if (prop.power) {
+ $("#nfc-polling").removeAttr("disabled");
+ $("#nfc-main-container").show();
+ } else {
+ $("#nfc-polling").attr("disabled", "disabled");
+ $("#nfc-type").removeAttr("disabled");
+ $("#nfc-main-container").hide();
+ }
+ }
+ if (prop && prop.connectedState !== undefined && prop.connectedState !== null) {
+ if (prop.connectedState) {
+ $("#nfc-type").attr("disabled", "disabled");
+ $("#nfc-tag-type-text").text($("#nfc-tag-type option:selected").text());
+ $("#nfc-tag-type").hide();
+ $("#nfc-tag-type-text").show();
+ $("#nfc-tag-NDEF-support-text").text($("#nfc-tag-NDEF-support option:selected").text());
+ $("#nfc-tag-NDEF-support").hide();
+ $("#nfc-tag-NDEF-support-text").show();
+ $("#nfc-raw-data").attr("disabled", "disabled");
+ } else {
+ $("#nfc-type").removeAttr("disabled");
+ $("#nfc-tag-type").show();
+ $("#nfc-tag-type-text").hide();
+ $("#nfc-tag-NDEF-support").show();
+ $("#nfc-tag-NDEF-support-text").hide();
+ $("#nfc-raw-data").removeAttr("disabled");
+ }
+ }
+}
- _dictionary: true
-};
+function _initializeElements() {
-/*
- * HVAC
- */
-_t.HVAC = {
- airflowDirection: _t.unsigned_short,
- fanSpeed: _t.unsigned_short,
- targetTemperature: _t.unsigned_short,
- airConditioning: _t.boolean,
- airRecirculation: _t.boolean,
- heater: _t.boolean,
- steeringWheelHeater: _t.boolean,
- seatHeater: _t.boolean,
- seatCooler: _t.boolean
-};
+ jQuery(function () {
+ var stop = false,
+ isSupportNDEF, type;
-/*
- * WindowStatus
- */
-_t.WindowStatus = {
- openness: _t.unsigned_short,
- defrost: _t.boolean
-};
+ jQuery("nfc-tag-ndef-container h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#nfc-tag-ndef-container").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ jQuery("nfc-nfcpeer h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#nfc-nfcpeer").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ jQuery("#nfc-tag-NDEF-support").bind("change", function () {
+ isSupportNDEF = jQuery("#nfc-tag-NDEF-support").val();
+ if (isSupportNDEF === "Yes") {
+ jQuery("#nfc-tag-ndef-container").fadeIn();
+ jQuery("#nfc-tag-raw-container").hide();
+ } else {
+ jQuery("#nfc-tag-ndef-container").hide();
+ jQuery("#nfc-tag-raw-container").fadeIn();
+ }
+ });
+ jQuery("#nfc-type").bind("change", function () {
+ type = jQuery("#nfc-type").val();
+ if (type === "Tag") {
+ jQuery("#nfc-nfctag").fadeIn();
+ jQuery("#nfc-nfcpeer").hide();
+ } else {
+ jQuery("#nfc-nfctag").hide();
+ jQuery("#nfc-nfcpeer").fadeIn();
+ }
+ elementEnableDisableSetting();
+ });
+ jQuery("#nfc-power").bind("change", function () {
+ var status;
+ status = jQuery("#nfc-power").val() === "On" ? true : false;
+ event.trigger("nfc-power-setting", [status]);
+ });
+ jQuery("#nfc-polling").bind("change", function () {
+ var status;
+ status = jQuery("#nfc-polling").val() === "On" ? true : false;
+ event.trigger("nfc-polling-setting", [status]);
+ });
+ jQuery("#nfc-attach").bind("click", function () {
+ var type, isAttached;
+ isAttached = jQuery("#nfc-attach").children().text() === "Attach" ? true : false;
+ jQuery("#nfc-attach-msg").text("\xa0");
-/*
- * Sunroof
- */
-_t.Sunroof = {
- openness: _t.unsigned_short,
- tilt: _t.unsigned_short
-};
+ if (!polling && isAttached) {
+ jQuery("#nfc-attach-msg").text("Polling:Off, attach won't work");
+ return;
+ }
+ type = jQuery("#nfc-type").val();
+ event.trigger("nfc-attach-setting", [type, isAttached]);
+ });
+ jQuery("#nfc-peer-send").bind("click", function () {
+ jQuery("#nfc-peer-send-msg").text("\xa0");
+ if (!isConnected) {
+ jQuery("#nfc-peer-send-msg").text("Disconnected. Send won't work");
+ return;
+ }
+ db.saveObject(_NFC_PEER, _peerNDEF);
+ event.trigger("nfc-peer-sending-ndef", []);
+ });
+ });
+}
-/*
- * ConvertibleRoof
- */
-_t.ConvertibleRoof = {
- openness: _t.unsigned_short
+module.exports = {
+ panel: {
+ domId: "nfc-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "NFC",
+ display: true
+ },
+ initialize: function () {
+ _initializeElements();
+ event.on("nfc-power-changed", function (status) {
+ powered = status;
+ if (powered === true) {
+ $("#nfc-power").val("On");
+ } else {
+ $("#nfc-power").val("Off");
+ }
+ elementEnableDisableSetting({power: status});
+ });
+ event.on("nfc-polling-changed", function (status) {
+ polling = status;
+ if (polling === true) {
+ $("#nfc-polling").val("On");
+ } else {
+ $("#nfc-polling").val("Off");
+ }
+ elementEnableDisableSetting();
+ });
+ event.on("nfc-connectedState-changed", function (state) {
+ var i, type, isSupportedNDEF, str, bytes = [];
+ isConnected = state;
+ elementEnableDisableSetting({connectedState: state});
+ type = jQuery("#nfc-type").val();
+ if (state) {
+ jQuery("#nfc-attach").children().text("Detach");
+ jQuery("#nfc-tag-connection").text("Connected");
+ jQuery("#nfc-peer-connection").text("Connected");
+ if (type === "Tag") {
+ isSupportedNDEF = jQuery("#nfc-tag-NDEF-support").val() === "Yes" ? true : false;
+ if (isSupportedNDEF) {
+ _tagNDEF.type = jQuery("#nfc-tag-type").val();
+ db.saveObject(_NFC_TAG, _tagNDEF);
+ } else {
+ _tagRaw.type = jQuery("#nfc-tag-type").val();
+ str = jQuery("#nfc-raw-data").val();
+ for (i = 0; i < str.length; i++) {
+ bytes.push(str.charCodeAt(i));
+ }
+ _tagRaw.rawData = bytes;
+ db.saveObject(_NFC_TAG, _tagRaw);
+ }
+ event.trigger("nfc-tag-send", [true]);
+ } else {
+ event.trigger("nfc-peer-send", [true]);
+ }
+ } else {
+ jQuery("#nfc-attach").children().text("Attach");
+ jQuery("#nfc-tag-connection").text("Disconnected");
+ jQuery("#nfc-peer-connection").text("Disconnected");
+ jQuery("#nfc-output").text("");
+ jQuery("#nfc-output-table").hide();
+ if (type === "Tag") {
+ event.trigger("nfc-tag-send", [false]);
+ } else {
+ event.trigger("nfc-peer-send", [false]);
+ }
+ }
+ });
+ event.on("nfc-output-msg", function () {
+ var msg;
+ msg = db.retrieve(_NFC_OUTPUT_MESSAGE);
+ jQuery("#nfc-output").text(msg);
+ jQuery("#nfc-output-table").show();
+ });
+ }
};
-/*
- * VehicleId
- */
-_t.VehicleId = {
- WMI: _t.DOMString,
- VIN: _t.DOMString
-};
+});
+define('ripple/ui/plugins/settings-dialog', function (require, exports, module) {
/*
- * Size
+ * Copyright 2011 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.
*/
-_t.Size = {
- width: _t.unsigned_long,
- height: _t.unsigned_long,
- length: _t.unsigned_long
-};
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ platform = require('ripple/platform'),
+ notifications = require('ripple/notifications'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ bus = require('ripple/bus'),
+ required = {
+ build: {
+ "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName"],
+ "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName"],
+ "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName"]
+ },
+ sign: {
+ "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "csk_password", "p12_password", "bundle_number"],
+ "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword", "bundle_number"],
+ "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword"]
+ },
+ launch: {
+ "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "device"],
+ "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "device"],
+ "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "simulator"]
+ }
+ },
+ _settings = {
+ get: function () {
+ var settings = db.retrieveObject("build-settings", platform.getPersistencePrefix()) || {};
+ settings.debug = !!settings["remoteInspector"];
-/*
- * FuelInfo
- */
-_t.FuelInfo = {
- type: _t.unsigned_short,
- refuelPosition: _t.unsigned_short
-};
+ return settings;
+ },
+ save: function (settings) {
+ db.saveObject("build-settings", settings, platform.getPersistencePrefix());
+ }
+ },
+ port = "9910",
+ host = "http://127.0.0.1:" + port + "/ripple",
+ progressContainer = jQuery("#options-progress"),
+ progressInterval,
+ _passwordFields = [
+ "signingPassword",
+ "devicePassword",
+ "csk_password",
+ "p12_password"
+ ],
+ _checkboxFields = [
+ "remoteInspector"
+ ],
+ _passwords = {},
+ _self;
-/*
- * VehicleType
- */
-_t.VehicleType = {
- type: _t.unsigned_short
-};
+function missing(settings, action) {
+ return required[action][platform.current().id].filter(function (field) {
+ return !settings.hasOwnProperty(field);
+ });
+}
-/*
- * Doors
- */
-_t.Doors = {
- doorsPerRow: [_t.unsigned_short]
-};
+function _isPasswordField(id) {
+ var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
+ return match && utils.some(_passwordFields, function (name) {
+ return match.test(name);
+ });
+}
-/*
- * TransmissionGearType
- */
-_t.TransmissionGearType = {
- transmissionGearType: _t.unsigned_short
-};
+function _isCheckboxField(id) {
+ var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
+ return match && utils.some(_checkboxFields, function (name) {
+ return match.test(name);
+ });
+}
-/*
- * WheelInformation
- */
-_t.WheelInformation = {
- frontWheelRadius: _t.unsigned_short,
- rearWheelRadius: _t.unsigned_short,
- wheelTrack: _t.unsigned_long,
- ABS: _t.boolean
-};
+function table(action) {
+ var _table = $("<table class='panel-table'>"),
+ _row = {
+ row: function (item, desc, opts) {
+ var id = "settings-field-" + item.toLowerCase(),
+ input = "",
+ save = function () {
+ var s = _settings.get(),
+ v = $("#" + id).val(),
+ val = opts.type === "number" ? parseInt(v, 10) : v;
-/*
- * Odometer
- */
-_t.Odometer = {
- odometer: _t.unsigned_long
-};
+ if (_isCheckboxField(item)) {
+ s[item] = $("#" + id).prop("checked");
+ }
+ else if (val) {
+ (_isPasswordField(item) ? _passwords : s)[item] = val;
+ }
+ else {
+ delete s[item];
+ }
+ _settings.save(s);
-/*
- * Fluid
- */
-_t.Fluid = {
- transmission: _t.unsigned_short,
- brake: _t.unsigned_short,
- washer: _t.unsigned_short
-};
+ if (opts.onChanged) {
+ opts.onChanged(s[item]);
+ }
+ },
+ row;
-/*
- * Battery
- */
-_t.Battery = {
- voltage: _t.double,
- current: _t.double
-};
+ opts = opts || { type: "text" };
-/*
- * TirePressure
- */
-_t.TirePressure = {
- leftFront: _t.double,
- rightFront: _t.double,
- leftRear: _t.double,
- rightRear: _t.double
-};
+ switch (opts.type) {
+ case "select":
+ input = "<select id='" + id + "' class='ui-state-default ui-corner-all' style='width:100%'/>";
+ break;
+ case "span":
+ input = "<span id = '" + id + "'>" + opts.text + "</span>";
+ break;
+ default:
+ input = "<input id='" + id + "' type='" + opts.type + "' class='ui-state-default ui-corner-all' style='width:90%' />";
+ break;
+ }
-/*
- * TireTemperature
- */
-_t.TireTemperature = {
- leftFront: _t.double,
- rightFront: _t.double,
- leftRear: _t.double,
- rightRear: _t.double
-};
+ row = $("<tr>" +
+ "<td><label for='" + id + "' class='ui-text-label'>" + desc + "</label></td>" +
+ "<td>" + input + "</td>" +
+ "</tr>");
-/*
- * SecurityAlert
- */
-_t.SecurityAlert = {
- securityAlert: _t.boolean
-};
+ row.appendTo(_table);
-/*
- * ParkingBrake
- */
-_t.ParkingBrake = {
- parkingBrake: _t.boolean
-};
+ //bind save handlers to the row
+ utils.bindAutoSaveEvent(row.find("#" + id).change(save), save);
-/*
- * ParkingLight
- */
-_t.ParkingLight = {
- parkingLight: _t.boolean
-};
+ return _row;
+ },
+ appendTo: function (id) {
+ var fs = $("<fieldset class='main'><legend class='cap-text'>" + action + "</legend></fieldset>");
-/*
- * HazardLight
- */
-_t.HazardLight = {
- hazardLight: _t.boolean
-};
+ $(_table).appendTo(fs);
+ fs.appendTo($(id));
+ }
+ };
-/*
- * AntilockBrakingSystem
- */
-_t.AntilockBrakingSystem = {
- antilockBrakingSystem: _t.boolean
-};
+ return _row;
+}
-/*
- * TractionControlSystem
- */
-_t.TractionControlSystem = {
- tractionControlSystem: _t.boolean
-};
+function create() {
+ var build = table('build'),
+ sign = table('sign'),
+ launch = table('launch');
-/*
- * VehicleTopSpeedLimit
- */
-_t.VehicleTopSpeedLimit = {
- vehicleTopSpeedLimit: _t.unsigned_short
-};
+ build
+ .row("sdk", "SDK Path")
+ .row("projectPath", "Project Root")
+ .row("projectName", "Archive Name")
+ .row("outputPath", "Output Folder")
+ .row("remoteInspector", "Enable Remote Web Inspector", {
+ type: "checkbox",
+ onChanged: function (enabled) {
+ if (enabled) {
+ $("#options-menu-build-warning").show();
+ tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
+ }
+ else {
+ $("#options-menu-build-warning").hide();
+ }
+ }
+ })
+ .appendTo("#settings-tabs-build");
-/*
- * AirbagStatus
- */
-_t.AirbagStatus = {
- airbagStatus: _t.unsigned_short
-};
+ switch (platform.current().id) {
+ case "webworks.handset":
+ sign.row("signingPassword", "Password", {
+ type: "password"
+ });
-/*
- * DoorStatus
- */
-_t.DoorStatus = {
- doorStatus: _t.unsigned_short,
- doorLockStatus: _t.boolean,
- childLockStatus: _t.boolean
-};
+ launch.row("simulator", "Simulator", {
+ type: "select"
+ });
-/*
- * SeatBeltStatus
- */
-_t.SeatBeltStatus = {
- seatBeltStatus: _t.boolean
-};
+ launch.row("simulatorstatus", "Simulator", {
+ type: "span",
+ text: "Searching for simulators ..."
+ });
+
+ break;
-/*
- * OccupantStatus
- */
-_t.OccupantStatus = {
- occupantStatus: _t.unsigned_short
-};
+ case "webworks.tablet":
+ sign.row("csk_password", "CSK Password", {
+ type: "password"
+ });
+ sign.row("p12_password", "P12 Password", {
+ type: "password"
+ });
+ sign.row("bundle_number", "Bundle Number", {
+ type: "number"
+ });
-/*
- * ObstacleDistance
- */
-_t.ObstacleDistance = {
- obstacleDistance: _t.double
-};
+ launch.row("device", "Playbook IP");
+ launch.row("devicePassword", "Playbook Password", {
+ type: "password"
+ });
-/*
- * NightMode
- */
-_t.NightMode = {
- nightMode: _t.boolean
-};
+ break;
-/*
- * DrivingMode
- */
-_t.DrivingMode = {
- drivingMode: _t.unsigned_short
-};
+ case "webworks.bb10":
+ sign.row("signingPassword", "Signing Password", {
+ type: "password"
+ });
+ sign.row("bundle_number", "Bundle Number", {
+ type: "number"
+ });
-/*
- * TurnSignal
- */
-_t.TurnSignal = {
- turnSignal: _t.unsigned_short
-};
+ launch.row("device", "Device IP");
+ launch.row("devicePassword", "Device Password", {
+ type: "password"
+ });
-/*
- * ButtonEvent
- */
-_t.ButtonEvent = {
- buttonEvent: _t.unsigned_short
-};
+ break;
+ }
-/*
- * VehiclePropertyType
- */
-_t.VehiclePropertyType = {
- time: _t.unsigned_long_long,
- zone: _t.short,
- source: _t.DOMString,
+ sign.appendTo("#settings-tabs-build");
+ launch.appendTo("#settings-tabs-build");
- _derived: [_t.VehicleSpeed, _t.EngineSpeed, _t.VehiclePowerMode,
- _t.TripMeter, _t.Acceleration, _t.Transmission,
- _t.CruiseControlStatus, _t.WheelBrake, _t.LightStatus,
- _t.InteriorLightStatus, _t.Horn, _t.Fuel, _t.EngineOil, _t.Location,
- _t.ExteriorBrightness, _t.Temperature, _t.RainSensor,
- _t.WindshieldWiper, _t.HVAC, _t.WindowStatus, _t.Sunroof,
- _t.ConvertibleRoof, _t.VehicleId, _t.Size, _t.FuelInfo, _t.VehicleType,
- _t.Doors, _t.TransmissionGearType, _t.WheelInformation, _t.Odometer,
- _t.Fluid, _t.Battery, _t.TirePressure, _t.TireTemperature,
- _t.SecurityAlert, _t.ParkingBrake, _t.ParkingLight, _t.HazardLight,
- _t.AntilockBrakingSystem, _t.TractionControlSystem,
- _t.VehicleTopSpeedLimit, _t.AirbagStatus, _t.DoorStatus,
- _t.SeatBeltStatus, _t.OccupantStatus, _t.ObstacleDistance,
- _t.NightMode, _t.TurnSignal, _t.ButtonEvent]
-};
+ $("#settings-field-simulator").parent().parent().hide();
+}
-/*
- * Constructor list definition
- */
+function populate(settings) {
+ var fill = function (action, prop) {
+ var element = $("#settings-field-" + prop.toLowerCase());
-/*
- * Generic constructor
- * Construct a prototype of constructor. A fake array of arguments type is
- * specified for constructor.
- *
- * Overloaded constructors
- * Construct an array of prototype of constructor. Each array element is
- * specified for one of constructors. The constructor with extra arguments
- * are recommended to be defined ahead of the one with fewer same arguments
- * for exact match.
- */
+ if (_isPasswordField(prop)) {
+ element.val(_passwords[prop]);
+ }
+ else if (_isCheckboxField(prop)) {
+ element.prop("checked", settings[prop]);
+ }
+ else {
+ element.val(settings[prop]);
+ }
+ };
-_c = {};
+ fill("build", "sdk");
+ fill("build", "projectPath");
+ fill("build", "outputPath");
+ fill("build", "projectName");
+ fill("build", "remoteInspector");
-/*
- * Interface prototype definition
- */
+ fill("sign", "signingPassword");
+ fill("sign", "csk_password");
+ fill("sign", "p12_password");
+ fill("sign", "bundle_number");
-_i = {
- // Vehicle
- Vehicle: {}
-};
+ fill("launch", "simulator");
+ fill("launch", "device");
+ fill("launch", "devicePassword");
+}
-_i.Vehicle.get = {
- 0: _t.DOMString,
- 1: _t.short,
+function url(action) {
+ var target = "";
- _optional: {
- // nullable
- 1: true
+ switch (platform.current().id) {
+ case "webworks.bb10":
+ target = "bb10";
+ break;
+ case "webworks.tablet":
+ target = "tablet";
+ break;
+ case "webworks.handset":
+ target = "smartphone";
+ break;
}
-};
-_i.Vehicle.subscribe = {
- 0: _t.DOMString,
- 1: _t.VehiclePropertyCallback,
- 2: _t.short,
- 3: _t.VehiclePropertyErrorCallback,
+ return host + "/" + action + "/" + target;
+}
- _optional: {
- // nullable
- 2: true,
- 3: true
+function enable(action) {
+ $("#options-menu-" + action).removeClass("not-ready");
+ if (action === "launch") {
+ $("#settings-field-simulatorstatus").parent().parent().hide();
+ $("#settings-field-simulator").parent().parent().show();
}
-};
+}
-_i.Vehicle.set = {
- 0: _t.DOMString,
- 1: _t.VehiclePropertyType,
- 2: _t.VehiclePropertyErrorCallback,
+function disable(action) {
+ $("#options-menu-" + action).addClass("not-ready");
+ if (action === "launch") {
+ $("#settings-field-simulatorstatus").parent().parent().show();
+ $("#settings-field-simulator").parent().parent().hide();
+ }
+}
- _optional: {
- // nullable
- 2: true
+function getSimulators() {
+ if (!_settings.get().sdk) {
+ $("#settings-field-simulatorstatus").text("");
+ disable("launch");
+ return;
}
-};
-_i.Vehicle.getHistory = {
- 0: _t.DOMString,
- 1: _t.short,
- 2: _t.Date,
- 3: _t.Date,
- 4: _t.VehiclePropertyListCallback,
- 5: _t.VehiclePropertyErrorCallback,
+ bus.ajax(
+ "POST",
+ host + "/simulators",
+ _settings.get(),
+ function (resp) {
+ var sims = resp.data.simulators;
- _optional: {
- // nullable
- 5: true
+ $("#settings-field-simulator").empty();
+ if (sims.length > 0) {
+ $(resp.data.simulators.map(function (sim) {
+ return "<option value='" + sim + "'>" + sim + "</option>";
+ }).join()).appendTo("#settings-field-simulator");
+
+ enable("launch");
+ }
+ else {
+ disable("launch");
+ $("#settings-field-simulatorstatus").text("No simulators found :(");
+ }
+ },
+ function () {
+ disable("launch");
+ $("#settings-field-simulatorstatus").text("Error attempting to get simulators :(");
+ }
+ );
+}
+
+function _startProgress() {
+ if (progressInterval) {
+ window.clearInterval(progressInterval);
}
-};
+ progressInterval = window.setInterval(function () {
+ if (progressContainer.html().length === 5) {
+ progressContainer.html(".");
+ }
+ else {
+ progressContainer.html(progressContainer.html() + ".");
+ }
+ }, 250);
+}
-_i.Vehicle.listZones = {
- 0: _t.DOMString
-};
+function _endProgress() {
+ window.clearInterval(progressInterval);
+ progressInterval = null;
+ progressContainer.html("");
+}
-// Exports
-_t.constructor = _c;
-_t.interface = _i;
-module.exports = _t;
+_self = {
+ initialize: function () {
+ $("#settings-dialog").dialog({
+ autoOpen: false,
+ modal: true,
+ width: 700,
+ title: "Settings",
+ position: 'center'
+ }).hide();
-});
-define('ripple/platform/ivi/3.0/vehicle', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 utils = require('ripple/utils'),
- event = require('ripple/event'),
- t = require('ripple/platform/ivi/3.0/typecast'),
- errorcode = require('ripple/platform/ivi/3.0/errorcode'),
- WebAPIError = require('ripple/platform/ivi/3.0/WebAPIError'),
- WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
- _self,
- _security = {
- "http://tizen.org/privilege/vehicle": ["supported", "get", "set",
- "getHistory", "subscribe", "listZones"]
- },
- _vehicleCacheData = {
- "supported": null,
- "data": null
- },
- _vehicleEvent = {subscribe: {}},
- VehiclePropertyType,
- VehicleSpeed,
- EngineSpeed,
- VehiclePowerMode,
- TripMeter,
- Acceleration,
- Transmission,
- CruiseControlStatus,
- WheelBrake,
- LightStatus,
- InteriorLightStatus,
- Horn,
- Fuel,
- EngineOil,
- Location,
- ExteriorBrightness,
- Temperature,
- RainSensor,
- WindshieldWiper,
- HVAC,
- WindowStatus,
- Sunroof,
- ConvertibleRoof,
- VehicleId,
- Size,
- FuelInfo,
- VehicleType,
- Doors,
- TransmissionGearType,
- WheelInformation,
- Odometer,
- Fluid,
- Battery,
- TirePressure,
- TireTemperature,
- SecurityAlert,
- ParkingBrake,
- ParkingLight,
- HazardLight,
- AntilockBrakingSystem,
- TractionControlSystem,
- VehicleTopSpeedLimit,
- AirbagStatus,
- DoorStatus,
- SeatBeltStatus,
- OccupantStatus,
- ObstacleDistance,
- NightMode,
- DrivingMode,
- TurnSignal,
- ButtonEvent,
- VehicleFactory;
-
-function _initialize () {
- event.on("vehicle-cache-refresh", function (supported, data) {
- _vehicleCacheData.supported = supported;
- _vehicleCacheData.data = data;
- });
-
- event.trigger("vehicle-cache-request", [_vehicleCacheData]);
-}
-
-/*function _reloadVehicle (data) {
- var property, name, format = {};
-
- for (name in data) {
- property = data[name];
-
- format[name] = new VehicleFactory(name, _vehicleCacheData.data[name]);
- }
+ $("#settings-tabs").tabs();
+ $("#settings-action").button();
- return format;
-}*/
+ create();
-_self = function () {
- var vehicle;
+ if (platform.current().id === "webworks.handset") {
+ enable("build");
+ enable("sign");
+ enable("settings");
- function supported () {
- if (!_security.supported) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ getSimulators();
+ $("#settings-field-sdk").change(getSimulators);
}
-
- return _vehicleCacheData.supported;
- }
-
- function get (property, zone) {
- if (!_security.get) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ else if (platform.current().id === "webworks.tablet") {
+ enable("build");
+ enable("sign");
+ enable("launch");
+ enable("settings");
}
-
- t.Vehicle("get", arguments);
-
- if (_vehicleCacheData.supported.indexOf(property) === -1) {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ else if (platform.current().id === "webworks.bb10") {
+ enable("build");
+ enable("sign");
+ enable("launch");
+ enable("settings");
}
+ },
- return new VehicleFactory(property, _vehicleCacheData.data[property]);
- }
-
- function subscribe (property, successCallback, zone, errorCallback) {
- if (!_security.subscribe) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
- }
+ can: function (action) {
+ var settings = {};
- t.Vehicle("subscribe", arguments);
+ utils.mixin(_settings.get(), settings);
+ utils.mixin(_passwords, settings);
- if (_vehicleCacheData.supported.indexOf(property) === -1) {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
- }
+ return action && missing(settings, action).length === 0;
+ },
- _vehicleEvent.subscribe[property] = {
- successCallback: successCallback,
- errorCallback: errorCallback
- };
+ value: function (prop) {
+ var settings = {};
- window.setTimeout(function () {
- if (! _vehicleEvent["vehicle-subscribe-response"]) {
- event.on("vehicle-subscribe-response", function (propertyObj) {
- var propertySub = _vehicleEvent.subscribe[propertyObj.type],
- success = propertySub.successCallback,
- error = propertySub.errorCallback;
+ utils.mixin(_settings.get(), settings);
+ return settings[prop];
+ },
- if (propertyObj.supported) {
- success(new VehicleFactory(propertyObj.type, propertyObj.val));
- }
- else {
- if (error) {
- error(new WebAPIError(errorcode.PROPERTY_UNAVAILABLE));
- }
- else {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
- }
- }
- });
- _vehicleEvent["vehicle-subscribe-response"] = true;
- }
- event.trigger("vehicle-subscribe-request", [property, true, zone]);
- }, 1);
- }
+ show: function (action) {
+ var settings = {};
- function set (property, value, errorCallback) {
- var val = utils.copy(value);
+ utils.mixin(_settings.get(), settings);
+ utils.mixin(_passwords, settings);
- if (!_security.set) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
- }
+ populate(settings);
- t.Vehicle("set", arguments);
+ $("#settings-dialog").dialog("open");
+ $("#settings-action").button("option", "label", action || "Close")[action ? "show" : "hide"]();
- if (_vehicleCacheData.supported.indexOf(property) === -1) {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
- }
+ if (action) {
+ missing(settings, action).forEach(function (field) {
+ $("#settings-field-" + field.toLowerCase()).effect("highlight", {color: "red"}, 1500);
+ });
- window.setTimeout(function () {
- event.once("vehicle-set-response", function (status) {
- if (!status) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.PROPERTY_UNAVAILABLE));
- }
- else {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
- }
+ $("#settings-action").unbind("click").click(function () {
+ if (_self.can(action)) {
+ _self.perform(action);
+ $("#settings-dialog").dialog("close");
+ }
+ else {
+ _self.show(action);
}
});
- event.trigger("vehicle-set-request", [property, val]);
- }, 1);
- }
-
- function getHistory (property, zone, startTime, endTime, successCallback, errorCallback) {
- var properties = [], i;
-
- if (!_security.getHistory) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
- }
-
- t.Vehicle("getHistory", arguments);
-
- if (_vehicleCacheData.supported.indexOf(property) === -1) {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
}
+ },
- startTime = startTime.getTime();
- endTime = endTime.getTime();
+ perform: function (action) {
+ var settings = _settings.get(),
+ data = {},
+ poll = function (resp) {
+ var notifications = require("ripple/notifications");
- window.setTimeout(function () {
- event.once("vehicle-history-response", function (values, status) {
- if (status) {
- for (i = 0; i < values.length; i++) {
- properties.push(new VehicleFactory(property, values[i]));
- }
- successCallback(properties);
+ if (resp && resp.code !== 0) {
+ notifications.openNotification("error", "Build request failed with message: " + resp.msg);
+ _endProgress();
}
else {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.PROPERTY_UNAVAILABLE));
+ if (resp && resp.data.status === "building") {
+ setTimeout(function () {
+ bus.ajax(
+ "GET",
+ host + "/build_status/" + resp.data.id,
+ null,
+ poll,
+ function (error) {
+ notifications.openNotification("error", "Build request failed with message: " + JSON.stringify(error));
+ _endProgress();
+ }
+ );
+ }, 500);
}
else {
- throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ if (action.match(/sign/)) {
+ settings["bundle_number"] = $("#settings-field-bundle_number").val(parseInt($("#settings-field-bundle_number").val(), 10) + 1).val();
+ _settings.save(settings);
+ }
+ notifications.openNotification("normal", "Build succeeded!");
+ _endProgress();
}
}
- });
- event.trigger("vehicle-history-request", [property, zone, startTime, endTime]);
- }, 1);
- }
-
- function listZones (property) {
- if (!_security.listZones) {
- throw new WebAPIException(errorcode.PERMISSION_DENIED);
- }
+ };
- t.Vehicle("listZones", arguments);
+ utils.mixin(settings, data);
+ utils.mixin(_passwords, data);
- return [0];
- }
+ bus.ajax(
+ "POST",
+ url(action),
+ data,
+ function (resp) {
+ _startProgress();
+ poll(resp);
+ },
+ function (error) {
+ var message = "Build request failded with message: " + error.data;
- function handleSubFeatures (subFeatures) {
- var i, subFeature;
+ if (error.code === 0 || error.code === 404) {
+ message += "<br>This could be due to the Build and Deploy services not running or not being installed";
+ }
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
+ notifications.openNotification("error", message);
}
- }
+ );
}
+};
- vehicle = {
- supported: supported,
- get: get,
- subscribe: subscribe,
- set: set,
- getHistory: getHistory,
- listZones: listZones,
- handleSubFeatures: handleSubFeatures
- };
-
- vehicle.__defineGetter__("ZONE_None", function () {
- return 0;
- });
-
- vehicle.__defineGetter__("ZONE_Front", function () {
- return 0x01;
- });
-
- vehicle.__defineGetter__("ZONE_Middle", function () {
- return 0x02;
- });
+module.exports = _self;
- vehicle.__defineGetter__("ZONE_Right", function () {
- return 0x04;
- });
+});
+define('ripple/ui/plugins/power', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation
+ *
+ * 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.
+ */
- vehicle.__defineGetter__("ZONE_Left", function () {
- return 0x08;
- });
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ constants = require('ripple/constants'),
+ _volume = document.getElementById(constants.BATTERY.VOLUME),
+ _volumeLabel = document.getElementById(constants.BATTERY.VOLUME + "-label"),
+ _charging = document.getElementById(constants.BATTERY.CHARGING),
+ _battery = {
+ volume: 600,
+ level: 1.0,
+ timerId: null,
+ charge: function (isStart, isCharge, callback) {
+ var currentVolume,
+ checkValue = function () {
+ if (_battery.level < 0 || _battery.level > 1.0 || !isStart) {
+ clearInterval(_battery.timerId);
+ _battery.timerId = null;
+ if (_battery.level < 0)
+ _battery.level = 0;
+ else if (_battery.level > 1.0)
+ _battery.level = 1.0;
+ }
+ };
- vehicle.__defineGetter__("ZONE_Rear", function () {
- return 0x10;
- });
+ if (isStart && !_battery.timerId) {
+ _battery.timerId = setInterval(function () {
+ currentVolume = isCharge ? _battery.level * _battery.volume + 1 : _battery.level * _battery.volume - 1;
+ _battery.level = currentVolume / _battery.volume;
+ checkValue();
+ return callback && callback();
+ }, 1000);
+ }
+ checkValue();
+ return callback && callback();
+ }
+ };
- vehicle.__defineGetter__("ZONE_Center", function () {
- return 0x20;
- });
+function _triggerEvent(chargingStatus, chargingTime, dischargingTime, level, type) {
+ var status = {
+ charging: chargingStatus,
+ chargingTime: chargingTime,
+ dischargingTime: dischargingTime,
+ level: level,
+ type: type
+ };
+ event.trigger("BatteryEvent", [status]); // for w3c battery api
+ // for tizen systeminfo api
+ if (type === "levelchange") {
+ event.trigger("BatteryLevelChanged", [level]);
+ }
+ if (type === "chargingchange") {
+ event.trigger("BatteryChargingChanged", [status]);
+ }
+}
- return vehicle;
-};
+function _updateLevelIcons() {
+ var colors = ["black", "black", "black", "black", "black", "black", "#404040", "#606060", "#808080", "#b0b0b0", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff"],
+ colorIndex = 10 - Math.round(_battery.level * 10),
+ index;
-VehicleFactory = function (vehicleType, value) {
- var instanceType;
+ //map the battery level to the color range
+ for (index = 0 ; index <= 5 ; index++) {
+ $("#block" + index).css("backgroundColor", colors[colorIndex]);
+ colorIndex++;
+ }
+}
- switch (vehicleType) {
- case "VehicleSpeed":
- instanceType = new VehicleSpeed(value);
- break;
- case "EngineSpeed":
- instanceType = new EngineSpeed(value);
- break;
- case "VehiclePowerMode":
- instanceType = new VehiclePowerMode(value);
- break;
- case "TripMeter":
- instanceType = new TripMeter(value);
- break;
- case "Acceleration":
- instanceType = new Acceleration(value);
- break;
- case "Transmission":
- instanceType = new Transmission(value);
- break;
- case "CruiseControlStatus":
- instanceType = new CruiseControlStatus(value);
- break;
- case "WheelBrake":
- instanceType = new WheelBrake(value);
- break;
- case "LightStatus":
- instanceType = new LightStatus(value);
- break;
- case "InteriorLightStatus":
- instanceType = new InteriorLightStatus(value);
- break;
- case "Horn":
- instanceType = new Horn(value);
- break;
- case "Fuel":
- instanceType = new Fuel(value);
- break;
- case "EngineOil":
- instanceType = new EngineOil(value);
- break;
- case "Location":
- instanceType = new Location(value);
- break;
- case "ExteriorBrightness":
- instanceType = new ExteriorBrightness(value);
- break;
- case "Temperature":
- instanceType = new Temperature(value);
- break;
- case "RainSensor":
- instanceType = new RainSensor(value);
- break;
- case "WindshieldWiper":
- instanceType = new WindshieldWiper(value);
- break;
- case "HVAC":
- instanceType = new HVAC(value);
- break;
- case "WindowStatus":
- instanceType = new WindowStatus(value);
- break;
- case "Sunroof":
- instanceType = new Sunroof(value);
- break;
- case "ConvertibleRoof":
- instanceType = new ConvertibleRoof(value);
- break;
- case "VehicleId":
- instanceType = new VehicleId(value);
- break;
- case "Size":
- instanceType = new Size(value);
- break;
- case "FuelInfo":
- instanceType = new FuelInfo(value);
- break;
- case "VehicleType":
- instanceType = new VehicleType(value);
- break;
- case "Doors":
- instanceType = new Doors(value);
- break;
- case "TransmissionGearType":
- instanceType = new TransmissionGearType(value);
- break;
- case "WheelInformation":
- instanceType = new WheelInformation(value);
- break;
- case "Odometer":
- instanceType = new Odometer(value);
- break;
- case "Fluid":
- instanceType = new Fluid(value);
- break;
- case "Battery":
- instanceType = new Battery(value);
- break;
- case "TirePressure":
- instanceType = new TirePressure(value);
- break;
- case "TireTemperature":
- instanceType = new TireTemperature(value);
- break;
- case "SecurityAlert":
- instanceType = new SecurityAlert(value);
- break;
- case "ParkingBrake":
- instanceType = new ParkingBrake(value);
- break;
- case "ParkingLight":
- instanceType = new ParkingLight(value);
- break;
- case "HazardLight":
- instanceType = new HazardLight(value);
- break;
- case "AntilockBrakingSystem":
- instanceType = new AntilockBrakingSystem(value);
- break;
- case "TractionControlSystem":
- instanceType = new TractionControlSystem(value);
- break;
- case "VehicleTopSpeedLimit":
- instanceType = new VehicleTopSpeedLimit(value);
- break;
- case "AirbagStatus":
- instanceType = new AirbagStatus(value);
- break;
- case "DoorStatus":
- instanceType = new DoorStatus(value);
- break;
- case "SeatBeltStatus":
- instanceType = new SeatBeltStatus(value);
- break;
- case "OccupantStatus":
- instanceType = new OccupantStatus(value);
- break;
- case "ObstacleDistance":
- instanceType = new ObstacleDistance(value);
- break;
- case "NightMode":
- instanceType = new NightMode(value);
- break;
- case "DrivingMode":
- instanceType = new DrivingMode(value);
- break;
- case "TurnSignal":
- instanceType = new TurnSignal(value);
- break;
- case "ButtonEvent":
- instanceType = new ButtonEvent(value);
- break;
+function _setVolumeReadOnly(flag) {
+ if (flag) {
+ $("#" + constants.BATTERY.VOLUME).hide();
+ $("#" + constants.BATTERY.VOLUME + "-label").show();
+ } else {
+ $("#" + constants.BATTERY.VOLUME).show();
+ $("#" + constants.BATTERY.VOLUME + "-label").hide();
}
+}
- function _construct () {
- var val;
+function _startDischarging() {
+ var remainVolume = 0;
- for (val in value) {
- instanceType[val] = value[val];
- }
- return instanceType;
+ if ($("#simulate-low-battery #low-battery-remain-time").val() <= 0) {
+ $("#simulate-low-battery #low-battery-remain-time").val(0);
+ }
+ remainVolume = Number($("#simulate-low-battery #low-battery-remain-time").val());
+ if ($("#simulate-low-battery #low-battery-start-at").val() > 100) {
+ $("#simulate-low-battery #low-battery-start-at").val(100);
+ }
+ if ($("#simulate-low-battery #low-battery-start-at").val() <= 0) {
+ $("#simulate-low-battery #low-battery-start-at").val(0);
+ }
+ _battery.level = $("#simulate-low-battery #low-battery-start-at").val() / 100.0;
+ if (_battery.level === 0 || remainVolume === 0) {
+ $("#simulate-low-battery").dialog("close");
+ _stopDischarging();
+ return;
+ }
+ _setVolumeReadOnly(true);
+ if (_charging.checked) {
+ _charging.checked = false;
+ _battery.charge(false);
}
- return _construct();
-};
+ _charging.disabled = true;
+ $("#remaining-time-label").html("Remaining Time to empty (seconds)");
+ $("#charging-state").html("Plugged in?");
-VehiclePropertyType = function (propertyTypes) {
- var vehiclePropertyType = {};
+ $("#remain-time").show();
+ _battery.volume = remainVolume / _battery.level;
+ _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
+ _battery.charge(true, false, function () {
+ _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
+ _volume.value = (_battery.level * 100).toFixed(2);
+ changeBatteryVolume();
+ $("#remain-time").html(Math.round(_battery.volume * _battery.level) + " Seconds");
+ _updateLevelIcons();
+ if (_battery.level <= 0.0) {
+ _stopDischarging();
+ }
+ });
+ $("#simulate-low-battery").dialog("close");
+ $("#simulate-low-battery-btn").hide();
+ $("#stop-btn").show();
+ _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingtimechange");
+}
- vehiclePropertyType.time = propertyTypes.time || undefined;
- vehiclePropertyType.zone = propertyTypes.zone || 0;
- vehiclePropertyType.source = propertyTypes.source || "";
+function _stopDischarging() {
+ _charging.disabled = false;
+ _battery.level = _volume.value / 100.0;
+ $("#remain-time").hide();
+ $("#remain-time").html("");
+ $("#remaining-time-label").html("Remaining Time (seconds)");
+ _setVolumeReadOnly(false);
+ _battery.charge(false);
+ $("#simulate-low-battery-btn").show();
+ $("#stop-btn").hide();
+ _updateLevelIcons();
+}
- this.__defineGetter__("time", function () {
- return vehiclePropertyType.time;
+function _setCharging() {
+ // update the UI parts
+ if (_charging.checked) {
+ _battery.volume = 600;
+ _battery.level = _volume.value / 100;
+ _setVolumeReadOnly(true);
+ $("#remain-time").show();
+ $("#remaining-time-label").html("Remaining Time to fully charged (seconds)");
+ $("#charging-state").html("Plugged in - charging rate 0.17%/second");
+ _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "chargingchange");
+ } else {
+ _battery.level = _volume.value / 100.0;
+ _updateLevelIcons();
+ $("#remain-time").hide();
+ $("#remain-time").html("");
+ _setVolumeReadOnly(false);
+ $("#remaining-time-label").html("Remaining Time (seconds)");
+ $("#charging-state").html("Plugged in?");
+ _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingchange");
+ }
+ // if it's unchecked, the timer will stop in this function call, the UI update blow it
+ _battery.charge(_charging.checked, true, function () {
+ _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
+ _volume.value = (_battery.level * 100).toFixed(2);
+ changeBatteryVolume();
+ $("#remain-time").html(Math.round(_battery.volume * (1 - _battery.level)) + " Seconds"); //show current remain time
+ _updateLevelIcons();
});
+}
- this.__defineSetter__("time", function (val) {
- try {
- vehiclePropertyType.time = t.unsigned_long_long(val);
- }
- catch (err) {
- }
- });
+function changeBatteryVolume() {
+ if (_volume.value < 0)
+ _volume.value = 0;
+ else if (_volume.value > 100)
+ _volume.value = 100;
- this.__defineGetter__("zone", function () {
- return vehiclePropertyType.zone;
- });
+ _battery.level = _volume.value / 100.0;
+ if (_charging.checked === true) {
+ _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "levelchange");
+ } else {
+ _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "levelchange");
+ }
+ db.save(constants.BATTERY.VOLUME, _volume.value);
+ _updateLevelIcons();
+}
- this.__defineSetter__("zone", function (val) {
- try {
- vehiclePropertyType.zone = t.short(val);
- }
- catch (err) {
- }
- });
+function initBattery() {
+ $("#" + constants.BATTERY.CHARGING).bind("change", _setCharging);
- this.__defineGetter__("source", function () {
- return vehiclePropertyType.source;
+ $("#simulate-low-battery-btn").bind("click", function () {
+ $("#simulate-low-battery").dialog("open");
});
- this.__defineSetter__("source", function (val) {
- try {
- vehiclePropertyType.source = t.DOMString(val);
- }
- catch (err) {
- }
+ $("#simulate-low-battery-cancel").bind("click", function () {
+ $("#low-battery-start-at").val = 20; //UI initialize
+ $("#low-battery-remain-time").val = 1200;
+ $("#simulate-low-battery").dialog("close");
});
-};
-
-VehicleSpeed = function (propertyTypes) {
- var vehicleSpeed = {};
-
- VehiclePropertyType.call(this, propertyTypes);
- vehicleSpeed.vehicleSpeed = propertyTypes.vehicleSpeed || 0;
+ $("#simulate-low-battery-start").bind("click", _startDischarging);
+ $("#stop-btn").bind("click", _stopDischarging);
- this.__defineGetter__("vehicleSpeed", function () {
- return vehicleSpeed.vehicleSpeed;
+ $("#" + constants.BATTERY.VOLUME).bind("change", function () {
+ changeBatteryVolume();
});
- this.__defineSetter__("vehicleSpeed", function (val) {
- try {
- vehicleSpeed.vehicleSpeed = t.unsigned_long(val);
- }
- catch (err) {
- }
+ _charging.checked = false;
+ _battery.level = db.retrieve(constants.BATTERY.VOLUME) / 100.0;
+ if (isNaN(_battery.level)) {
+ _battery.level = 1;
+ }
+ _volume.value = (_battery.level * 100).toFixed(2);
+ _updateLevelIcons();
+ $("#simulate-low-battery").dialog({
+ resizable: false,
+ draggable: true,
+ modal: true,
+ autoOpen: false,
+ position: 'center',
+ minWidth: '460',
+ minHeight: '240'
});
-};
+}
-EngineSpeed = function (propertyTypes) {
- var engineSpeed = {};
+module.exports = {
+ panel: {
+ domId: "power-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Power Manager",
+ display: true
+ },
- VehiclePropertyType.call(this, propertyTypes);
+ initialize: function () {
+ initBattery();
+ }
+};
- engineSpeed.engineSpeed = propertyTypes.engineSpeed || 0;
+});
+define('ripple/ui/plugins/settings-menu', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ platform = require('ripple/platform'),
+ db = require('ripple/db'),
+ _applicationStateId
+ ;
- this.__defineGetter__("engineSpeed", function () {
- return engineSpeed.engineSpeed;
- });
- this.__defineSetter__("engineSpeed", function (val) {
- try {
- engineSpeed.engineSpeed = t.unsigned_long(val);
- }
- catch (err) {
- }
- });
-};
+function reload() {
+ window.tinyHipposReload = true;
+ location.reload();
+}
-VehiclePowerMode = function (propertyTypes) {
- var vehiclePowerMode = {};
+function _showSettingMenu() {
+ var contentTable = "",
+ settings = [],
+ _applicationState = [],
+ _applicationStateTmp = [],
+ unselectedNum = 0,
+ i = 0;
- VehiclePropertyType.call(this, propertyTypes);
+ if ($("#settings-menu-popup").is(":visible")) {
+ $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
+ $("#overlayBackground").hide("fade", "slow");
+ return;
+ }
- vehiclePowerMode.vehiclePowerMode = propertyTypes.vehiclePowerMode || 0;
+ _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;
- this.__defineGetter__("VEHICLEPOWERMODE_OFF", function () {
- return 0;
- });
+ _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];
- this.__defineGetter__("VEHICLEPOWERMODE_ACCESSORY1", function () {
- return 1;
+ utils.forEach(_applicationStateTmp, function (obj) {
+ if (obj.display)
+ _applicationState.push(obj);
});
- this.__defineGetter__("VEHICLEPOWERMODE_ACCESSORY2", function () {
- return 2;
+ utils.forEach(_applicationStateTmp, function (obj) {
+ if (!obj.display)
+ _applicationState.push(obj);
});
- this.__defineGetter__("VEHICLEPOWERMODE_RUN", function () {
- return 3;
- });
+ $("#settings-menu-content-panel-table").remove();
- this.__defineGetter__("vehiclePowerMode", function () {
- return vehiclePowerMode.vehiclePowerMode;
+ contentTable = '<table id="settings-menu-content-panel-table" class="settings-menu-content-table">';
+ utils.forEach(_applicationState, function (obj) {
+ var checked = obj.display ? 'checked="yes"':"";
+ contentTable += '<tr><td><input name="panel-display-setting" type="checkbox" class="settings-menu-checkbox "' +
+ checked + '></input>' +
+ obj.titleName + '</td></tr>\n';
});
+ contentTable += "</table>";
- this.__defineSetter__("vehiclePowerMode", function (val) {
- try {
- val = t.octet(val);
- if (val < 0 || val > 3) {
- return;
- }
- vehiclePowerMode.vehiclePowerMode = val;
- }
- catch (err) {
- }
- });
-};
+ $("#settings-menu-container-div").append(contentTable);
+ $("#settings-menu-popup").css("top", 50);
+ $("#settings-menu-popup").css("left", $(window).width() - 340);
-TripMeter = function (propertyTypes) {
- var tripMeter = {};
+ $("#overlayBackground").css("width", $(window).width());
+ $("#overlayBackground").css("height", $(window).height());
+ $("#overlayBackground").show("fade", "slow");
+ $("#settings-menu-popup").show("slide", {direction: "up"}, "slow");
- VehiclePropertyType.call(this, propertyTypes);
+ $("#settings-menu-save-btn").unbind('click');
+ $("#settings-menu-save-btn").bind("click", function (event) {
+ $("input[name='panel-display-setting']").each(function (i, a) {
+ settings.push(a.checked);
+ });
- tripMeter.tripMeters = propertyTypes.tripMeters || [];
+ utils.forEach(_applicationState, function (obj) {
+ if (!settings[i])
+ obj.collapsed = true;
+ obj.display = settings[i];
+ i++;
+ }, this);
+
+ db.saveObject(_applicationStateId, _applicationState);
+ _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];
- this.__defineGetter__("tripMeters", function () {
- return tripMeter.tripMeters;
+ $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
+ $("#overlayBackground").hide("fade", "slow");
+ setTimeout(reload, 500);
});
- this.__defineSetter__("tripMeters", function (val) {
- try {
- //Changing any items in the array will reset the item's value to '0';
- tripMeter.tripMeters = t.unsigned_long(val, "[]");
+ $(".settings-menu-content-table td").unbind('click');
+ $(".settings-menu-content-table td").bind("click", function (event) {
+ var checkbox;
+ if (($(event.target).children().length === 0)) {
+ return;
+ } else {
+ checkbox = $(event.target).children();
}
- catch (err) {
+
+ if (checkbox.is(':checked')) {
+ checkbox.prop('checked', false);
}
- });
-};
-
-Acceleration = function (propertyTypes) {
- var acceleration = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- acceleration.x = propertyTypes.x || 0;
- acceleration.y = propertyTypes.y || 0;
- acceleration.z = propertyTypes.z || 0;
-
- this.__defineGetter__("x", function () {
- return acceleration.x;
+ else
+ checkbox.prop('checked', true);
});
- this.__defineSetter__("x", function (val) {
- try {
- acceleration.x = t.unsigned_long(val);
- }
- catch (err) {
+ $("#settings-menu-close-btn").unbind('click');
+ $("#settings-menu-close-btn").bind("click", function (event) {
+ if ($("#settings-menu-popup").is(":visible")) {
+ $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
+ $("#overlayBackground").hide("fade", "slow");
+ return;
}
});
- this.__defineGetter__("y", function () {
- return acceleration.y;
+ $(window).bind('resize', function () {
+ $("#settings-menu-popup").css("top", 50);
+ $("#settings-menu-popup").css("left", $(window).width() - 340);
+ $("#overlayBackground").css("width", $(window).width());
+ $("#overlayBackground").css("height", $(window).height());
});
- this.__defineSetter__("y", function (val) {
- try {
- acceleration.y = t.unsigned_long(val);
- }
- catch (err) {
+ $(".settings-menu-checkbox").each(function (i, a) {
+ if (a.checked === false) {
+ unselectedNum++;
}
});
- this.__defineGetter__("z", function () {
- return acceleration.z;
- });
+ if (unselectedNum === 0) {
+ $("#select_unselect_text").text("Unselect All");
+ $("#panelSettingSelectAll").prop('checked', true);
+ }
- this.__defineSetter__("z", function (val) {
- try {
- acceleration.z = t.unsigned_long(val);
+ $("#panelSettingSelectAll").unbind('click');
+ $("#panelSettingSelectAll").bind("click", function (event) {
+ if ($("#panelSettingSelectAll").is(':checked')) {
+ $("#select_unselect_text").text("Unselect All");
+ $(".settings-menu-checkbox").prop('checked', true);
}
- catch (err) {
+ else {
+ $("#select_unselect_text").text("Select All");
+ $(".settings-menu-checkbox").prop('checked', false);
}
});
-};
-
-Transmission = function (propertyTypes) {
- var transmission = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- transmission.gearPosition = propertyTypes.gearPosition || 0;
- transmission.mode = propertyTypes.mode || 0;
-
- this.__defineGetter__("TRANSMISSIONPOSITION_NEUTRAL", function () {
- return 0;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_FIRST", function () {
- return 1;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_SECOND", function () {
- return 2;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_THIRD", function () {
- return 3;
- });
+}
- this.__defineGetter__("TRANSMISSIONPOSITION_FORTH", function () {
- return 4;
- });
+module.exports = {
+ initialize: function () {
+ $("#options-button-panels").bind("click", function (event) {
+ _showSettingMenu();
+ });
+ }
+};
- this.__defineGetter__("TRANSMISSIONPOSITION_FIFTH", function () {
- return 5;
- });
+});
+define('ripple/ui/plugins/communication', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- this.__defineGetter__("TRANSMISSIONPOSITION_SIXTH", function () {
- return 6;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_SEVENTH", function () {
- return 7;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_EIGHTH", function () {
- return 8;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_NINTH", function () {
- return 9;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_TENTH", function () {
- return 10;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_CVT", function () {
- return 64;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_REVERSE", function () {
- return 128;
- });
-
- this.__defineGetter__("TRANSMISSIONPOSITION_PARK", function () {
- return 255;
- });
-
- this.__defineGetter__("TRANSMISSIONMODE_NORMAL", function () {
- return 0;
- });
+var ui = require('ripple/ui'),
+ event = require('ripple/event'),
+ deviceSettings = require('ripple/deviceSettings'),
+ db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _messageType = {
+ sms: "SMS",
+ mms: "MMS",
+ email: "E-mail"
+ },
+ _attachments = [],
+/*
+ _exception = {
+ "": "Connection Issue",
+ "unknown": "Unknown",
+ "network": "Network",
+ "unreachable": "Unreachable",
+ "no-answer": "No Answer",
+ "bad-number": "Bad Number",
+ "number-not-in-use": "Number Not In Use",
+ "media": "Media",
+ "no-sim": "No Sim Card",
+ "account-down": "Account Down",
+ "credit-down": "Credit Down",
+ "barred": "Barred",
+ "network-busy": "Network Busy",
+ "network-down": "Network Down"
+ },
+*/
+ _status = {
+ IDLE: 0,
+ DIALED: 1,
+ INPROGRESS: 2,
+ },
+ _data = {
+ status: _status.IDLE,
+// isInException: false,
+ conversationStartTime: null
+ },
+ _contactNameArr = [],
+ _contactNumArr = [],
+ _CONTACT_KEY = "tizen1-contact",
+ _record = {},
+ _conversationSeconds = 0,
+ _conversationTimer,
+ _msgTimer,
+ _audioPlayersStatus = [];
- this.__defineGetter__("TRANSMISSIONMODE_SPORT", function () {
- return 1;
- });
+function _showMsg() {
+ var messageName = jQuery("#communication-senderName").val(),
+ messageContent = jQuery("#communication-messageContent").val(),
+ disMsgName = jQuery(".communication-messageContainer tr:first-child td"),
+ disMsgContent = jQuery(".communication-messageContainer tr:nth-child(2) td textarea");
- this.__defineGetter__("TRANSMISSIONMODE_ECONOMY", function () {
- return 2;
- });
+ ui.showOverlay("communication-window");
- this.__defineGetter__("TRANSMISSIONMODE_OEMCUSTOM1", function () {
- return 3;
- });
+ disMsgName.text(messageName ? messageName : "Unknown name");
+ disMsgContent.val(messageContent ? messageContent : "");
- this.__defineGetter__("TRANSMISSIONMODE_OEMCUSTOM2", function () {
- return 4;
- });
+ jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
+ .show("slide", {direction: "up"}, "fast");
+ jQuery(".communication-callContainer").hide();
+ jQuery(".communication-messageContainer").show();
+}
- this.__defineGetter__("gearPosition", function () {
- return transmission.gearPosition;
- });
+function _msgEventInitialize() {
+ jQuery("#communication-messageRadioStatus").hide();
+ jQuery("#communication-sendMessage").unbind("click").click(function () {
+ var messageItem,
+ number = jQuery("#communication-senderName").val(),
+ text = jQuery("#communication-messageContent").val(),
+ type = jQuery("#communication-msgType").val(),
+ message = {
+ type: type,
+ body: text,
+ from: number,
+ time: new Date(),
+ attachments: _attachments
+ };
- this.__defineSetter__("gearPosition", function (val) {
- try {
- val = t.octet(val);
- if ((val >= 0 && val <= 10) || val === 64 || val === 128 ||
- val === 255) {
- transmission.gearPosition = val;
- }
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
+ (type === 'sms' || type === 'mms')) {
+ jQuery("#communication-messageRadioStatus").html('cellular radio is off<br \>Turn it on from Network Management Panel.');
+ jQuery("#communication-messageRadioStatus").show();
+ setTimeout(function () {
+ jQuery("#communication-messageRadioStatus").hide();
+ }, 3000);
+ return;
}
- catch (err) {
+ if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
+ type === 'email') {
+ jQuery("#communication-messageRadioStatus").html('wifi radio is off<br \>Turn it on from Network Management Panel.');
+ jQuery("#communication-messageRadioStatus").show();
+ setTimeout(function () {
+ jQuery("#communication-messageRadioStatus").hide();
+ }, 3000);
+ return;
}
- });
- this.__defineGetter__("mode", function () {
- return transmission.mode;
- });
+ event.trigger("MessageReceived", [message]);
+ _attachments = [];
+ event.trigger("CommWinShow", [true]);
+ _showMsg();
- this.__defineSetter__("mode", function (val) {
- try {
- val = t.octet(val);
- if (val < 0 || val > 4) {
- return;
+ jQuery(".communication-messageContainer textarea").attr("disabled", "disabled");
+ jQuery("#communication-messageOut td:nth-child(3)").text(jQuery("#communication-messageContent").val());
+ messageItem = jQuery("#communication-messageOut").html();
+ jQuery("#communication-messageDisplay").append(messageItem);
+
+ clearTimeout(_msgTimer);
+ _msgTimer = setTimeout(function () {
+ if (_data.status === _status.IDLE) {
+ ui.hideOverlay("communication-window");
+ event.trigger("CommWinShow", [false]);
+ } else {
+ _showCall();
}
- transmission.mode = val;
- }
- catch (err) {
- }
+ }, 5000);
});
-};
-
-CruiseControlStatus = function (propertyTypes) {
- var cruiseControlStatus = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- cruiseControlStatus.activated = propertyTypes.activated || false;
- cruiseControlStatus.speed = propertyTypes.speed || 0;
- this.__defineGetter__("activated", function () {
- return cruiseControlStatus.activated;
- });
+ jQuery("#communication-clearMessage").unbind("click").click(function () {
+ jQuery("#communication-messageDisplay").empty();
+ });
- this.__defineSetter__("activated", function (val) {
- try {
- cruiseControlStatus.activated = t.boolean(val);
- }
- catch (err) {
- }
- });
+ event.on("LayoutChanged", function () {
+ jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"));
- this.__defineGetter__("speed", function () {
- return cruiseControlStatus.speed;
});
+ event.on("OutsideMessageReceived", function (message) {
+ var i = 0,
+ recipients = [],
+ recipientsStatus = {},
+ messageItem;
- this.__defineSetter__("speed", function (val) {
- try {
- cruiseControlStatus.speed = t.unsigned_short(val);
- }
- catch (err) {
+ recipientsStatus.id = message.id;
+ recipientsStatus.msg = message.msg;
+ for (i in message.to) {
+ recipientsStatus[message.to[i]] = true;
+ recipients.push(message.to[i]);
}
- });
-};
-
-WheelBrake = function (propertyTypes) {
- var wheelBrake = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- wheelBrake.engaged = propertyTypes.engaged || false;
-
- this.__defineGetter__("engaged", function () {
- return wheelBrake.engaged;
- });
-
- this.__defineSetter__("engaged", function (val) {
- try {
- wheelBrake.engaged = t.boolean(val);
+ for (i in message.cc) {
+ recipientsStatus[message.cc[i]] = true;
+ recipients.push(message.cc[i]);
}
- catch (err) {
+ for (i in message.bcc) {
+ recipientsStatus[message.bcc[i]] = true;
+ recipients.push(message.bcc[i]);
}
- });
-};
-
-LightStatus = function (propertyTypes) {
- var lightStatus = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- lightStatus.head = propertyTypes.head || false;
- lightStatus.rightTurn = propertyTypes.rightTurn || false;
- lightStatus.leftTurn = propertyTypes.leftTurn || false;
- lightStatus.brake = propertyTypes.brake || false;
- lightStatus.fog = propertyTypes.fog || false;
- lightStatus.hazard = propertyTypes.hazard || false;
- lightStatus.parking = propertyTypes.parking || false;
- lightStatus.highBeam = propertyTypes.highBeam || false;
- this.__defineGetter__("head", function () {
- return lightStatus.head;
+ event.trigger("MessageSent", [recipientsStatus]);
+ jQuery("#communication-messageIn td:nth-child(1)").text(message.body);
+ messageItem = jQuery("#communication-messageIn").html();
+ jQuery("#communication-messageDisplay").append(messageItem);
});
- this.__defineSetter__("head", function (val) {
- try {
- lightStatus.head = t.boolean(val);
- }
- catch (err) {
+ jQuery("#communication-ok").unbind("click").click(function () {
+ if (_data.status === _status.IDLE) {
+ ui.hideOverlay("communication-window");
+ event.trigger("CommWinShow", [false]);
+ } else {
+ _showCall();
}
+ clearTimeout(_msgTimer);
});
+}
- this.__defineGetter__("rightTurn", function () {
- return lightStatus.rightTurn;
- });
+function _msgInitialize() {
+ _msgEventInitialize();
- this.__defineSetter__("rightTurn", function (val) {
- try {
- lightStatus.rightTurn = t.boolean(val);
- }
- catch (err) {
- }
- });
+ utils.forEach(_messageType, function (msgTypeText, msgType) {
+ var typeNode = utils.createElement("option", {
+ "innerText": msgTypeText,
+ "value": msgType
+ });
- this.__defineGetter__("leftTurn", function () {
- return lightStatus.leftTurn;
+ jQuery("#communication-msgType").append(typeNode);
});
+}
- this.__defineSetter__("leftTurn", function (val) {
- try {
- lightStatus.leftTurn = t.boolean(val);
+function pauseAllAudioPlayer() {
+ var audios = $("#document").contents().find("audio"),
+ index;
+ for (var index = 0; index < audios.length; index++) {
+ if (audios[index].paused) {
+ _audioPlayersStatus[index] = 0;
}
- catch (err) {
+ else {
+ _audioPlayersStatus[index] = 1;
+ audios[index].pause();
}
- });
-
- this.__defineGetter__("brake", function () {
- return lightStatus.brake;
- });
+ }
+}
- this.__defineSetter__("brake", function (val) {
- try {
- lightStatus.brake = t.boolean(val);
- }
- catch (err) {
+function playAllAudioPlayer() {
+ var audios = $("#document").contents().find("audio"),
+ index;
+ for (var index = 0; index < audios.length; index++) {
+ if (_audioPlayersStatus[index] === 1) {
+ audios[index].play();
}
- });
-
- this.__defineGetter__("fog", function () {
- return lightStatus.fog;
- });
+ }
+ _audioPlayersStatus = [];
+}
- this.__defineSetter__("fog", function (val) {
- try {
- lightStatus.fog = t.boolean(val);
- }
- catch (err) {
- }
- });
+function _showCall() {
+ var callName = jQuery("#communication-callerName").val(),
+ callNum = jQuery("#communication-callNum").val(),
+ disCallName = jQuery(".communication-callContainer tr:first-child td"),
+ disCallNum = jQuery(".communication-callContainer tr:nth-child(2) td");
- this.__defineGetter__("hazard", function () {
- return lightStatus.hazard;
- });
+ ui.showOverlay("communication-window");
+ event.trigger("CommWinShow", [true]);
- this.__defineSetter__("hazard", function (val) {
- try {
- lightStatus.hazard = t.boolean(val);
- }
- catch (err) {
- }
- });
+ disCallName.text(callName ? callName : "Unknown Name");
+ disCallNum.text(callNum ? callNum : "Unknown Number");
- this.__defineGetter__("parking", function () {
- return lightStatus.parking;
- });
+ jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
+ .show("slide", {direction: "up"}, "fast");
+ jQuery(".communication-callContainer").show();
+ jQuery(".communication-messageContainer").hide();
+ pauseAllAudioPlayer();
+}
- this.__defineSetter__("parking", function (val) {
- try {
- lightStatus.parking = t.boolean(val);
- }
- catch (err) {
- }
- });
+function _initRecord() {
+ var callerName = jQuery("#communication-callerName").val(),
+ callerNum = jQuery("#communication-callNum").val(),
+ displayName = callerName ? callerName : "Unknown",
+ displayNum = callerNum ? callerNum : "Unknown";
- this.__defineGetter__("highBeam", function () {
- return lightStatus.highBeam;
- });
+ _record = {};
+ _record.type = "TEL";
+ if ($("#is-videoCall").prop("checked") === true) {
+ _record.features = ["CALL", "VIDEOCALL"];
+ } else {
+ _record.features = ["CALL", "VOICECALL"];
+ }
+ _record.remoteParties = [{
+ remoteParty: displayNum,
+ personId: displayName,
+ }];
+ _record.startTime = new Date();
+}
- this.__defineSetter__("highBeam", function (val) {
- try {
- lightStatus.highBeam = t.boolean(val);
- }
- catch (err) {
- }
- });
-};
+function _endCall(callEndReason) {
+ _record.duration = _data.conversationStartTime ? _conversationSeconds : 0;
-InteriorLightStatus = function (propertyTypes) {
- var interiorLightStatus = {};
+ _data.conversationStartTime = null;
- VehiclePropertyType.call(this, propertyTypes);
+ switch (callEndReason) {
+ case 'rejected':
+ _record.direction = "REJECTED";
+ break;
+ case 'remote':
+ _record.direction = "RECEIVED";
+ break;
+ case 'local':
+ _record.direction = "MISSEDNEW";
+ break;
+ }
- interiorLightStatus.passenger = propertyTypes.passenger || false;
- interiorLightStatus.driver = propertyTypes.driver || false;
- interiorLightStatus.center = propertyTypes.center || false;
+ event.trigger("CallRecorded", [_record]);
+ event.trigger("CallInProgress", [false]);
- this.__defineGetter__("passenger", function () {
- return interiorLightStatus.passenger;
- });
+ _data.status = _status.IDLE;
+ _record = {};
- this.__defineSetter__("passenger", function (val) {
- try {
- interiorLightStatus.passenger = t.boolean(val);
- }
- catch (err) {
- }
- });
+ _conversationSeconds = 0;
+ window.clearInterval(_conversationTimer);
+ ui.hideOverlay("communication-window");
+ event.trigger("CommWinShow", [false]);
+ playAllAudioPlayer();
+}
- this.__defineGetter__("driver", function () {
- return interiorLightStatus.driver;
- });
+function _callEventInitialize() {
+ jQuery("#communication-cellularStatus").hide();
+ jQuery("#communication-callStart").unbind('click').click(
+ function () {
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false) {
+ jQuery("#communication-cellularStatus").show();
+ setTimeout(function () {
+ jQuery("#communication-cellularStatus").hide();
+ }, 3000);
- this.__defineSetter__("driver", function (val) {
- try {
- interiorLightStatus.driver = t.boolean(val);
- }
- catch (err) {
- }
- });
+ return;
+ }
+ if (_data.status === _status.IDLE) {
+ _data.status = _status.DIALED;
+ _initRecord();
+ _showCall();
+ jQuery("#callSettings tr:last-child td").text("Calling...");
+ jQuery("#communication-callStart > span").text("End Call");
+ jQuery("#callSettings input").attr("disabled", "disabled");
+ } else {
+ _endCall("local");
- this.__defineGetter__("center", function () {
- return interiorLightStatus.center;
- });
+ jQuery("#callSettings tr:last-child td").text("");
+ jQuery("#communication-callStart > span").text("Call");
+ jQuery(".communication-callContainer tr:nth-child(3)").show();
+ jQuery(".communication-callContainer tr:last-child").hide();
+ jQuery("#callSettings input").removeAttr("disabled");
+ }
- this.__defineSetter__("center", function (val) {
- try {
- interiorLightStatus.center = t.boolean(val);
- }
- catch (err) {
}
- });
-};
-
-Horn = function (propertyTypes) {
- var horn = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- horn.on = propertyTypes.on || false;
-
- this.__defineGetter__("on", function () {
- return horn.on;
- });
+ );
- this.__defineSetter__("on", function (val) {
- try {
- horn.on = t.boolean(val);
- }
- catch (err) {
+ event.on("ApplicationLoad", function () {
+ switch (_data.status) {
+ case _status.INPROGRESS:
+ jQuery("#communication-callStart").click();
+ break;
+ case _status.DIALED:
+ jQuery("#communication-ignore").click();
+ break;
+ default:
+ break;
}
});
-};
-
-Fuel = function (propertyTypes) {
- var fuel = {};
-
- VehiclePropertyType.call(this, propertyTypes);
- fuel.level = propertyTypes.level || 0;
- fuel.range = propertyTypes.range || 0;
- fuel.instantConsumption = propertyTypes.instantConsumption || 0;
- fuel.instantEconomy = propertyTypes.instantEconomy || 0;
- fuel.averageEconomy = propertyTypes.averageEconomy || 0;
+ jQuery("#communication-ignore").unbind('click').click(function () {
+ _endCall("rejected");
- this.__defineGetter__("level", function () {
- return fuel.level;
+ jQuery("#callSettings tr:last-child td").text("");
+ jQuery("#communication-callStart > span").text("Call");
+ jQuery("#communication-callStart").removeData();
+ jQuery("#callSettings input").removeAttr("disabled");
});
- this.__defineSetter__("level", function (val) {
- try {
- fuel.level = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ jQuery("#communication-answer").unbind('click').click(function () {
+ _data.conversationStartTime = new Date();
+ event.trigger("CallInProgress", [true]);
+ _data.status = _status.INPROGRESS;
- this.__defineGetter__("range", function () {
- return fuel.range;
- });
+ _conversationTimer = setInterval(function () {
+ var timeObj = new Date(1970, 0, 1),
+ timeString;
- this.__defineSetter__("range", function (val) {
- try {
- fuel.range = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ timeObj.setSeconds(_conversationSeconds);
+ timeString = timeObj.toTimeString().substr(0, 8);
+ jQuery("#callSettings tr:last-child td").text(timeString);
+ _conversationSeconds = _conversationSeconds + 1;
+ }, 1000);
- this.__defineGetter__("instantConsumption", function () {
- return fuel.instantConsumption;
+ jQuery(".communication-callContainer tr:nth-child(3)").hide();
+ jQuery(".communication-callContainer tr:last-child").show();
});
- this.__defineSetter__("instantConsumption", function (val) {
- try {
- fuel.instantConsumption = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ jQuery("#communication-end").unbind('click').click(function () {
+ _endCall("remote");
- this.__defineGetter__("instantEconomy", function () {
- return fuel.instantEconomy;
+ jQuery("#callSettings tr:last-child td").text("");
+ jQuery("#communication-callStart > span").text("Call");
+ jQuery("#communication-callStart").removeData();
+ jQuery(".communication-callContainer tr:nth-child(3)").show();
+ jQuery(".communication-callContainer tr:last-child").hide();
+ jQuery("#callSettings input").removeAttr("disabled");
});
-
- this.__defineSetter__("instantEconomy", function (val) {
- try {
- fuel.instantEconomy = t.unsigned_short(val);
- }
- catch (err) {
+/*
+ jQuery("#communication-callEndReason").unbind("change").change(function () {
+ if (!jQuery("#communication-callEndReason").val()) {
+ _data.isInException = false;
+ } else {
+ _data.isInException = true;
+ if (_data.isInException && (_data.status !== _status.IDLE)) {
+ _endCall(jQuery("#communication-callEndReason").val());
+ }
}
- });
-
- this.__defineGetter__("averageEconomy", function () {
- return fuel.averageEconomy;
- });
- this.__defineSetter__("averageEconomy", function (val) {
- try {
- //Setting this to any value should reset the counter to '0'
- fuel.averageEconomy = t.unsigned_short(val);
- }
- catch (err) {
- }
+ jQuery("#callSettings tr:last-child td").text("");
+ jQuery("#communication-callStart > span").text("Call");
+ jQuery("#communication-callStart").removeData();
+ jQuery(".communication-callContainer tr:nth-child(3)").show();
+ jQuery(".communication-callContainer tr:last-child").hide();
+ jQuery("#callSettings input").removeAttr("disabled");
});
-};
-
-EngineOil = function (propertyTypes) {
- var engineOil = {};
+*/
+}
- VehiclePropertyType.call(this, propertyTypes);
+function _contactInitialize() {
+ var data = db.retrieveObject(_CONTACT_KEY),
+ displayName = null, number = null, index = 0;
- engineOil.remaining = propertyTypes.remaining || 0;
- engineOil.temperature = propertyTypes.temperature || 0;
- engineOil.pressure = propertyTypes.Pressure || 0;
+ _contactNameArr = [];
+ _contactNumArr = [];
- this.__defineGetter__("remaining", function () {
- return engineOil.remaining;
+ utils.forEach(data, function (addrBook) {
+ utils.forEach(addrBook._contacts, function (contact) {
+ if (contact.name && contact.name && contact.phoneNumbers && contact.phoneNumbers.length > 0) {
+ displayName = contact.name.firstName + ' ' + contact.name.lastName;
+ number = contact.phoneNumbers[0].number;
+ _contactNameArr.push(displayName);
+ _contactNumArr[displayName] = number;
+ index++;
+ }
+ });
});
- this.__defineSetter__("remaining", function (val) {
- try {
- engineOil.remaining = t.unsigned_short(val);
- }
- catch (err) {
+ jQuery("#communication-callerName").autocomplete({
+ source: _contactNameArr,
+ select: function (event, ui) {
+ jQuery("#communication-callNum").val(_contactNumArr[ui.item.value]);
}
});
-
- this.__defineGetter__("temperature", function () {
- return engineOil.temperature;
+ jQuery("#communication-senderName").autocomplete({
+ source: _contactNameArr
});
+}
- this.__defineSetter__("temperature", function (val) {
- try {
- engineOil.temperature = t.long(val);
- }
- catch (err) {
- }
- });
+function _callInitialize() {
+ _callEventInitialize();
- this.__defineGetter__("pressure", function () {
- return engineOil.pressure;
- });
+ _contactInitialize();
+/*
+ utils.forEach(_exception, function (value, key) {
+ var typeNode = utils.createElement("option", {
+ "innerText": value,
+ "value": key
+ });
- this.__defineSetter__("pressure", function (val) {
- try {
- engineOil.pressure = t.unsigned_short(val);
- }
- catch (err) {
- }
+ jQuery("#communication-callEndReason").append(typeNode);
});
-};
-
-Location = function (propertyTypes) {
- var location = {};
+*/
+}
- VehiclePropertyType.call(this, propertyTypes);
+function _pushEventInitialize() {
+ function register(appService) {
+ appService.registrationId = Math.uuid(null, 16);
- location.latitude = propertyTypes.latitude || 0;
- location.longitude = propertyTypes.longitude || 0;
- location.altitude = propertyTypes.altitude || 0;
- location.direction = propertyTypes.direction || 0;
+ window.setTimeout(function () {
+ var appLabel;
- this.__defineGetter__("latitude", function () {
- return location.latitude;
- });
+ if ($("#communication-push-" + appService.appId).length !== 0) {
+ $("#" + appService.appId).click();
+ $("#communication-push-status-" + appService.appId).html("||");
+ $("#communication-push-status-" + appService.appId).css("color", "#ff0000");
- this.__defineSetter__("latitude", function (val) {
- try {
- val = t.double(val);
- if (val >= -180 && val <= 180) {
- location.latitude = val;
+ return;
}
- }
- catch (err) {
- }
- });
-
- this.__defineGetter__("longitude", function () {
- return location.longitude;
- });
- this.__defineSetter__("longitude", function (val) {
- try {
- val = t.double(val);
- if (val >= -90 && val <= 90) {
- location.longitude = val;
+ if (!$("#communication-push-app > tbody").html()) {
+ $("#communication-push-header").show();
+ $("#communication-push-submit").removeAttr("disabled");
}
- }
- catch (err) {
- }
- });
- this.__defineGetter__("altitude", function () {
- return location.altitude;
- });
+ appLabel = appService.appControl.uri || appService.appId;
- this.__defineSetter__("altitude", function (val) {
- try {
- val = t.double(val);
- if (val >= 0) {
- location.altitude = val;
- }
- }
- catch (err) {
- }
- });
+ $("#communication-push-app").append(
+ "<tr id='communication-push-" + appService.appId + "'>" +
+ "<td style='width: 90%'><input type='radio' name='communication-push-list' id='" +
+ appService.appId + "' style='margin: 5px' checked='checked' />" +
+ "<label for='" + appService.appId + "'>" + appLabel + "</label></td>" +
+ "<td id='communication-push-status-" + appService.appId + "'>||</td>" +
+ "</tr>");
- this.__defineGetter__("direction", function () {
- return location.direction;
- });
+ $("label[for='" + appService.appId + "']").css({
+ "display": "inline-block",
+ "width": "220px",
+ "white-space": "nowrap",
+ "overflow": "hidden",
+ "text-overflow": "ellipsis"
+ });
- this.__defineSetter__("direction", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val < 360) {
- location.direction = val;
- }
- }
- catch (err) {
- }
- });
-};
+ $("#communication-push-status-" + appService.appId).css({
+ "width": "10%",
+ "color": "#ff0000",
+ "text-align": "center",
+ "font-weight": "bold",
+ "font-size": "14px"
+ });
-ExteriorBrightness = function (propertyTypes) {
- var eb = {};
+ $("#communication-push-app tr:even").css("background-color", "white");
+ $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
+ }, 1);
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ function unregister(appId) {
+ if ($("#communication-push-" + appId).length === 0)
+ return;
- eb.exteriorBrightness = propertyTypes.exteriorBrightness || 0;
+ $("tr[id='communication-push-" + appId + "']").remove();
- this.__defineGetter__("exteriorBrightness", function () {
- return eb.exteriorBrightness;
- });
+ if (!$("#communication-push-app > tbody").html()) {
+ $("#communication-push-header").hide();
+ $("#communication-push-submit").attr("disabled", "disabled");
- this.__defineSetter__("exteriorBrightness", function (val) {
- try {
- eb.exteriorBrightness = t.unsigned_long(val);
+ return;
}
- catch (err) {
+
+ if ($("input[name='communication-push-list']:checked").length === 0) {
+ $("#communication-push-app input:first").click();
}
- });
-};
-Temperature = function (propertyTypes) {
- var temperature = {};
+ $("#communication-push-app tr:even").css("background-color", "white");
+ $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ function connect(appId) {
+ $("#communication-push-status-" + appId).html("<=>");
+ $("#communication-push-status-" + appId).css("color", "#32cd32");
+ }
- temperature.interior = propertyTypes.interior || 0;
- temperature.exterior = propertyTypes.exterior || 0;
+ function disconnect(appId) {
+ $("#communication-push-status-" + appId).html("||");
+ $("#communication-push-status-" + appId).css("color", "#ff0000");
+ }
- this.__defineGetter__("interior", function () {
- return temperature.interior;
- });
+ event.on("PushRequest", function (command, cmdData) {
+ switch (command) {
+ case "REGISTER":
+ register(cmdData);
+ break;
- this.__defineSetter__("interior", function (val) {
- try {
- temperature.interior = t.short(val);
- }
- catch (err) {
- }
- });
+ case "UNREGISTER":
+ unregister(cmdData);
+ break;
- this.__defineGetter__("exterior", function () {
- return temperature.exterior;
- });
+ case "CONNECT":
+ connect(cmdData);
+ break;
- this.__defineSetter__("exterior", function (val) {
- try {
- temperature.exterior = t.short(val);
- }
- catch (err) {
+ case "DISCONNECT":
+ disconnect(cmdData);
+ break;
}
});
-};
+}
-RainSensor = function (propertyTypes) {
- var rainSensor = {};
+function _pushElementInitialize() {
+ $("#communication-push-submit").attr("disabled", "disabled");
+ $("#communication-push-submit").unbind('click').click(function () {
+ var appId, pushMessage;
- VehiclePropertyType.call(this, propertyTypes);
+ appId = $("#communication-push-app :checked").attr("id");
+ if (!appId)
+ return;
- rainSensor.rainSensor = propertyTypes.rainSensor || 0;
+ pushMessage = {
+ appData: $("#communication-push-data").val(),
+ alertMessage: $("#communication-push-msg").val(),
+ date: new Date()
+ };
- this.__defineGetter__("rainSensor", function () {
- return rainSensor.rainSensor;
+ if (!pushMessage.appData || !pushMessage.alertMessage)
+ return;
+
+ event.trigger("PushNotified", [appId, pushMessage]);
});
- this.__defineSetter__("rainSensor", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 10) {
- rainSensor.rainSensor = val;
- }
- }
- catch (err) {
- }
+ $("#communication-push-clear").unbind('click').click(function () {
+ $("#communication-push-msg").val("");
+ $("#communication-push-data").val("");
});
-};
+}
-WindshieldWiper = function (propertyTypes) {
- var windshieldWiper = {};
+function _pushInitialize() {
+ _pushEventInitialize();
+ _pushElementInitialize();
+}
- VehiclePropertyType.call(this, propertyTypes);
+module.exports = {
+ panel: {
+ domId: "communication-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Communications",
+ display: true
+ },
+ initialize: function () {
+ jQuery("#communication-select").tabs();
+ _callInitialize();
+ _msgInitialize();
+ _pushInitialize();
+ }
+};
- windshieldWiper.windshieldWiper = propertyTypes.windshieldWiper || 0;
+});
+define('ripple/ui/plugins/package', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- this.__defineGetter__("WIPERSPEED_OFF", function () {
- return 0;
- });
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ dbinit = require('ripple/platform/tizen/2.0/dbinit'),
+ PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
+ DB_PACKAGE_KEY = "tizen-db-package",
+ _data = {
+ packageList: {},
+ installedList: {}
+ },
+ _currentPackageId = null,
+ _packages,
+ _installedList,
+ _packageListTemplate,
+ _packageInstalledTemplate;
- this.__defineGetter__("WIPERSPEED_SLOWEST", function () {
- return 1;
+function _get() {
+ _data = db.retrieveObject(DB_PACKAGE_KEY);
+ if (_data === undefined) {
+ _data = {
+ packageList: _packages,
+ installedList: _installedList
+ };
+ }
+ utils.forEach(_data.installedList, function (item) {
+ item.lastModified = new Date(item.lastModified);
});
+}
- this.__defineGetter__("WIPERSPEED_FASTEST", function () {
- return 5;
- });
+function _save() {
+ db.saveObject(DB_PACKAGE_KEY, _data);
+}
- this.__defineGetter__("WIPERSPEED_AUTO", function () {
- return 10;
+function loadPackageList() {
+ var nodes = jQuery("#package-list-select");
+ nodes.html("");
+ utils.forEach(_data.packageList, function (item, index) {
+ nodes.append(utils.createElement("option", {
+ "value": index,
+ "innerText": item.name
+ }));
});
+ renderPackageListBox($("#package-list-select option:selected").val());
+}
- this.__defineGetter__("windshieldWiper", function () {
- return windshieldWiper.windshieldWiper;
+function loadInstalledList() {
+ var html = "";
+ jQuery("#package-installed-box").empty();
+ utils.forEach(_data.installedList, function (item) {
+ html += _packageInstalledTemplate.replace(/#Name/g, item.name)
+ .replace(/#ID/g, item.id)
+ .replace(/#IconPath/, item.iconPath)
+ .replace(/#Version/, item.version)
+ .replace(/#TotalSize/, item.totalSize)
+ .replace(/#DataSize/, item.dataSize)
+ .replace(/#LastModified/, item.lastModified)
+ .replace(/#Author/, item.author)
+ .replace(/#Description/, item.description)
+ .replace(/#APPIDs/, item.appIds.join("<br>"));
});
-
- this.__defineSetter__("windshieldWiper", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1 || val === 5 || val === 10) {
- windshieldWiper.windshieldWiper = val;
- }
- }
- catch (err) {
- }
+ $("#package-installed-box").accordion("destroy");
+ $("#package-installed-box").html(html).accordion({
+ active: false,
+ collapsible: true,
+ autoHeight: false
});
-};
+ $("." + "package-remove-btn").bind("click", function () {
+ var id = this.id;
+ if (id === _currentPackageId) {
+ $("#msg-" + id).html("Can't Uninstall:<br> Package including running app");
+ setTimeout(function () {
+ $("#msg-" + id).text("");
+ }, 5000);
+ return;
+ }
+ utils.forEach(_data.packageList, function (item) {
+ if (item.id === id) {
+ event.trigger("remove-apps", [item.appIds]);
+ }
+ });
+ delete _data.installedList[this.id];
+ _save();
+ loadPackageList();
+ loadInstalledList();
+ event.trigger("uninstall-package", [this.id]);
+ });
+}
-HVAC = function (propertyTypes) {
- var hvac = {};
+function renderPackageListBox(path) {
+ var item, html;
+ jQuery("#package-list-box").empty();
+ item = _data.packageList[path];
+ html = _packageListTemplate.replace(/#Path/, path)
+ .replace(/#ID/, item.id)
+ .replace(/#Name/, item.name)
+ .replace(/#IconPath/, item.iconPath)
+ .replace(/#Version/, item.version)
+ .replace(/#TotalSize/, item.totalSize)
+ .replace(/#DataSize/, item.dataSize)
+ .replace(/#Author/, item.author)
+ .replace(/#Description/, item.description)
+ .replace(/#APPList/, item.appIds.join("<br>"));
+ jQuery("#package-list-box").html(html);
+ if (_data.installedList[item.id]) {
+ jQuery("#package-update-btn").show();
+ } else {
+ jQuery("#package-install-btn").show();
+ }
+}
- VehiclePropertyType.call(this, propertyTypes);
+function addPackage(path, type) {
+ var item;
+ if (!_data.packageList[path]) {
+ return;
+ }
+ item = _data.packageList[path];
+ _data.installedList[item.id] = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, new Date(),
+ item.author, item.description, item.appIds
+ );
+ if (type === "install") {
+ event.trigger("install-apps", [item.appIds]);
+ } else {
+ event.trigger("update-apps", [item.appIds]);
+ }
+ _save();
+}
- hvac.airflowDirection = propertyTypes.airflowDirection || 0;
- hvac.fanSpeed = propertyTypes.fanSpeed || 0;
- hvac.targetTemperature = propertyTypes.targetTemperature || 0;
- hvac.airConditioning = propertyTypes.airConditioning || false;
- hvac.airRecirculation = propertyTypes.airRecirculation || false;
- hvac.heater = propertyTypes.heater || false;
- hvac.steeringWheelHeater = propertyTypes.steeringWheelHeater || false;
- hvac.seatHeater = propertyTypes.seatHeater || false;
- hvac.seatCooler = propertyTypes.seatCooler || false;
+module.exports = {
+ panel: {
+ domId: "package-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Packages and Applications",
+ display: true
+ },
+ initialize: function () {
+ _packages = dbinit.Package.packages;
+ _installedList = dbinit.Package.installedList;
+ _packageListTemplate = jQuery("#package-list-template").html();
+ _packageInstalledTemplate = jQuery("#package-installed-template").html();
- this.__defineGetter__("AIRFLOWDIRECTION_FRONTPANEL", function () {
- return 0;
- });
+ _get();
+ _save();
+ loadPackageList();
+ loadInstalledList();
+ jQuery("#package-list-select").bind("focus change", function () {
+ var path = $("#package-list-select option:selected").val();
+ renderPackageListBox(path);
+ });
+ jQuery("#package-install-btn").live("click", function () {
+ var path = $("#package-list-select option:selected").val();
+ addPackage(path, "install");
+ _get();
+ loadPackageList();
+ loadInstalledList();
+ event.trigger("install-packge", [path]);
+ });
+ jQuery("#package-update-btn").live("click", function () {
+ var path = $("#package-list-select option:selected").val();
+ addPackage(path, "update");
+ loadPackageList();
+ loadInstalledList();
+ event.trigger("update-package", [path]);
+ });
+ jQuery("#package-select").tabs();
+ event.on("installedList-updated", function () {
+ _get();
+ loadPackageList();
+ loadInstalledList();
+ });
+ event.on("install-current-package", function (item) {
+ _data.installedList[item.id] = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, item.lastModified,
+ item.author, item.description, item.appIds);
+ _currentPackageId = item.id;
+ loadInstalledList();
+ });
+ }
+};
- this.__defineGetter__("AIRFLOWDIRECTION_FLOORDUCT", function () {
- return 1;
- });
+});
+define('ripple/ui/plugins/application', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- this.__defineGetter__("AIRFLOWDIRECTION_FRONT", function () {
- return 0x02;
- });
+var event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ dbinit = require('ripple/platform/tizen/2.0/dbinit'),
+ DB_APPLICATION_KEY = "tizen1-db-application",
+ _data = {
+ appList: {},
+ installedAppList: {}
+ },
+ _appInstalledTemplate,
+ _apps,
+ _installedAppList;
- this.__defineGetter__("AIRFLOWDIRECTION_DEFROSTER", function () {
- return 0x04;
- });
+function _get() {
+ _data = db.retrieveObject(DB_APPLICATION_KEY);
+ if (_data === undefined) {
+ _data = {
+ appList: _apps,
+ installedAppList: _installedAppList
+ };
+ }
+}
- this.__defineGetter__("airflowDirection", function () {
- return hvac.airflowDirection;
- });
+function _save() {
+ db.saveObject(DB_APPLICATION_KEY, _data);
+}
- this.__defineSetter__("airflowDirection", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1 || val === 0x02 || val === 0x04) {
- hvac.airflowDirection = val;
- }
- }
- catch (err) {
- }
+function _loadInstalledAppList() {
+ var html = "";
+ jQuery("#application-installed-box").empty();
+ utils.forEach(_data.installedAppList, function (item) {
+ html += _appInstalledTemplate.replace(/#Name/g, item.name)
+ .replace(/#ID/g, item.id)
+ .replace(/#IconPath/, item.iconPath)
+ .replace(/#Version/, item.version)
+ .replace(/#Show/, item.show)
+ .replace(/#Categories/, item.categories.join("<br>"))
+ .replace(/#InstallDate/, item.installDate)
+ .replace(/#Size/, item.size)
+ .replace(/#PackageID/, item.packageId)
+ .replace(/#SharedURI/, item.sharedURI)
+ .replace(/#Operation/, item.operation)
+ .replace(/#URI/, item.appControl.uri)
+ .replace(/#MIME/, item.appControl.mime)
+ .replace(/#category/, item.appControl.category)
+ .replace(/#Data/, item.appControl.data);
});
-
- this.__defineGetter__("fanSpeed", function () {
- return hvac.fanSpeed;
+ jQuery("#application-installed-box").accordion("destroy");
+ jQuery("#application-installed-box").html(html).accordion({
+ active: false,
+ collapsible: true,
+ autoHeight: false
});
+}
- this.__defineSetter__("fanSpeed", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 7) {
- hvac.fanSpeed = val;
- }
- }
- catch (err) {
- }
- });
+function _displayInfo(text) {
+ var html = "<b>" + text + "</b>";
+ document.getElementById("application-error").innerHTML = html;
+}
- this.__defineGetter__("targetTemperature", function () {
- return hvac.targetTemperature;
- });
+function _programChanged(status, id) {
+ event.trigger("programChanged", [status, id]);
+}
- this.__defineSetter__("targetTemperature", function (val) {
- try {
- hvac.targetTemperature = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+function updateApp(id, updateFlag) {
+ var item = _data.appList[id];
+ if (!item) {
+ return;
+ }
+ _data.installedAppList[id] = {
+ id: item.id,
+ name: item.name,
+ iconPath: item.iconPath,
+ version: item.version,
+ show: item.show,
+ categories: item.categories,
+ installDate: new Date(),
+ size: item.size,
+ packageId: item.packageId,
+ sharedURI: item.sharedURI,
+ operation: item.operation,
+ appControl: {
+ uri: item.appControl.uri,
+ mime: item.appControl.mime,
+ category: item.appControl.category,
+ data: item.appControl.data
+ },
+ type: item.type,
+ value: item.value
+ };
+ _save();
+ if (updateFlag) {
+ _programChanged("updated", id);
+ } else {
+ _programChanged("installed", id);
+ }
+ _loadInstalledAppList();
+}
- this.__defineGetter__("airConditioning", function () {
- return hvac.airConditioning;
- });
+function removeApp(id) {
+ delete _data.installedAppList[id];
+ _save();
+ _programChanged("uninstalled", id);
+ _loadInstalledAppList();
+}
- this.__defineSetter__("airConditioning", function (val) {
- try {
- hvac.airConditioning = t.boolean(val);
- }
- catch (err) {
- }
- });
+event.on("install-current-app", function (item) {
+ _data.installedAppList[item.id] = {
+ id: item.id,
+ name: item.name,
+ iconPath: item.iconPath,
+ version: item.version,
+ show: item.show,
+ categories: item.categories,
+ installDate: item.installDate,
+ size: item.size,
+ packageId: item.packageId,
+ sharedURI: item.sharedURI,
+ operation: item.operation,
+ appControl: {
+ uri: item.appControl.uri,
+ mime: item.appControl.mime,
+ category: item.appControl.category,
+ data: item.appControl.data
+ },
+ type: item.type,
+ value: item.value
+ };
+ _loadInstalledAppList();
+});
- this.__defineGetter__("airRecirculation", function () {
- return hvac.airRecirculation;
- });
+event.on("appServiceReplied", function () {
+ _displayInfo("The application has been launched successfully");
+});
- this.__defineSetter__("airRecirculation", function (val) {
- try {
- hvac.airRecirculation = t.boolean(val);
- }
- catch (err) {
- }
+event.on("install-apps", function (ids) {
+ utils.forEach(ids, function (id) {
+ updateApp(id, false);
});
+});
- this.__defineGetter__("heater", function () {
- return hvac.heater;
+event.on("update-apps", function (ids) {
+ utils.forEach(ids, function (id) {
+ updateApp(id, true);
});
+});
- this.__defineSetter__("heater", function (val) {
- try {
- hvac.heater = t.boolean(val);
- }
- catch (err) {
- }
+event.on("remove-apps", function (ids) {
+ utils.forEach(ids, function (id) {
+ removeApp(id);
});
+});
- this.__defineGetter__("steeringWheelHeater", function () {
- return hvac.steeringWheelHeater;
- });
+module.exports = {
+ initialize: function () {
+ _apps = dbinit.Application.apps;
+ _installedAppList = dbinit.Application.installedAppList;
+ _appInstalledTemplate = jQuery("#application-installed-template").html();
+ _get();
+ _save();
+ _loadInstalledAppList();
+ }
+};
- this.__defineSetter__("steeringWheelHeater", function (val) {
- try {
- hvac.steeringWheelHeater = t.boolean(val);
- }
- catch (err) {
- }
- });
+});
+define('ripple/ui/plugins/sensorSettings', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- this.__defineGetter__("seatHeater", function () {
- return hvac.seatHeater;
- });
+var constants = require('ripple/constants'),
+ sensorSettings = require('ripple/sensorSettings'),
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ platform = require('ripple/platform'),
+ _CONST = {
+ "CONTENT_CONTAINER_ID": "sensorsettings-content-container",
+ "UKNOWN_CONTROL_MESSAGE": "Unknown sensor control type"
+ },
+ _contentContainer,
+ _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;
- this.__defineSetter__("seatHeater", function (val) {
- try {
- hvac.seatHeater = t.boolean(val);
- }
- catch (err) {
- }
- });
+function _appendSettingNode(labelNode, inputNode, label) {
+ var frag = document.createDocumentFragment(),
+ rowNode = frag.appendChild(utils.createElement("tr")),
+ tempTdNode;
- this.__defineGetter__("seatCooler", function () {
- return hvac.seatCooler;
- });
+ rowNode.appendChild(utils.createElement("td"))
+ .appendChild(labelNode);
- this.__defineSetter__("seatCooler", function (val) {
- try {
- hvac.seatCooler = t.boolean(val);
- }
- catch (err) {
- }
- });
-};
+ tempTdNode = rowNode.appendChild(utils.createElement("td"));
-WindowStatus = function (propertyTypes) {
- var windowStatus = {};
+ if (label) {
+ tempTdNode.appendChild(label);
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ tempTdNode.appendChild(inputNode);
- windowStatus.openness = propertyTypes.openness || 0;
- windowStatus.defrost = propertyTypes.defrost || false;
+ return frag;
+}
- this.__defineGetter__("WINDOWLOCATION_DRIVER", function () {
- return 0;
- });
+function _buildDOMNode(setting, settingType, key) {
+ var settingsNode, tagName, jNode,
+ fullKey = settingType + "." + key,
+ savedSetting = sensorSettings.retrieve(fullKey),
+ // TODO: move this into Utils (isSet method)
+ currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value,
+ domNode,
+ domNodeLabel = null;
- this.__defineGetter__("WINDOWLOCATION_PASSENGER", function () {
- return 1;
- });
+ switch (setting.control.type) {
+ case "text":
+ case "number":
+ case "range":
+ case "checkbox":
+ tagName = "input";
+ break;
+ case "textarea":
+ tagName = "textarea";
+ break;
+ case "select":
+ tagName = "select";
+ break;
+ default:
+ exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
+ }
- this.__defineGetter__("WINDOWLOCATION_LEFTREAR", function () {
- return 2;
- });
+ settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);
- this.__defineGetter__("WINDOWLOCATION_RIGHTREAR", function () {
- return 3;
- });
+ // TODO: this should really be part of utils.createControl? add element of type "range" with label?
+ if (setting.control.type === "range") {
+ domNodeLabel = utils.createElement("label", {
+ "class": constants.UI.LEFT_RANGE_LABEL_CLASS
+ });
+ }
- this.__defineGetter__("WINDOWLOCATION_REAR", function () {
- return 4;
- });
+ domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": constants.UI.TEXT_LABEL_CLASS}), settingsNode, domNodeLabel);
- this.__defineGetter__("openness", function () {
- return windowStatus.openness;
- });
+ jNode = jQuery(settingsNode);
+ jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);
- this.__defineSetter__("openness", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 100) {
- windowStatus.openness = val;
+ switch (setting.control.type) {
+ case "checkbox":
+ jNode.bind("click", function () {
+ var checked = this.checked ? true : false;
+ sensorSettings.persist(fullKey, checked);
+ if (typeof setting.callback === "function") {
+ setting.callback(checked);
}
+ });
+
+ if (currentSetting === true) {
+ jNode.attr("checked", "checked");
}
- catch (err) {
- }
- });
- this.__defineGetter__("defrost", function () {
- return windowStatus.defrost;
- });
+ break;
- this.__defineSetter__("defrost", function (val) {
- try {
- windowStatus.defrost = t.boolean(val);
+ case "text":
+ case "textarea":
+ case "number":
+ jNode.val(currentSetting);
+ utils.bindAutoSaveEvent(jNode, function () {
+ sensorSettings.persist(fullKey, jNode.val());
+ if (typeof setting.callback === "function") {
+ setting.callback(jNode.val());
+ }
+ });
+ break;
+
+ case "select":
+ case "range":
+ if (setting.control.type === "select") {
+ utils.forEach(setting.options, function (value, option) {
+ jNode.append(utils.createElement("option", {
+ "value": option,
+ "innerText": value
+ }));
+ });
}
- catch (err) {
+ else {
+ if (domNodeLabel) {
+ domNodeLabel.innerText = currentSetting;
+ }
}
- });
-};
-Sunroof = function (propertyTypes) {
- var sunroof = {};
+ jNode.val(currentSetting)
+ .bind("change", function () {
+ if (setting.control.type === "range" && domNodeLabel) {
+ domNodeLabel.innerText = jQuery(this).val();
+ }
+ sensorSettings.persist(fullKey, jQuery(this).val());
- VehiclePropertyType.call(this, propertyTypes);
+ if (typeof setting.callback === "function") {
+ setting.callback(jQuery(this).val());
+ }
+ }
+ );
+ }
- sunroof.openness = propertyTypes.openness || 0;
- sunroof.tilt = propertyTypes.tilt || 0;
+ // TODO: Brent, do in DeviceSettings on load instead?
+ if (currentSetting !== setting.control.value) {
+ sensorSettings.register(fullKey, currentSetting);
+ }
- this.__defineGetter__("openness", function () {
- return sunroof.openness;
- });
+ return domNode;
+}
- this.__defineSetter__("openness", function (val) {
- try {
- sunroof.openness = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+// goes through current platforms sensor settings
+// adds nodes to panel and binds respective events
+// talks to SensorSettings for persistence
+module.exports = {
+ panel: {
+ domId: "sensors-panel-container",
+ collapsed: true,
+ pane: "right",
+ titleName: "Sensors",
+ display: true
+ },
+ initialize: function () {
+ var settings;
- this.__defineGetter__("tilt", function () {
- return sunroof.tilt;
- });
+ _contentContainer = document.getElementById(_CONTAINER_ID);
- this.__defineSetter__("tilt", function (val) {
- try {
- sunroof.tilt = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
-};
+ settings = platform.current().sensor;
-ConvertibleRoof = function (propertyTypes) {
- var convertibleRoof = {};
+ utils.forEach(settings, function (settingSection, settingType) {
- VehiclePropertyType.call(this, propertyTypes);
+ var currentTableNode, flag = false;
+
+ utils.forEach(settingSection, function (setting, key) {
+ if (typeof setting === "object") {
+ flag = true;
+ return;
+ }
+ });
- convertibleRoof.openness = propertyTypes.openness || 0;
+ if (flag) {
+ _contentContainer.appendChild(utils.createElement("h3", { "innerText": settingType }));
+ }
- this.__defineGetter__("openness", function () {
- return convertibleRoof.openness;
- });
+ currentTableNode = utils.createElement("table", {
+ "class": constants.UI.PANEL_TABLE_CLASS
+ });
- this.__defineSetter__("openness", function (val) {
- try {
- convertibleRoof.openness = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ _contentContainer.appendChild(currentTableNode);
+
+ utils.forEach(settingSection, function (setting, key) {
+ if (typeof setting === "object") {
+ currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
+ }
+
+ });
+ });
+ }
};
-VehicleId = function (propertyTypes) {
- var vehicleId = {};
+});
+define('ripple/ui/plugins/configWindow', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ db = require('ripple/db'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ platform = require('ripple/platform'),
+ items = [{name: "DEVICE", id: "device-conf-panel"},
+ {name: "SYSTEM SETTINGS", id: "system-settings-conf-panel"},
+ {name: "NETWORK", id: "network-conf-panel"}
+ ],
+ _KEY = "tizen-configuration-window-setting",
+ _PERSISTENCE_KEY = "devicesettings",
+ _DEVICESETTING_SAVE_KEY = "tizen-configuration-window-device-setting",
+ _DB_APPLICATION_KEY = "tizen1-db-application",
+ _DB_APPLICATION_SAVE_KEY = "tizen-configuration-window-application-key";
- VehiclePropertyType.call(this, propertyTypes);
+function reload() {
+ window.tinyHipposReload = true;
+ location.reload();
+}
- vehicleId.WMI = propertyTypes.WMI || "";
- vehicleId.VIN = propertyTypes.VIN || "";
+function _hideConfigWindow() {
+ $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
+ $("#overlayBackground").hide("fade", "slow");
+}
- this.__defineGetter__("WMI", function () {
- return vehicleId.WMI;
- });
- this.__defineSetter__("WMI", function (val) {
- try {
- //?
- vehicleId.WMI = t.DOMString(val);
- }
- catch (err) {
- }
- });
+function checkResolutionValue(val) {
+ var ret = false;
+ if (val >= 200 && val <= 2000) {
+ ret = true;
+ }
+ return ret;
+}
- this.__defineGetter__("VIN", function () {
- return vehicleId.VIN;
+function _showConfigWindow() {
+ var position_x;
+ $("#item_container").empty();
+ items.forEach(function (item) {
+ $("#item_container").append('<div class="configuration-window-item">' + item.name + '</div>');
+ $("#" + item.id).hide();
});
- this.__defineSetter__("VIN", function (val) {
- try {
- //?
- vehicleId.VIN = t.DOMString(val);
- }
- catch (err) {
- }
+ $("#content_container").show();
+ $("#" + items[0].id).show("fast");
+
+ $(".configuration-window-item:eq(0)").css("background-color", "#003399");
+ $(".configuration-window-item:eq(0)").css("color", "#ffffff");
+
+ $(".configuration-window-item").unbind('click');
+ $(".configuration-window-item").bind("click", function () {
+ $(".configuration-window-item").css("background-color", "#eeeeee");
+ $(".configuration-window-item").css("color", "#333333");
+
+ $(this).css("background-color", "#003399");
+ $(this).css("color", "#ffffff");
+
+ items.forEach(function (item) {
+ $("#" + item.id).hide();
+ });
+ $("#" + items[$(this).index()].id).show("fast");
});
-};
-Size = function (propertyTypes) {
- var size = {};
+ if ($("#configure-window-popup").is(":visible")) {
+ $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
+ $("#overlayBackground").hide("fade", "slow");
+ return;
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ position_x = (($(window).width() - 800) / 2) < 0 ? 0 : ($(window).width() - 800) / 2;
+ $("#configure-window-popup").css("top", 80);
+ $("#configure-window-popup").css("left", position_x);
- size.width = propertyTypes.width || 0;
- size.height = propertyTypes.height || 0;
- size.length = propertyTypes.length || 0;
+ position_x = (($(window).width() - 400) / 2) < 0 ? 0 : ($(window).width() - 400) / 2;
+ $("#configure-window-done-popup").css("top", 80);
+ $("#configure-window-done-popup").css("left", position_x);
- this.__defineGetter__("width", function () {
- return size.width;
- });
+ $("#overlayBackground").css("width", $(window).width());
+ $("#overlayBackground").css("height", $(window).height());
+ $("#overlayBackground").show("fade", "slow");
+ $("#configure-window-popup").show("slide", {direction: "up"}, "slow");
- this.__defineSetter__("width", function (val) {
- try {
- size.width = t.unsigned_long(val);
- }
- catch (err) {
- }
- });
+ $("#configuration-window-done-btn").unbind('click');
+ $("#configuration-window-done-btn").bind("click", function () {
+ var platformId, version, device, type, width, height, url;
- this.__defineGetter__("height", function () {
- return size.height;
- });
+ // device & resolution setting
+ platformId = jQuery("#platform-select").val();
+ version = jQuery("#version-select").val();
+ device = jQuery("#device-select").val();
+ width = jQuery("#resolution-custom-width").val();
+ height = jQuery("#resolution-custom-height").val();
+ type = jQuery('input:radio[name="resolution-type"]:checked').val();
- this.__defineSetter__("height", function (val) {
- try {
- size.height = t.unsigned_long(val);
+ if (type === "custom") {
+ device = "custom";
+ if (!checkResolutionValue(width) || !checkResolutionValue(height)) {
+ return;
+ }
}
- catch (err) {
+
+ if (platformId === "mobile" || platformId === "tizen") {
+ platformId = "tizen";
+ version = "2.0";
+ }
+ else {
+ platformId = "ivi";
+ version = "3.0";
}
- });
- this.__defineGetter__("length", function () {
- return size.length;
+ platform.changeEnvironment({
+ "name": platformId,
+ "version": version
+ }, device, function () {
+ _hideConfigWindow();
+ window.tinyHipposReload = true;
+ url = location.href.replace(/&platform=(.+?)-(.+?)$/, "&platform=" + platformId + "-" + version);
+ location.href = url;
+ //reload();
+ });
});
- this.__defineSetter__("length", function (val) {
- try {
- size.length = t.unsigned_long(val);
- }
- catch (err) {
+ $("#configuration-window-close-btn").unbind('click');
+ $("#configuration-window-close-btn").bind("click", function () {
+ if ($("#configure-window-popup").is(":visible")) {
+ _hideConfigWindow();
+ return;
}
});
-};
-
-FuelInfo = function (propertyTypes) {
- var fuelInfo = {};
-
- VehiclePropertyType.call(this, propertyTypes);
+ tooltip.create("#configuration-window-save-btn", "Save Configuration");
+ $("#configuration-window-save-btn").unbind('click');
+ $("#configuration-window-save-btn").bind("click", function () {
+ var _type, _device, _custom_width = 0, _custom_height = 0, programs, deviceInfo, _settings;
- fuelInfo.type = propertyTypes.type || 0;
- fuelInfo.refuelPosition = propertyTypes.refuelPosition || 0;
+ deviceInfo = db.retrieveObject(_PERSISTENCE_KEY);
+ db.saveObject(_DEVICESETTING_SAVE_KEY, deviceInfo);
- this.__defineGetter__("FUELTYPE_GASOLINE", function () {
- return 0;
- });
+ _device = jQuery("#device-select").val();
+ _type = jQuery('input:radio[name="resolution-type"]:checked').val();
+ if (_type === "custom") {
+ _device = "custom";
+ _custom_width = jQuery("#resolution-custom-width").val();
+ _custom_height = jQuery("#resolution-custom-height").val();
+ }
+ _settings = {
+ platformId : jQuery("#platform-select").val(),
+ version : jQuery("#version-select").val(),
+ device : _device,
+ type : _type,
+ custom_width : _custom_width,
+ custom_height : _custom_height
+ };
+ db.saveObject(_KEY, _settings);
+ programs = db.retrieveObject(_DB_APPLICATION_KEY);
+ db.saveObject(_DB_APPLICATION_SAVE_KEY, programs);
- this.__defineGetter__("FUELTYPE_HIGH_OCTANE", function () {
- return 1;
});
+ tooltip.create("#configuration-window-load-btn", "Load Configuration");
+ $("#configuration-window-load-btn").unbind('click');
+ $("#configuration-window-load-btn").bind("click", function () {
+ var platformList,
+ programs,
+ deviceInfo,
+ _settings,
+ versionSelect = document.getElementById("version-select");
+ if (db.retrieveObject(_DEVICESETTING_SAVE_KEY) === undefined) {
+ //Never saving data exist
+ return;
+ }
+ //reload system & network setting
+ deviceInfo = db.retrieveObject(_DEVICESETTING_SAVE_KEY);
+ db.saveObject("devicesettings", deviceInfo);
+ jQuery("#devicesettings-content-container").empty();
+ jQuery("#networksettings-content-container").empty();
+ require('ripple/deviceSettings').initialize();
+ require('ripple/ui/plugins/deviceSettings').terminate();
+ require('ripple/ui/plugins/deviceSettings').initialize();
- this.__defineGetter__("FUELTYPE_DIESEL", function () {
- return 2;
- });
+ //reload device setting
+ jQuery(versionSelect).empty();
+ _settings = db.retrieveObject(_KEY);
+ jQuery("#platform-select").val(_settings.platformId);
+ jQuery("#device-select").val(_settings.device);
+ if (_settings.type === "custom") {
+ $('input:radio[name="resolution-type"][value="custom"]').click();
+ jQuery("#resolution-custom-width").val(parseInt(_settings.custom_width, 10));
+ jQuery("#resolution-custom-height").val(parseInt(_settings.custom_height, 10));
+ } else {
+ $('input:radio[name="resolution-type"][value="predefined"]').click();
+ }
- this.__defineGetter__("FUELTYPE_ELECTRIC", function () {
- return 3;
+ platformList = platform.getList();
+ utils.forEach(platformList, function (platform) {
+ utils.forEach(platform, function (version, versionNumber) {
+ if (_settings.platformId === version.id) {
+ versionSelect.appendChild(utils.createElement("option", {
+ "innerText": versionNumber,
+ "value": versionNumber
+ }));
+ }
+ });
+ });
+ jQuery("#version-select").val(_settings.version);
});
- this.__defineGetter__("FUELTYPE_HYDROGEN", function () {
- return 4;
- });
+ $(window).bind('resize', function () {
+ var position_x = 0;
+ $("#configure-window-popup").css("top", 80);
+ position_x = (($(window).width() - 800) / 2) < 0 ? 0 : ($(window).width() - 800) / 2;
+ $("#configure-window-popup").css("left", position_x);
- this.__defineGetter__("REFUELPOSITION_LEFT", function () {
- return 0;
- });
+ $("#configure-window-done-popup").css("top", 180);
+ position_x = (($(window).width() - 400) / 2) < 0 ? 0 : ($(window).width() - 400) / 2;
+ $("#configure-window-done-popup").css("left", position_x);
- this.__defineGetter__("REFUELPOSITION_RIGHT", function () {
- return 1;
+ $("#overlayBackground").css("width", $(window).width());
+ $("#overlayBackground").css("height", $(window).height());
});
- this.__defineGetter__("REFUELPOSITION_FRONT", function () {
- return 2;
- });
+ if (jQuery("#platform-select").val() === "ivi") {
+ jQuery("#configuration-window-save-btn").hide();
+ jQuery("#configuration-window-load-btn").hide();
- this.__defineGetter__("REFUELPOSITION_REAR", function () {
- return 3;
- });
+ jQuery("#item_container :nth-child(2)").hide();
+ jQuery("#item_container :nth-child(3)").hide();
- this.__defineGetter__("type", function () {
- return fuelInfo.type;
- });
+ //jQuery("#hwkeys-panel").hide();
+ }
+ else {
+ jQuery("#configuration-window-save-btn").show();
+ jQuery("#configuration-window-load-btn").show();
- this.__defineSetter__("type", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 4) {
- fuelInfo.type = val;
- }
- }
- catch (err) {
- }
- });
+ jQuery("#item_container :nth-child(2)").show();
+ jQuery("#item_container :nth-child(3)").show();
- this.__defineGetter__("refuelPosition", function () {
- return fuelInfo.refuelPosition;
- });
+ //jQuery("#hwkeys-panel").show();
+ }
+}
- this.__defineSetter__("refuelPosition", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 3) {
- fuelInfo.refuelPosition = val;
- }
- }
- catch (err) {
+module.exports = {
+ initialize: function () {
+ if (platform.current().id === "cordova") {
+ items.splice(1, 1);
}
- });
+ $("#options-button-config-window").bind("click", function () {
+ _showConfigWindow();
+ });
+ }
};
-VehicleType = function (propertyTypes) {
- var vehicleType = {};
+});
+define('ripple/ui/plugins/firstRunCheck', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ _platform = require('ripple/platform'),
+ db = require('ripple/db');
- VehiclePropertyType.call(this, propertyTypes);
+function _handleFirstRunResponse(platform, version) {
+ var device = jQuery("#device-select").val(),
+ api = {
+ name: platform.id,
+ version: version
+ };
- vehicleType.type = propertyTypes.type || 0;
- this.__defineGetter__("VEHICLETYPE_SEDAN", function () {
- return 0;
+ _platform.changeEnvironment(api, device, function () {
+ window.tinyHipposReload = true;
+ location.reload();
});
+}
- this.__defineGetter__("VEHICLETYPE_COUPE", function () {
- return 1;
- });
+function _addPlatformButton(platform, version) {
+ var section = jQuery(".platform-select-buttons"),
+ buttonID = "platform-" + platform.id,
+ button = utils.createElement("button", {
+ "id": buttonID,
+ "class": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
+ });
- this.__defineGetter__("VEHICLETYPE_CABRIOLE", function () {
- return 2;
- });
+ button.appendChild(utils.createElement("span", {
+ "class": "ui-button-text",
+ "innertext" : platform.name
+ }));
- this.__defineGetter__("VEHICLETYPE_ROADSTER", function () {
- return 3;
- });
+ section.append(button);
- this.__defineGetter__("VEHICLETYPE_SUV", function () {
- return 4;
+ document.getElementById(buttonID).addEventListener("click", function () {
+ _handleFirstRunResponse(platform, version);
});
+}
- this.__defineGetter__("VEHICLETYPE_TRUCK", function () {
- return 5;
- });
+function _initializeFirstRunCheck() {
+ var savedPlatform = db.retrieveObject("api-key"),
+ firstRunOverlayNode, firstRunOptionsNode,
+ width, p;
- this.__defineGetter__("type", function () {
- return vehicleType.type;
- });
+ if (!savedPlatform) {
+ width = jQuery(document).width();
+ p = (width / 2) - 277;
- this.__defineSetter__("type", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 5) {
- vehicleType.type = val;
- }
- }
- catch (err) {
+ firstRunOverlayNode = jQuery(".first-run-window").css({display: 'block'});
+ firstRunOptionsNode = jQuery(".platform-select-dialog").css({display: 'block', left: p + "px"});
+
+ utils.forEach(_platform.getList(), function (platform) {
+ utils.forEach(platform, function (details, version) {
+ _addPlatformButton(details, version);
+ });
+ });
+ }
+}
+
+module.exports = {
+ initialize: function () {
+ if (utils.map(_platform.getList(), function (platform) {
+ return platform;
+ }).length > 1) {
+ _initializeFirstRunCheck();
}
- });
+ }
};
-Doors = function (propertyTypes) {
- var doors = {};
-
- VehiclePropertyType.call(this, propertyTypes);
+});
+define('ripple/ui/plugins/themeSwitcher', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ THEME_KEY = "ui-theme",
+ THEME_SELECTOR = "#theme-select",
+ _currentTheme;
- doors.doorsPerRow = propertyTypes.doorsPerRow || [];
+function _saveAndReload(key, value) {
+ jWorkflow.order(function (prev, baton) {
+ baton.take();
+ db.save(key, value, null, baton.pass);
+ }).start(function () {
+ window.tinyHipposReload = true;
+ location.reload();
+ });
+}
- this.__defineGetter__("doorsPerRow", function () {
- return doors.doorsPerRow;
- });
+module.exports = {
+ initialize: function () {
+ var themeToSet = db.retrieve(THEME_KEY);
- this.__defineSetter__("doorsPerRow", function (val) {
- try {
- doors.doorsPerRow = t.unsigned_short(val, "[]");
- }
- catch (err) {
- }
- });
+ // Hide the theme switcher and always set the theme to light
+ jQuery(".theme-switcher").hide();
+ if (themeToSet !== "light") {
+ _saveAndReload(THEME_KEY, "light");
+ }
+ return;
+ }
};
-TransmissionGearType = function (propertyTypes) {
- var trans = {};
+});
+define('ripple/ui/plugins/about-dialog', function (require, exports, module) {
+/*
+ * Copyright 2011 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 bus = require('ripple/bus');
- VehiclePropertyType.call(this, propertyTypes);
+module.exports = {
+ initialize: function () {
+ $("#about-dialog").dialog({
+ resizable: false,
+ draggable: false,
+ modal: true,
+ autoOpen: false,
+ position: 'center',
+ minWidth: '464',
+ minHeight: '262'
+ });
+ },
+ show: function () {
+ //TODO: Restore this line once framework issue is resolved
+ //var port = window.stagewebview ? stagewebview.serverPort : "9900";
+ var port = "9910";
- trans.transmissionGearType = propertyTypes.transmissionGearType || 0;
+ bus.send("version", null, function (resp) {
+ $("#about-dialog-ripple-ui-version").html("(v" + resp + ")");
+ });
- this.__defineGetter__("TRANSMISSIONGEARTYPE_AUTO", function () {
- return 0;
- });
+ bus.ajax(
+ "GET",
+ "http://127.0.0.1:" + port + "/ripple/about",
+ null,
+ function (resp) {
+ $("#about-dialog-ripple-build-deploy-version").html("(v" + resp.data.version + ")");
+ },
+ function (error) {
+ var version = error.data;
+
+ if (error.code === 0 || error.code === 404) {
+ version = "The service is not running";
+ }
+ $("#about-dialog-ripple-build-deploy-version").html("(" + version + ")");
+ }
+ );
- this.__defineGetter__("TRANSMISSIONGEARTYPE_MANUAL", function () {
- return 1;
- });
+ $("#about-dialog").dialog("open");
+ }
+};
- this.__defineGetter__("TRANSMISSIONGEARTYPE_CV", function () {
- return 2;
- });
+});
+define('ripple/ui/plugins/videoPlayer', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ event = require('ripple/event');
- this.__defineGetter__("transmissionGearType", function () {
- return trans.transmissionGearType;
- });
+module.exports = {
+ initialize: function () {
+ var videoObj,
+ videoProgress = document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_PROGRESS_ID);
- this.__defineSetter__("transmissionGearType", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 2) {
- trans.transmissionGearType = val;
+ event.on("MultimediaAppVideoPlayerCreated", function (videoDOMObj) {
+ videoObj = videoDOMObj;
+
+ videoObj.addEventListener("timeupdate", function () {
+ var s = parseInt(videoObj.currentTime % 60, 10),
+ m = parseInt((videoObj.currentTime / 60) % 60, 10);
+
+ videoProgress.innerText = ((m > 9) ? m : "0" + m) + ':' + ((s > 9) ? s : "0" + s);
+ }, false);
+ });
+
+ event.on("MultimediaVolumeChanged", function (volume) {
+ if (videoObj) {
+ videoObj.volume = parseFloat(volume / 10);
}
- }
- catch (err) {
- }
- });
+ });
+
+ event.on("MultimediaVideoStateChanged", function (state) {
+ document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_STATE_FIELD_ID).innerText = state;
+ document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_FILE_FIELD_ID).innerText = videoObj.getAttribute("src");
+ });
+ }
};
-WheelInformation = function (propertyTypes) {
- var wheelInfo = {};
+});
+define('ripple/ui/plugins/information', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ devices = require('ripple/devices'),
+ event = require('ripple/event'),
+ platform = require('ripple/platform'),
+ utils = require('ripple/utils'),
+ app = require('ripple/app'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ db = require('ripple/db');
- VehiclePropertyType.call(this, propertyTypes);
+function _updateInformationView() {
+ var infoPane = document.getElementById(constants.COMMON.INFO_SECTION),
+ infoList = [],
+ device = devices.getCurrentDevice(),
+ tempString = "",
+ widgetInfo = app.getInfo(),
+ layout = db.retrieve("layout") || "portrait",
+ _systemSettings = db.retrieveObject("tizen2-systemsetting") || {"HOME_SCREEN": "", "LOCK_SCREEN": "", "INCOMING_CALL": "", "NOTIFICATION_EMAIL": ""};
- wheelInfo.frontWheelRadius = propertyTypes.frontWheelRadius || 0;
- wheelInfo.rearWheelRadius = propertyTypes.rearWheelRadius || 0;
- wheelInfo.wheelTrack = propertyTypes.wheelTrack || 0;
- wheelInfo.ABS = propertyTypes.ABS || false;
+ //TODO: refactor this stuff to grab info from API, do this in a loop rather then hardcoded. Better DOM injection approach. This is legacy code
- this.__defineGetter__("frontWheelRadius", function () {
- return wheelInfo.frontWheelRadius;
- });
+ infoList.push('<section id=\"information-banner\" style=\"display:none\"><img id=\"information-banner-icon\" width=\"16px\" height=\"16px\"/> <span id=\"information-banner-count\"></span></section>');
- this.__defineSetter__("frontWheelRadius", function (val) {
- try {
- wheelInfo.frontWheelRadius =t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ if (widgetInfo.icon) {
+ infoList.push('<section style="position: absolute; left: 260px;" class="information-widgeticon"><img class="ui-corner-all" width="64" src="' + utils.appLocation() + widgetInfo.icon + '" alt="widget icon"/></section>');
+ }
+ if (widgetInfo.name) {
+ infoList.push("<section><div id=\"systemSummaryAppNameContainer\" style=\"width:240px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">App Name: </label><span class=\"text-is-selectable\">" + widgetInfo.name + "</span></div></section>");
+ //Update Title
+ document.title = "Web Simulator - " + widgetInfo.name;
+ }
- this.__defineGetter__("rearWheelRadius", function () {
- return wheelInfo.rearWheelRadius;
- });
+ infoList.push('<table class="tf_panel-table" style="border-spacing: 0px;">');
+
+ if (widgetInfo.version) {
+ infoList.push('<section class="information-widgetversion"><label class=\"ui-text-label\">Version: </label><span class="text-is-selectable">' + widgetInfo.version + '</span></section>');
+ }
+ infoList.push("<section><label class=\"ui-text-label\">Platform: </label><span class=\"text-is-selectable\">" + platform.current().name + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">Device: </label><span class=\"text-is-selectable\">" + device.name + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">OS: </label><span class=\"text-is-selectable\">" + device.osName + " " + device.osVersion + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">Manufacturer: </label><span class=\"text-is-selectable\">" + device.manufacturer + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">Screen: </label><span class=\"text-is-selectable\">" + device.screen.width + "x" + device.screen.height + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">Viewport: </label><span class=\"text-is-selectable\">" + device.viewPort[layout].width.toFixed(0) + "x" + device.viewPort[layout].height.toFixed(0) + "</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\">Density: </label><span class=\"text-is-selectable\">" + device.ppi + " PPI</span></section>");
+ infoList.push("<section><label class=\"ui-text-label\" style=\"float:left; padding-top: 0px; \">User Agent: </label>" +
+ "<div class=\"text-is-selectable\" style=\"padding-left: 80px\">" + device.userAgent + "</div></section>");
- this.__defineSetter__("rearWheelRadius", function (val) {
- try {
- wheelInfo.rearWheelRadius =t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+ if (device.notes) {
+ utils.forEach(device.notes, function (note) {
+ tempString += "<li class=\"text-is-selectable\">" + note + "</li>";
+ });
+ infoList.push("<section><div style=\"clear:both;\"></div><label class=\"ui-text-label\">Notes: </label><ul>" + tempString + "</ul></section>");
+ }
- this.__defineGetter__("wheelTrack", function () {
- return wheelInfo.wheelTrack;
- });
+ infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryHomeScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Home Screen Image: </label><span>" + _systemSettings["HOME_SCREEN"] + "</span></div></section>");
+ infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryLockScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Lock Screen Image: </label><span>" + _systemSettings["LOCK_SCREEN"] + "</span></div></section>");
+ infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryInComingCallContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Incoming Call Number: </label><span>" + _systemSettings["INCOMING_CALL"] + "</span></div></section>");
+ infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryNotiEMailContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Notification Email: </label><span>" + _systemSettings["NOTIFICATION_EMAIL"] + "</span></div></section>");
+ infoList.push("<section><div style=\"clear:both;\"></div><div id=\"NFCExclusiveModeContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">NFC Exclusive Mode: </label><span id=\"NFCExclusiveModeValue\">false</span></div></section>");
+ infoPane.innerHTML = infoList.join("");
- this.__defineSetter__("wheelTrack", function (val) {
- try {
- wheelInfo.wheelTrack =t.unsigned_long(val);
- }
- catch (err) {
- }
- });
+ // Make tooltip if it needed
+ if ((jQuery("#systemSummaryAppNameContainer").children("label").width() + jQuery("#systemSummaryAppNameContainer").children("span").width()) > 240) {
+ tooltip.create("#systemSummaryAppNameContainer", jQuery("#systemSummaryAppNameContainer").children("span").text());
+ }
+ if ((jQuery("#systemSummaryHomeScreenContainer").children("label").width() + jQuery("#systemSummaryHomeScreenContainer").children("span").width()) > 320) {
+ tooltip.create("#systemSummaryHomeScreenContainer", jQuery("#systemSummaryHomeScreenContainer").children("span").text());
+ }
+ if ((jQuery("#systemSummaryLockScreenContainer").children("label").width() + jQuery("#systemSummaryLockScreenContainer").children("span").width()) > 320) {
+ tooltip.create("#systemSummaryLockScreenContainer", jQuery("#systemSummaryLockScreenContainer").children("span").text());
+ }
+ if ((jQuery("#systemSummaryInComingCallContainer").children("label").width() + jQuery("#systemSummaryInComingCallContainer").children("span").width()) > 320) {
+ tooltip.create("#systemSummaryInComingCallContainer", jQuery("#systemSummaryInComingCallContainer").children("span").text());
+ }
+ if ((jQuery("#systemSummaryNotiEMailContainer").children("label").width() + jQuery("#systemSummaryNotiEMailContainer").children("span").width()) > 320) {
+ tooltip.create("#systemSummaryNotiEMailContainer", jQuery("#systemSummaryNotiEMailContainer").children("span").text());
+ }
+}
- this.__defineGetter__("ABS", function () {
- return wheelInfo.ABS;
- });
+function _updateBanner(icon, count) {
+ var bannerSection = document.getElementById("information-banner"),
+ iconImg = document.getElementById("information-banner-icon"),
+ countSpan = document.getElementById("information-banner-count");
- this.__defineSetter__("ABS", function (val) {
- try {
- wheelInfo.ABS =t.boolean(val);
- }
- catch (err) {
- }
- });
-};
+ if (icon && (count === undefined || count !== 0)) {
+ count = count || "";
+ jQuery("#" + constants.COMMON.INFO_SECTION).show();
+ jQuery(bannerSection).fadeToggle(1000);
+ jQuery(bannerSection).fadeIn(1000);
+ }
+ else {
+ jQuery(bannerSection).fadeOut(1000);
+ }
-Odometer = function (propertyTypes) {
- var odm = {};
+ iconImg.src = utils.appLocation() + icon;
+ if (icon.indexOf("http") === 0) {
+ iconImg.src = icon;
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ countSpan.innerHTML = count > 99 ? "99+" : count;
+}
- odm.odometer = propertyTypes.odometer || 0;
+module.exports = {
+ panel: {
+ domId: "information-container",
+ collapsed: false,
+ pane: "left",
+ titleName: "System Summary",
+ display: true
+ },
+ initialize: function () {
+ event.on("BannerUpdated", function (icon, count) {
+ _updateBanner(icon, count);
+ });
- this.__defineGetter__("odometer", function () {
- return odm.odometer;
- });
+ event.on("PlatformChangedEvent", function () {
+ _updateInformationView();
+ });
- this.__defineSetter__("odometer", function (val) {
- try {
- odm.odometer = t.unsigned_long(val);
- }
- catch (err) {
- }
- });
+ event.on("WidgetInformationUpdated", function () {
+ _updateInformationView();
+ });
+
+ event.on("SystemSettingChanged", function () {
+ _updateInformationView();
+ });
+
+ event.on("ScreenChangeDimensions", function() {
+ _updateInformationView();
+ });
+ _updateInformationView();
+ }
};
-Fluid = function (propertyTypes) {
- var fluid = {};
+});
+define('ripple/ui/plugins/vehicle', function (require, exports, module) {
+/*
+ * 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 event = require('ripple/event'),
+ exception = require('ripple/exception'),
+ vehiclePanelEngine = require('ripple/platform/ivi/3.0/VehiclePanelEngine').VehiclePanelEngine,
+ _vehicleGlobalVars = {
+ currentAutoStatus: false,
+ currentDataIndex: 0,
+ timeFlag: null,
+ timeInterval: 1000, //ms
+ timeCurrent: 0,
+ timeHistoryArray: [],
+ timeHistoryLimit: 60 * 60,
+ registerListeners: {},
+ vehicleCache: {},
+ history: {},
+ notShowProperties: [
+ "zone", "time", "source"
+ ]
+ };
- VehiclePropertyType.call(this, propertyTypes);
+function _interceptString (str, length) {
+ return str.length > length ? str.substring(0, length) + "...": str;
+}
- fluid.transmission = propertyTypes.transmission || 0;
- fluid.brake = propertyTypes.brake || 0;
- fluid.washer = propertyTypes.washer || 0;
+function _setVehicleConfigurationSel (configuration) {
+ var selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
+ html = "", i = 0;
- this.__defineGetter__("transmission", function () {
- return fluid.transmission;
- });
+ for (var value in configuration) {
+ html += '<option value="' + value + '">' +
+ 'Car ' + i +
+ '</option>';
- this.__defineSetter__("transmission", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 100) {
- fluid.transmission = val;
- }
- }
- catch (err) {
- }
- });
+ i++;
+ }
- this.__defineGetter__("brake", function () {
- return fluid.brake;
- });
+ selContainer.html(html);
+}
- this.__defineSetter__("brake", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 100) {
- fluid.brake = val;
+function _setVehicleConfiguration (configuration, currentType) {
+ var container = jQuery("#vehicle-container #vehicle-configuration-show"),
+ selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
+ current, property, propertyList, item, unit, html = "", i,
+ enums, showValue;
+
+ if (currentType !== selContainer.val()) {
+ for (i = 0; i < selContainer[0].options.length; i++) {
+ if (selContainer[0].options[i].value === currentType) {
+ selContainer[0].selectedIndex = i;
+ break;
}
}
- catch (err) {
+ if (i >= selContainer[0].options.length ) {
+ throw "undefined configuration: " + currentType + ".";
}
- });
+ }
- this.__defineGetter__("washer", function () {
- return fluid.washer;
- });
+ current = configuration[currentType];
+ if (!current) {
+ throw "undefined configuration: " + currentType + ".";
+ }
- this.__defineSetter__("washer", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val >= 0 && val <= 100) {
- fluid.washer = val;
+ for (property in current) {
+ html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
+
+ propertyList = current[property];
+ for (item in propertyList) {
+ showValue = propertyList[item];
+ unit = vehiclePanelEngine.getPropertyUnit(property, item);
+ enums = vehiclePanelEngine.getPropertyConstant(property, item);
+ if (enums) {
+ showValue = enums["val" + showValue];
}
- }
- catch (err) {
- }
- });
-};
-Battery = function (propertyTypes) {
- var battery = {};
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label"> ' + item + unit + '</td>' +
+ '<td class="vehicle-property-value" id="' + property + '-' + item + '-show">' + showValue + '</td>' +
+ '<td style="display: none;">' +
+ '<input id="' + property + '-' + item + '-set" type="hidden" ' + 'value="' + propertyList[item] + '" />' +
+ '</td></tr>';
+ }
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ container.html(html);
+ return;
+}
- battery.voltage = propertyTypes.voltage || 0;
- battery.current = propertyTypes.current || 0;
+function _setVehicleSupported (properties, supported) {
+ var hideContainer = jQuery("#vehicle-container #vehicle-supported-hide"),
+ showContainer = jQuery("#vehicle-container #vehicle-supported-show"),
+ hideHtml = "", showHtml = "", tempHtml, column = 0, columnNum = 3, className,
+ i, property, propertyAbbr;
- this.__defineGetter__("voltage", function () {
- return battery.voltage;
- });
+ for (i = 0; i < properties.length; i++) {
+ property = properties[i];
+ propertyAbbr = _interceptString(property, 12);
- this.__defineSetter__("voltage", function (val) {
- try {
- battery.voltage = t.double(val);
+ if (supported.indexOf(property) > -1) {
+ className = "vehicle-property-supported";
+ hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" checked="checked" />';
}
- catch (err) {
+ else {
+ className = "vehicle-property-unsupported";
+ hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" />';
}
- });
- this.__defineGetter__("current", function () {
- return battery.current;
- });
+ tempHtml = '<td id="' + property + '-supported-show" ' + 'class="' + className + '" title="' + property + '">' + propertyAbbr + '</td>';
- this.__defineSetter__("current", function (val) {
- try {
- battery.current = t.double(val);
- }
- catch (err) {
+ if (column % columnNum === 0) {
+ showHtml += '<tr>' + tempHtml;
}
- });
-};
-
-TirePressure = function (propertyTypes) {
- var tirePressure = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- tirePressure.leftFront = propertyTypes.leftFront || 0;
- tirePressure.rightFront = propertyTypes.rightFront || 0;
- tirePressure.leftRear = propertyTypes.leftRear || 0;
- tirePressure.rightRear = propertyTypes.rightRear || 0;
-
- this.__defineGetter__("leftFront", function () {
- return tirePressure.leftFront;
- });
-
- this.__defineSetter__("leftFront", function (val) {
- try {
- tirePressure.leftFront = t.double(val);
+ else if (column % columnNum === (columnNum - 1)){
+ showHtml += tempHtml + '</tr>';
}
- catch (err) {
+ else {
+ showHtml += tempHtml;
}
- });
+ column++;
+ }
- this.__defineGetter__("rightFront", function () {
- return tirePressure.rightFront;
- });
+ hideContainer.html(hideHtml);
+ showContainer.html(showHtml);
+}
- this.__defineSetter__("rightFront", function (val) {
- try {
- tirePressure.rightFront = t.double(val);
- }
- catch (err) {
- }
- });
+function _setVehicleSetting (settings) {
+ var settingContainer = jQuery("#vehicle-container #vehicle-setting-show"),
+ property, propertyItems, item, html = "", unit, range,
+ optionHtml = "", i, optionName, option, options;
- this.__defineGetter__("leftRear", function () {
- return tirePressure.leftRear;
- });
+ for (property in settings) {
+ html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
- this.__defineSetter__("leftRear", function (val) {
- try {
- tirePressure.leftRear = t.double(val);
- }
- catch (err) {
- }
- });
+ propertyItems = settings[property];
+ for (item in propertyItems) {
+ unit = vehiclePanelEngine.getPropertyUnit(property, item);
- this.__defineGetter__("rightRear", function () {
- return tirePressure.rightRear;
- });
+ if (propertyItems[item].type === "radio" || propertyItems[item].type === "select") {
+ optionHtml = "";
+ options = propertyItems[item].options;
+ for (i = 0; i < options.length; i++) {
+ option = options[i];
+ for (optionName in option) {
+ if (option[optionName].toString() === propertyItems[item].value.toString()) {
+ optionHtml += '<option value="' + option[optionName] + '" selected>' +
+ optionName + '</option>';
+ }
+ else {
+ optionHtml += '<option value="' + option[optionName] + '">' +
+ optionName + '</option>';
+ }
+ break;
+ }
+ }
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
+ '<td class="vehicle-property-value">' +
+ '<select id="' + property + '-' + item + '-set">' + optionHtml + '</select>' +
+ '</td></tr>';
+ }
+ else if (propertyItems[item].type === "range") {
+ range = vehiclePanelEngine.getPropertyRange(property, item);
- this.__defineSetter__("rightRear", function (val) {
- try {
- tirePressure.rightRear = t.double(val);
- }
- catch (err) {
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
+ '<td class="vehicle-property-value">' +
+ '<label id="' + property + '-' + item + '-num">' + propertyItems[item].value + '</label>' +
+ '<input id="' + property + '-' + item + '-set" type="range" value="' + propertyItems[item].value + '"' +
+ ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />' +
+ '</td></tr>';
+ }
+ else if (propertyItems[item].type === "text") {
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
+ '<td class="vehicle-property-value">' +
+ '<input id="' + property + '-' + item + '-set" type="text" value="' + propertyItems[item].value + '" />' +
+ '</td></tr>';
+ }
}
- });
-};
+ }
-TireTemperature = function (propertyTypes) {
- var tireTemperature = {};
+ settingContainer.html(html);
+}
- VehiclePropertyType.call(this, propertyTypes);
+function _addArrayValueEnter (property, item, value) {
+ var itemValue, html = "", i,
+ id = property + '-' + item + "-set";
- tireTemperature.leftFront = propertyTypes.leftFront || 0;
- tireTemperature.rightFront = propertyTypes.rightFront || 0;
- tireTemperature.leftRear = propertyTypes.leftRear || 0;
- tireTemperature.rightRear = propertyTypes.rightRear || 0;
+ itemValue = value.split(",");
- this.__defineGetter__("leftFront", function () {
- return tireTemperature.leftFront;
- });
+ if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
+ html += '<td colspan="3">';
+ }
+ else {
+ html += '<tr id="'+ id + 'Array" class="vehicle-property-array">' +
+ '<td colspan="3">';
+ }
- this.__defineSetter__("leftFront", function (val) {
- try {
- tireTemperature.leftFront = t.double(val);
- }
- catch (err) {
+ if (itemValue.length === 0) {
+ html += '<div class="vehicle-property-arrayItem">' +
+ '<button>add</button>' +
+ '<input type="text" value="0" />' +
+ '<button>del</button>' +
+ '</div>';
+ }
+ else {
+ for (i = 0; i < itemValue.length; i++) {
+ if (i === itemValue.length - 1) {
+ html += '<div class="vehicle-property-arrayItem">' +
+ '<button style="margin-left: -60px;">add</button>' +
+ '<input type="text" value="' + itemValue[i] + '" />' +
+ '<button >del</button>' +
+ '</div>';
+ }
+ else {
+ html += '<div class="vehicle-property-arrayItem">' +
+ '<button style="display: none;">add</button>' +
+ '<input type="text" value="' + itemValue[i] + '" />' +
+ '<button >del</button>' +
+ '</div>';
+ }
}
- });
+ }
- this.__defineGetter__("rightFront", function () {
- return tireTemperature.rightFront;
- });
+ if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
+ html += '</td>';
- this.__defineSetter__("rightFront", function (val) {
- try {
- tireTemperature.rightFront = t.double(val);
- }
- catch (err) {
- }
- });
+ jQuery("#" + id + "Array").html(html);
+ }
+ else {
+ html += '</td></tr>';
- this.__defineGetter__("leftRear", function () {
- return tireTemperature.leftRear;
- });
+ html += '<tr id="'+ id + 'OK" class="vehicle-property-array">' +
+ '<td colspan="3">';
+ html += '<button class="vehicle-property-arrayOk">OK</button>';
+ html += '</td></tr>';
+ }
- this.__defineSetter__("leftRear", function (val) {
- try {
- tireTemperature.leftRear = t.double(val);
- }
- catch (err) {
- }
- });
+ return html;
+}
- this.__defineGetter__("rightRear", function () {
- return tireTemperature.rightRear;
- });
+function _setVehicleAutoRunning (autoRunning, isFill) {
+ var autoContainer = jQuery("#vehicle-container #vehicle-running-show"),
+ timeStamp, html = "", unit, range, property, propertyItem, value, data,
+ showContainer, setContainer, valueField, options, option, optionName, i,
+ enums, showValue;
- this.__defineSetter__("rightRear", function (val) {
- try {
- tireTemperature.rightRear = t.double(val);
- }
- catch (err) {
- }
- });
-};
+ timeStamp = (new Date()).getTime();
+ data = autoRunning["auto" + _vehicleGlobalVars.currentDataIndex];
+ if (!data) {
+ _vehicleGlobalVars.currentDataIndex = 0;
+ data = autoRunning["auto0"];
+ }
+ _vehicleGlobalVars.timeCurrent = timeStamp;
-SecurityAlert = function (propertyTypes) {
- var securityAlert = {};
+ if (!isFill) {
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label">Time</td>' +
+ '<td class="vehicle-property-value" id="vehicle-time-show">' + timeStamp + '</td></tr>';
- VehiclePropertyType.call(this, propertyTypes);
+ for (property in data) {
+ html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
- securityAlert.securityAlert = propertyTypes.securityAlert || false;
+ for (propertyItem in data[property]) {
+ value = data[property][propertyItem].value;
+ unit = vehiclePanelEngine.getPropertyUnit(property, propertyItem);
- this.__defineGetter__("securityAlert", function () {
- return securityAlert.securityAlert;
- });
+ if (Object.prototype.toString.call(value) === '[object Array]') {
+ value = value.join(",");
+ }
- this.__defineSetter__("securityAlert", function (val) {
- try {
- securityAlert.securityAlert = t.boolean(val);
- }
- catch (err) {
- }
- });
-};
+ if (data[property][propertyItem].type === "radio" || data[property][propertyItem].type === "select") {
+ valueField = "";
+ options = data[property][propertyItem].options;
+ for (i = 0; i < options.length; i++) {
+ option = options[i];
+ for (optionName in option) {
+ if (option[optionName].toString() === data[property][propertyItem].value) {
+ valueField += '<option value="' + option[optionName] + '" selected>' +
+ optionName + '</option>';
+ }
+ else {
+ valueField += '<option value="' + option[optionName] + '">' +
+ optionName + '</option>';
+ }
+ break;
+ }
+ }
-ParkingBrake = function (propertyTypes) {
- var parkingBrake = {};
+ valueField = '<select id="' + property + '-' + propertyItem + '-set">' + valueField + '</select>';
+ }
+ else if (data[property][propertyItem].type === "range") {
+ range = vehiclePanelEngine.getPropertyRange(property, propertyItem);
- VehiclePropertyType.call(this, propertyTypes);
+ valueField = '<label id="' + property + '-' + propertyItem + '-num">' + value + '</label>' +
+ '<input id="' + property + '-' + propertyItem + '-set" type="range" value="' + value + '"' +
+ ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />';
+ }
+ else if (data[property][propertyItem].type === "text") {
+ valueField = '<input type="text" value="' + value +'" id="' + property + '-' + propertyItem + '-set" disabled />';
+ }
- parkingBrake.parkingBrake = propertyTypes.parkingBrake || false;
+ enums = vehiclePanelEngine.getPropertyConstant(property, propertyItem);
+ if (enums) {
+ showValue = enums["val" + value];
+ }
- this.__defineGetter__("parkingBrake", function () {
- return parkingBrake.parkingBrake;
- });
+ html += '<tr class="vehicle-property-content">' +
+ '<td class="vehicle-property-label" title="' + propertyItem + unit + '">' + _interceptString(propertyItem + unit, 18) + '</td>' +
+ '<td class="vehicle-property-value vehicle-property-value-auto" id="' + property + '-' + propertyItem + '-show">' + showValue + '</td>' +
+ '<td class="vehicle-property-value vehicle-property-value-manual">' +
+ valueField +
+ '</td></tr>';
- this.__defineSetter__("parkingBrake", function (val) {
- try {
- parkingBrake.parkingBrake = t.boolean(val);
- }
- catch (err) {
+ if (data[property][propertyItem].type === "text") {
+ html += _addArrayValueEnter(property, propertyItem, value);
+ }
+
+ if (_vehicleGlobalVars.registerListeners[property]) {
+ event.trigger("vehicle-subscribe-request", [property, false, 0]);
+ }
+ }
}
- });
-};
-ParkingLight = function (propertyTypes) {
- var parkingLight = {};
+ autoContainer.html(html);
+ _switchAutoManual(false);
+ }
+ else {
+ if (_vehicleGlobalVars.currentAutoStatus) {
+ for (property in data) {
- VehiclePropertyType.call(this, propertyTypes);
+ for (propertyItem in data[property]) {
+ value = data[property][propertyItem].value;
- parkingLight.parkingLight = propertyTypes.parkingLight || false;
+ showContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-show");
+ setContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-set");
- this.__defineGetter__("parkingLight", function () {
- return parkingLight.parkingLight;
- });
+ if (Object.prototype.toString.call(value) === '[object Array]') {
+ value = value.join(",");
+ }
- this.__defineSetter__("parkingLight", function (val) {
- try {
- parkingLight.parkingLight = t.boolean(val);
+ if (data[property][propertyItem].type === "text") {
+ _addArrayValueEnter(property, propertyItem, value);
+ }
+
+ if (showContainer && setContainer) {
+ showContainer.html(value);
+ setContainer.val(value);
+ }
+ }
+ }
}
- catch (err) {
+ else {
}
- });
-};
+ jQuery("#vehicle-container #vehicle-running-show #vehicle-time-show").html(timeStamp);
+ }
-HazardLight = function (propertyTypes) {
- var hazardLight = {};
+ for (property in _vehicleGlobalVars.registerListeners) {
+ event.trigger("vehicle-subscribe-request", [property, false, 0]);
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ _saveVehicleData();
+ _vehicleGlobalVars.currentDataIndex++;
+}
- hazardLight.hazardLight = propertyTypes.hazardLight || false;
+function _formatHistory (historyData, time, zone, source) {
+ var format = {}, property, name, item, value;
- this.__defineGetter__("hazardLight", function () {
- return hazardLight.hazardLight;
- });
+ for (property in historyData) {
+ name = property.split("-")[0];
+ item = property.split("-")[1];
- this.__defineSetter__("hazardLight", function (val) {
- try {
- hazardLight.hazardLight = t.boolean(val);
+ if (!format[name]) {
+ format[name] = {};
+ format[name].time = time;
+ format[name].zone = zone;
+ format[name].source = source;
}
- catch (err) {
+
+ value = historyData[property];
+ if (value.indexOf(",") > -1) {
+ value = value.split(",");
}
- });
-};
+ if (value === "true") value = true;
+ if (value === "false") value = false;
-AntilockBrakingSystem = function (propertyTypes) {
- var abs = {};
+ format[name][item] = value;
+ }
- VehiclePropertyType.call(this, propertyTypes);
+ return format;
+}
- abs.antilockBrakingSystem = propertyTypes.antilockBrakingSystem || false;
+function _saveVehicleData () {
+ var configurationContainer = jQuery("#vehicle-container #vehicle-configuration-show *[id$='-set']"),
+ currentConfigContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
+ settingContainer = jQuery("#vehicle-container #vehicle-setting-show *[id$='-set']"),
+ autoContainer = jQuery("#vehicle-container #vehicle-running-show *[id$='-set']"),
+ supportedContainer = jQuery("#vehicle-container #vehicle-supported-hide *[id$='-supported']:checked"),
+ supported = [], currentConfig, configuration = [], setting = [], autoRunning = [],
+ history = {}, itemKey, format, delTime, time, zone, source;
- this.__defineGetter__("antilockBrakingSystem", function () {
- return abs.antilockBrakingSystem;
+ supportedContainer.each(function (index, item) {
+ supported.push(item.value);
});
- this.__defineSetter__("antilockBrakingSystem", function (val) {
- try {
- abs.antilockBrakingSystem = t.boolean(val);
- }
- catch (err) {
- }
- });
-};
+ currentConfig = currentConfigContainer.val().replace("configuration", "");
-TractionControlSystem = function (propertyTypes) {
- var tcs = {};
+ configurationContainer.each(function (index, item) {
+ itemKey = item.id.replace("-set", "");
+ history[itemKey] = item.value;
- VehiclePropertyType.call(this, propertyTypes);
+ configuration.push(item.value);
+ });
- tcs.tractionControlSystem = propertyTypes.tractionControlSystem || false;
+ settingContainer.each(function (index, item) {
+ itemKey = item.id.replace("-set", "");
+ history[itemKey] = item.value;
- this.__defineGetter__("tractionControlSystem", function () {
- return tcs.tractionControlSystem;
+ setting.push(item.value);
});
- this.__defineSetter__("tractionControlSystem", function (val) {
- try {
- tcs.tractionControlSystem = t.boolean(val);
- }
- catch (err) {
- }
- });
-};
-
-VehicleTopSpeedLimit = function (propertyTypes) {
- var vtl = {};
+ autoContainer.each(function (index, item) {
+ var value;
- VehiclePropertyType.call(this, propertyTypes);
+ value = item.value;
+ if (item.id.indexOf("TripMeter") > -1) {
+ value = item.value.split(",");
+ }
- vtl.vehicleTopSpeedLimit = propertyTypes.vehicleTopSpeedLimit || false;
+ itemKey = item.id.replace("-set", "");
+ history[itemKey] = value;
- this.__defineGetter__("vehicleTopSpeedLimit", function () {
- return vtl.vehicleTopSpeedLimit;
+ autoRunning.push(value);
});
- this.__defineSetter__("vehicleTopSpeedLimit", function (val) {
- try {
- vtl.vehicleTopSpeedLimit = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
-};
+ _vehicleGlobalVars.timeHistoryArray.push(_vehicleGlobalVars.timeCurrent);
+ if (_vehicleGlobalVars.timeHistoryArray.length > _vehicleGlobalVars.timeHistoryLimit) {
+ delTime = _vehicleGlobalVars.timeHistoryArray.shift();
+ delete _vehicleGlobalVars.history[delTime];
+ }
-AirbagStatus = function (propertyTypes) {
- var airbagStatus = {};
+ time = _vehicleGlobalVars.timeCurrent;
+ source = "";
+ zone = 0;
- VehiclePropertyType.call(this, propertyTypes);
+ format = _formatHistory(history, time, zone, source);
+ _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent] = format;
+ event.trigger("vehicle-cache-refresh", [supported, format]);
- airbagStatus.airbagStatus = propertyTypes.airbagStatus || 0;
+ vehiclePanelEngine.saveData(supported, currentConfig, configuration, setting, autoRunning);
+}
- this.__defineGetter__("AIRBAGSTATUS_INACTIVE", function () {
- return 0;
- });
+function _switchAutoManual (isAuto) {
+ var autoContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-auto"),
+ manualContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-manual"),
+ arrayContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-array"),
+ autoBtnContainer = jQuery("#vehicle-container #vehicle-running-auto");
- this.__defineGetter__("AIRBAGSTATUS_ACTIVE", function () {
- return 1;
- });
+ if (isAuto) {
+ autoBtnContainer.addClass("vehicle-property-supported");
+ autoBtnContainer.removeClass("vehicle-property-unsupported");
+ autoContainer.show();
+ manualContainer.hide();
+ arrayContainer.hide();
+ }
+ else {
+ autoBtnContainer.addClass("vehicle-property-unsupported");
+ autoBtnContainer.removeClass("vehicle-property-supported");
+ autoContainer.hide();
+ manualContainer.show();
+ arrayContainer.show();
+ }
+}
- this.__defineGetter__("AIRBAGSTATUS_DEPLOYED", function () {
- return 2;
- });
+function _addVehicleDomEventListener () {
+ var configSelection = jQuery("#vehicle-container #vehicle-configuration-types"),
+ supportedSelection = jQuery("#vehicle-container #vehicle-supported-show td"),
+ autoSelection = jQuery("#vehicle-container #vehicle-running-auto"),
+ arraySelection = jQuery("#vehicle-container .vehicle-property-array"),
+ arrayOKSelection = jQuery("#vehicle-container .vehicle-property-arrayOk"),
+ rangeSelection = jQuery("#vehicle-container input[type='range']");
- this.__defineGetter__("airbagStatus", function () {
- return airbagStatus.airbagStatus;
- });
+ arraySelection.delegate("button", "click", function () {
+ var els = jQuery(this), appHtml;
- this.__defineSetter__("airbagStatus", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1 || val === 2) {
- airbagStatus.airbagStatus = val;
- }
+ appHtml = '<div class="vehicle-property-arrayItem">' +
+ '<button style="margin-left: -60px;">add</button>' +
+ '<input type="text" value="0" />' +
+ '<button >del</button>' +
+ '</div>';
+
+ if (els.html() === "add") {
+ jQuery(appHtml).insertAfter(els.parent());
+ els.hide();
}
- catch (err) {
+ else if (els.html() === "del") {
+ if (els.parent().prev().length === 0 && els.parent().next().length === 0)
+ return;
+ els.parent().prev().find("button")[0].style.marginLeft = "-60px";
+ els.parent().prev().find("button")[0].style.display = "";
+ els.parent().remove();
}
});
-};
-DoorStatus = function (propertyTypes) {
- var doorStatus = {};
+ arrayOKSelection.click("click", function () {
+ var els = jQuery(this), inputEls, i, trEls,
+ setElsId, value = [];
- VehiclePropertyType.call(this, propertyTypes);
+ trEls = els.parent().parent();
+ setElsId = trEls.attr("id").replace("OK", "");
- doorStatus.doorStatus = propertyTypes.doorStatus || 0;
- doorStatus.doorLockStatus = propertyTypes.doorLockStatus || false;
- doorStatus.childLockStatus = propertyTypes.childLockStatus || false;
+ inputEls = trEls.prev().find("input");
+ for (i = 0; i < inputEls.length; i++) {
+ value.push(inputEls[i].value);
+ }
- this.__defineGetter__("DOORSTATUS_CLOSED", function () {
- return 0;
+ jQuery("#vehicle-container #" + setElsId).val(value.join(","));
});
- this.__defineGetter__("DOORSTATUS_OPEN", function () {
- return 1;
- });
+ rangeSelection.bind("change", function () {
+ var domJQuery = jQuery(this);
- this.__defineGetter__("DOORSTATUS_AJAR", function () {
- return 2;
+ domJQuery.prev().html(domJQuery.val());
});
- this.__defineGetter__("doorStatus", function () {
- return doorStatus.doorStatus;
- });
+ configSelection.bind("change", function () {
+ var configuration, current,
+ domJQuery = jQuery(this);
- this.__defineSetter__("doorStatus", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1 || val === 2) {
- doorStatus.doorStatus = val;
- }
- }
- catch (err) {
- }
+ configuration = _vehicleGlobalVars.vehicleCache.configurationData;
+ current = domJQuery.val();
+ _setVehicleConfiguration(configuration, current);
});
- this.__defineGetter__("doorLockStatus", function () {
- return doorStatus.doorLockStatus;
- });
+ //add vehicle supported click event
+ supportedSelection.bind("click", function () {
+ var domJQuery = jQuery(this), vehicleChecked,
+ propertiesSelector = "#vehicle-container #vehicle-supported-hide",
+ content, supportedId, inputJQuery;
- this.__defineSetter__("doorLockStatus", function (val) {
- try {
- doorStatus.doorLockStatus = t.boolean(val);
+ content = domJQuery.html();
+ supportedId = content + "-supported";
+ inputJQuery = jQuery(propertiesSelector + " #" + supportedId);
+ if (domJQuery.hasClass("vehicle-property-unsupported")) {
+ inputJQuery.attr("checked", "checked");
+ domJQuery.removeClass("vehicle-property-unsupported");
+ domJQuery.addClass("vehicle-property-supported");
}
- catch (err) {
+ else {
+ inputJQuery.removeAttr("checked");
+ domJQuery.removeClass("vehicle-property-supported");
+ domJQuery.addClass("vehicle-property-unsupported");
}
- });
- this.__defineGetter__("childLockStatus", function () {
- return doorStatus.childLockStatus;
+ vehicleChecked = jQuery("#vehicle-container #vehicle-supported-hide input:checked");
+ _vehicleGlobalVars.vehicleCache.supported.length = 0;
+ vehicleChecked.each(function (index, els) {
+ _vehicleGlobalVars.vehicleCache.supported.push(els.value);
+ });
});
- this.__defineSetter__("childLockStatus", function (val) {
- try {
- doorStatus.childLockStatus = t.boolean(val);
+ //add vehicle auto click event
+ autoSelection.bind("click", function () {
+ if (_vehicleGlobalVars.currentAutoStatus) {
+ _vehicleGlobalVars.currentAutoStatus = false;
+ jQuery("#vehicle-container #vehicle-configuration-noOperation").hide();
+ jQuery("#vehicle-container #vehicle-supported-noOperation").hide();
}
- catch (err) {
+ else {
+ _vehicleGlobalVars.currentAutoStatus = true;
+ jQuery("#vehicle-container #vehicle-configuration-noOperation").show();
+ jQuery("#vehicle-container #vehicle-supported-noOperation").show();
}
- });
-};
-
-SeatBeltStatus = function (propertyTypes) {
- var seatBeltStatus = {};
-
- VehiclePropertyType.call(this, propertyTypes);
+ _switchAutoManual(_vehicleGlobalVars.currentAutoStatus);
- seatBeltStatus.seatBeltStatus = propertyTypes.seatBeltStatus || false;
+ _vehicleGlobalVars.timeFlag = setInterval(function () {
+ _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
+ }, _vehicleGlobalVars.timeInterval);
+ });
+}
- this.__defineGetter__("seatBeltStatus", function () {
- return seatBeltStatus.seatBeltStatus;
+function _addVehicleEventListener () {
+ event.once("vehicle-cache-request", function (data) {
+ data.supported = _vehicleGlobalVars.vehicleCache.supported;
+ data.data = _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent];
});
- this.__defineSetter__("seatBeltStatus", function (val) {
- try {
- seatBeltStatus.seatBeltStatus = t.boolean(val);
- }
- catch (err) {
+ event.on("vehicle-subscribe-request", function (property, isRegister, zone) {
+ if (isRegister) {
+ _vehicleGlobalVars.registerListeners[property] = true;
+ return;
}
- });
-};
-OccupantStatus = function (propertyTypes) {
- var occupantStatus = {};
+ var value, status, time, history,
+ propertyObj = {};
- VehiclePropertyType.call(this, propertyTypes);
+ if (_vehicleGlobalVars.vehicleCache.supported.indexOf(property) === -1) {
+ propertyObj.val = null;
+ propertyObj.supported = false;
+ propertyObj.type = property;
+ }
+ else {
+ history = _vehicleGlobalVars.history;
+ time = _vehicleGlobalVars.timeCurrent;
- occupantStatus.occupantStatus = propertyTypes.occupantStatus || 0;
+ value = history[time][property];
+ value.time = time;
+ status = true;
- this.__defineGetter__("OCCUPANTSTATUS_VACANT", function () {
- return 0;
- });
+ propertyObj.val = value;
+ propertyObj.supported = status;
+ propertyObj.type = property;
+ }
- this.__defineGetter__("OCCUPANTSTATUS_CHILD", function () {
- return 1;
+ event.trigger("vehicle-subscribe-response", [propertyObj]);
});
- this.__defineGetter__("OCCUPANTSTATUS_ADULT", function () {
- return 2;
- });
+ event.on("vehicle-set-request", function (property, value) {
+ var status = true, enums, showValue;
- this.__defineGetter__("occupantStatus", function () {
- return occupantStatus.occupantStatus;
- });
+ for (var item in value) {
+ var enterID = property + "-" + item + "-set";
+ var showID = property + "-" + item + "-show";
+ var enterContainer = jQuery("#vehicle-container #" + enterID);
+ var showContainer = jQuery("#vehicle-container #" + showID);
- this.__defineSetter__("occupantStatus", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1 || val === 2) {
- occupantStatus.occupantStatus = val;
+ if (Object.prototype.toString.call(value[item]) === '[object Array]') {
+ enterContainer.val(value[item].join(","));
+ }
+ else {
+ enterContainer.val(value[item].toString());
+ }
+ if (showContainer) {
+ enums = vehiclePanelEngine.getPropertyConstant(property, item);
+ showValue = value[item];
+ if (enums) {
+ showValue = enums["val" + value[item]];
+ }
+ showContainer.html(showValue);
}
}
- catch (err) {
- }
- });
-};
-
-ObstacleDistance = function (propertyTypes) {
- var obstacleDistance = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- obstacleDistance.obstacleDistance = propertyTypes.obstacleDistance || 0;
-
- this.__defineGetter__("DISTANCESENSORLOCATION_LEFTFRONT", function () {
- return 0;
- });
-
- this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTFRONT", function () {
- return 1;
- });
-
- this.__defineGetter__("DISTANCESENSORLOCATION_LEFTREAR", function () {
- return 2;
- });
-
- this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTREAR", function () {
- return 3;
- });
-
- this.__defineGetter__("DISTANCESENSORLOCATION_LEFTBLINDSPOT", function () {
- return 4;
- });
-
- this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTBLINDSPOT", function () {
- return 5;
- });
-
- this.__defineGetter__("obstacleDistance", function () {
- return obstacleDistance.obstacleDistance;
- });
- this.__defineSetter__("obstacleDistance", function (val) {
- try {
- obstacleDistance.obstacleDistance = t.double(val);
- }
- catch (err) {
- }
+ event.trigger("vehicle-set-response", [status]);
});
-};
-NightMode = function (propertyTypes) {
- var nightMode = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- nightMode.nightMode = propertyTypes.nightMode || false;
+ event.on("vehicle-history-request", function (property, zone, startTime, endTime) {
+ var history, historyResponse = [], obj, status, time;
- this.__defineGetter__("nightMode", function () {
- return nightMode.nightMode;
- });
+ history = _vehicleGlobalVars.history;
- this.__defineSetter__("nightMode", function (val) {
- try {
- nightMode.nightMode = t.boolean(val);
- }
- catch (err) {
+ for (time in history) {
+ if (time >= startTime && time <= endTime &&
+ history[time].hasOwnProperty(property)) {
+ obj = history[time][property];
+ obj.time = time;
+ historyResponse.push(obj);
+ }
}
- });
-};
-
-DrivingMode = function (propertyTypes) {
- var drivingMode = {};
-
- VehiclePropertyType.call(this, propertyTypes);
-
- drivingMode.drivingMode = propertyTypes.drivingMode || 0;
+ status = true;
- this.__defineGetter__("drivingMode", function () {
- return drivingMode.drivingMode;
+ event.trigger("vehicle-history-response", [historyResponse, status]);
});
+}
- this.__defineSetter__("drivingMode", function (val) {
- try {
- val = t.unsigned_short(val);
- if (val === 0 || val === 1) {
- drivingMode.drivingMode = val;
- }
- }
- catch (err) {
- }
- });
-};
+function _initializeVehiclePanel () {
+ try {
+ var stop = false,
+ configuration, current, properties, supported, settings,
+ autoRunning;
-TurnSignal = function (propertyTypes) {
- var turnSignal = {};
+ _vehicleGlobalVars.timeHistoryArray = [];
- VehiclePropertyType.call(this, propertyTypes);
+ configuration = vehiclePanelEngine.getConfiguration();
+ current = vehiclePanelEngine.getCurrentConfiguration();
+ _setVehicleConfigurationSel(configuration);
+ _vehicleGlobalVars.vehicleCache.configurationData = configuration;
+ _vehicleGlobalVars.vehicleCache.currentConfiguration = current;
+ _setVehicleConfiguration(configuration, current);
- turnSignal.turnSignal = propertyTypes.turnSignal || 0;
+ properties = vehiclePanelEngine.getProperties();
+ supported = vehiclePanelEngine.getSupported();
+ _vehicleGlobalVars.vehicleCache.properties = properties;
+ _vehicleGlobalVars.vehicleCache.supported = supported;
+ _setVehicleSupported(properties, supported);
- this.__defineGetter__("turnSignal", function () {
- return turnSignal.turnSignal;
- });
+ settings = vehiclePanelEngine.getSettings();
+ _vehicleGlobalVars.vehicleCache.settingData = settings;
+ _setVehicleSetting(settings);
- this.__defineSetter__("turnSignal", function (val) {
- try {
- turnSignal.turnSignal = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
-};
+ autoRunning = vehiclePanelEngine.getAutoRunning();
+ _vehicleGlobalVars.vehicleCache.autoRunningData = autoRunning;
+ _setVehicleAutoRunning(autoRunning, false);
+ _vehicleGlobalVars.currentDataIndex = 0;
-ButtonEvent = function (propertyTypes) {
- var buttonEvent = {};
+ _vehicleGlobalVars.timeFlag = setInterval(function () {
+ _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
+ }, _vehicleGlobalVars.timeInterval);
- VehiclePropertyType.call(this, propertyTypes);
+ _addVehicleDomEventListener();
- buttonEvent.buttonEvent = propertyTypes.buttonEvent || 0;
+ _addVehicleEventListener();
- this.__defineGetter__("buttonEvent", function () {
- return buttonEvent.buttonEvent;
- });
+ jQuery("#vehicle-properties h3").click(function (event) {
+ if (stop) {
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ stop = false;
+ }
+ });
+ jQuery("#vehicle-properties").accordion("destroy").accordion({
+ header: "> div > h3",
+ autoHeight: false
+ });
+ } catch (e) {
+ exception.handle(e, true);
+ }
+}
- this.__defineSetter__("buttonEvent", function (val) {
- try {
- buttonEvent.buttonEvent = t.unsigned_short(val);
- }
- catch (err) {
- }
- });
+module.exports = {
+ panel: {
+ domId: "vehicle-container",
+ collapsed: true,
+ pane: "right",
+ titleName: "Vehicle Information",
+ display: true
+ },
+ initialize: function () {
+ _initializeVehiclePanel();
+ }
};
-_initialize();
-
-module.exports = _self;
-
});
-define('ripple/platform/phonegap/1.0.0/AVCodecsAttributes', function (require, exports, module) {
+define('ripple/ui/plugins/build', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (info, id, audioCodecs, videoCodecs) {
- return {
- info: info,
- id: id,
- audioCodecs: audioCodecs,
- videoCodecs: videoCodecs
- };
-};
+var tooltip = require('ripple/ui/plugins/tooltip'),
+ settings = require('ripple/ui/plugins/settings-dialog'),
+ bus = require('ripple/bus');
-});
-define('ripple/platform/phonegap/1.0.0/Acceleration', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (x, y, z) {
- return {
- x: x || 0,
- y: y || 0,
- z: z || 0,
- timestamp: new Date().getTime()
- };
-};
+function handleBuild() {
+ var node = $(this),
+ action = node.attr('id').split("-")[2];
-});
-define('ripple/platform/phonegap/1.0.0/AudioCodecAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, compFormats, encode, decode) {
- return {
- info: info,
- id: id,
- compFormats: compFormats,
- encode: encode,
- decode: decode
- };
-};
+ if (node.hasClass("not-ready")) {
+ return;
+ }
-});
-define('ripple/platform/phonegap/1.0.0/AudioDeviceAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (type, freqRangeLow, freqRangeHigh, volumeLevel, info) {
- return {
- type: type,
- freqRangeLow: freqRangeLow,
- freqRangeHigh: freqRangeHigh,
- volumeLevel: volumeLevel,
- info: info
- };
+ if (!settings.can(action)) {
+ settings.show(action);
+ }
+ else {
+ settings.perform(action);
+ }
+}
-};
+function areServicesRunning(success, fail) {
+ bus.ajax(
+ "GET",
+ "http://127.0.0.1:9910/ripple/about",
+ null,
+ function () {
+ success();
+ },
+ function (error) {
+ fail();
+ }
+ );
+}
-});
-define('ripple/platform/phonegap/1.0.0/BrailleDeviceAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (nbCells, info) {
- return {
- nbCells: nbCells,
- info: info
- };
+function manageServices(action, callBack) {
+ bus.send("services", action, function () {
+ if (typeof callBack === "function") {
+ callBack();
+ }
+ });
+}
-};
+module.exports = {
+ panel: {
+ domId: "build-container",
+ collapsed: true,
+ pane: "right"
+ },
-});
-define('ripple/platform/phonegap/1.0.0/CPUAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, usage) {
- return {
- info: info,
- id: id,
- usage: usage
- };
-};
+ initialize: function () {
+ $("#options-menu-build").click(handleBuild);
+ $("#options-menu-sign").click(handleBuild);
+ $("#options-menu-launch").click(handleBuild);
-});
-define('ripple/platform/phonegap/1.0.0/CameraAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (supportsVideo, hasFlash, sensorPixels, maxZoomFactor) {
- return {
- supportsVideo: supportsVideo,
- hasFlash: hasFlash,
- sensorPixels: sensorPixels,
- maxZoomFactor: maxZoomFactor
- };
+ $('#options-menu-start-service').click(function () {
+ manageServices("start", function (result) {
+ $('#options-menu-services-stop').show();
+ $('#options-menu-services-start').hide();
+ });
+ });
-};
+ $('#options-menu-stop-service').click(function () {
+ manageServices("stop", function (result) {
+ $('#options-menu-services-stop').hide();
+ $('#options-menu-services-start').show();
+ });
+ });
-});
-define('ripple/platform/phonegap/1.0.0/Connection', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- UNKNOWN: "unknown",
- ETHERNET: "ethernet",
- WIFI: "wifi",
- CELL_2G: "2g",
- CELL_3G: "3g",
- CELL_4G: "4g",
- NONE: "none"
-};
+ $("#options-menu-settings").click(function () {
+ settings.show();
+ });
-});
-define('ripple/platform/phonegap/1.0.0/ConnectionAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, type, currentOrientation, currentUploadBandwidth, maxDownloadBandwidth, maxUploadBandwidth, currentSignalStrength, roaming) {
- return {
- info: info,
- id: id,
- type: type,
- currentDownloadBandwidth: currentOrientation,
- currentUploadBandwidth: currentUploadBandwidth,
- maxDownloadBandwidth: maxDownloadBandwidth,
- maxUploadBandwidth: maxUploadBandwidth,
- currentSignalStrength: currentSignalStrength,
- roaming: roaming
- };
+ if (settings.value("remoteInspector")) {
+ $("#options-menu-build-warning").show();
+ tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
+ }
+
+ areServicesRunning(
+ function () {
+ $('#options-menu-services-stop').show();
+ $('#options-menu-services-start').hide();
+ },
+ function () {
+ $('#options-menu-services-stop').hide();
+ $('#options-menu-services-start').show();
+ }
+ );
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/Contact', function (require, exports, module) {
+define('ripple/ui/plugins/sensors', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright (c) 2010 Epic Train Hack
+ * Copyright (c) 2011 Research In Motion Limited
+ * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
*
- * 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
+ * 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:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-var utils = require('ripple/utils'),
- event = require('ripple/event');
+var event = require('ripple/event'),
+ accelerometer = require('ripple/accelerometer'),
+ deviceSettings = require('ripple/deviceSettings'),
+ Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
+ Rotation = require('ripple/platform/w3c/1.0/Rotation'),
+ sensorSettings = require('ripple/sensorSettings'),
+ _oldX, _oldY, _oldAlphaX,
+ _camera, _scene, _renderer, _mesh,
+ _offsets = {
+ x: 0,
+ y: 0,
+ z: -9.81,
+ },
+ _flag, // whether the browser supports webGL
+ _shape =
+ //
+ // The front side
+ //
+ // x, y, z x, y, z x, y, z
+ // for some strange reason for y -100 is top, 100 is bottom
+ "-30,30,10, 30,30,10, 30,60,10, 100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
+ "-30,30,10, 30,60,10, -30,60,10, 100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
+ // front side "the phone display"
+ "-20,-50,11, 20,-50,11, 20,20,11, 100,100,100,-1,0;" +
+ "-20,-50,11, 20,20,11, -20,20,11, 100,100,100,-1,0;" +
+ // below the display
+ "-30,30,10, 30,20,10, 30,30,10, 0,0,0,-1,0;" +
+ "-30,30,10, -30,20,10, 30,20,10, 0,0,0,-1,0;" +
+ // above the display
+ "-30,-60,10, 30,-60,10, 30,-50,10, 0,0,0,-1,0;" +
+ "-30,-60,10, 30,-50,10, -30,-50,10, 0,0,0,-1,0;" +
+ // left of the display
+ "-30,-50,10, -20,-50,10, -20,20,10, 0,0,0,-1,0;" +
+ "-30,-50,10, -20,20,10, -30,20,10, 0,0,0,-1,0;" +
+ // right of the display
+ "20,-50,10, 30,-50,10, 30,20,10, 0,0,0,-1,0;" +
+ "20,-50,10, 30,20,10, 20,20,10, 0,0,0,-1,0;" +
-function _properties(obj) {
- var prop, newObj = {};
- for (prop in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, prop)) {
- if (typeof obj[prop] !== "function") {
- newObj[prop] = utils.copy(obj[prop]);
+
+ // back side, opposite side to the above one
+ "-30,-60,-10, 30,60,-10, 30,-60,-10, 0,0,0,-1,0;" +
+ "-30,-60,-10, -30,60,-10, 30,60,-10, 0,00,-1,0;" +
+ // right side
+ "30,-60,-10, 30,60,-10, 30,60,10, 50,50,80,-1,0;" +
+ "30,-60,-10, 30,60,10, 30,-60,10, 50,50,80,-1,0;" +
+ // left side
+ "-30,-60,-10, -30,60,10, -30,60,-10, 50,50,80,-1,0;" +
+ "-30,-60,-10, -30,-60,10, -30,60,10, 50,50,80,-1,0;" +
+
+ // top
+ "30,-60,-10, -30,-60,10, -30,-60,-10, 50,80,50,-1,0;" +
+ "30,-60,-10, 30,-60,10, -30,-60,10, 50,80,50,-1,0;" +
+ // bottom
+ "30,60,-10, -30,60,-10, -30,60,10, 80,50,50,-1,0;" +
+ "30,60,-10, -30,60,10, 30,60,10, 80,50,50,-1,0";
+
+function _createThreeDModel() {
+ var node,
+ shader,
+ hemiLight,
+ dirLight,
+ material,
+ uniforms,
+ container,
+ loader,
+ directionalLight,
+ isDiffuseTextureLoaded,
+ isNormalTextureLoaded,
+ shiftKeyDown,
+ mouseDown,
+ ctrlKeyDown = false;
+
+ if (_flag) {
+ // create a 3D phone model with three.js if webGL is supported
+ node = document.getElementById("accelerometer-div");
+ container = document.createElement("div");
+ $("#accelerometer-div").append(container);
+
+ _camera = new THREE.PerspectiveCamera(50, 1.5, 0.1, 100);
+ _camera.position.set(4.32823, 3.74714, 2.62985);
+ _scene = new THREE.Scene();
+ _scene.add(new THREE.AmbientLight(0xffffff));
+ directionalLight = new THREE.DirectionalLight(0xffffff, 1);
+ directionalLight.position.set(1, 1, 1).normalize();
+ _scene.add(directionalLight);
+ hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
+ hemiLight.color.setHSV(0.6, 0.75, 1);
+ hemiLight.groundColor.setHSV(0.095, 0.5, 1);
+ hemiLight.position.set(0, 500, 0);
+ _scene.add(hemiLight);
+ dirLight = new THREE.DirectionalLight(0xffffff, 1);
+ dirLight.color.setHSV(0.1, 0.1, 1);
+ dirLight.position.set(-1, 1.75, 1);
+ dirLight.position.multiplyScalar(50);
+ _scene.add(dirLight);
+ shader = THREE.ShaderSkin["skin"];
+ uniforms = THREE.UniformsUtils.clone(shader.uniforms);
+ uniforms["tNormal"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tNormal.png", {}, function () {
+ isNormalTextureLoaded = true;
+ if (isDiffuseTextureLoaded) {
+ _renderer.clear();
+ _renderer.render(_scene, _camera);
}
- }
+ });
+ uniforms["uNormalScale"].value = 0.75;
+ uniforms["tDiffuse"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tDiffuse.png", {}, function () {
+ isDiffuseTextureLoaded = true;
+ if (isNormalTextureLoaded) {
+ _renderer.clear();
+ _renderer.render(_scene, _camera);
+ }
+ });
+ uniforms["uDiffuseColor"].value.setHex(0xbbbbbb);
+ uniforms["uSpecularColor"].value.setHex(0x070707);
+ uniforms["uAmbientColor"].value.setHex(0x111111);
+ uniforms["uRoughness"].value = 0.185;
+ uniforms["uSpecularBrightness"].value = 0.8;
+ material = new THREE.ShaderMaterial({ fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true });
+ loader = new THREE.JSONLoader(true);
+ document.body.appendChild(loader.statusDomElement);
+
+ loader.load("phoneModel.js", function (geometry) {
+ loader.statusDomElement.style.display = "none";
+ geometry.computeTangents();
+ _mesh = new THREE.Mesh(geometry, material);
+ _mesh.position.set(7, 2, -50);
+ _mesh.scale.set(18, 12, 18);
+ _scene.add(_mesh);
+ _renderer.clear();
+ _renderer.render(_scene, _camera);
+ });
+
+ _renderer = new THREE.WebGLRenderer({antialias: false});
+ _renderer.setSize(300, 280);
+ _renderer.setClearColorHex(0xffffff, 1);
+ _renderer.autoClear = false;
+
+ container.appendChild(_renderer.domElement);
+ } else { // create the model with 3d.js
+ node = document.querySelector("#accelerometer-canvas");
+
+ jQuery("#accelerometer-div").css("display", "none");
+ jQuery("#accelerometer-canvas").css("display", "block");
+ ThreeDee.setCenter(150, 100);
+ ThreeDee.setLight(-300, -300, 800);
+ _updateCanvas(0, 0);
}
- return newObj;
-}
-module.exports = function (
- id,
- displayName,
- name,
- nickname,
- phoneNumbers,
- emails,
- addresses,
- ims,
- organizations,
- birthday,
- note,
- photos,
- categories,
- urls
-) {
+ //change accelerometer and phone by moving the mouse and the key "shift"
+ node.addEventListener("mousemove", function (event) {
+ var cosX, sinX, cosY, sinY,
+ alpha = accelerometer.getInfo().orientation.alpha,
+ beta = accelerometer.getInfo().orientation.beta,
+ gamma = accelerometer.getInfo().orientation.gamma,
+ x = accelerometer.getInfo().acceleration.x,
+ y = accelerometer.getInfo().acceleration.y,
+ z = accelerometer.getInfo().acceleration.z;
- return {
- id: id || Math.uuid(undefined, 16),
- displayName: displayName || null,
- name: name || null,
- nickname: nickname || null,
- phoneNumbers: phoneNumbers || null,
- emails: emails || null,
- addresses: addresses || null,
- ims: ims || null,
- organizations: organizations || null,
- birthday: birthday || null,
- note: note || null,
- photos: photos || null,
- categories: categories || null,
- urls: urls || null,
- save: function (success, error) {
- var _self = this,
- lastUpdated = this.updated; // hackish
+ if (!mouseDown) {
+ return;
+ }
- this.updated = new Date();
+ // if the shift key is pressed down, only the alpha value will be chagned
+ if (!shiftKeyDown) {
+ _offsets.x = (_offsets.x + _oldX - event.offsetX) % 360;
+ _offsets.y = (_offsets.y + _oldY - event.offsetY) % 360;
- if (!this.id) {
- this.id = Math.uuid(undefined, 16);
+ alpha = alpha || 0;
+
+ // enforce gamma in [-90,90] as per w3c spec
+ gamma = -_offsets.x;
+ if (gamma < -90) {
+ gamma = -90;
+ }
+ if (gamma > 90) {
+ gamma = 90;
}
- event.trigger("phonegap-contact-save", [_properties(this), success, function (e) {
- _self.updated = lastUpdated;
- error(e);
- }]);
- },
- remove: function (success, error) {
- event.trigger("phonegap-contact-remove", [this.id, success, error]);
- },
- clone: function () {
- var copy = utils.copy(this);
- copy.id = null;
- return copy;
- }
- };
-};
+ // enforce beta in [-180,180] as per w3c spec
+ beta = -_offsets.y % 360;
+ if (beta < -180) {
+ beta += 360;
+ }
+ else if (beta >= 180) {
+ beta -= 360;
+ }
-});
-define('ripple/platform/phonegap/1.0.0/ContactAccount', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (domain, username, userid) {
- return {
- domain: domain,
- username: username,
- userid: userid
- };
-};
+ cosX = Math.cos(gamma * (Math.PI / 180));
+ sinX = Math.sin(gamma * (Math.PI / 180));
+ cosY = Math.cos(beta * (Math.PI / 180));
+ sinY = Math.sin(beta * (Math.PI / 180));
+ x = 9.81 * cosY * sinX;
+ y = -9.81 * sinY;
+ z = -9.81 * cosY * cosX;
-});
-define('ripple/platform/phonegap/1.0.0/ContactAddress', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (pref, type, formatted, streetAddress, locality, region, postalCode, country, id) {
- return {
- pref: pref || null,
- type: type || null,
- formatted: formatted || null,
- streetAddress: streetAddress || null,
- locality: locality || null,
- region: region || null,
- postalCode: postalCode || null,
- country: country || null,
- id: id || null
+ } else {
+ alpha = (alpha - (_oldAlphaX - event.offsetX) * 2.5) % 360;
+ }
+ _oldX = event.offsetX;
+ _oldY = event.offsetY;
+ _oldAlphaX = event.offsetX;
+ if (_flag)
+ _updatePhoneModel(alpha, beta, gamma);
+ else
+ _updateCanvas(alpha, -beta, gamma);
+ accelerometer.setInfo({
+ x: x,
+ y: y,
+ z: z,
+ alpha: alpha,
+ beta: beta,
+ gamma: gamma
+ });
+ }, false);
+
+ node.addEventListener("mousedown", function (e) {
+ mouseDown = true;
+ _oldX = e.offsetX;
+ _oldY = e.offsetY;
+ if (shiftKeyDown) {
+ _oldAlphaX = _oldX;
+ }
+ });
+
+ node.addEventListener("mouseup", function () {
+ mouseDown = false;
+ });
+
+ document.addEventListener("mouseup", function () {
+ //Catch mouseup events that fire when outside canvas bounds
+ mouseDown = false;
+ });
+
+ document.addEventListener("keydown", function (e) {
+ switch (e.keyCode) {
+ case 16: // Shift Key
+ shiftKeyDown = true;
+ break;
+ case 17: // Ctrl Key
+ ctrlKeyDown = true;
+ break;
+ case 74: // J Key
+ if (shiftKeyDown && ctrlKeyDown) { //if shift+ctrl+j keydown in the meantime, console comes up rather than shift key down
+ shiftKeyDown = false;
+ ctrlKeyDown = false;
+ }
+ break;
+ }
+ });
+
+ document.addEventListener("keyup", function (e) {
+ if (e.keyCode === 16) { // Shift Key
+ shiftKeyDown = false;
+ }
+ });
+}
+
+// update the 3d model created by 3d.js
+function _updateCanvas(a, b, g) {
+ ThreeDee.loadMesh(_shape);
+ g = g || 0;
+ ThreeDee.rotate(0, g, 0);
+ ThreeDee.rotate(b, 0, a);
+ ThreeDee.backface();
+ ThreeDee.shade();
+ ThreeDee.zSort();
+ Draw.initialize(document.querySelector("#accelerometer-canvas"));
+ Draw.clear(0, 0, 480, 300);
+ Draw.drawScene(ThreeDee.getTranslation(), 3);
+}
+
+// update the 3d model created by three.js
+function _updatePhoneModel(a, b, g) {
+ _mesh.rotation.x = b / 90 * 1.5;
+ _mesh.rotation.y = g / 90 * 1.5;
+ _mesh.rotation.z = a / 90 * 1.5;
+ _renderer.clear();
+ _renderer.render(_scene, _camera);
+}
+
+function _resetAccelerometer() {
+ _oldX = 0;
+ _oldY = 0;
+ _oldAlphaX = 0;
+ _offsets = {
+ x: 0,
+ y: 0,
+ z: -9.81
};
-};
+ if (_flag) {
+ _mesh.rotation.x = 0;
+ _mesh.rotation.y = 0;
+ _mesh.rotation.z = 0;
+ _renderer.clear();
+ _renderer.render(_scene, _camera);
+ } else {
+ _updateCanvas(0, 0);
+ }
-});
-define('ripple/platform/phonegap/1.0.0/ContactError', function (require, exports, module) {
-/*
- * Copyright 2011 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 ContactError(code) {
- this.code = code || null;
+ accelerometer.setInfo({
+ acceleration: new Acceleration(0, 0, 0),
+ accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
+ rotationRate: new Rotation(0, 0, 0),
+ orientation: new Rotation(0, 0, 0),
+ timestamp: new Date().getTime()
+ });
+ accelerometer.triggerEvent();
}
-ContactError.UNKNOWN_ERROR = 0;
-ContactError.INVALID_ARGUMENT_ERROR = 1;
-ContactError.NOT_FOUND_ERROR = 2;
-ContactError.TIMEOUT_ERROR = 3;
-ContactError.PENDING_OPERATION_ERROR = 4;
-ContactError.IO_ERROR = 5;
-ContactError.NOT_SUPPORTED_ERROR = 6;
-ContactError.PERMISSION_DENIED_ERROR = 20;
+function _resetMagneticField() {
+ jQuery("#magnetic-x").val("100");
+ jQuery("#magnetic-y").val("100");
+ jQuery("#magnetic-z").val("100");
+}
-module.exports = ContactError;
+function _resetLightLevel() {
+ $("#display-state").children().each(function() {
+ if ($(this).val() === "OFF") {
+ $(this).attr("selected", "true");
+ this.selected = true;
+ }
+ else {
+ $(this).attr("selected", "false");
+ this.selected = false;
+ }
+ });
+}
-});
-define('ripple/platform/phonegap/1.0.0/ContactField', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (type, value, pref) {
- return {
- type: type,
- value: value,
- pref: pref || false
+
+// set a typical mode for accelerometer simulation, when the phone drops,
+// x will become to be 0, y will become to be -9.81 and z will become to be 0
+function _setDrop() {
+ //duration = 20 * 50 = 1000ms. 20 is ths number of steps and 50 is the duration of steps.
+ var alpha = Number(accelerometer.getInfo().orientation.alpha),
+ beta = Number(accelerometer.getInfo().orientation.beta),
+ gamma = Number(accelerometer.getInfo().orientation.gamma),
+ cosX, cosY, sinX, sinY, x, y, z,
+ alphaStep = Math.abs(alpha) / 20,
+ betaStep = Math.abs(beta - 90) / 20,
+ gammaStep = Math.abs(gamma) / 20,
+ counts = 0, dropTimeout,
+ drop = function () {
+ if (counts >= 20) {
+ window.clearTimeout(dropTimeout);
+ // to avoid showing "-0" or "-0.00"
+ if (_flag)
+ _updatePhoneModel(0, 90, 0);
+ else
+ _updateCanvas(0, -90, 0);
+ accelerometer.setInfo({
+ x: 0,
+ y: -9.81,
+ z: 0,
+ alpha: 0,
+ beta: 90,
+ gamma: 0
+ });
+ } else {
+ dropTimeout = setTimeout(drop, 50);
+ step();
+ counts++;
+ }
+ },
+ step = function () {
+ var _beta;
+
+ alpha = alpha > 0 ? alpha - alphaStep : alpha + alphaStep;
+ beta = beta > 90 ? beta - betaStep : beta + betaStep;
+ gamma = gamma > 0 ? gamma - gammaStep : gamma + gammaStep;
+ _beta = _flag ? beta + betaStep : -(beta + betaStep);
+ if (_flag)
+ _updatePhoneModel(alpha, _beta, gamma);
+ else
+ _updateCanvas(alpha, _beta, gamma);
+
+ cosX = Math.cos(gamma * (Math.PI / 180));
+ sinX = Math.sin(gamma * (Math.PI / 180));
+ cosY = Number(Math.cos(beta * (Math.PI / 180)).toFixed(6));
+ sinY = Math.sin(beta * (Math.PI / 180));
+ x = 9.81 * cosY * sinX;
+ y = -9.81 * sinY;
+ z = -9.81 * cosY * cosX;
+ accelerometer.setInfo({
+ x: x,
+ y: y,
+ z: z,
+ alpha: alpha,
+ beta: beta,
+ gamma: gamma
+ });
+ _offsets.x = -gamma;
+ _offsets.y = -beta;
+ };
+
+ drop();
+}
+
+function _initializeSensorSettings() {
+ var sensorsInputID = ["accelerometer-alpha", "accelerometer-beta", "accelerometer-gamma", "magnetic-x", "magnetic-y", "magnetic-z"],
+ magneticEvent = ["MagneticField-xChanged", "MagneticField-yChanged", "MagneticField-zChanged"],
+ magneticData = ["MagneticField.x", "MagneticField.y", "MagneticField.z"],
+ oldValue, oldInputX,
+ inputMouseDown,
+ triggerFunction,
+ selectedInputID = null;
+
+ triggerFunction = function (val, index) {
+ var cosX, cosY, sinX, sinY, x, y, z,
+ alpha = accelerometer.getInfo().orientation.alpha,
+ beta = accelerometer.getInfo().orientation.beta,
+ gamma = accelerometer.getInfo().orientation.gamma;
+
+ //choose which value to change according to index
+ switch (index) {
+ case 0:
+ alpha = val;
+ break;
+ case 1:
+ beta = val;
+ break;
+ case 2:
+ gamma = val;
+ break;
+ default:
+ sensorSettings.persist(magneticData[index - 3], val);
+ event.trigger(magneticEvent[index - 3], [val]);
+ }
+
+ //change the phone model and values of other inputs when changing a value of input
+ if (_flag)
+ _updatePhoneModel(alpha, beta, gamma);
+ else
+ _updateCanvas(alpha, -beta, gamma);
+ cosX = Math.cos(gamma * (Math.PI / 180));
+ sinX = Math.sin(gamma * (Math.PI / 180));
+ cosY = Math.cos(beta * (Math.PI / 180));
+ sinY = Math.sin(beta * (Math.PI / 180));
+ x = 9.81 * cosY * sinX;
+ y = -9.81 * sinY;
+ z = -9.81 * cosY * cosX;
+ accelerometer.setInfo({
+ x: x,
+ y: y,
+ z: z,
+ alpha: alpha,
+ beta: beta,
+ gamma: gamma
+ });
+ _offsets.x = -gamma;
+ _offsets.y = -beta;
};
-};
-});
-define('ripple/platform/phonegap/1.0.0/ContactFindOptions', function (require, exports, module) {
+ // make the input elements more powful: drag mouse to left to decrease the value and right to increase it;
+ // also change the value with arrow keys.
+
+
+ sensorsInputID.forEach(function (id, index) {
+ jQuery("#" + id).mousedown(function (e) {
+ selectedInputID = id;
+ oldValue = parseInt(this.value, 10);
+ oldInputX = e.offsetX;
+ inputMouseDown = true;
+ });
+
+ jQuery("#" + id).mousemove(function (e) {
+ if (inputMouseDown && (selectedInputID !== null)) {
+ jQuery("#" + selectedInputID).val(parseInt(oldValue + (e.offsetX - oldInputX) / 2, 10));
+ if (parseInt(this.value, 10) <= parseInt(jQuery(this).attr("minValue"), 10)) {
+ this.value = jQuery(this).attr("minValue");
+ }
+ if (parseInt(this.value, 10) >= parseInt(jQuery(this).attr("maxValue"), 10)) {
+ this.value = jQuery(this).attr("maxValue");
+ }
+ triggerFunction(this.value, index);
+ }
+ });
+
+ jQuery("#" + id).mouseup(function () {
+ selectedInputID = null;
+ inputMouseDown = false;
+ });
+ jQuery(document).mouseup(function () {
+ selectedInputID = null;
+ inputMouseDown = false;
+ });
+
+ jQuery("#" + id).click(function () {
+ this.select();
+ });
+
+ jQuery("#" + id).blur(function () {
+ if (isNaN(this.value)) {
+ this.value = 0;
+ }
+ else if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("maxValue"), 10))
+ this.value = jQuery(this).attr("maxValue");
+ else if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("minValue"), 10))
+ this.value = jQuery(this).attr("minValue");
+ else
+ this.value = parseInt(this.value, 10);
+ triggerFunction(this.value, index);
+ });
+
+ jQuery("#" + id).keydown(function (e) {
+ switch (e.keyCode) {
+ case 38:
+ if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("maxValue"), 10)) {
+ this.value = parseInt(this.value, 10) + 1;
+ triggerFunction(this.value, index);
+ }
+ break;
+ case 40:
+ if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("minValue"), 10)) {
+ this.value = parseInt(this.value, 10) - 1;
+ triggerFunction(this.value, index);
+ }
+ break;
+ default:
+ return;
+ }
+ });
+ });
+}
+
/*
- * Copyright 2011 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 = function (filter, multiple, updatedSince) {
- return {
- filter: filter || "",
- multiple: multiple || false,
- updatedSince: updatedSince || ""
- };
+//initialize light settings
+function _initializeLightSettings() {
+ var displayObj = document.getElementById("display-state"),
+ DISPLAY_STATE = require('ripple/constants').POWER_RESOURCE.SCREEN.STATE,
+ brightness;
+
+ displayObj.addEventListener("change", function () {
+ var state = displayObj.value, value;
+ value = DISPLAY_STATE[state].VALUE;
+ deviceSettings.persist("Display.brightness", value);
+ event.trigger("DisplayBrightnessChanged", [value]);
+ });
+
+ brightness = deviceSettings.retrieve("Display.brightness");
+ if (brightness === DISPLAY_STATE.SCREEN_OFF.MAX) {
+ displayObj.options[0].selected = true;
+ } else if (brightness <= DISPLAY_STATE.SCREEN_DIM.MAX) {
+ displayObj.options[1].selected = true;
+ } else if (brightness <= DISPLAY_STATE.SCREEN_NORMAL.MAX) {
+ displayObj.options[2].selected = true;
+ } else {
+ displayObj.options[3].selected = true;
+ }
+}
+*/
+
+module.exports = {
+ panel: {
+ domId: "sensors-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Sensors",
+ display: true
+ },
+ initialize: function () {
+ var gl,
+ testCanvas = document.getElementById("accelerometer-canvas");
+
+ try { // check whether the browser supports webGL, returns null if not support
+ gl = testCanvas.getContext("experimental-webgl");
+ gl.viewport(0, 0, testCanvas.width, testCanvas.height);
+ } catch (e) {
+ console.log("unsupport webgl");
+ }
+
+ _flag = gl ? true : false;
+
+ accelerometer.init();
+ _createThreeDModel();
+ _initializeSensorSettings();
+ //_initializeLightSettings();
+
+ jQuery("#accelerometer-shake").click(function () {
+ window.setTimeout(require('ripple/ui/plugins/goodVibrations').shakeDevice(8), 1);
+ accelerometer.shake();
+ });
+
+ jQuery("#sensor-reset-all").click(function () {
+ _resetAccelerometer();
+ _resetMagneticField();
+ _resetLightLevel();
+ });
+
+ jQuery("#accelerometer-drop").click(_setDrop);
+
+ event.on("AccelerometerInfoChangedEvent", function (motion) {
+ jQuery("#accelerometer-x").html(motion.accelerationIncludingGravity.x.toFixed(2));
+ jQuery("#accelerometer-y").html(motion.accelerationIncludingGravity.y.toFixed(2));
+ jQuery("#accelerometer-z").html(motion.accelerationIncludingGravity.z.toFixed(2));
+ jQuery("#accelerometer-alpha").val(Number(motion.orientation.alpha).toFixed(2));
+ jQuery("#accelerometer-beta").val(Number(motion.orientation.beta).toFixed(2));
+ jQuery("#accelerometer-gamma").val(Number(motion.orientation.gamma).toFixed(2));
+ }, this);
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/ContactName', function (require, exports, module) {
+define('ripple/ui/plugins/push', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (formatted, familyName, givenName, middleName, honorificPrefix, honorificSuffix) {
- return {
- formatted: formatted,
- familyName: familyName,
- givenName: givenName,
- middleName: middleName,
- honorificPrefix: honorificPrefix,
- honorificSuffix: honorificSuffix
- };
+var constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ PUSH_OPTIONS = constants.PUSH.OPTIONS;
+
+function _updatePushPanel(ports) {
+ var portsSelect = document.getElementById("port-select"),
+ currentPort = portsSelect.value;
+
+ portsSelect.innerHTML = "";
+
+ ports.forEach(function (port) {
+ portsSelect.appendChild(utils.createElement("option", {
+ innerText: port,
+ value: port,
+ selected: currentPort === port
+ }));
+ });
+}
+
+module.exports = {
+ panel: {
+ domId: "push-container",
+ collapsed: true,
+ pane: "left"
+ },
+ initialize: function () {
+ event.on("PushListenersChanged", function (listeners) {
+ _updatePushPanel(listeners);
+ jQuery("#port-select").effect("highlight", {color: "#62B4C8"}, 1000);
+ });
+
+ _updatePushPanel([]);
+
+ document.getElementById("push-send")
+ .addEventListener("click", function () {
+ var port = document.getElementById("port-select").value,
+ text = document.getElementById(PUSH_OPTIONS.PAYLOAD).value,
+ pushData = {
+ headerField: ["21f39092"],
+ requestURI: "/",
+ source: "ripple",
+ isChannelEncrypted: false,
+ payload: text
+ };
+
+ event.trigger("Push", [pushData, port], true);
+ }, false);
+
+ utils.bindAutoSaveEvent(jQuery("#" + PUSH_OPTIONS.PAYLOAD), function () {
+ db.save(PUSH_OPTIONS.PAYLOAD, document.getElementById(PUSH_OPTIONS.PAYLOAD).value);
+ });
+
+ document.getElementById(PUSH_OPTIONS.PAYLOAD).value = db.retrieve(PUSH_OPTIONS.PAYLOAD) || "My payload data";
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/ContactOrganization', function (require, exports, module) {
+define('ripple/ui/plugins/accelerometer', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright (c) 2010 Epic Train Hack
+ * Copyright (c) 2011 Research In Motion Limited
+ * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
*
- * 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
+ * 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:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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 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.
*/
-module.exports = function (pref, type, name, dept, title) {
- return {
- pref: pref || null,
- type: type || null,
- name: name || null,
- department: dept || null,
- title: title || null
+var ui = require('ripple/ui'),
+ goodVibrations = require('ripple/ui/plugins/goodVibrations'),
+ accelerometer = require('ripple/accelerometer'),
+ event = require('ripple/event'),
+ Rotation = require('ripple/platform/w3c/1.0/Rotation'),
+ Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
+ _mouseDown,
+ _shiftKeyDown,
+ _offsets = {
+ x: 0,
+ y: 0,
+ z: -9.81,
+ },
+ _oldX,
+ _oldY,
+ _oldAlphaX,
+ _shape =
+ //
+ // The front side
+ //
+ // x, y, z x, y, z x, y, z
+ // for some strange reason for y -100 is top, 100 is bottom
+ "-30,30,10, 30,30,10, 30,60,10, 100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
+ "-30,30,10, 30,60,10, -30,60,10, 100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
+ // front side "the phone display"
+ "-20,-50,11, 20,-50,11, 20,20,11, 100,100,100,-1,0;" +
+ "-20,-50,11, 20,20,11, -20,20,11, 100,100,100,-1,0;" +
+ // below the display
+ "-30,30,10, 30,20,10, 30,30,10, 0,0,0,-1,0;" +
+ "-30,30,10, -30,20,10, 30,20,10, 0,0,0,-1,0;" +
+ // above the display
+ "-30,-60,10, 30,-60,10, 30,-50,10, 0,0,0,-1,0;" +
+ "-30,-60,10, 30,-50,10, -30,-50,10, 0,0,0,-1,0;" +
+ // left of the display
+ "-30,-50,10, -20,-50,10, -20,20,10, 0,0,0,-1,0;" +
+ "-30,-50,10, -20,20,10, -30,20,10, 0,0,0,-1,0;" +
+ // right of the display
+ "20,-50,10, 30,-50,10, 30,20,10, 0,0,0,-1,0;" +
+ "20,-50,10, 30,20,10, 20,20,10, 0,0,0,-1,0;" +
+
+
+ // back side, opposite side to the above one
+ "-30,-60,-10, 30,60,-10, 30,-60,-10, 0,0,0,-1,0;" +
+ "-30,-60,-10, -30,60,-10, 30,60,-10, 0,00,-1,0;" +
+ // right side
+ "30,-60,-10, 30,60,-10, 30,60,10, 50,50,80,-1,0;" +
+ "30,-60,-10, 30,60,10, 30,-60,10, 50,50,80,-1,0;" +
+ // left side
+ "-30,-60,-10, -30,60,10, -30,60,-10, 50,50,80,-1,0;" +
+ "-30,-60,-10, -30,-60,10, -30,60,10, 50,50,80,-1,0;" +
+
+ // top
+ "30,-60,-10, -30,-60,10, -30,-60,-10, 50,80,50,-1,0;" +
+ "30,-60,-10, 30,-60,10, -30,-60,10, 50,80,50,-1,0;" +
+ // bottom
+ "30,60,-10, -30,60,-10, -30,60,10, 80,50,50,-1,0;" +
+ "30,60,-10, -30,60,10, 30,60,10, 80,50,50,-1,0";
+
+function _shakeDevice() {
+ window.setTimeout(goodVibrations.shakeDevice(8), 1);
+ accelerometer.shake();
+}
+
+function _updateAccelerometerPanel(motion) {
+ jQuery("#accelerometer-x").html(Math.round(motion.accelerationIncludingGravity.x * 100) / 100);
+ jQuery("#accelerometer-y").html(Math.round(motion.accelerationIncludingGravity.y * 100) / 100);
+ jQuery("#accelerometer-z").html(Math.round(motion.accelerationIncludingGravity.z * 100) / 100);
+ jQuery("#accelerometer-alpha").html(Math.round(motion.orientation.alpha));
+ jQuery("#accelerometer-beta").html(Math.round(motion.orientation.beta));
+ jQuery("#accelerometer-gamma").html(Math.round(motion.orientation.gamma));
+}
+
+function _updateCanvas(a, b, g) {
+ ThreeDee.loadMesh(_shape);
+ g = g || 0;
+ ThreeDee.rotate(0, g, 0);
+ ThreeDee.rotate(b, 0, a);
+ ThreeDee.backface();
+ ThreeDee.shade();
+ ThreeDee.zSort();
+ Draw.initialize(document.querySelector("#accelerometer-canvas"));
+ Draw.clear(0, 0, 480, 300);
+ Draw.drawScene(ThreeDee.getTranslation(), 3);
+}
+
+function _createCanvas() {
+ var node = document.querySelector("#accelerometer-canvas"),
+ x = 0, y = 0, z = -9.81,
+ alpha = 0, beta = 0, gamma = 0,
+ cosX, sinX, cosY, sinY,
+ deltaAlpha = 360;
+
+ ThreeDee.setCenter(150, 100);
+ ThreeDee.setLight(-300, -300, 800);
+
+ node.addEventListener("mousemove", function (e) {
+ if (!_mouseDown)
+ return;
+
+ if (!_shiftKeyDown) {
+ _offsets.x = (_offsets.x + _oldX - e.offsetX) % 360;
+ _offsets.y = (_offsets.y + _oldY - e.offsetY) % 360;
+
+ alpha = alpha || 0;
+
+ // enforce gamma in [-90,90] as per w3c spec
+ gamma = -_offsets.x;
+ if (gamma < -90) {
+ gamma = -90;
+ }
+ if (gamma > 90) {
+ gamma = 90;
+ }
+
+ // enforce beta in [-180,180] as per w3c spec
+ beta = -_offsets.y % 360;
+ if (beta < -180) {
+ beta += 360;
+ }
+ else if (beta >= 180) {
+ beta -= 360;
+ }
+
+ cosX = Math.cos((gamma) * (Math.PI / 180));
+ sinX = Math.sin((gamma) * (Math.PI / 180));
+ cosY = Math.cos((beta) * (Math.PI / 180));
+ sinY = Math.sin((beta) * (Math.PI / 180));
+ x = 9.81 * cosY * sinX;
+ y = -9.81 * sinY;
+ z = -9.81 * cosY * cosX;
+
+ }
+ else {
+ deltaAlpha = (deltaAlpha - (_oldAlphaX - e.offsetX) * 2.5) % 360;
+ alpha = (360 - deltaAlpha) % 360;
+ }
+
+ _oldX = e.offsetX;
+ _oldY = e.offsetY;
+ _oldAlphaX = e.offsetX;
+
+ _updateCanvas(deltaAlpha, -beta, gamma);
+ accelerometer.setInfo({
+ x: x,
+ y: y,
+ z: z,
+ alpha: alpha,
+ beta: beta,
+ gamma: gamma
+ });
+
+ });
+
+ node.addEventListener("mousedown", function (e) {
+ _oldX = e.offsetX;
+ _oldY = e.offsetY;
+ if (_shiftKeyDown) {
+ _oldAlphaX = _oldX;
+ }
+ _mouseDown = true;
+ });
+
+ node.addEventListener("mouseup", function (e) {
+ _mouseDown = false;
+ });
+
+ node.addEventListener("dblclick", function (e) {
+ x = 0;
+ y = 0;
+ z = -9.81;
+ alpha = 0;
+ beta = 0;
+ gamma = 0;
+ deltaAlpha = 360;
+ _resetAccelerometer();
+ });
+
+ document.addEventListener("mouseup", function (e) {
+ //Catch mouseup events that fire when outside canvas bounds
+ _mouseDown = false;
+ });
+
+ document.addEventListener("keydown", function (e) {
+ if (e.keyCode === 16) { // Shift Key
+ _shiftKeyDown = true;
+ }
+ });
+
+ document.addEventListener("keyup", function (e) {
+ if (e.keyCode === 16) { // Shift Key
+ _shiftKeyDown = false;
+ }
+ });
+}
+
+function _resetAccelerometer() {
+ _updateCanvas(0, 0);
+ _oldX = 0;
+ _oldY = 0;
+ _oldAlphaX = 0;
+ _offsets = {
+ x: 0,
+ y: 0,
+ z: -9.81,
};
+ accelerometer.setInfo({
+ acceleration: new Acceleration(0, 0, 0),
+ accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
+ rotationRate: new Rotation(0, 0, 0),
+ orientation: new Rotation(0, 0, 0),
+ timestamp: new Date().getTime()
+ });
+}
+
+module.exports = {
+ panel: {
+ domId: "accelerometer-container",
+ collapsed: true,
+ pane: "left",
+ titleName: "Accelerometer",
+ display: true
+ },
+ initialize: function () {
+ _createCanvas();
+
+ _resetAccelerometer();
+
+ _updateAccelerometerPanel(accelerometer.getInfo());
+
+ jQuery("#accelerometer-shake").click(_shakeDevice);
+
+ event.on("AccelerometerInfoChangedEvent", _updateAccelerometerPanel, this);
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/DisplayDeviceAttributes', function (require, exports, module) {
+define('ripple/ui/plugins/phone', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (orientation, brightness, contrast, blanked, dotsPerInchW, dotsPerInchH, physicalWidth, physicalHeight, info) {
- return {
- orientation: orientation,
- brightness: brightness,
- contrast: contrast,
- blanked: blanked,
- dotsPerInchW: dotsPerInchW,
- dotsPerInchH: dotsPerInchH,
- physicalWidth: physicalWidth,
- physicalHeight: physicalHeight,
- info: info
- };
+var utils = require('ripple/utils'),
+ Phone = require('ripple/platform/webworks.handset/2.0.0/client/Phone'),
+ CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
+ event = require('ripple/event'),
+ _console = require('ripple/console'),
+ eventSelect = document.getElementById("phone-event-types"),
+ eventErrorContainer = document.getElementById("phone-event-error-container"),
+ eventErrorSelect = document.getElementById("phone-event-error-types");
+
+function _firePhoneLogEvents(type, number, error) {
+ if (type === Phone.CB_CALL_INITIATED ||
+ type === Phone.CB_CALL_ANSWERED) {
+ event.trigger("PhoneCallLogAdded", [{
+ date: new Date(),
+ number: number,
+ status: CallLog.STATUS_NORMAL,
+ type: CallLog.TYPE_RECEIVED_CALL
+ }], true);
+ } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
+ type === Phone.CB_CALL_FAILED) {
+ event.trigger("PhoneCallLogAdded", [{
+ date: new Date(),
+ number: number,
+ status: CallLog.STATUS_NORMAL,
+ type: CallLog.TYPE_PLACED_CALL
+ }], true);
+ }
+}
+
+function _updateActiveCalls(type, number, error) {
+ if (type === Phone.CB_CALL_INITIATED ||
+ type === Phone.CB_CALL_CONNECTED ||
+ type === Phone.CB_CALL_CONFERENCECALL_ESTABLISHED ||
+ type === Phone.CB_CALL_DIRECTCONNECT_CONNECTED ||
+ type === Phone.CB_CALL_ANSWERED) {
+ event.trigger("PhoneCallInitiated", [{
+ id: number,
+ onhold: false,
+ outgoing: false,
+ recipient: {
+ name: "",
+ number: String(number)
+ }
+ }], true);
+ } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
+ type === Phone.CB_CALL_FAILED ||
+ type === Phone.CB_CALL_DISCONNECTED ||
+ type === Phone.CB_CONFERENCECALL_DISCONNECTED ||
+ type === Phone.CB_CALL_DIRECTCONNECT_DISCONNECTED) {
+ event.trigger("PhoneCallEnded", [{
+ id: number
+ }], true);
+ }
+}
+
+module.exports = {
+ panel: {
+ domId: "phone-container",
+ collapsed: true,
+ pane: "right"
+ },
+ initialize: function (prev, baton) {
+ utils.forEach(Phone, function (value, prop) {
+ if (prop.match(/^CB_/)) {
+ eventSelect.appendChild(utils.createElement("option", {
+ value: value,
+ innerHTML: prop.replace(/^CB_(CALL_)?/, "")
+ }));
+ }
+
+ if (prop.match(/^CALL_ERROR_/)) {
+ eventErrorSelect.appendChild(utils.createElement("option", {
+ value: value,
+ innerHTML: prop.replace(/^CALL_ERROR_/, "")
+ }));
+ }
+ });
+
+ document.getElementById("phone-event-types").addEventListener("change", function () {
+ eventErrorContainer.setAttribute("style", parseInt(eventSelect.value, 10) === Phone.CB_CALL_FAILED ? "" : "display: none");
+ });
+
+ document.getElementById("phone-logs-clear").addEventListener("click", function () {
+ event.trigger("PhoneCallLogReset");
+ });
+
+ document.getElementById("phone-event-send").addEventListener("click", function () {
+ var type = parseInt(eventSelect.value, 10),
+ error = type === Phone.CB_CALL_FAILED ? eventErrorSelect.value : undefined,
+ callId = document.getElementById("phone-call-id").value;
+
+ _firePhoneLogEvents(type, callId, error);
+ _updateActiveCalls(type, callId, error);
+
+ event.trigger("PhoneEvent", [type, callId, error]);
+
+ _console.log("Fired PhoneEvent (type " + type + ") CallID: " +
+ callId + (error ? (" (error type " + error + ")") : ""));
+ }, false);
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/InputDevicesAttributes', function (require, exports, module) {
+define('ripple/ui/plugins/HWKeys', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (info, id, pointingDevices, activePointingDevices, keyboards, activeKeyboards, cameras, activeCameras, microphones, activeMicrophones) {
- return {
- info: info,
- id: id,
- pointingDevices: pointingDevices,
- activePointingDevices: activePointingDevices,
- keyboards: keyboards,
- activeKeyboards: activeKeyboards,
- cameras: cameras,
- activeCameras: activeCameras,
- microphones: microphones,
- activeMicrophones: activeMicrophones
- };
+var db = require('ripple/db'),
+ event = require('ripple/event');
+
+
+function initHWKey() {
+ var left = 0,
+ orientation = db.retrieve('deviceOrientation'),
+ scaleFactor = db.retrieve('deviceScaleFactor');
+
+ if (orientation === 'portrait') {
+ if (db.retrieve("layout") === "portrait") {
+ left = 350 + $('#device-layout').width()*scaleFactor;
+ } else {
+ left = 470 + $('#device-layout').height()*scaleFactor;
+ }
+ } else {
+ if (db.retrieve("layout") === "portrait") {
+ left = 490 + $('#device-layout').height()*scaleFactor;
+ } else {
+ left = 350 + $('#device-layout').width()*scaleFactor;
+ }
+ }
+
+ $("#hwkeys-panel").css("top", "40px");
+ $("#hwkeys-panel").css("left", left+"px");
+ $("#hwkeys-panel").draggable({ cursor: 'move', containment: [0, 52, 1480, 800]});
+
+ jQuery("#hwkey-menu-btn").bind("click", function () {
+ event.trigger("tizenhwkeyEvent", ["menu"], true);
+ });
+ jQuery("#hwkey-back-btn").bind("click", function () {
+ event.trigger("tizenhwkeyEvent", ["back"], true);
+ });
+}
+
+module.exports = {
+ initialize: function () {
+ initHWKey();
+ }
};
});
-define('ripple/platform/phonegap/1.0.0/KeyboardAttributes', function (require, exports, module) {
+define('ripple/ui/plugins/panelCollapse', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (type, isHardware, info) {
- return {
- type: type,
- isHardware: isHardware,
- info: info
- };
-};
+// TODO: could use a bit of refactoring sugar
+var db = require('ripple/db'),
+ constants = require('ripple/constants'),
+ _LEFT_PANEL_COLLAPSE = ".left-panel-collapse",
+ _RIGHT_PANEL_COLLAPSE = ".right-panel-collapse",
+ _LEFT_PANEL = ".left",
+ _RIGHT_PANEL = ".right",
+ _SAVE_KEY = "panel-collapsed",
+ platform = require('ripple/platform'),
+ devices = require('ripple/devices'),
+ _leftEngaged, _rightEngaged, _store;
-});
-define('ripple/platform/phonegap/1.0.0/MicrophoneAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (type, freqRangeLow, freqRangeHigh, info, name, types) {
- return {
- type: type,
- freqRangeLow: freqRangeLow,
- freqRangeHigh: freqRangeHigh,
- info: info,
- name: name,
- types: types
- };
-};
+$(function () {
+ $(window).resize(function () {
+ var windowHeight = $(window).height();
+ jQuery(".PanelCollapseBar").css("top", windowHeight - 56);
+ jQuery("#left_div").css("height", $(window).height() - 21);
+ if (_store["left"] === true) {
+ jQuery("#middle_div").css("width", $(window).width());
+ } else {
+ jQuery("#middle_div").css("width", $(window).width());
+ }
+ });
});
-define('ripple/platform/phonegap/1.0.0/NetworkAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, activeConnections) {
- return {
- info: info,
- id: id,
- activeConnections: activeConnections || []
- };
-};
-});
-define('ripple/platform/phonegap/1.0.0/NetworkStatus', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- NOT_REACHABLE: 0,
- REACHABLE_VIA_CARRIER_DATA_NETWORK: 1,
- REACHABLE_VIA_WIFI_NETWORK: 2
-};
-});
-define('ripple/platform/phonegap/1.0.0/OutputDevicesAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, displayDevices, activeDisplayDevices, printingDevices, activePrintingDevice, brailleDevices, activeBrailleDevice, audioDevices, activeAudioDevices) {
- return {
- info: info,
- id: id,
- displayDevices: displayDevices,
- activeDisplayDevices: activeDisplayDevices,
- printingDevices: printingDevices,
- activePrintingDevice: activePrintingDevice,
- brailleDevices: brailleDevices,
- activeBrailleDevice: activeBrailleDevice,
- audioDevices: audioDevices,
- activeAudioDevices: activeAudioDevices
- };
-};
+function _persist() {
+ db.saveObject(_SAVE_KEY, _store);
+}
-});
-define('ripple/platform/phonegap/1.0.0/PhoneGap', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- available: true
-};
-});
-define('ripple/platform/phonegap/1.0.0/PointerAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (type, supportsMultiTouch, info) {
- return {
- type: type,
- supportsMultiTouch: supportsMultiTouch,
- info: info
- };
-};
+function updateZoomingValues(value, origin) {
+ var scaleFactor = value / 100, scaleString;
+ scaleString = "scale(" + scaleFactor + ")";
+ jQuery('#device-layout').css('-webkit-transform', scaleString);
+ if (origin === "center") {
+ jQuery('#device-layout').css('-webkit-transform-origin', 'center top');
+ } else {
+ jQuery('#device-layout').css('-webkit-transform-origin', 'left top');
+ }
+}
-});
-define('ripple/platform/phonegap/1.0.0/PowerAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, level, timeRemaining, isBattery, isCharging) {
- return {
- info: info,
- id: id,
- level: level,
- timeRemaining: timeRemaining,
- isBattery: isBattery,
- isCharging: isCharging
- };
-};
-});
-define('ripple/platform/phonegap/1.0.0/PrintingDeviceAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (type, resolution, color, info) {
- return {
- type: type,
- resolution: resolution,
- color: color,
- info: info
- };
-};
+function _process(collapseNode, panelNode, side, callback) {
+ var jNode = collapseNode.children("span"),
+ jPanelNode = jQuery(panelNode),
+ properties = {},
+ collapseProperties = {},
+ options = {
+ duration: 600,
+ complete: callback
+ },
+ oldIcon, newIcon,
+ zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING);
-});
-define('ripple/platform/phonegap/1.0.0/SensorAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (value, min, max, normalizedValue) {
- return {
- value: value,
- min: min,
- max: max,
- normalizedValue: normalizedValue
- };
-};
+ if (_store[side] === true) {
+ _store[side] = false;
+
+ if (side === "left") {
+ jQuery('#left_div').show("fast");
+ collapseNode.removeClass("PanelCollapseBarCollapsed");
+ collapseNode.addClass("PanelCollapseBar");
+ collapseNode.children().remove();
+ collapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
+ collapseNode.css("top", $(window).height() - 56);
+ collapseNode.css("left", 0);
+ jQuery("#middle_div").css("width", $(window).width());
+ updateZoomingValues(zoomingValue, "left");
+ }
+ oldIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");
+ newIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");
-});
-define('ripple/platform/phonegap/1.0.0/StorageUnitAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, type, isWritable, capacity, availableCapacity, isRemoveable) {
- return {
- info: info,
- id: id,
- type: type,
- isWritable: isWritable,
- capacity: capacity,
- availableCapacity: availableCapacity,
- isRemoveable: isRemoveable
- };
-};
+ properties[side] = "0px";
+ collapseProperties[side] = "345px";
+ properties.opacity = "1";
-});
-define('ripple/platform/phonegap/1.0.0/SystemInfoOptions', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (highThreshold, lowThreshold, thresholdTarget, timeout, id) {
- return {
- highThreshold: highThreshold,
- lowThreshold: lowThreshold,
- thresholdTarget: thresholdTarget,
- timeout: timeout,
- id: id
- };
-};
+ if (jQuery("#device-layout").position().left < 290 ) {
+ jQuery("#device-layout").animate({left: "350px"}, 200 );
+ }
+ } else {
+ _store[side] = true;
+
+ if (side === "left") {
+ collapseNode.removeClass("PanelCollapseBar");
+ collapseNode.addClass("PanelCollapseBarCollapsed");
+ collapseNode.children().remove();
+ collapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
+ collapseNode.css("top", 10);
+ collapseNode.css("left", 0);
+ collapseNode.css("margin-left", 0);
+ jQuery('#left_div').hide("slow");
+ jQuery("#middle_div").css("width", $(window).width());
+ updateZoomingValues(zoomingValue, "left");
+ }
-});
-define('ripple/platform/phonegap/1.0.0/ThermalAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, state) {
- return {
- info: info,
- id: id,
- state: state
- };
-};
+ oldIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");
+ newIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");
-});
-define('ripple/platform/phonegap/1.0.0/VideoCodecAttributes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (info, id, compFormats, containerFormats, hwAccel, profiles, frameTypes, rateTypes) {
- return {
- info: info,
- id: id,
- compFormats: compFormats,
- containerFormats: containerFormats,
- hwAccel: hwAccel,
- profiles: profiles,
- frameTypes: frameTypes,
- rateTypes: rateTypes
- };
-};
+ properties[side] = "-340px";
+ collapseProperties[side] = "5px";
+ properties.opacity = "0.1";
+ }
-});
-define('ripple/platform/phonegap/1.0.0/accelerometer', function (require, exports, module) {
-/*
- * Copyright 2011 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 Acceleration = require('ripple/platform/phonegap/1.0.0/Acceleration'),
- utils = require('ripple/utils'),
- event = require('ripple/event'),
- _accelerometerInfo = new Acceleration(),
- _watches = {},
- self;
+ jNode.removeClass(oldIcon).addClass(newIcon);
-module.exports = self = {
- getCurrentAcceleration: function (onSuccess, onError) {
- // TODO: implement error call if accelerometer is not available, to be driven by behaviours?
+ jPanelNode.animate(properties, options);
+ _persist();
+}
- if (typeof onSuccess === "function") {
- setTimeout(function () {
- // TODO: build facility to trigger onError() from emulator
- // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
- onSuccess(utils.copy(_accelerometerInfo));
- }, 1);
- }
+module.exports = {
+ initialize: function () {
+ var rightCollapseNode = jQuery(_RIGHT_PANEL_COLLAPSE),
+ leftCollapseNode = jQuery(_LEFT_PANEL_COLLAPSE),
+ device = devices.getCurrentDevice(),
+ zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING),
+ deviceNode = jQuery("#device-layout");
+
+ _store = db.retrieveObject(_SAVE_KEY) || {
+ left: false,
+ right: false
+ };
- },
+ jQuery("#left_div").css("height", $(window).height() - 21);
+ jQuery("#middle_div").css("width", $(window).width());
- watchAcceleration: function (accelerometerSuccess, accelerometerError, accelerometerOptions) {
- var watchId = (new Date()).getTime().toString(),
- watchObj = {};
+ jQuery("#device-container").bind("mousedown", function () {
+ jQuery("#device-maskmask").show();
+ });
+ jQuery("#device-container").bind("mouseup", function () {
+ jQuery("#device-maskmask").hide();
+ });
- if (accelerometerOptions &&
- accelerometerOptions.frequency && typeof
- accelerometerOptions.frequency === "number" &&
- accelerometerOptions.frequency === Math.floor(accelerometerOptions.frequency)) {
+ jQuery("#deviceTitleBar").bind("mousedown", function () {
+ jQuery("#device-maskmask").show();
+ });
- watchObj = {
- onSuccess: accelerometerSuccess,
- onError: accelerometerError,
- interval: accelerometerOptions.frequency
- };
+ jQuery("#deviceTitleBar").bind("mouseup", function () {
+ jQuery("#device-maskmask").hide();
+ });
- _watches[watchId] = watchObj;
+ deviceNode.draggable({ cursor: 'move', handle: "#deviceTitleBar", containment: [0, 52, 1280, 800]});
+ jQuery("#deviceTitle").text(device.name);
+ if (_store.left === true) {
+ jQuery(_LEFT_PANEL).css({
+ left: "-340px",
+ opacity: "0.1"
+ });
- _watches[watchId].intervalId = setInterval(function () {
- self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
- }, accelerometerOptions.frequency);
+ leftCollapseNode.removeClass("PanelCollapseBar");
+ leftCollapseNode.addClass("PanelCollapseBarCollapsed");
+ leftCollapseNode.children().remove();
+ leftCollapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
+ leftCollapseNode.css("top", 10);
+ leftCollapseNode.css("left", 0);
+ leftCollapseNode.css("margin-left", 0);
+ jQuery('#left_div').hide();
+ jQuery("#device-layout").css("left", "21px");
+ updateZoomingValues(zoomingValue, "left");
+ } else {
+ jQuery('#left_div').show("fast");
+ leftCollapseNode.removeClass("PanelCollapseBarCollapsed");
+ leftCollapseNode.addClass("PanelCollapseBar");
+ leftCollapseNode.children().remove();
+ leftCollapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
+ leftCollapseNode.css("top", $(window).height() - 56);
+ leftCollapseNode.css("left", 0);
+ jQuery("#device-layout").css("left", "350px");
+ updateZoomingValues(zoomingValue, "left");
+ }
- }
- else {
- if (typeof accelerometerError === "function") {
- setTimeout(function () {
- accelerometerError();
- }, 1);
- }
+ if (_store.right === true) {
+ jQuery(_RIGHT_PANEL).css({
+ right: "-340px",
+ opacity: "0.1"
+ });
+
+ rightCollapseNode.css({
+ right: "5px"
+ }).children("span").removeClass("ui-icon-arrowthick-1-e").addClass("ui-icon-arrowthick-1-w");
}
- return watchId;
- },
+ leftCollapseNode.bind("click", function () {
+ if (!_leftEngaged) {
+ _leftEngaged = true;
+ _process(leftCollapseNode, _LEFT_PANEL, "left", function () {
+ _leftEngaged = false;
+ });
+ }
+ });
- clearWatch: function (watchId) {
- clearInterval(_watches[watchId].intervalId);
+ rightCollapseNode.bind("click", function () {
+ if (!_rightEngaged) {
+ _rightEngaged = true;
+ _process(rightCollapseNode, _RIGHT_PANEL, "right", function () {
+ _rightEngaged = false;
+ });
+ }
+ });
}
};
-event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
- _accelerometerInfo.x = accelerometerInfo.accelerationIncludingGravity.x / 9.8;
- _accelerometerInfo.y = accelerometerInfo.accelerationIncludingGravity.y / 9.8;
- _accelerometerInfo.z = accelerometerInfo.accelerationIncludingGravity.z / 9.8;
- _accelerometerInfo.timestamp = (new Date()).getTime();
-});
-
});
-define('ripple/platform/phonegap/1.0.0/camera', function (require, exports, module) {
+define('ripple/ui/plugins/eulaCheck', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- getPicture: function (cameraSuccess, cameraError, cameraOptions) {
- if (cameraError) {
- cameraError.apply(null, ["not implemented"]);
- }
- else {
- throw "not implemented";
- }
- }
-};
+var utils = require('ripple/utils'),
+ bus = require('ripple/bus');
-});
-define('ripple/platform/phonegap/1.0.0/compass', function (require, exports, module) {
-/*
- * Copyright 2011 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 geo = require('ripple/geo');
+function _initializeEulaCheck() {
+ var width = jQuery(document).width(),
+ p = (width / 2) - 277;
-function _getHeading() {
- return geo.getPositionInfo().heading;
+
+ $(".eula-window").show();
+ $(".eula-dialog").show().css({left: p + "px"});
+
+ $("#eula-accept").click(function () {
+ bus.send("acceptEula", null, function (result) {
+ $(".eula-window").hide();
+ $(".eula-dialog").hide();
+ });
+ });
+
+ $("#eula-decline").click(function () {
+ bus.send("disable", null, null);
+ });
}
module.exports = {
- getCurrentHeading: function (compassSuccess, compassError, compassOptions) {
- setTimeout(function () {
- compassSuccess(_getHeading());
- }, 1);
- },
- watchHeading: function (compassSuccess, compassError, compassOptions) {
- compassOptions = compassOptions || {};
- return setInterval(function () {
- compassSuccess(_getHeading());
- }, compassOptions.frequency || 100);
- },
- clearWatch: function (watchId) {
- clearInterval(watchId);
+ initialize: function () {
+ //HACK: there has to be a better way!!!
+ if ($("#extension-url").val().match(/geelfhphabnejjhdalkjhgipohgpdnoc/)) {
+ // do nothing, extension was installed from the Chrome Store
+ return;
+ }
+
+ bus.send("checkEula", null, function (response) {
+ console.log("eula response: ", response);
+ if (response === false) {
+ _initializeEulaCheck();
+ }
+ });
}
};
});
-define('ripple/platform/phonegap/1.0.0/contacts', function (require, exports, module) {
+define('ripple/ui/plugins/platformEvents', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var Contact = require('./Contact'),
- ContactName = require('./ContactName'),
- ContactError = require('./ContactError'),
- ContactField = require('./ContactField'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
+var _console = require('ripple/console'),
+ platform = require('ripple/platform'),
event = require('ripple/event'),
- _defaultContacts =
- [{
- "id": Math.uuid(undefined, 16),
- "name": new ContactName("Brent Lintner"),
- "displayName": "Brent Lintner",
- "emails": [new ContactField("work", "brent@tinyhippos.com", false)]
- }, {
- "id": Math.uuid(undefined, 16),
- "name": new ContactName("PJ Lowe"),
- "displayName": "PJ Lowe",
- "emails": [new ContactField("work", "pj@tinyhippos.com", false)]
- }, {
- "id": Math.uuid(undefined, 16),
- "name": new ContactName("Dan Silivestru"),
- "displayName": "Dan Silivestru",
- "emails": [new ContactField("work", "dan@tinyhippos.com", false)]
- }, {
- "id": Math.uuid(undefined, 16),
- "name": new ContactName("Gord Tanner"),
- "displayName": "Gord Tanner",
- "emails": [new ContactField("work", "gord@tinyhippos.com", true)]
- }, {
- "id": Math.uuid(undefined, 16),
- "name": new ContactName("Mark McArdle"),
- "displayName": "Mark McArdle",
- "emails": [new ContactField("work", "mark@tinyhippos.com", false)]
- }],
- self;
-
-function _error(callback, code, msg) {
- var e = new ContactError();
- e.code = code;
- e.message = msg;
- window.setTimeout(function () {
- callback(e);
- }, 1);
-}
-
-
-function _getContacts() {
- return db.retrieveObject("phonegap-contacts") ||
- _defaultContacts.map(function (person) {
- var contact = new Contact();
- contact.updated = new Date();
- utils.forEach(person, function (value, prop) {
- contact[prop] = value;
- });
-
- return contact;
- });
-}
-
-function _saveContacts(contacts) {
- db.saveObject("phonegap-contacts", contacts);
-}
-
-function _filtered(compare, options) {
- // this could be done a lot better..
- var found = false;
- if (!options.filter || options.filter === "") {
- found = true;
- } else if (typeof compare === "string" &&
- compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
- found = true;
- } else if (typeof compare === "object" || compare instanceof Array) {
- utils.forEach(compare, function (value) {
- if (!found) {
- found = _filtered(value, options);
- }
- });
- }
- return found;
-}
-
-event.on("phonegap-contact-save", function (contactProperties, success, error) {
- var contacts = _getContacts(),
- existsIndex = contacts.reduce(function (result, value, index) {
- return value.id === contactProperties.id ? index : result;
- }, -1),
- contact = existsIndex >= 0 ? contacts[existsIndex] : new Contact();
-
- utils.mixin(contactProperties, contact);
- if (existsIndex < 0) {
- contacts.push(contact);
- }
- _saveContacts(contacts);
- success(contact);
-});
+ exception = require('ripple/exception'),
+ utils = require('ripple/utils');
-event.on("phonegap-contact-remove", function (id, success, error) {
- if (!id) {
- _error(error, ContactError.NOT_FOUND_ERROR, "id is falsy (" + id + ")");
- } else {
- var contacts = _getContacts(),
- toDelete = contacts.reduce(function (result, current, index) {
- return current.id === id ? index : result;
- }, -1);
+module.exports = {
+ panel: {
+ domId: "platform-events-container",
+ collapsed: true,
+ pane: "right",
+ titleName: "Platform Events",
+ display: true
+ },
+ initialize: function () {
+ var eventSelect = document.getElementById("platform-events-select"),
+ spec = platform.current();
- if (toDelete >= 0) {
- contacts.splice(toDelete, 1);
- _saveContacts(contacts);
- success();
- } else {
- _error(error, ContactError.NOT_FOUND_ERROR, "could not find contact with id (" + id + ")");
+ if (!spec.events) {
+ return;
}
- }
-});
-self = module.exports = {
- create: function (properties) {
- var contact = new Contact();
- utils.forEach(properties, function (value, key) {
- contact[key] = value;
+ utils.forEach(spec.events, function (method, name) {
+ eventSelect.appendChild(utils.createElement("option", {
+ "innerText": name,
+ "value": name
+ }));
});
- return contact;
- },
- find: function (fields, success, error, options) {
- var foundContacts = [],
- tempContact = self.create(),
- contacts = _getContacts(),
- errorFlag = false;
-
- options = options || {};
- // not a fan of error handling at the moment
- if (!fields || !("forEach" in fields)) {
- errorFlag = true;
- _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing contact fields array");
- return;
- }
+ jQuery("#platform-events-fire").click(function () {
+ var eventName = document.getElementById("platform-events-select").value,
+ args = spec.events[eventName].args ? document.getElementById("platform-events-args").value : null,
+ callback = spec.events[eventName].callback;
- // handle special case of ["*"] to return all fields
- if (fields.length === 1 && fields[0] === "*") {
- fields = utils.map(tempContact, function (v, k) {
- return k;
- });
- }
+ _console.log("fired event => " + eventName);
- fields.forEach(function (prop) {
- if (!(tempContact.hasOwnProperty(prop))) {
- errorFlag = true;
- _error(error, ContactError.INVALID_ARGUMENT_ERROR, "invalid contact field (" + prop + ")");
+ try {
+ callback(args);
+ } catch (e) {
+ exception.throwMaskedException(e);
}
});
- if (typeof success !== "function" && !errorFlag) {
- errorFlag = true;
- _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing success callback");
- }
-
- if (errorFlag) {
- return;
- }
-
- if (fields.length > 0) {
- contacts.forEach(function (contact, index) {
- var newContact = utils.copy(contact);
+ jQuery(eventSelect).change(function () {
+ var argsSelect = jQuery("#platform-events-args"),
+ args = spec.events[this.value].args;
- if (options && (!_filtered(contact, options) ||
- options.updatedSince && contact.updated && contact.updated.getTime() < options.updatedSince.getTime())) {
- return;
- }
+ argsSelect.empty();
- utils.forEach(newContact, function (value, prop) {
- if (typeof newContact[prop] !== "function" && prop !== "id" &&
- !fields.some(function (field) {
- return field === prop;
- })) {
- delete newContact[prop];
- }
+ if (args) {
+ utils.forEach(spec.events[this.value].args, function (arg, index) {
+ argsSelect.append(utils.createElement("option", {
+ innerText: arg,
+ value: index
+ }));
});
- foundContacts.push(newContact);
- });
- }
-
- window.setTimeout(function () {
- // TODO: don't loop over entire db just to slice the array
- if (options.multiple === false) {
- foundContacts = foundContacts.splice(0, 1);
+ argsSelect.show();
+ } else {
+ argsSelect.hide();
}
- success(foundContacts);
- }, 1);
+ });
}
};
});
-define('ripple/platform/phonegap/1.0.0/device', function (require, exports, module) {
+define('ripple/ui/themes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self = {},
- event = require('ripple/event'),
- devices = require('ripple/devices');
-
-
-event.on("HardwareKey", function (key) {
- event.trigger("HardwareKeyDefault", [key]);
-});
-
-_self.__defineGetter__("name", function () {
- return devices.getCurrentDevice().name;
-});
-
-_self.__defineGetter__("platform", function () {
- return devices.getCurrentDevice().osName;
-});
-
-_self.__defineGetter__("uuid", function () {
- return devices.getCurrentDevice().uuid;
-});
-
-_self.__defineGetter__("version", function () {
- return devices.getCurrentDevice().osVersion;
-});
-
-_self.phonegap = "placeholder string";
-
-module.exports = _self;
+//module.exports = ["dark", "light"];
+module.exports = ["light"];
});
-define('ripple/platform/phonegap/1.0.0/map', function (require, exports, module) {
+define('ripple/xhr', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var constants = require('ripple/constants'),
+ utils = require('ripple/utils'),
+ ui = require('ripple/ui'),
+ helpers = require('ripple/xhr/helpers'),
+ XHR = window.XMLHttpRequest;
+
module.exports = {
- show: function () {
- throw "not implemented";
+ initialize: function (previous, baton) {
+ window.XMLHttpRequest = require('ripple/xhr/base');
+
+ if (helpers.proxyEnabled() && !ui.registered("omnibar")) {
+ var isFileScheme = utils.location().protocol.match(/^file:/);
+ window.XMLHttpRequest = require(isFileScheme ? 'ripple/xhr/jsonp' : 'ripple/xhr/cors');
+ }
}
};
});
-define('ripple/platform/phonegap/1.0.0/navigator', function (require, exports, module) {
+define('ripple/sensorSettings', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var nav = require('ripple/platform/w3c/1.0/navigator'),
- event = require('ripple/event'),
- _console = require('ripple/console'),
- utils = require('ripple/utils'),
- emulatorBridge = require('ripple/emulatorBridge'),
- _self = {};
+var _PERSISTENCE_KEY = "sensorsettings",
+ db = require('ripple/db'),
+ platform = require('ripple/platform'),
+ _currentSensorSettings = {},
+ _self;
-event.on("TinyHipposLoaded", function () {
- var doc = emulatorBridge.document(),
- evt = doc.createEvent("Events");
- evt.initEvent("deviceready", true, true);
- doc.dispatchEvent(evt);
- _console.log("fired deviceready event!");
-});
+function _default(key) {
+ var keys = key.split("."),
+ defaults = platform.current().sensor;
-utils.mixin(nav, _self);
+ if (keys.length === 1)
+ return defaults[key];
-module.exports = _self;
+ return keys.length === 2 &&
+ defaults[keys[0]] &&
+ defaults[keys[0]][keys[1]] &&
+ defaults[keys[0]][keys[1]].control ?
+ defaults[keys[0]][keys[1]].control.value : undefined;
+}
-});
-define('ripple/platform/phonegap/1.0.0/network', function (require, exports, module) {
-/*
- * Copyright 2011 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 deviceSettings = require('ripple/deviceSettings'),
- _self = {
- connection: {
+_self = {
+ initialize: function () {
+ _currentSensorSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
+ },
+ register: function (key, obj) {
+ _currentSensorSettings[key] = obj;
+ },
+
+ persist: function (key, obj) {
+ if (key) {
+ _currentSensorSettings[key] = obj;
}
- };
-_self.connection.__defineGetter__("type", function () {
- return deviceSettings.retrieve("NetworkStatus.connectionType");
-});
+ db.saveObject(_PERSISTENCE_KEY, _currentSensorSettings);
+ },
+
+ retrieve: function (key) {
+ return _currentSensorSettings.hasOwnProperty(key) ?
+ _currentSensorSettings[key] : _default(key);
+ },
+
+ retrieveAsInt: function (key) {
+ return parseInt(_self.retrieve(key), 10);
+ },
+
+ retrieveAsBoolean: function (key) {
+ return !!_self.retrieve(key);
+ }
+};
module.exports = _self;
});
-define('ripple/platform/phonegap/1.0.0/notification', function (require, exports, module) {
+define('ripple/utils', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var notifications = require('ripple/notifications'),
+var self,
+ exception = require('ripple/exception'),
constants = require('ripple/constants'),
- _console = require('ripple/console'),
- ui = require('ripple/ui'),
- goodVibrations = require('ripple/ui/plugins/goodVibrations');
+ _HtmlElements = ['header', 'footer', 'section', 'aside', 'nav', 'article'];
-module.exports = {
- alert: function (message, title, buttonName) {
- notifications.openNotification("normal", message);
- },
+self = module.exports = {
+ validateNumberOfArguments: function (lowerBound, upperBound, numberOfArguments, customExceptionType, customExceptionMessage, customExceptionObject) {
- beep: function (times) {
- for (var i = times; i > 0; i--) {
- _console.log("beep!");
+ customExceptionMessage = customExceptionMessage || "";
+
+ if (arguments.length < 3 || arguments.length > 6) {
+ exception.raise(exception.types.Argument, "Wrong number of arguments when calling: validateNumberOfArguments()");
}
- notifications.openNotification("normal", "BEEP x " + times);
+
+ if (isNaN(lowerBound) && isNaN(upperBound) && isNaN(numberOfArguments)) {
+ exception.raise(exception.types.ArgumentType, "(validateNumberOfArguments) Arguments are not numbers");
+ }
+
+ lowerBound = parseInt(lowerBound, 10);
+ upperBound = parseInt(upperBound, 10);
+ numberOfArguments = parseInt(numberOfArguments, 10);
+
+ if (numberOfArguments < lowerBound || numberOfArguments > upperBound) {
+ exception.raise((customExceptionType || exception.types.ArgumentLength), (customExceptionMessage + "\n\nWrong number of arguments"), customExceptionObject);
+ }
+
},
- vibrate: function (milliseconds) {
- milliseconds = milliseconds || 500;
- goodVibrations.vibrateDevice(milliseconds);
+ validateArgumentType: function (arg, argType, customExceptionType, customExceptionMessage, customExceptionObject) {
+ var invalidArg = false,
+ msg;
+
+ switch (argType) {
+ case "array":
+ if (!arg instanceof Array) {
+ invalidArg = true;
+ }
+ break;
+ case "date":
+ if (!arg instanceof Date) {
+ invalidArg = true;
+ }
+ break;
+ case "integer":
+ if (typeof arg === "number") {
+ if (arg !== Math.floor(arg)) {
+ invalidArg = true;
+ }
+ }
+ else {
+ invalidArg = true;
+ }
+ break;
+ default:
+ if (typeof arg !== argType) {
+ invalidArg = true;
+ }
+ break;
+ }
+
+ if (invalidArg) {
+ msg = customExceptionMessage + ("\n\nInvalid Argument type. argument: " + arg + " ==> was expected to be of type: " + argType);
+ exception.raise((customExceptionType || exception.types.ArgumentType), msg, customExceptionObject);
+ }
+ },
+
+ validateMultipleArgumentTypes: function (argArray, argTypeArray, customExceptionType, customExceptionMessage, customExceptionObject) {
+ for (var i = 0; i < argArray.length; i++) {
+ this.validateArgumentType(argArray[i], argTypeArray[i], customExceptionType, customExceptionMessage, customExceptionObject);
+ }
+ },
+
+ createElement: function (elementType, attributes) {
+ var d = document.createElement(elementType);
+
+ if (attributes) {
+ this.forEach(attributes, function (attributeValue, attributeName) {
+
+ switch (attributeName.toLowerCase()) {
+
+ case "innerhtml":
+ d.innerHTML = attributeValue;
+ break;
+
+ case "innertext":
+ d.innerText = attributeValue;
+ break;
+
+ default:
+ d.setAttribute(attributeName, attributeValue);
+ }
+
+ });
+ }
+
+ return d;
+ },
+
+
+ loadHTMLElements: function () {
+ for (var i = 0; i < _HtmlElements.length; i += 1) {
+ document.createElement(_HtmlElements[i]);
+ }
+ },
+
+ getAllStylesheetRules: function getAllStylesheetRules(title) {
+ this.validateNumberOfArguments(1, 1, arguments.length);
+
+ var i, x, sheet, rules, styles_array = [];
+
+ // get style sheet according to title
+ for (i = 0; i < document.styleSheets.length; i += 1) {
+
+ sheet = document.styleSheets[i];
+ rules = sheet.cssRules;
+
+ if (rules) {
+ for (x = 0; x < rules.length; x += 1) {
+ if (rules[x].selectorText && rules[x].selectorText === (title.toString())) {
+ styles_array.push(rules[x]);
+ }
+ }
+ }
+ }
+
+ return (styles_array);
+ },
+
+ location: function () {
+ return window.location;
+ },
+
+ queryString: function () {
+ // trim the leading ? and split each name=value
+ var args = this.location().search.replace(/^\?/, '').split('&');
+
+ return args.reduce(function (obj, value) {
+ if (value) {
+ value = value.toLowerCase().split("=");
+ obj[value[0]] = value[1];
+ }
+ return obj;
+ }, {});
+ },
+
+ extensionUrl: function () {
+ return document.getElementById("extension-url").innerText;
+ },
+
+ appLocation: function () {
+ if (require('ripple/ui').registered("omnibar")) {
+ /* rootURL can only get url saved from 'FrameHistoryChange' event
+ it causes trouble when navigating directory through online
+ version as index.html is automatically loaded.
+ Need a way to get more updated URL */
+
+ var path = require('ripple/ui/plugins/omnibar').rootURL(),
+ parts;
+
+ if ((parts = path.match(/^((http[s]?|ftp|file):\/\/)(.+\/)?([^\/].+)$/i)) !== null && parts.length === 5) {
+ // this is a path already.
+ if (path.search(/\/$/, "") !== -1) {
+ return path;
+ }
+ if (parts[4] === "about:blank") {
+ path = "";
+ }
+ else if (parts[3]) {
+ path = parts[1] + parts[3];
+ if (parts[4].indexOf(".") === -1) {
+ path += parts[4] + "/";
+ }
+ }
+ else {
+ path = parts[1] + parts[4] + "/";
+ }
+ }
+ else {
+ path = "";
+ }
+ return path;
+ }
+ return self.rippleLocation();
+ },
+
+ rippleLocation: function () {
+ var loc = self.location(),
+ parts = loc.pathname.replace(/\/$/, "").split("/"),
+ base = "",
+ port = loc.port ? ":" + loc.port : "";
+
+ if (parts[parts.length - 1].indexOf(".") !== -1) {
+ parts = parts.splice(0, parts.length - 1);
+ }
+ base = parts.join("/");
+
+ return loc.protocol + "//" + loc.hostname + port + base + "/";
+ },
+
+ arrayContains: function (array, obj) {
+ var i = array.length;
+ while (i--) {
+ if (array[i] === obj) {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ some: function (obj, predicate, scope) {
+ if (obj instanceof Array) {
+ return obj.some(predicate, scope);
+ }
+ else {
+ var values = self.map(obj, predicate, scope);
+
+ return self.reduce(values, function (some, value) {
+ return value ? value : some;
+ }, false);
+ }
+ },
+
+ count: function (obj) {
+ return self.sum(obj, function (total) {
+ return 1;
+ });
+ },
+
+ sum: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (total, value) {
+ return total + value;
+ });
+ },
+
+ max: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (max, value) {
+ return max < value ? value : max;
+ }, Number.MIN_VALUE);
+ },
+
+ min: function (obj, selector, scope) {
+ var values = self.map(obj, selector, scope);
+ return self.reduce(values, function (min, value) {
+ return min > value ? value : min;
+ }, Number.MAX_VALUE);
+ },
+
+ forEach: function (obj, action, scope) {
+ if (obj instanceof Array) {
+ return obj.forEach(action, scope);
+ }
+ else {
+ self.map(obj, action, scope);
+ }
+ },
+
+ filter: function (obj, predicate, scope) {
+ if (obj instanceof Array) {
+ return obj.filter(predicate, scope);
+ }
+ else {
+ var result = [];
+ self.forEach(obj, function (value, index) {
+ if (predicate.apply(scope, [value, index])) {
+ result.push(value);
+ }
+
+ }, scope);
+
+ return result;
+ }
+ },
+
+ reduce: function (obj, func, init, scope) {
+ var i,
+ initial = init === undefined ? 0 : init,
+ result = initial;
+
+
+ if (obj instanceof Array) {
+ return obj.reduce(func, initial);
+ }
+ else if (obj instanceof NamedNodeMap) {
+ for (i = 0; i < obj.length; i++) {
+ result = func.apply(scope, [result, obj[i], i]);
+ }
+ }
+ else {
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ result = func.apply(scope, [result, obj[i], i]);
+ }
+ }
+ }
+
+ return result;
+
+ },
+
+ map: function (obj, func, scope) {
+ var i,
+ returnVal = null,
+ result = [];
+
+ if (obj instanceof Array) {
+ return obj.map(func, scope);
+ }
+ else if (obj instanceof NamedNodeMap) {
+ for (i = 0; i < obj.length; i++) {
+ returnVal = func.apply(scope, [obj[i], i]);
+ result.push(returnVal);
+ }
+ }
+ else {
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ returnVal = func.apply(scope, [obj[i], i]);
+ result.push(returnVal);
+ }
+ }
+ }
+
+ return result;
+ },
+
+ regexSanitize: function (regexString) {
+ return regexString.replace("^", "\\^")
+ .replace("$", "\\$")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ .replace("<", "\\<")
+ .replace("[", "\\[")
+ .replace("{", "\\{")
+ .replace(/\\/, "\\\\")
+ .replace("|", "\\|")
+ .replace(">", "\\>")
+ .replace(".", "\\.")
+ .replace("*", "\\*")
+ .replace("+", "\\+")
+ .replace("?", "\\?");
+ },
+
+ bindAutoSaveEvent: function (node, saveCallback) {
+ var oldSetTimeoutId,
+ jNode = jQuery(node);
+
+ jNode.bind("keyup", function (event) {
+ if (event.keyCode !== 9) {
+ clearTimeout(oldSetTimeoutId);
+ oldSetTimeoutId = window.setTimeout(function () {
+ saveCallback();
+ }, 500);
+ }
+ });
+ },
+
+ find: function (comparison, collection, startInx, endInx, callback) {
+ var results = [],
+ compare = function (s, pattern) {
+
+ if (typeof(s) !== "string" || pattern === null) {
+ return s === pattern;
+ }
+
+ var regex = pattern.replace(/\./g, "\\.")
+ .replace(/\^/g, "\\^")
+ .replace(/\*/g, ".*")
+ .replace(/\\\.\*/g, "\\*");
+
+ regex = "^".concat(regex, "$");
+
+ return !!s.match(new RegExp(regex, "i"));
+ };
+
+ self.forEach(collection, function (c) {
+ var match,
+ fail = false;
+
+ self.forEach(comparison, function (value, key) {
+ if (!fail && value !== undefined) {
+
+ if (compare(c[key], value)) {
+ match = c;
+ }
+ else {
+ fail = true;
+ match = null;
+ }
+ }
+ });
+
+ if (match) {
+ results.push(match);
+ }
+ });
+
+ if (callback) {
+ if (startInx === undefined) {
+ startInx = 0;
+ }
+ if (endInx === undefined) {
+ endInx = results.length;
+ }
+ if (startInx === endInx) {
+ endInx = startInx + 1;
+ }
+
+ callback.apply(null, [results.slice(startInx, endInx)]);
+ }
+ },
+
+ mixin: function (mixin, to) {
+ for (var prop in mixin) {
+ if (Object.hasOwnProperty.call(mixin, prop)) {
+ to[prop] = mixin[prop];
+ }
+ }
+ return to;
+ },
+
+ copy: function (obj) {
+ var i,
+ newObj = jQuery.isArray(obj) ? [] : {};
+
+ if (typeof obj === 'number' ||
+ typeof obj === 'string' ||
+ typeof obj === 'boolean' ||
+ obj === null ||
+ obj === undefined) {
+ return obj;
+ }
+
+ if (obj instanceof Date) {
+ return new Date(obj);
+ }
+
+ if (obj instanceof RegExp) {
+ return new RegExp(obj);
+ }
+
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (obj[i] && typeof obj[i] === "object") {
+ if (obj[i] instanceof Date) {
+ newObj[i] = obj[i];
+ }
+ else {
+ newObj[i] = self.copy(obj[i]);
+ }
+ }
+ else {
+ newObj[i] = obj[i];
+ }
+ }
+ }
+
+ return newObj;
+ },
+
+ navHelper: function () {
+ return {
+ getHeading: function (lat1, lon1, lat2, lon2) {
+ var dLon = this.rad(lon2 - lon1),
+ llat1 = this.rad(lat1),
+ llat2 = this.rad(lat2),
+ y = Math.sin(dLon) * Math.cos(llat2),
+ x = Math.cos(llat1) * Math.sin(llat2) - Math.sin(llat1) * Math.cos(llat2) * Math.cos(dLon);
+ return (this.deg(Math.atan2(y, x)) + 360) % 360;
+ },
+
+ getDistance: function (lat1, lon1, lat2, lon2) {
+ var dLat = this.rad(lat2 - lat1),
+ dLon = this.rad(lon2 - lon1),
+ a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.rad(lat1)) * Math.cos(this.rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2),
+ c = 2 * Math.asin(Math.sqrt(a)),
+ d = 6378100 * c;
+ return d;
+ },
+
+ simulateTravel: function (lat, lon, hdg, dist) {
+ var lat1 = this.rad(lat),
+ lon1 = this.rad(lon),
+ brng = this.rad(hdg),
+ angularDistance = dist / 6378100,
+ lat2 = Math.asin(Math.sin(lat1) * Math.cos(angularDistance) + Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(brng)),
+ lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angularDistance) * Math.cos(lat1), Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2));
+ lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // Normalise to -180..+180
+
+ return {
+ latitude: this.deg(lat2),
+ longitude: this.deg(lon2)
+ };
+ },
+
+ deg: function (num) {
+ return num * 180 / Math.PI;
+ },
+
+ rad: function (num) {
+ return num * Math.PI / 180;
+ }
+ };
+ },
+
+ getURIParams: function (uriString) {
+ var params = {};
+
+ uriString.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
+ params[key] = value;
+ });
+
+ return params;
}
};
});
-define('ripple/platform/phonegap/1.0.0/orientation', function (require, exports, module) {
+define('ripple/fs', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- currentOrientation: null,
- getCurrentOrientation: function (onSuccess, onFail) {
- throw "not implemented";
+var utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ _console = require('ripple/console'),
+ _self, _fs;
+
+function _map(array, callback) {
+ var map = [], i;
+ for (i = 0; i < array.length; i++) {
+ map[i] = callback(array[i], i);
+ }
+ return map;
+}
+
+function _resolveLocalFileSystemURL(path, success, error) {
+ return (window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL)(path, success, error);
+}
+
+function _blobBuilder() {
+ var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder;
+ return new BlobBuilder();
+}
+
+function _error(e) {
+ var msg = '';
+
+ switch (e.code) {
+ case FileError.QUOTA_EXCEEDED_ERR:
+ msg = 'QUOTA_EXCEEDED_ERR';
+ break;
+ case FileError.NOT_FOUND_ERR:
+ msg = 'NOT_FOUND_ERR';
+ break;
+ case FileError.SECURITY_ERR:
+ msg = 'SECURITY_ERR';
+ break;
+ case FileError.INVALID_MODIFICATION_ERR:
+ msg = 'INVALID_MODIFICATION_ERR';
+ break;
+ case FileError.INVALID_STATE_ERR:
+ msg = 'INVALID_STATE_ERR';
+ break;
+ default:
+ msg = 'Unknown Error';
+ break;
+ }
+
+ _console.log('FileSystem error: ' + msg);
+}
+
+_self = {
+ initialize: function (prev, baton) {
+ try {
+ var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+
+ if (requestFileSystem) {
+ baton.take();
+ }
+
+ requestFileSystem(window.TEMPORARY, constants.FS_SIZE, function (fs) {
+ _fs = fs;
+ event.trigger("FileSystemInitialized", null, true);
+ baton.pass();
+ }, _error);
+ }
+ catch (e) {
+ console.log("File System Not Available");
+ }
},
- watchOrientation: function () {
- throw "not implemented";
+
+ ls: function (path, success, error) {
+ path = path || "/";
+
+ _fs.root.getDirectory(path, {}, function (dirEntry) {
+ var dirReader = dirEntry.createReader();
+ dirReader.readEntries(function (entries) {
+ success(_map(entries, function (entry, index) {
+ return entry;
+ }));
+ }, error);
+ }, error);
+ },
+
+ rm: function (path, success, error, options) {
+ options = options || {};
+
+ _fs.root[options.recursive ? "getDirectory" : "getFile"](path, {create: false}, function (entry) {
+ entry[options.recursive ? "removeRecursively" : "remove"](function () {
+ success();
+ }, error);
+ }, error);
+ },
+
+ rmdir: function (path, success, error, options) {
+ options = options || {};
+
+ _fs.root.getDirectory(path, {create: false}, function (entry) {
+ entry.remove(function () {
+ success();
+ }, error);
+ }, error);
+ },
+
+ mkdir: function (path, success, error) {
+ _fs.root.getDirectory(path, {create: true}, function (dirEntry) {
+ success(dirEntry);
+ }, error);
+ },
+
+ mv: function (from, to, success, error) {
+ var path = to.replace(/^\//, "").split("/"),
+ fileName = path.splice(path.length - 1, 1).toString();
+
+ _self.stat(from, function (entry) {
+ _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
+ entry.moveTo(dest, fileName, function (finalDestination) {
+ success(finalDestination);
+ }, error);
+ }, error);
+ }, error);
+ },
+
+ touch: function (path, success, error) {
+ _fs.root.getFile(path, {create: true}, function (fileEntry) {
+ success(fileEntry);
+ }, error);
+ },
+
+ cp: function (from, to, success, error) {
+ var path = to.replace(/^\//, "").split("/"),
+ fileName = path.splice(path.length - 1, 1).toString();
+
+ _self.stat(from, function (entry) {
+ _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
+ entry.copyTo(dest, fileName, function (finalDestination) {
+ success(finalDestination);
+ }, error);
+ }, error);
+ }, error);
+ },
+
+ stat: function (path, success, error) {
+ var url = "filesystem:" + utils.location().origin + "/temporary/" + path;
+ _resolveLocalFileSystemURL(url, function (entry) {
+ success(entry);
+ }, error);
+ },
+
+ write: function (path, contents, success, error, options) {
+ options = options || {};
+
+ function write(entry) {
+ entry.createWriter(function (fileWriter) {
+ var bb = _blobBuilder();
+
+ fileWriter.onwriteend = function (progressEvent) {
+ success(entry);
+ };
+ fileWriter.onerror = error;
+
+ if (options.mode === "append") {
+ fileWriter.seek(fileWriter.length);
+ }
+
+ bb.append(contents);
+ fileWriter.write(bb.getBlob('text/plain'));
+ }, error);
+ }
+
+ _self.stat(path, function (entry) {
+ if (options.mode === "append") {
+ write(entry);
+ } else {
+ _self.rm(path, function () {
+ _self.touch(path, write, error);
+ }, error);
+ }
+ }, function (e) {
+ if (e.code === FileError.NOT_FOUND_ERR) {
+ _self.touch(path, write, error);
+ } else {
+ error(e);
+ }
+ });
+ },
+
+ read: function (path, success, error) {
+ _self.stat(path, function (entry) {
+ entry.file(function (file) {
+ var reader = new FileReader();
+
+ reader.onloadend = function (progressEvent) {
+ success(progressEvent.target.result);
+ };
+ reader.onerror = error;
+
+ reader.readAsText(file);
+ }, error);
+ }, error);
}
};
+module.exports = _self;
+
});
-define('ripple/platform/phonegap/1.0.0/service', function (require, exports, module) {
+define('ripple/geo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// for form, but could probably just delete
-module.exports = {};
+var db = require('ripple/db'),
+ exception = require('ripple/exception'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ _positionInfo = {
+ "latitude": 39.968362,
+ "longitude": 116.410186,
+ "altitude": 50,
+ "accuracy": 150,
+ "altitudeAccuracy": 80,
+ "heading": 0,
+ "speed": 0,
+ "cellID": 1130433
+ },
+ self;
+
+function _serialize(settings) {
+ var tempSettings = utils.copy(settings);
+ tempSettings.position.timeStamp = "new Date(" + tempSettings.position.timeStamp.getTime() + ")";
+ return tempSettings;
+}
+
+function _validatePositionInfo(pInfo) {
+ return (pInfo &&
+ !(isNaN(pInfo.latitude) ||
+ isNaN(pInfo.longitude) ||
+ isNaN(pInfo.altitude) ||
+ isNaN(pInfo.accuracy) ||
+ isNaN(pInfo.altitudeAccuracy) ||
+ isNaN(pInfo.heading) ||
+ isNaN(pInfo.speed) ||
+ isNaN(pInfo.cellID))) ? true : false;
+}
+
+self = module.exports = {
+ initialize: function () {
+ var settings = db.retrieveObject("geosettings");
+ if (settings) {
+ utils.forEach(_positionInfo, function (value, key) {
+ _positionInfo[key] = parseFloat(settings.position[key] || value);
+ });
+
+ self.timeout = settings.timeout;
+ self.delay = settings.delay || 0;
+
+ }
+ },
+
+ getPositionInfo: function () {
+ var pi = utils.copy(_positionInfo);
+ pi.timeStamp = new Date();
+
+ return pi;
+ },
+
+ updatePositionInfo: function (newPositionInfo, delay, timeout) {
+ if (!_validatePositionInfo(newPositionInfo)) {
+ exception.raise(exception.types.Geo, "invalid positionInfo object");
+ }
+
+ _positionInfo = utils.copy(newPositionInfo);
+ _positionInfo.timeStamp = new Date();
+
+ self.delay = delay || 0;
+ self.timeout = timeout;
+
+ db.saveObject("geosettings", _serialize({
+ position: _positionInfo,
+ delay: self.delay,
+ timeout: self.timeout
+ }));
+
+ event.trigger("PositionInfoUpdatedEvent", [_positionInfo]);
+ },
+
+ timeout: false,
+ delay: 0,
+ map: {}
+};
});
-define('ripple/platform/phonegap/1.0.0/sms', function (require, exports, module) {
+define('ripple/console', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- send: function () {
- throw "not implemented";
+var _self;
+
+function _log(msg, method) {
+ try {
+ console[method](_self.prefix ? _self.prefix + " :: " + msg : msg);
+ } catch (e) {
+ // silent
+ }
+}
+
+_self = {
+ log: function (msg) {
+ _log(msg, "log");
+ },
+
+ warn: function (msg) {
+ _log(msg, "warn");
+ },
+
+ error: function (msg) {
+ _log(msg, "error");
}
};
+module.exports = _self;
+
});
-define('ripple/platform/phonegap/1.0.0/spec/config', function (require, exports, module) {
+define('ripple/resizer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants');
+var db = require('ripple/db'),
+ exception = require('ripple/exception'),
+ utils = require('ripple/utils'),
+ devices = require('ripple/devices'),
+ constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ _win,
+ _doc,
+ _self;
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
- (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));
+function _validateLayoutType(layoutType) {
+ return (layoutType === "landscape" || layoutType === "portrait");
+}
- return valid;
+function _validateOrientation(orientation) {
+ return (orientation === "landscape" || orientation === "portrait");
+}
+
+function _getContainers() {
+ return {
+ device: {
+ div: document.getElementById("device-container"),
+ containerClass: document.getElementById("device-container").getAttribute("class") || ""
+ },
+ viewport: {
+ div: document.getElementById("viewport-container"),
+ containerClass: document.getElementById("viewport-container").getAttribute("class") || ""
+ },
+ "menu-button": {
+ div: document.getElementById(constants.COMMON.MENU_BUTTON),
+ containerClass: document.getElementById(constants.COMMON.MENU_BUTTON).getAttribute("class") || ""
+ },
+ "back-button": {
+ div: document.getElementById(constants.COMMON.BACK_BUTTON),
+ containerClass: document.getElementById(constants.COMMON.BACK_BUTTON).getAttribute("class") || ""
+ }
+ };
+}
+
+function _setContainers(containers, device, orientation) {
+ var suffix = {
+ portrait: "-wrapper" + (device.skin ? "-" + device.skin : ""),
+ landscape: "-wrapper-landscape" + (device.skin ? "-" + device.skin : "")
+ };
+
+ utils.forEach(containers, function (container, key) {
+ container.div.setAttribute("class", container.containerClass.replace(/\s.*$/, "") + " " + key + suffix[orientation]);
+ });
+}
+
+function _getDimensions(device, orientation) {
+ return {
+ deviceWidth: orientation === "portrait" ? device.screen.width : device.screen.height,
+ deviceHeight: orientation === "portrait" ? device.screen.height : device.screen.width,
+ paddingLeft: device.viewPort[orientation].paddingLeft,
+ paddingTop: device.viewPort[orientation].paddingTop,
+ viewPort: {
+ width: device.viewPort[orientation].width,
+ height: device.viewPort[orientation].height
+ }
+ };
+}
+
+function _formatSkin(containers, dimensions) {
+ var scaleFactor = dimensions.deviceWidth / dimensions.viewPort.width,
+ scaleString = "scale(" + scaleFactor + ")";
+
+ containers.device.div.style.width = (dimensions.deviceWidth + 4) + "px";
+ containers.device.div.style.height = (dimensions.deviceHeight + 4) + "px";
+ containers.viewport.div.style.width = dimensions.viewPort.width + "px";
+ containers.viewport.div.style.height = dimensions.viewPort.height + "px";
+ containers.viewport.div.style.padding = "0";
+
+ jQuery('#viewport-container').css('-webkit-transform', scaleString);
+ jQuery('#viewport-container').css('-webkit-transform-origin', 'left top');
+}
+
+function _setOrientation(layout) {
+ _win.orientation = window.orientation = layout === "portrait" ? 0 : 90;
+}
+
+function _upDateHWKeyPanelPosition(orientation, scaleFactor) {
+ var left = 0;
+
+ if (orientation === 'portrait') {
+ if (db.retrieve("layout") === "portrait") {
+ left = 350 + $('#device-layout').width()*scaleFactor;
+ } else {
+ left = 470 + $('#device-layout').height()*scaleFactor;
+ }
+ } else {
+ if (db.retrieve("layout") === "portrait") {
+ left = 490 + $('#device-layout').height()*scaleFactor;
+ } else {
+ left = 350 + $('#device-layout').width()*scaleFactor;
+ }
+ }
+
+ $("#hwkeys-panel").css("top", "40px");
+ $("#hwkeys-panel").css("left", left+"px");
+}
+
+function _getTransformString(orientation, scaleFactor) {
+ var transformString = "",
+ offset;
+
+ if (orientation === "landscape") {
+ if (db.retrieve("layout") === "portrait") {
+ offset = devices.getCurrentDevice().screen.height * scaleFactor + 170;
+ transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
+ } else {
+ transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
+ }
+ } else {
+ if (db.retrieve("layout") === "portrait") {
+ transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
+ } else {
+ offset = devices.getCurrentDevice().screen.width * scaleFactor + 150;
+ transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
+ }
+ }
+
+ return transformString;
+}
+
+
+_self = {
+ init: function (win, doc) {
+ _win = win;
+ _doc = doc;
+
+ var layout = db.retrieve("layout") || "portrait";
+
+ _setOrientation(layout);
+
+ _win.onorientationchange = undefined;
},
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
+ // TODO: redo/refactor this in general, seems bloated, also devices REQUIRE viewport schemas which they shouldnt
+ resize: function (device) {
+ var layout = db.retrieve("layout"),
+ orientation = "portrait",
+ containers, dimensions;
+
+ if (layout && layout === "landscape" && device.viewPort.landscape) {
+ orientation = "landscape";
}
- var widgetInfo = {};
+ containers = _getContainers();
+ _setContainers(containers, device, orientation);
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+ dimensions = _getDimensions(device, orientation);
+ if (!device.skin) {
+ _formatSkin(containers, dimensions);
+ }
- return widgetInfo;
+ event.trigger("ScreenChangeDimensions", [dimensions.viewPort.width, dimensions.viewPort.height]);
},
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:gap": {
- attributeName: "xmlns:gap",
- required: true,
- type: "list",
- listValues: ["http://phonegap.com/ns/1.0"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["floating", "fullscreen"]
- }
- },
- children: {
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "short": {
- attributeName: "short",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- email: {
- attributeName: "email",
- type: "regex",
- required: false,
- regex: constants.REGEX.EMAIL
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- encoding: {
- attributeName: "encoding",
- type: "string",
- required: false
- },
- type: {
- attributeName: "type",
- type: "string",
- required: false
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "list",
- required: true,
- listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
- "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
- "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
- "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
- "http://api.phonegap.com/1.0/storage"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- }
- },
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "string",
- required: true
- },
- value: {
- type: "string",
- attributeName: "value",
- required: false
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
- }
- }
+
+ changeLayoutType: function (layoutType) {
+ var orientation = db.retrieve("deviceOrientation") || "portrait";
+ if (!_validateLayoutType(layoutType)) {
+ exception.raise(exception.types.LayoutType, "unknown layout type requested!");
+ }
+
+ db.save("layout", layoutType);
+ _self.resize(devices.getCurrentDevice());
+ _self.rotateDevice(orientation);
+
+ if (!_win) return;
+ _setOrientation(layoutType);
+ },
+
+ scaleDevice: function (scaleFactor) {
+ var orientation = db.retrieve("deviceOrientation") || "portrait",
+ transformString = _getTransformString(orientation, scaleFactor);
+ _upDateHWKeyPanelPosition(orientation, scaleFactor);
+ db.save("deviceScaleFactor", scaleFactor);
+ jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
+ jQuery('#device-layout').css('-webkit-transform', transformString);
+ },
+
+ rotateDevice: function (orientation) {
+ if (!_validateOrientation(orientation)) {
+ exception.raise(exception.types.OrientationType, "unknown orientation type requested!");
+ }
+
+ db.save("deviceOrientation", orientation);
+ jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
+ jQuery('#device-layout').css('-webkit-transform',
+ _getTransformString(orientation, db.retrieve("deviceScaleFactor")));
+ _upDateHWKeyPanelPosition(orientation, db.retrieve("deviceScaleFactor"))
+ if (!_win) return;
+ if (_win.onorientationchange) {
+ _win.onorientationchange();
}
+
+ var evt = _doc.createEvent("Event");
+ evt.initEvent("orientationchange", true, true);
+ _win.dispatchEvent(evt);
}
};
+module.exports = _self;
+
});
-define('ripple/platform/phonegap/1.0.0/spec/device', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/BluetoothSocket', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
-module.exports = {
- "NetworkStatus": {
- "connectionType": {
- "name": "Connection Type",
- "control": {
- "type": "select",
- "value": "ethernet"
- },
- "options": {
- "unknown": "UNKNOWN",
- "ethernet": "ETHERNET",
- "wifi": "WIFI",
- "2g": "CELL_2G",
- "3g": "CELL_3G",
- "4g": "CELL_4G",
- "none": "none"
- },
- "callback": function (setting) {
- var connected = setting !== "none";
- require('ripple/bus').send("network", connected);
- }
- },
- "lag": {
- "name": "Lag the network",
- "control": {
- type: "checkbox",
- value: false
- },
- "callback": function (setting) {
- require('ripple/bus').send("lag", setting);
- }
- },
- }
-};
+var utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BluetoothSocket,
+ _security;
-});
-define('ripple/platform/phonegap/1.0.0/spec/events', function (require, exports, module) {
-function _fires(name, data) {
- return function () {
- var doc = require("ripple/emulatorBridge").document(),
- evt = doc.createEvent("Events");
+BluetoothSocket = function (prop) {
+ var bluetoothSocket = {}, buffer = [];
- evt.initEvent(name, true, false);
- doc.dispatchEvent(evt);
+ _security = prop.metaData;
+
+ bluetoothSocket.uuid = prop.uuid;
+ bluetoothSocket.state = prop.state;
+ bluetoothSocket.peer = prop.peer;
+ bluetoothSocket.onmessage = null;
+ bluetoothSocket.onclose = null;
+
+ this.__defineGetter__("uuid", function () {
+ return bluetoothSocket.uuid;
+ });
+
+ this.__defineGetter__("state", function () {
+ return bluetoothSocket.state;
+ });
+
+ this.__defineGetter__("peer", function () {
+ return bluetoothSocket.peer;
+ });
+
+ this.__defineGetter__("onmessage", function () {
+ return bluetoothSocket.onmessage;
+ });
+ this.__defineSetter__("onmessage", function (val) {
+ try {
+ bluetoothSocket.onmessage = t.SuccessCallback(val, "?");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("onclose", function () {
+ return bluetoothSocket.onclose;
+ });
+ this.__defineSetter__("onclose", function (val) {
+ try {
+ bluetoothSocket.onclose = t.SuccessCallback(val, "?");
+ } catch (e) {
+ }
+ });
+
+ this.writeData = function (data) {
+ if (!_security.writeData) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothSocket("writeData", arguments);
+
+ if (bluetoothSocket.state === "CLOSED") {
+ return;
+ }
+
+ event.trigger("bt-service-write-msg", [bluetoothSocket.peer.address,
+ bluetoothSocket.uuid, data]);
+
+ return data.length;
};
-}
-module.exports = {
- "deviceready": {
- callback: _fires("deviceready")
- },
- "backbutton": {
- callback: _fires("backbutton")
- },
- "menubutton": {
- callback: _fires("menubutton")
- },
- "pause": {
- callback: _fires("pause")
- },
- "resume": {
- callback: _fires("resume")
- },
- "searchbutton": {
- callback: _fires("searchbutton")
- },
- "online": {
- callback: _fires("online")
- },
- "offline": {
- callback: _fires("offline")
- }
+ this.readData = function () {
+ var data;
+
+ if (!_security.readData) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ if (bluetoothSocket.state === "CLOSED") {
+ return;
+ }
+
+ data = utils.copy(buffer);
+ buffer = [];
+
+ return data;
+ };
+
+ this.close = function () {
+ if (!_security.close) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ bluetoothSocket.state = "CLOSED";
+
+ event.trigger("bt-service-state-changed", [bluetoothSocket.peer.address,
+ bluetoothSocket.uuid, false]);
+ event.trigger("bt-device-connected-update",
+ [bluetoothSocket.peer.address, false]);
+
+ if (bluetoothSocket.onclose) {
+ bluetoothSocket.onclose();
+ }
+ };
+
+ event.on("bt-service-state-update", function (addr, state) {
+ var stateStr = "CLOSED";
+
+ if (addr !== bluetoothSocket.peer.address) {
+ return;
+ }
+ if (state) {
+ stateStr = "OPEN";
+ }
+
+ bluetoothSocket.state = stateStr;
+
+ event.trigger("bt-service-state-changed",
+ [bluetoothSocket.peer.address, bluetoothSocket.uuid,
+ state]);
+ event.trigger("bt-device-connected-update",
+ [bluetoothSocket.peer.address, state]);
+ });
+
+ event.on("bt-service-rawdata-received", function (addr, uuid, msg) {
+ var i;
+
+ if ((addr !== bluetoothSocket.peer.address) ||
+ (uuid !== bluetoothSocket.uuid)) {
+ return;
+ }
+ buffer = [];
+ for (i = 0; i < msg.length; i++) {
+ buffer.push(msg.charCodeAt(i));
+ }
+ if (bluetoothSocket.onmessage) {
+ bluetoothSocket.onmessage();
+ }
+ });
+
+ event.on("bt-device-connected-changed", function (addr, isConnected) {
+ bluetoothSocket.state = isConnected ? "OPEN" : "CLOSED";
+ });
};
+module.exports = BluetoothSocket;
+
});
-define('ripple/platform/phonegap/1.0.0/spec/ui', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/msg_utils', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- plugins: [
- "accelerometer",
- "deviceSettings",
- "geoView",
- "widgetConfig",
- "platformEvents"
- ]
-};
-
-});
-define('ripple/platform/phonegap/1.0.0/spec', function (require, exports, module) {
-module.exports = {
- id: "phonegap",
- version: "1.0.0",
- name: "PhoneGap",
- type: "platform",
- persistencePrefix: "phonegap-",
- config: require('ripple/platform/phonegap/1.0.0/spec/config'),
- device: require('ripple/platform/phonegap/1.0.0/spec/device'),
- ui: require('ripple/platform/phonegap/1.0.0/spec/ui'),
- events: require('ripple/platform/phonegap/1.0.0/spec/events'),
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
+ _TIZEN_MESSAGE_DB_KEY = "tizen_db_messages",
+ MessageElement = function (_type, _id) {
+ return {
+ type: _type,
+ id: _id,
+ msg: {},
+ conv: {}
+ };
+ },
- initialize: function () { },
+ _conversationCount = function (msg, cid, rst) {
+ var old_time = new Date(0), t;
- objects: {
- PhoneGap: {
- path: "phonegap/1.0.0/PhoneGap"
- },
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- Acceleration: {
- path: "phonegap/1.0.0/Acceleration"
- },
- navigator: {
- path: "phonegap/1.0.0/navigator",
- children: {
- accelerometer: {
- path: "phonegap/1.0.0/accelerometer"
- },
- geolocation: {
- path: "w3c/1.0/geolocation"
- },
- notification: {
- path: "phonegap/1.0.0/notification"
- },
- contacts: {
- path: "phonegap/1.0.0/contacts"
- },
- network: {
- path: "phonegap/1.0.0/network"
- },
- camera: {
- path: "phonegap/1.0.0/camera"
- },
- sms: {
- path: "phonegap/1.0.0/sms"
- },
- telephony: {
- path: "phonegap/1.0.0/telephony"
- },
- map: {
- path: "phonegap/1.0.0/map"
- },
- orientation: {
- path: "phonegap/1.0.0/orientation"
- },
- system: {
- path: "phonegap/1.0.0/system"
- },
- compass: {
- path: "phonegap/1.0.0/compass"
+ utils.forEach(msg.msg, function (o) {
+ if (o.priv.conversationId === cid &&
+ o.priv.messageStatus !== "DRAFT") {
+ rst.cnt += 1;
+ t = new Date(o.priv.timestamp);
+ if (t > old_time) {
+ rst.lastid = o.priv.id;
+ old_time = t;
+ }
+ if (o.isRead === false) {
+ rst.unread++;
}
}
- },
- ContactError: {
- path: "phonegap/1.0.0/ContactError"
- },
- Contact: {
- path: "phonegap/1.0.0/Contact"
- },
- ContactName: {
- path: "phonegap/1.0.0/ContactName"
- },
- ContactAccount: {
- path: "phonegap/1.0.0/ContactAccount"
- },
- ContactAddress: {
- path: "phonegap/1.0.0/ContactAddress"
- },
- ContactOrganization: {
- path: "phonegap/1.0.0/ContactOrganization"
- },
- ContactFindOptions: {
- path: "phonegap/1.0.0/ContactFindOptions"
- },
- ContactField: {
- path: "phonegap/1.0.0/ContactField"
- },
- NetworkStatus: {
- path: "phonegap/1.0.0/NetworkStatus"
- },
- device: {
- path: "phonegap/1.0.0/device"
- },
- SystemInfoOptions: {
- path: "phonegap/1.0.0/SystemInfoOptions"
- },
- PowerAttributes: {
- path: "phonegap/1.0.0/PowerAttributes"
- },
- CPUAttributes: {
- path: "phonegap/1.0.0/CPUAttributes"
- },
- ThermalAttributes: {
- path: "phonegap/1.0.0/ThermalAttributes"
- },
- NetworkAttributes: {
- path: "phonegap/1.0.0/NetworkAttributes"
- },
- Connection: {
- path: "phonegap/1.0.0/Connection"
- },
- ConnectionAttributes: {
- path: "phonegap/1.0.0/ConnectionAttributes"
- },
- SensorAttributes: {
- path: "phonegap/1.0.0/SensorAttributes"
- },
- AVCodecsAttributes: {
- path: "phonegap/1.0.0/AVCodecsAttributes"
- },
- AudioCodecAttributes: {
- path: "phonegap/1.0.0/AudioCodecAttributes"
- },
- VideoCodecAttributes: {
- path: "phonegap/1.0.0/VideoCodecAttributes"
- },
- StorageUnitAttributes: {
- path: "phonegap/1.0.0/StorageUnitAttributes"
- },
- InputDevicesAttributes: {
- path: "phonegap/1.0.0/InputDevicesAttributes"
- },
- OutputDevicesAttributes: {
- path: "phonegap/1.0.0/OutputDevicesAttributes"
- },
- DisplayDeviceAttributes: {
- path: "phonegap/1.0.0/DisplayDeviceAttributes"
- },
- AudioDeviceAttributes: {
- path: "phonegap/1.0.0/AudioDeviceAttributes"
- },
- PrintingDeviceAttributes: {
- path: "phonegap/1.0.0/PrintingDeviceAttributes"
- },
- BrailleDeviceAttributes: {
- path: "phonegap/1.0.0/BrailleDeviceAttributes"
- },
- PointerAttributes: {
- path: "phonegap/1.0.0/PointerAttributes"
- },
- KeyboardAttributes: {
- path: "phonegap/1.0.0/KeyboardAttributes"
- },
- CameraAttributes: {
- path: "phonegap/1.0.0/CameraAttributes"
- },
- MicrophoneAttributes: {
- path: "phonegap/1.0.0/MicrophoneAttributes"
+ });
+ },
+
+ _updateConversation = function (msg, cid) {
+ var privConv = {}, lastm, rst = {};
+
+ rst.cnt = 0;
+ rst.unread = 0;
+ rst.lastid = "";
+ _conversationCount(msg, cid, rst);
+ if (rst.cnt === 0) {
+ if (msg.conv[cid] !== undefined) {
+ delete msg.conv[cid];
+ }
+ return;
}
- }
+ lastm = msg.msg[rst.lastid];
-};
+ privConv.id = cid;
+ privConv.type = msg.type;
+ privConv.timestamp = new Date(lastm.priv.timestamp);
+ privConv.messageCount = rst.cnt;
+ privConv.unreadMessages = rst.unread;
+ privConv.preview = lastm.body.plainBody;
+ privConv.subject = lastm.subject;
+ privConv.isRead = lastm.isRead;
+ privConv.from = lastm.priv.from;
+ privConv.to = lastm.to.slice(0);
+ privConv.cc = lastm.cc.slice(0);
+ privConv.bcc = lastm.bcc.slice(0);
+ privConv.lastMessageId = rst.lastid;
+ msg.conv[cid] = privConv;
+ };
-});
-define('ripple/platform/phonegap/1.0.0/system', function (require, exports, module) {
module.exports = {
- get: function () {
- throw "not implemented";
+ conversationCount: _conversationCount,
+ setMsg: function (m, newm) {
+ if ((m.to === null) || (m.to === undefined)) {
+ newm.to = [];
+ } else {
+ if (tizen1_utils.isValidArray(m.to)) {
+ newm.to = m.to.slice(0);
+ } else {
+ return false;
+ }
+ }
+
+ if ((m.cc === null) || (m.cc === undefined)) {
+ newm.cc = [];
+ } else {
+ if (tizen1_utils.isValidArray(m.cc)) {
+ newm.cc = m.cc.slice(0);
+ } else {
+ return false;
+ }
+ }
+
+ if ((m.bcc === null) || (m.bcc === undefined)) {
+ newm.bcc = [];
+ } else {
+ if (tizen1_utils.isValidArray(m.bcc)) {
+ newm.bcc = m.bcc.slice(0);
+ } else {
+ return false;
+ }
+ }
+
+ if ((m.body === null) || (m.body === undefined)) {
+ if (m.htmlBody === null || m.htmlBody === undefined) {
+ m.htmlBody = "";
+ }
+ if (m.plainBody === null || m.plainBody === undefined) {
+ m.plainBody = "";
+ }
+ if (typeof m.plainBody !== 'string' || typeof m.htmlBody !== 'string') {
+ return false;
+ }
+ m.body = new MessageBody(null, true, m.plainBody, m.htmlBody, []);
+ } else {
+ if (typeof m.body.plainBody !== 'string' || typeof m.body.htmlBody !== 'string') {
+ return false;
+ }
+ m.body = new MessageBody(null, true, m.body.plainBody, m.body.htmlBody, []);
+ }
+ newm.body = utils.copy(m.body);
+
+ if (typeof m.isRead === 'boolean') {
+ newm.isRead = m.isRead;
+ } else {
+ newm.isRead = false;
+ }
+
+ if (typeof m.isHighPriority === 'boolean') {
+ newm.isHighPriority = m.isHighPriority;
+ } else {
+ newm.isHighPriority = false;
+ }
+
+ if ((m.subject === null) || (m.subject === undefined)) {
+ newm.subject = "";
+ } else {
+ newm.subject = String(m.subject);
+ }
+
+ if ((m.inResponseTo === null) || (m.inResponseTo === undefined)) {
+ newm.inResponseTo = null;
+ } else {
+ newm.inResponseTo = String(m.inResponseTo);
+ }
+
+ if ((m.attachments === null) || (m.attachments === undefined)) {
+ newm.attachments = [];
+ } else {
+ newm.attachments = utils.copy(m.attachments);
+ }
+ return true;
},
- has: function () {
- throw "not implemented";
+
+ loadMsg: function (type, id) {
+ var i, ret, msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || null;
+ if (msg === null) {
+ ret = new MessageElement(type, id);
+ } else {
+ for (i = 0; i < msg.length; i++) {
+ if (msg[i].type === type && msg[i].id === id) {
+ ret = msg[i];
+ break;
+ }
+ }
+ if (ret === undefined) {
+ ret = new MessageElement(type, id);
+ } else {
+ /* after getting Date out of DB, Date will become
+ a string, so need to recast it back to Date */
+ for (i in ret.msg) {
+ ret.msg[i].priv.timestamp = new Date(ret.msg[i].priv.timestamp);
+ }
+ }
+ }
+ return ret;
},
- monitor: function () {
- throw "not implemented";
- }
-};
-});
-define('ripple/platform/phonegap/1.0.0/telephony', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- send: function () {
- throw "not implemented";
- }
-};
+ delMsg: function (m) { // m is a PrivMessage
+ var i, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
+ if (_msg.length === 0) {
+ return;
+ } else {
+ for (i = 0; i < _msg.length; i++) {
+ if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
+ delete _msg[i].msg[m.priv.id];
+ if (m.priv.messageStatus !== "DRAFT") {
+ _updateConversation(_msg[i], m.priv.conversationId);
+ }
+ db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
+ return;
+ }
+ }
+ }
+ },
-});
-define('ripple/platform/spec', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- //"phonegap": {"1.0.0": require('ripple/platform/phonegap/1.0.0/spec')},
- "tizen": {"2.0": require('ripple/platform/tizen/2.0/spec')},
- "ivi": {"3.0": require('ripple/platform/ivi/3.0/spec')},
- //"cordova": {"2.0.0": require('ripple/platform/cordova/2.0.0/spec')},
- //"webworks.bb10": {"1.0.0": require('ripple/platform/webworks.bb10/1.0.0/spec')},
- //"webworks.handset": {"2.0.0": require('ripple/platform/webworks.handset/2.0.0/spec')},
- //"webworks.tablet": {"2.0.0": require('ripple/platform/webworks.tablet/2.0.0/spec')},
- //"web": {"default": require('ripple/platform/web/default/spec')},
+ saveMsg: function (m) { // m is a PrivMessage
+ var i, new_msg, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
+ if (_msg.length === 0) {
+ _msg = new MessageElement(m.priv.type, m.priv.serviceId);
+ _msg.msg[m.priv.id] = m;
+ if (m.priv.messageStatus !== "DRAFT") {
+ _updateConversation(_msg, m.priv.conversationId);
+ }
+ db.saveObject(_TIZEN_MESSAGE_DB_KEY, [_msg]);
+ } else {
+ for (i = 0; i < _msg.length; i++) {
+ if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
+ _msg[i].msg[m.priv.id] = m;
+ if (m.priv.messageStatus !== "DRAFT") {
+ _updateConversation(_msg[i], m.priv.conversationId);
+ }
+ db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
+ break;
+ }
+ }
+ if (i === _msg.length) {
+ new_msg = new MessageElement(m.priv.type, m.priv.serviceId);
+ new_msg.msg[m.priv.id] = m;
+ if (m.priv.messageStatus !== "DRAFT") {
+ _updateConversation(new_msg, m.priv.conversationId);
+ }
+ _msg.push(new_msg);
+ db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
+ }
+ }
+ },
- "get": function (name, version) {
- var platform = module.exports[name] || {};
- return (platform[version] || platform[Object.keys(platform)[0]]);
+ loadConv: function (type, id) {
+ var i, ret;
+ ret = this.loadMsg(type, id).conv;
+ for (i in ret) {
+ ret[i].timestamp = new Date(ret[i].timestamp);
+ }
+ return ret;
}
};
});
-define('ripple/platform/tizen/2.0/AccountBase', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-module.exports = function (appId, userName, displayName, service) {
- var _self,
- _id = Math.uuid(null, 16);
+var BluetoothClassDeviceMajor = function () {
+ this.__defineGetter__("MISC", function () {
+ return 0x00;
+ });
- _self = {
- appId : appId || "",
- userName : userName || "",
- displayName : displayName || "",
- service : service || {}
- };
+ this.__defineGetter__("COMPUTER", function () {
+ return 0x01;
+ });
- _self.__defineGetter__("id", function () {
- return _id;
+ this.__defineGetter__("PHONE", function () {
+ return 0x02;
});
- return _self;
-};
+ this.__defineGetter__("NETWORK", function () {
+ return 0x03;
+ });
-});
-define('ripple/platform/tizen/2.0/AccountService', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ this.__defineGetter__("AUDIO_VIDEO", function () {
+ return 0x04;
+ });
-module.exports = function (serviceName, serviceType, tag, displayName, icon, settings) {
- var _self,
- _id = Math.uuid(null, 16);
+ this.__defineGetter__("PERIPHERAL", function () {
+ return 0x05;
+ });
- _self = {
- serviceName : serviceName || "",
- serviceType : serviceType || "",
- displayName : displayName || null,
- icon : icon || null,
- settings : settings || null,
- tag : tag || []
- };
+ this.__defineGetter__("IMAGING", function () {
+ return 0x06;
+ });
- _self.__defineGetter__("id", function () {
- return _id;
+ this.__defineGetter__("WEARABLE", function () {
+ return 0x07;
});
- return _self;
+ this.__defineGetter__("TOY", function () {
+ return 0x08;
+ });
+
+ this.__defineGetter__("HEALTH", function () {
+ return 0x09;
+ });
+
+ this.__defineGetter__("UNCATEGORIZED", function () {
+ return 0x1F;
+ });
};
+module.exports = BluetoothClassDeviceMajor;
+
});
-define('ripple/platform/tizen/2.0/AlarmAbsolute', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/SyncServiceInfo', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
+var db = require('ripple/db'),
t = require('ripple/platform/tizen/2.0/typecast'),
- _byDayValue = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"],
- PERIOD_WEEK = (7 * 24 * 60 * 60), MILLI_SECOND = 1000,
- AlarmAbsolute;
-
-AlarmAbsolute = function () {
- var alarm, period = null, daysOfTheWeek = [], ascDays = [], voc, date;
+ SyncServiceInfo,
+ _accounts = {},
+ _counter = 0;
- function getScheduleDateByPeriod(current, date, period) {
- var diff = period * MILLI_SECOND,
- triggerDate = new Date(date);
+SyncServiceInfo = function (enable, serviceType, serverDatabaseUri, id,
+ password) {
+ var syncServiceInfo = {}, index;
- while (current > (triggerDate - MILLI_SECOND)) { // In advance 1s - MILLI_SECOND
- triggerDate.setTime(triggerDate.getTime() + diff);
- }
- return triggerDate;
+ function save() {
+ _accounts[index] = {
+ id: syncServiceInfo.id,
+ password: syncServiceInfo.password
+ };
+ db.saveObject("save-syncserviceinfo", _accounts);
}
- function getSchedulteDateByDay(current, triggerTime, startDay, endDay) {
- startDay = (7 + (endDay - startDay)) % 7;
- current.setHours(triggerTime.getHours());
- current.setMinutes(triggerTime.getMinutes());
- current.setSeconds(triggerTime.getSeconds());
- current.setMilliseconds(triggerTime.getMilliseconds());
- current.setDate(current.getDate() + startDay);
- return current;
- }
+ t.SyncServiceInfo(arguments, this);
- function getAscDays() { // Get asc order array
- for (var i in daysOfTheWeek) {
- ascDays.push(_byDayValue.lastIndexOf(daysOfTheWeek[i]));
- }
- return ascDays.sort();
- }
-
- /*
- * Return
- * true: A is bigger than B
- * false: otherwise
- */
- function compareTime(current, triggerTime) {
- var diff = current.getHours() - triggerTime.getHours();
- if (diff !== 0)
- return (diff > 0);
-
- diff = current.getMinutes() - triggerTime.getMinutes();
- if (diff !== 0)
- return (diff > 0);
-
- diff = current.getSeconds() - triggerTime.getSeconds();
- if (diff < -1) // Delay 1s
- return false;
-
- return true;
- }
-
- alarm = new AlarmBase(this);
-
- voc = [
- function (_date, _daysOfTheWeek) {
- date = _date;
- daysOfTheWeek = _daysOfTheWeek;
- period = PERIOD_WEEK;
- },
- function (_date, _period) {
- date = _date;
- period = _period;
- },
- function (_date) {
- date = _date;
- }
- ];
-
- t.AlarmAbsolute(arguments, this, voc);
-
- this.getNextScheduledDate = function () {
- var current = new Date(),
- diff, isPass, today, total, i, nextDate;
-
- diff = current - date;
- if (diff < -1000) // Advance 1s
- return date; // Before first trigger, return date
-
- if (period === null)
- return null;
-
- if (period !== PERIOD_WEEK)
- return getScheduleDateByPeriod(current, date, period); // Repeat by period
-
- today = current.getDay(); // 0~6
- ascDays = getAscDays();
- total = ascDays.length;
-
- if ((ascDays[0] <= today) && (today <= ascDays[total - 1])) { // Today out of ascDays
- for (i in ascDays) { // Today in ascDays
- if (ascDays[i] < today) {
- continue;
- } else if (ascDays[i] > today) {
- nextDate = ascDays[i];
- break;
- } else {
- isPass = compareTime(current, date); // Is triggerTime pass
- if (isPass) {
- nextDate = ascDays[(i < total - 1) ? (parseInt(i, 10) + 1) : 0];
- } else {
- nextDate = today;
- }
- break;
- }
- }
- } else {
- nextDate = ascDays[0];
- }
-
- return getSchedulteDateByDay(current, date, today, nextDate);
- };
-
- this.__defineGetter__("date", function () {
- return new Date(date);
- });
-
- this.__defineGetter__("period", function () {
- return period;
- });
-
- this.__defineGetter__("daysOfTheWeek", function () {
- return daysOfTheWeek;
- });
-};
-
-module.exports = AlarmAbsolute;
-
-});
-define('ripple/platform/tizen/2.0/AlarmBase', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 = function (self) {
- self = self || this;
-
- self.__defineGetter__("id", function () {
- return null;
- });
-};
-
-});
-define('ripple/platform/tizen/2.0/AlarmRelative', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- AlarmRelative;
-
-AlarmRelative = function (delay, period) {
- var alarm, date;
-
- t.AlarmRelative(arguments, this);
-
- alarm = new AlarmBase(this);
- period = period || null;
- date = new Date(); // Alarm settime
-
- this.getRemainingSeconds = function () {
- var current, diff, triggerDate, MILLI_SECOND = 1000;
- current = new Date();
- triggerDate = new Date(delay * MILLI_SECOND + date.getTime()); // First triggerDate
- diff = Math.round((triggerDate - current) / MILLI_SECOND);
-
- if (diff > 0) // Before first trigger
- return diff;
-
- if (period === null)
- return null; // Alarm is expired
-
- while (current - triggerDate >= 0) { // Trigger repeatly
- triggerDate = new Date(period * MILLI_SECOND + triggerDate.getTime());
- }
- diff = Math.round(((triggerDate - current) / MILLI_SECOND));
- return diff;
- };
-
- this.__defineGetter__("delay", function () {
- return delay;
- });
-
- this.__defineGetter__("period", function () {
- return period;
- });
-};
-
-module.exports = AlarmRelative;
-
-});
-define('ripple/platform/tizen/2.0/ApplicationControl', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- ApplicationControlData = require('ripple/platform/tizen/2.0/ApplicationControlData');
-
-var ApplicationControl = function (operation, uri, mime, category, data) {
- var applicationControl = {}, i;
-
- t.ApplicationControl(arguments, this);
-
- applicationControl.operation = operation;
- applicationControl.uri = uri || null;
- applicationControl.mime = mime || null;
- applicationControl.category = category || null;
- applicationControl.data = [];
-
- if (data) {
- for (i in data) {
- applicationControl.data[i] = new ApplicationControlData(data[i].key,
- data[i].value);
- }
- }
+ syncServiceInfo.enable = enable;
+ syncServiceInfo.serviceType = serviceType;
+ syncServiceInfo.serverDatabaseUri = serverDatabaseUri;
+ syncServiceInfo.id = id || null;
+ syncServiceInfo.password = password || null;
- this.__defineGetter__("operation", function () {
- return applicationControl.operation;
+ this.__defineGetter__("enable", function () {
+ return syncServiceInfo.enable;
});
- this.__defineSetter__("operation", function (val) {
+ this.__defineSetter__("enable", function (enable) {
try {
- applicationControl.operation = t.DOMString(val);
+ syncServiceInfo.enable = t.boolean(enable);
} catch (e) {
}
});
- this.__defineGetter__("uri", function () {
- return applicationControl.uri;
+ this.__defineGetter__("serviceType", function () {
+ return syncServiceInfo.serviceType;
});
- this.__defineSetter__("uri", function (val) {
+ this.__defineSetter__("serviceType", function (serviceType) {
try {
- applicationControl.uri = t.DOMString(val, "?");
+ syncServiceInfo.serviceType = t.SyncServiceType(serviceType);
} catch (e) {
}
});
- this.__defineGetter__("mime", function () {
- return applicationControl.mime;
+ this.__defineGetter__("serverDatabaseUri", function () {
+ return syncServiceInfo.serverDatabaseUri;
});
- this.__defineSetter__("mime", function (val) {
+ this.__defineSetter__("serverDatabaseUri", function (serverDatabaseUri) {
try {
- applicationControl.mime = t.DOMString(val, "?");
+ syncServiceInfo.serverDatabaseUri = t.DOMString(serverDatabaseUri);
} catch (e) {
}
});
- this.__defineGetter__("category", function () {
- return applicationControl.category;
+ this.__defineGetter__("id", function () {
+ return null;
});
- this.__defineSetter__("category", function (val) {
+ this.__defineSetter__("id", function (id) {
try {
- applicationControl.category = t.DOMString(val, "?");
+ syncServiceInfo.id = t.DOMString(id);
+ save();
} catch (e) {
}
});
- this.__defineGetter__("data", function () {
- return applicationControl.data;
+ this.__defineGetter__("password", function () {
+ return null;
});
- this.__defineSetter__("data", function (val) {
- var i;
-
+ this.__defineSetter__("password", function (password) {
try {
- t.ApplicationControlData(val, "[]");
- for (i in val) {
- applicationControl.data[i] = new ApplicationControlData(
- val[i].key, val[i].value);
- }
+ syncServiceInfo.password = t.DOMString(password);
+ save();
} catch (e) {
}
});
+
+ index = _counter++;
+ Object.defineProperty(this, "__syncServiceInfoID__", {
+ "configurable": false,
+ "enumerable": false,
+ "get": (function (_id_) {
+ return function () { return _id_; };
+ })(index)
+ });
+ save();
};
-module.exports = ApplicationControl;
+module.exports = SyncServiceInfo;
});
-define('ripple/platform/tizen/2.0/ApplicationControlData', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/systeminfo', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ApplicationControlData;
-
-ApplicationControlData = function (key, value) {
- var applicationControlData = {};
-
- t.ApplicationControlData(arguments, this);
-
- applicationControlData.key = key;
- applicationControlData.value = value;
+var deviceSettings = require('ripple/deviceSettings'),
+ db = require('ripple/db'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ typedef = require('ripple/platform/tizen/2.0/typedef'),
+ constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ tizen_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ SystemInfoDeviceCapability,
+ _systemInfoProperties = typedef.SystemInfoPropertyId,
+ _propertyMap = {}, // Object like: {"BATTERY": ["level", "isCharging"], ...}
+ _batteryEvent = ["BatteryLevelChanged", "BatteryChargingChanged"],
+ _watches = {},
+ _firstCall_watches = {},
+ _powerData = {},
+ _systemInfoDeviceCapability = null,
+ _security = {
+ "http://tizen.org/privilege/system": ["SystemInfoSIM", "webApiVersion",
+ "nativeApiVersion", "platformVersion"],
+ "http://tizen.org/privilege/systemmanager": ["NetworkImei"]
+ },
+ _self;
- this.__defineGetter__("key", function () {
- return applicationControlData.key;
- });
- this.__defineSetter__("key", function (val) {
- try {
- applicationControlData.key = t.DOMString(val);
- } catch (e) {
+function _prepareObj(obj, aspect, property, value) {
+ if ((aspect === "CELLULAR_NETWORK") && (property === "imei")) {
+ obj.__defineGetter__("imei", function () {
+ if (!_security.NetworkImei) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ return deviceSettings.retrieve("CELLULAR_NETWORK.imei");
+ });
+ } else {
+ if (aspect === "WIFI_NETWORK" || aspect === "CELLULAR_NETWORK") {
+ if (property === 'status') {
+ if (value === true) {
+ value = "ON";
+ } else {
+ value = "OFF";
+ }
+ }
}
- });
+ obj.__defineGetter__(property, function () {
+ return value;
+ });
+ }
+}
- this.__defineGetter__("value", function () {
- return applicationControlData.value;
- });
- this.__defineSetter__("value", function (val) {
- try {
- applicationControlData.value = t.DOMString(val, '[]');
- } catch (e) {
- }
- });
-};
+function _getValue(aspect, successCallback) {
+ var properties = [], value, index = 0, property, obj = {};
-module.exports = ApplicationControlData;
+ if ((aspect === "SIM") && !_security.SystemInfoSIM) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-});
-define('ripple/platform/tizen/2.0/AttributeFilter', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ if (aspect === "BATTERY") {
+ successCallback(_powerData);
+ return;
+ }
-var t = require('ripple/platform/tizen/2.0/typecast'),
- AttributeFilter;
+ properties = _propertyMap[aspect];
+ for (; index < properties.length; index++) {
+ property = properties[index];
+ value = deviceSettings.retrieve(aspect + "." + property);
+ _prepareObj(obj, aspect, property, value);
+ }
-AttributeFilter = function (attributeName, matchFlag, matchValue) {
- var attributeFilter = {};
+ if (aspect === "STORAGE") {
+ obj.__defineGetter__("units", function () {
+ return [obj];
+ });
+ }
- t.AttributeFilter(arguments, this);
+ successCallback(obj);
+}
- attributeFilter.attributeName = attributeName;
- attributeFilter.matchFlag = matchFlag || "EXACTLY";
- attributeFilter.matchValue = (matchFlag === "EXISTS") ? null :
- matchValue || null;
+function _initialize() {
+ var aspectName, index, i, vol;
- this.__defineGetter__("attributeName", function () {
- return attributeFilter.attributeName;
- });
- this.__defineSetter__("attributeName", function (val) {
- try {
- attributeFilter.attributeName = t.DOMString(val);
- } catch (e) {
+ for (index = 0; index < _systemInfoProperties.length; index++) {
+ aspectName = _systemInfoProperties[index];
+ _propertyMap[aspectName] = [];
+ for (i in deviceSettings.retrieve(aspectName)) {
+ _propertyMap[aspectName].push(i);
}
- });
+ }
- this.__defineGetter__("matchFlag", function () {
- return attributeFilter.matchFlag;
- });
- this.__defineSetter__("matchFlag", function (val) {
- try {
- attributeFilter.matchFlag = t.FilterMatchFlag(val);
- } catch (e) {
- }
- });
+ _propertyMap.BATTERY.push("level");
+ _propertyMap.BATTERY.push("isCharging");
- this.__defineGetter__("matchValue", function () {
- return attributeFilter.matchValue;
+ _powerData.__defineGetter__("isCharging", function () {
+ return false;
});
- this.__defineSetter__("matchValue", function (val) {
- try {
- if (attributeFilter.matchFlag === "EXISTS") {
- return;
- }
- attributeFilter.matchValue = t.any(val);
- } catch (e) {
- }
+
+ vol = db.retrieve(constants.BATTERY.VOLUME) || 100.0;
+ _powerData.__defineGetter__("level", function () {
+ return Number((vol / 100.0).toFixed(4));
});
-};
-module.exports = AttributeFilter;
+ event.on("BatteryEvent", function (status) {
+ _powerData.__defineGetter__("isCharging", function () {
+ return status.charging;
+ });
+ _powerData.__defineGetter__("level", function () {
+ return Number(status.level.toFixed(4));
+ });
+ });
+}
-});
-define('ripple/platform/tizen/2.0/AttributeRangeFilter', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 _isPropertyFound(property) {
+ if (tizen_utils.isEmptyObject(_propertyMap)) {
+ _initialize();
+ }
-var t = require('ripple/platform/tizen/2.0/typecast'),
- AttributeRangeFilter;
+ if (_propertyMap[property]) {
+ return true;
+ }
-AttributeRangeFilter = function (attributeName, initialValue, endValue) {
- var attributeRangeFilter = {};
+ return false;
+}
- t.AttributeRangeFilter(arguments, this);
+function _delayGetValue(timeout, property, successCallback, errorCallback) {
+ return window.setInterval(function () {
+ _getValue(property, successCallback, errorCallback);
+ }, timeout);
+}
- this.__defineGetter__("attributeName", function () {
- return attributeRangeFilter.attributeName;
- });
- this.__defineSetter__("attributeName", function (val) {
- try {
- attributeRangeFilter.attributeName = t.DOMString(val);
- } catch (e) {
+_self = function () {
+ function getCapabilities() {
+ if (_systemInfoDeviceCapability === null) {
+ _systemInfoDeviceCapability = new SystemInfoDeviceCapability();
}
- });
-
- attributeRangeFilter.attributeName = attributeName;
+ return _systemInfoDeviceCapability;
+ }
- this.initialValue = initialValue || null;
- this.endValue = endValue || null;
-};
+ function getPropertyValue(property, successCallback, errorCallback) {
+ t.SystemInfo("getPropertyValue", arguments);
-module.exports = AttributeRangeFilter;
+ if (!_isPropertyFound(property)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
-});
-define('ripple/platform/tizen/2.0/BluetoothClass', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ window.setTimeout(function () {
+ _getValue(property, successCallback, errorCallback);
+ }, 1);
+ }
-var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BluetoothClass,
- _security;
+ function addPropertyValueChangeListener(property, successCallback, options) {
+ var WatchOBJ, watchId = Number(Math.uuid(8, 10)),
+ _options = new Object(options), properties, prop, index = 0,
+ deviceEventType, watchObj, firstCallWatchObj;
-BluetoothClass = function (prop, metaData) {
- var bluetoothClass = {};
+ t.SystemInfo("addPropertyValueChangeListener", arguments);
- _security = metaData;
+ if (!_isPropertyFound(property)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- bluetoothClass.major = prop.major || 0;
- bluetoothClass.minor = prop.minor || 0;
- bluetoothClass.services = prop.services || [];
+ WatchOBJ = function (deviceEventType, property, successCallback) {
+ var obj = this;
- this.__defineGetter__("major", function () {
- return bluetoothClass.major;
- });
+ this.eventType = deviceEventType;
+ this.onEvent = function (newValue) {
+ if (obj.timeout) {
+ window.clearInterval(obj.intervalId);
+ obj.intervalId = window.setInterval(function () {
+ _getValue(property, successCallback, null);
+ }, obj.timeout);
+ }
- this.__defineGetter__("minor", function () {
- return bluetoothClass.minor;
- });
+ if ((obj.highThreshold && (newValue < obj.highThreshold)) ||
+ (obj.lowThreshold && (newValue > obj.lowThreshold))) {
+ return;
+ }
- this.__defineGetter__("services", function () {
- return bluetoothClass.services;
- });
+ _getValue(property, successCallback, null);
+ };
+ };
- bluetoothClass.services.forEach(function (service, i) {
- bluetoothClass.services.__defineGetter__(i, function () {
- return service;
- });
- });
+ // A listener will listen all the properties of one aspect, each of the property
+ // will have an internal watchObj to record the information.
+ _watches[watchId] = [];
- this.hasService = function (service) {
- if (!_security.hasService) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (property === "BATTERY") {
+ properties = _batteryEvent;
+ } else {
+ properties = _propertyMap[property];
}
- t.BluetoothClass("hasService", arguments);
+ for (; index < properties.length; index++) {
+ prop = properties[index];
+ if (property === "BATTERY") {
+ deviceEventType = prop;
+ } else {
+ deviceEventType = deviceSettings.retrieve(property)[prop].event;
+ }
- return (bluetoothClass.services.join(",").indexOf(service) !== -1);
- };
-};
+ if (deviceEventType === undefined) continue;
+ // These two items are needed when delete an event listener.
+ watchObj = new WatchOBJ(deviceEventType, property, successCallback);
-module.exports = BluetoothClass;
+ if (options && _options.timeout) {
+ watchObj.intervalId = _delayGetValue(_options.timeout, property,
+ successCallback, null);
+ }
-});
-define('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ if ((watchObj.eventType === "CpuLoadChanged") ||
+ (watchObj.eventType === "DisplayBrightnessChanged") ||
+ (watchObj.eventType === "BatteryLevelChanged")) {
+ if (options && _options.highThreshold) {
+ watchObj.highThreshold = _options.highThreshold;
+ }
-var BluetoothClassDeviceMajor = function () {
- this.__defineGetter__("MISC", function () {
- return 0x00;
- });
+ if (options && _options.lowThreshold) {
+ watchObj.lowThreshold = _options.lowThreshold;
+ }
+ }
- this.__defineGetter__("COMPUTER", function () {
- return 0x01;
- });
+ _watches[watchId].push(watchObj);
+ if (watchObj.eventType) {
+ event.on(watchObj.eventType, watchObj.onEvent);
+ }
+ }
- this.__defineGetter__("PHONE", function () {
- return 0x02;
- });
+ firstCallWatchObj = window.setTimeout(function () {
+ _getValue(property, successCallback, null);
+ delete _firstCall_watches[watchId];
+ }, 1);
- this.__defineGetter__("NETWORK", function () {
- return 0x03;
- });
+ _firstCall_watches[watchId] = firstCallWatchObj;
- this.__defineGetter__("AUDIO_VIDEO", function () {
- return 0x04;
- });
+ return watchId;
+ }
- this.__defineGetter__("PERIPHERAL", function () {
- return 0x05;
- });
+ function removePropertyValueChangeListener(listenerID) {
+ var _handler = listenerID, index = 0, watchObjs = [], watchObj;
- this.__defineGetter__("IMAGING", function () {
- return 0x06;
- });
+ if (!_watches[_handler])
+ return;
- this.__defineGetter__("WEARABLE", function () {
- return 0x07;
- });
+ watchObjs = _watches[_handler];
+ if (watchObjs) {
+ for (; index < watchObjs.length; index++) {
+ watchObj = watchObjs[index];
+ event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);
+ if (watchObj.intervalId) {
+ window.clearInterval(watchObj.intervalId);
+ }
+ }
+ delete _watches[_handler];
+ }
- this.__defineGetter__("TOY", function () {
- return 0x08;
- });
+ if (_firstCall_watches[_handler]) {
+ window.clearTimeout(_firstCall_watches[_handler]);
+ delete _firstCall_watches[_handler];
+ }
+ }
- this.__defineGetter__("HEALTH", function () {
- return 0x09;
- });
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- this.__defineGetter__("UNCATEGORIZED", function () {
- return 0x1F;
- });
-};
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
-module.exports = BluetoothClassDeviceMajor;
+ var systeminfo = {
+ getCapabilities: getCapabilities,
+ getPropertyValue: getPropertyValue,
+ addPropertyValueChangeListener: addPropertyValueChangeListener,
+ removePropertyValueChangeListener: removePropertyValueChangeListener,
+ handleSubFeatures: handleSubFeatures
+ };
-});
-define('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ return systeminfo;
+};
-var BluetoothClassDeviceMinor = function () {
- // COMPUTER
- this.__defineGetter__("COMPUTER_UNCATEGORIZED", function () {
- return 0x00;
+SystemInfoDeviceCapability = function () {
+ this.__defineGetter__("bluetooth", function () {
+ return true;
});
-
- this.__defineGetter__("COMPUTER_DESKTOP", function () {
- return 0x01;
+ this.__defineGetter__("nfc", function () {
+ return true;
});
-
- this.__defineGetter__("COMPUTER_SERVER", function () {
- return 0x02;
+ this.__defineGetter__("nfcReservedPush", function () {
+ return false;
});
-
- this.__defineGetter__("COMPUTER_LAPTOP", function () {
- return 0x03;
+ this.__defineGetter__("multiTouchCount", function () {
+ return 5;
});
-
- this.__defineGetter__("COMPUTER_HANDHELD_PC_OR_PDA", function () {
- return 0x04;
+ this.__defineGetter__("inputKeyboard", function () {
+ return false;
});
-
- this.__defineGetter__("COMPUTER_PALM_PC_OR_PDA", function () {
- return 0x05;
+ this.__defineGetter__("inputKeyboardLayout", function () {
+ return false;
});
-
- this.__defineGetter__("COMPUTER_WEARABLE", function () {
- return 0x06;
+ this.__defineGetter__("wifi", function () {
+ return true;
});
-
- // PHONE
- this.__defineGetter__("PHONE_UNCATEGORIZED", function () {
- return 0x00;
+ this.__defineGetter__("wifiDirect", function () {
+ return true;
});
-
- this.__defineGetter__("PHONE_CELLULAR", function () {
- return 0x01;
+ this.__defineGetter__("opengles", function () {
+ return false;
});
-
- this.__defineGetter__("PHONE_CORDLESS", function () {
- return 0x02;
+ this.__defineGetter__("openglestextureFormat", function () {
+ return "";
});
-
- this.__defineGetter__("PHONE_SMARTPHONE", function () {
- return 0x03;
+ this.__defineGetter__("openglesVersion1_1", function () {
+ return false;
});
-
- this.__defineGetter__("PHONE_MODEM_OR_GATEWAY", function () {
- return 0x04;
+ this.__defineGetter__("openglesVersion2_0", function () {
+ return false;
});
-
- this.__defineGetter__("PHONE_ISDN", function () {
- return 0x05;
+ this.__defineGetter__("fmRadio", function () {
+ return false;
});
-
- // AUDIO_VIDEO
- this.__defineGetter__("AV_UNRECOGNIZED", function () {
- return 0x00;
+ this.__defineGetter__("platformVersion", function () {
+ if (!_security.platformVersion) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ return "2.2.0";
});
-
- this.__defineGetter__("AV_WEARABLE_HEADSET", function () {
- return 0x01;
+ this.__defineGetter__("webApiVersion", function () {
+ if (!_security.webApiVersion) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ return "2.2";
});
-
- this.__defineGetter__("AV_HANDSFREE", function () {
- return 0x02;
+ this.__defineGetter__("nativeApiVersion", function () {
+ if (!_security.nativeApiVersion) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ return "2.2";
});
-
- this.__defineGetter__("AV_MICROPHONE", function () {
- return 0x04;
+ this.__defineGetter__("platformName", function () {
+ return "Tizen";
});
-
- this.__defineGetter__("AV_LOUDSPEAKER", function () {
- return 0x05;
+ this.__defineGetter__("camera", function () {
+ return false;
});
-
- this.__defineGetter__("AV_HEADPHONES", function () {
- return 0x06;
+ this.__defineGetter__("cameraFront", function () {
+ return false;
});
-
- this.__defineGetter__("AV_PORTABLE_AUDIO", function () {
- return 0x07;
+ this.__defineGetter__("cameraFrontFlash", function () {
+ return false;
});
-
- this.__defineGetter__("AV_CAR_AUDIO", function () {
- return 0x08;
+ this.__defineGetter__("cameraBack", function () {
+ return false;
});
-
- this.__defineGetter__("AV_SETTOP_BOX", function () {
- return 0x09;
+ this.__defineGetter__("cameraBackFlash", function () {
+ return false;
});
-
- this.__defineGetter__("AV_HIFI", function () {
- return 0x0a;
+ this.__defineGetter__("location", function () {
+ return true;
});
-
- this.__defineGetter__("AV_VCR", function () {
- return 0x0b;
+ this.__defineGetter__("locationGps", function () {
+ return true;
});
-
- this.__defineGetter__("AV_VIDEO_CAMERA", function () {
- return 0x0c;
+ this.__defineGetter__("locationWps", function () {
+ return false;
});
-
- this.__defineGetter__("AV_CAMCORDER", function () {
- return 0x0d;
+ this.__defineGetter__("microphone", function () {
+ return false;
});
-
- this.__defineGetter__("AV_MONITOR", function () {
- return 0x0e;
+ this.__defineGetter__("usbHost", function () {
+ return true;
});
-
- this.__defineGetter__("AV_DISPLAY_AND_LOUDSPEAKER", function () {
- return 0x0f;
+ this.__defineGetter__("usbAccessory", function () {
+ return false;
});
-
- this.__defineGetter__("AV_VIDEO_CONFERENCING", function () {
- return 0x10;
+ this.__defineGetter__("screenOutputRca", function () {
+ return false;
});
-
- this.__defineGetter__("AV_GAMING_TOY", function () {
- return 0x12;
+ this.__defineGetter__("screenOutputHdmi", function () {
+ return false;
});
-
- // PERIPHERAL
- this.__defineGetter__("PERIPHERAL_UNCATEGORIZED", function () {
- return 0;
+ this.__defineGetter__("platformCoreCpuArch", function () {
+ return "x86";
});
-
- this.__defineGetter__("PERIPHERAL_KEYBOARD", function () {
- return 0x10;
+ this.__defineGetter__("platformCoreFpuArch", function () {
+ return "ssse3";
});
-
- this.__defineGetter__("PERIPHERAL_POINTING_DEVICE", function () {
- return 0x20;
+ this.__defineGetter__("sipVoip", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE", function () {
- return 0x30;
+ this.__defineGetter__("duid", function () {
+ return "device unique ID";
});
-
- this.__defineGetter__("PERIPHERAL_JOYSTICK", function () {
- return 0x01;
+ this.__defineGetter__("speechRecognition", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_GAMEPAD", function () {
- return 0x02;
+ this.__defineGetter__("speechSynthesis", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_REMOTE_CONTROL", function () {
- return 0x03;
+ this.__defineGetter__("accelerometer", function () {
+ return true;
});
-
- this.__defineGetter__("PERIPHERAL_SENSING_DEVICE", function () {
- return 0x04;
+ this.__defineGetter__("accelerometerWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_DEGITIZER_TABLET", function () {
- return 0x05;
+ this.__defineGetter__("barometer", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_CARD_READER", function () {
- return 0x06;
+ this.__defineGetter__("barometerWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_DIGITAL_PEN", function () {
- return 0x07;
+ this.__defineGetter__("gyroscope", function () {
+ return true;
});
-
- this.__defineGetter__("PERIPHERAL_HANDHELD_SCANNER", function () {
- return 0x08;
+ this.__defineGetter__("gyroscopeWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("PERIPHERAL_HANDHELD_INPUT_DEVICE", function () {
- return 0x09;
+ this.__defineGetter__("magnetometer", function () {
+ return false;
});
-
- // IMAGING
- this.__defineGetter__("IMAGING_UNCATEGORIZED", function () {
- return 0x00;
+ this.__defineGetter__("magnetometerWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("IMAGING_DISPLAY", function () {
- return 0x04;
+ this.__defineGetter__("photometer", function () {
+ return false;
});
-
- this.__defineGetter__("IMAGING_CAMERA", function () {
- return 0x08;
+ this.__defineGetter__("photometerWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("IMAGING_SCANNER", function () {
- return 0x10;
+ this.__defineGetter__("proximity", function () {
+ return false;
});
-
- this.__defineGetter__("IMAGING_PRINTER", function () {
- return 0x20;
+ this.__defineGetter__("proximityWakeup", function () {
+ return false;
});
-
- // WEARABLE
- this.__defineGetter__("WEARABLE_WRITST_WATCH", function () {
- return 0x01;
+ this.__defineGetter__("tiltmeter", function () {
+ return false;
});
-
- this.__defineGetter__("WEARABLE_PAGER", function () {
- return 0x02;
+ this.__defineGetter__("tiltmeterWakeup", function () {
+ return false;
});
-
- this.__defineGetter__("WEARABLE_JACKET", function () {
- return 0x03;
- });
-
- this.__defineGetter__("WEARABLE_HELMET", function () {
- return 0x04;
- });
-
- this.__defineGetter__("WEARABLE_GLASSES", function () {
- return 0x05;
- });
-
- // TOY
- this.__defineGetter__("TOY_ROBOT", function () {
- return 0x01;
- });
-
- this.__defineGetter__("TOY_VEHICLE", function () {
- return 0x02;
+ this.__defineGetter__("dataEncryption", function () {
+ return false;
});
-
- this.__defineGetter__("TOY_DOLL", function () {
- return 0x03;
+ this.__defineGetter__("graphicsAcceleration", function () {
+ return false;
});
-
- this.__defineGetter__("TOY_CONTROLLER", function () {
- return 0x04;
+ this.__defineGetter__("push", function () {
+ return true;
});
-
- this.__defineGetter__("TOY_GAME", function () {
- return 0x05;
+ this.__defineGetter__("telephony", function () {
+ return true;
});
-
- // HEALTH
- this.__defineGetter__("HEALTH_UNDEFINED", function () {
- return 0x00;
+ this.__defineGetter__("telephonyMms", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_BLOOD_PRESSURE_MONITOR", function () {
- return 0x01;
+ this.__defineGetter__("telephonySms", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_THERMOMETER", function () {
- return 0x02;
+ this.__defineGetter__("screenSizeNormal", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_WEIGHING_SCALE", function () {
- return 0x03;
+ this.__defineGetter__("screenSize480_800", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_GLUCOSE_METER", function () {
- return 0x04;
+ this.__defineGetter__("screenSize720_1280", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_PULSE_OXIMETER", function () {
- return 0x05;
+ this.__defineGetter__("autoRotation", function () {
+ return true;
});
-
- this.__defineGetter__("HEALTH_PULSE_RATE_MONITOR", function () {
- return 0x06;
+ this.__defineGetter__("shellAppWidget", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_DATA_DISPLAY", function () {
- return 0x07;
+ this.__defineGetter__("visionImageRecognition", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_STEP_COUNTER", function () {
- return 0x08;
+ this.__defineGetter__("visionQrcodeGeneration", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_BODY_COMPOSITION_ANALYZER", function () {
- return 0x09;
+ this.__defineGetter__("visionQrcodeRecognition", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_PEAK_FLOW_MONITOR", function () {
- return 0x0a;
+ this.__defineGetter__("visionFaceRecognition", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_MEDICATION_MONITOR", function () {
- return 0x0b;
+ this.__defineGetter__("secureElement", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_KNEE_PROSTHESIS", function () {
- return 0x0c;
+ this.__defineGetter__("nativeOspCompatible", function () {
+ return false;
});
-
- this.__defineGetter__("HEALTH_ANKLE_PROSTHESIS", function () {
- return 0x0d;
+ this.__defineGetter__("profile", function () {
+ return "MOBILE_WEB";
});
};
-module.exports = BluetoothClassDeviceMinor;
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/BluetoothClassDeviceService', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/map', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2012 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var BluetoothClassDeviceService = function () {
- this.__defineGetter__("LIMITED_DISCOVERABILITY", function () {
- return 0x0001;
- });
+var lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
+ mapProviders = [],
+ MapStyle,
+ MapProvider,
+ _self;
- this.__defineGetter__("POSITIONING", function () {
- return 0x0008;
- });
+function _initialize() {
+ // EPSG:3857 is a Spherical Mercator projection coordinate system popularized by web services such as Google and later OpenStreetMap
+ // mapStyles are from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
+ var projection = "EPSG:3857",
+ mapStyle1 = new MapStyle("Mapnik", "http://b.tile.openstreetmap.org/${z}/${x}/${y}.png"),
+ mapStyle2 = new MapStyle("Cycle", "http://b.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png");
- this.__defineGetter__("NETWORKING", function () {
- return 0x0010;
- });
+ mapProviders = [new MapProvider({name: "OpenStreetMap", connectivity: "ONLINE"}, projection, [mapStyle1, mapStyle2])];
+}
- this.__defineGetter__("RENDERING", function () {
- return 0x0020;
- });
+_self = {
+ getDefaultProvider: function () {
+ return mapProviders[0];
+ },
+ getProviders: function () {
+ return mapProviders;
+ }
+};
- this.__defineGetter__("CAPTURING", function () {
- return 0x0040;
- });
+MapStyle = function (name, url) {
+ return {
+ name: name,
+ url: url
+ };
+};
- this.__defineGetter__("OBJECT_TRANSFER", function () {
- return 0x0080;
- });
+MapProvider = function (prop, projection, mapStyles) {
+ var mapProvider = new lbs.LocationServiceProvider(prop);
- this.__defineGetter__("AUDIO", function () {
- return 0x0100;
+ mapProvider.__defineGetter__("projection", function () {
+ return projection;
});
- this.__defineGetter__("TELEPHONY", function () {
- return 0x0200;
+ mapProvider.__defineGetter__("mapStyles", function () {
+ return mapStyles;
});
- this.__defineGetter__("INFORMATION", function () {
- return 0x0400;
- });
+ return mapProvider;
};
-module.exports = BluetoothClassDeviceService;
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/BluetoothDevice', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/datasync', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2013 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BluetoothClass = require('ripple/platform/tizen/2.0/BluetoothClass'),
- BluetoothSocket = require('ripple/platform/tizen/2.0/BluetoothSocket'),
- BluetoothDevice,
- _security;
+ SyncInfoMod = require('ripple/platform/tizen/2.0/SyncInfo'),
+ SyncServiceInfoMod = require('ripple/platform/tizen/2.0/SyncServiceInfo'),
+ SyncProfileInfoMod = require('ripple/platform/tizen/2.0/SyncProfileInfo'),
+ SyncStatistics = require('ripple/platform/tizen/2.0/SyncStatistics'),
+ _data = {
+ DB_DATASYNC_ITEMS: "tizen1-db-datasync-items",
+ DB_DATASYNC_COUNTER: "tizen1-db-datasync-counter",
+ MAX_PROFILE_NUMBER: 5,
+ profile_num: 0,
+ profiles: {},
+ sync_accounts: {},
+ service_accounts: {},
+ item_counter: 1000,
+ type_table: {
+ "TWO_WAY": 1,
+ "SLOW": 2,
+ "ONE_WAY_FROM_CLIENT": 3,
+ "REFRESH_FROM_CLIENT": 4,
+ "ONE_WAY_FROM_SERVER": 5,
+ "REFRESH_FROM_SERVER": 6
+ },
+ mode_table: {
+ "TWO_WAY": 200,
+ "SLOW": 201,
+ "ONE_WAY_FROM_CLIENT": 202,
+ "REFRESH_FROM_CLIENT": 203,
+ "ONE_WAY_FROM_SERVER": 204,
+ "REFRESH_FROM_SERVER": 205
+ },
+ items: {}
+ },
+ _security = {
+ "http://tizen.org/privilege/datasync":
+ ["add", "update", "remove", "getMaxProfilesNum", "getProfilesNum",
+ "get", "getAll", "startSync", "stopSync", "getLastSyncStatistics"]
+ },
+ _self,
+ syncml = {
+ adapter: require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
+ agent: require('ripple/platform/tizen/2.0/syncml-js-lib/agent'),
+ base64: require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
+ codec: require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
+ common: require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant: require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ context: require('ripple/platform/tizen/2.0/syncml-js-lib/context'),
+ ctype: require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
+ devinfo: require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
+ item: require('ripple/platform/tizen/2.0/syncml-js-lib/item'),
+ localadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
+ matcher: require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
+ protocol: require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
+ remoteadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
+ router: require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
+ state: require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
+ storage: require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
+ store: require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
+ synchronizer: require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
+ useragent: require('ripple/platform/tizen/2.0/syncml-js-lib/useragent')
+ },
+ TizenAgent;
-BluetoothDevice = function (prop) {
- var bluetoothDevice = {}, sockets = {}, self;
+function _get() {
+ _data.item_counter = db.retrieveObject(_data.DB_DATASYNC_COUNTER) || 1000;
+ _data.items = db.retrieveObject(_data.DB_DATASYNC_ITEMS) || {};
+}
- bluetoothDevice.name = prop.name || "";
- bluetoothDevice.address = prop.address || "";
- bluetoothDevice.deviceClass = new BluetoothClass(prop.deviceClass,
- prop.metaData) || {};
- bluetoothDevice.isBonded = prop.isBonded || false;
- bluetoothDevice.isTrusted = prop.isTrusted || false;
- bluetoothDevice.isConnected = prop.isConnected || false;
- bluetoothDevice.services = prop.services;
- bluetoothDevice.uuids = [];
+function _save() {
+ db.saveObject(_data.DB_DATASYNC_COUNTER, _data.item_counter);
+ db.saveObject(_data.DB_DATASYNC_ITEMS, _data.items);
+}
- _security = prop.metaData;
- self = this;
+TizenAgent = syncml.agent.Agent.extend({
+ constructor: function() {
+ },
+ getContentTypes: function() {
+ return [
+ new syncml.ctype.ContentTypeInfo('text/x-vcard', '2.1',{preferred: true})
+ ];
+ },
+ dumpsItem: function(item, contentType, version, cb) {
+ var cdata = new ET.CdataElement(item.item);
+ cb(null, cdata);
+ },
+ loadsItem: function(data, contentType, version, cb) {
+ return cb(null, {item: data._node.textContent});
+ },
+ getAllItems: function(cb) {
+ var items = [];
+ utils.forEach(_data.items, function(contact) {
+ items.push(contact);
+ });
+ return cb(null, items);
+ },
+ addItem: function(item, cb) {
+ _data.item_counter++;
+ item.id = _data.item_counter.toString();
+ _data.items[item.id] = item;
+ _save();
+ return cb(null, item);
+ },
+ getItem: function(itemID, cb) {
+ return cb(null, _data.items[itemID]);
+ },
+ replaceItem: function(item, reportChanges, cb) {
+ _data.items[item.id] = item;
+ _save();
+ return cb(null, null);
+ },
+ deleteItem: function(itemID, cb) {
+ delete _data.items[itemID];
+ _save();
+ return cb(null);
+ }
+});
- event.on("bt-device-connected-update", function (addr, isConnected) {
- if (addr === bluetoothDevice.address) {
- bluetoothDevice.isConnected = isConnected;
- event.trigger("bt-device-connected-changed",
- [bluetoothDevice.address, bluetoothDevice.isConnected]);
+function _initialize() {
+ _data.agent = new TizenAgent();
+ _get();
+}
+
+_self = function () {
+ var datasync;
+
+ // private
+ function createInternalProfile(profile) {
+ var _profile, sync_account, service_accounts;
+
+ sync_account = db.retrieveObject("save-syncinfo")[profile.syncInfo.__syncInfoID__];
+
+ _profile = {
+ profileName: profile.profileName,
+ syncInfo: {
+ url: profile.syncInfo.url,
+ id: sync_account.id,
+ password: sync_account.password,
+ mode: profile.syncInfo.mode
+ },
+ serviceInfo: []
+ };
+
+ switch (_profile.syncInfo.mode) {
+ case "MANUAL":
+ _profile.syncInfo.type = profile.syncInfo.type || "TWO_WAY";
+ break;
+ case "PERIODIC":
+ //TODO: set 1_HOUR as default value
+ _profile.interval = profile.syncInfo.interval || "1_HOUR";
+ _profile.syncInfo.type = "TWO_WAY";
+ break;
+ case "PUSH":
+ _profile.syncInfo.type = "TWO_WAY";
+ break;
}
- });
- utils.forEach(bluetoothDevice.services, function (service) {
- bluetoothDevice.uuids.push(service.uuid);
- sockets[service.uuid] = new BluetoothSocket({
- uuid: service.uuid,
- protocol: service.protocol,
- state: "CLOSED",
- peer: self,
- metaData: _security
- });
- });
+ if (profile.serviceInfo) {
+ service_accounts = db.retrieveObject("save-syncserviceinfo");
+ utils.forEach(profile.serviceInfo, function (service) {
+ _profile.serviceInfo.push({
+ enable: service.enable,
+ serviceType: service.serviceType,
+ serverDatabaseUri: service.serverDatabaseUri,
+ id: service_accounts[service.__syncServiceInfoID__].id,
+ password: service_accounts[service.__syncServiceInfoID__].password
+ });
+ });
+ }
- this.__defineGetter__("name", function () {
- return bluetoothDevice.name;
- });
+ return _profile;
+ }
- this.__defineGetter__("address", function () {
- return bluetoothDevice.address;
- });
+ function createExternalProfile(profileId) {
+ var profile, i, _syncinfo, _serviceinfo, p;
- this.__defineGetter__("deviceClass", function () {
- return bluetoothDevice.deviceClass;
- });
+ p = _data.profiles[profileId];
- this.__defineGetter__("isBonded", function () {
- return bluetoothDevice.isBonded;
- });
+ switch (p.syncInfo.mode) {
+ case "MANUAL":
+ _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "MANUAL", p.syncInfo.type);
+ _syncinfo.interval = null;
+ break;
+ case "PERIODIC":
+ _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PERIODIC", p.syncInfo.interval);
+ break;
+ case "PUSH":
+ _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PUSH");
+ break;
+ }
- this.__defineGetter__("isTrusted", function () {
- return bluetoothDevice.isTrusted;
- });
+ if (p.serviceInfo) {
+ _serviceinfo = [];
+ for (i in p.serviceInfo) {
+ var info;
+ info = new SyncServiceInfoMod(p.serviceInfo[i].enable,
+ p.serviceInfo[i].serviceType, p.serviceInfo[i].serverDatabaseUri,
+ p.serviceInfo[i].id || null, p.serviceInfo[i].password || null);
+ _serviceinfo.push(info);
+ }
+ }
- this.__defineGetter__("isConnected", function () {
- return bluetoothDevice.isConnected;
- });
+ profile = new SyncProfileInfoMod(p.profileName, _syncinfo, _serviceinfo);
+ Object.defineProperty(profile, "profileId", {value: p.profileId, writable: false});
- this.__defineGetter__("uuids", function () {
- return bluetoothDevice.uuids;
- });
+ return profile;
+ }
- this.connectToServiceByUUID = function (uuid, successCallback,
- errorCallback) {
- if (!_security.all && !_security.connectToServiceByUUID) {
+ // public
+ function add(profile) {
+ var _profile;
+
+ if (!_security.add) {
throw new WebAPIException(errorcode.SECURITY_ERR);
}
- t.BluetoothDevice("connectToServiceByUUID", arguments);
+ t.DataSynchronizationManager("add", arguments);
- window.setTimeout(function () {
- if (bluetoothDevice.uuids.join(",").indexOf(uuid) === -1) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ _profile = createInternalProfile(profile);
+
+ if (_data.profile_num > _data.MAX_PROFILE_NUMBER) {
+ throw new WebAPIException(errorcode.QUOTA_EXCEEDED_ERR);
+ }
+
+ _profile.profileId = Math.uuid(null, 16);
+ _data.profiles[_profile.profileId] = _profile;
+ _data.profile_num++;
+
+ Object.defineProperty(profile, "profileId", {value: _profile.profileId, writable: false});
+ }
+
+ function update(profile) {
+ var _profile;
+
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.DataSynchronizationManager("update", arguments);
+
+ _profile = createInternalProfile(profile);
+
+ if (!profile.profileId || !_data.profiles[profile.profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ _profile.profileId = profile.profileId;
+ _data.profiles[_profile.profileId] = _profile;
+ }
+
+ function remove(profileId) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.DataSynchronizationManager("remove", arguments);
+
+ if (!_data.profiles[profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ delete _data.profiles[profileId];
+ _data.profile_num--;
+ }
+
+ function getMaxProfilesNum() {
+ if (!_security.getMaxProfilesNum) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ return _data.MAX_PROFILE_NUMBER;
+ }
+
+ function getProfilesNum() {
+ if (!_security.getProfilesNum) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ return _data.profile_num;
+ }
+
+ function get(profileId) {
+ var profile;
+
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.DataSynchronizationManager("get", arguments);
+
+ if (!_data.profiles[profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ profile = createExternalProfile(profileId);
+
+ return profile;
+ }
+
+ function getAll() {
+ var profiles = [], i;
+
+ if (!_security.getAll) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ for (i in _data.profiles) {
+ profiles.push(createExternalProfile(_data.profiles[i].profileId));
+ }
+
+ return profiles;
+ }
+
+ function startSync(profileId, progressCallback) {
+ var _profile, _stores, _routes, sync_peer;
+
+ if (!_security.startSync) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.DataSynchronizationManager("startSync", arguments);
+
+ if (!_data.profiles[profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ _data.profiles[profileId].stop_flag = false;
+
+ sync_peer = function(adapter, store, peer, type) {
+ adapter.sync(peer, type, function(err, stats) {
+ var p, name, hereTotal, peerTotal;
+ p = _data.profiles[profileId];
+ if (p.stop_flag === true) {
+ p.syncStatistics =[{
+ syncStatus: "STOP",
+ serviceType: p.serviceInfo[0].serviceType,
+ lastSyncTime: new Date(),
+ serverToClientTotal: 0,
+ serverToClientAdded: 0,
+ serverToClientUpdated: 0,
+ serverToClientRemoved: 0,
+ clientToServerTotal: 0,
+ clientToServerAdded: 0,
+ clientToServerUpdated: 0,
+ clientToServerRemoved: 0
+ }];
+ p.stop_flag = false;
+ return;
+ }
+ if (err) {
+ if (progressCallback) {
+ if (progressCallback.onfailed) {
+ progressCallback.onfailed(profileId, new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ }
+ p.syncStatistics =[{
+ syncStatus: "FAIL",
+ serviceType: p.serviceInfo[0].serviceType,
+ lastSyncTime: new Date(),
+ serverToClientTotal: 0,
+ serverToClientAdded: 0,
+ serverToClientUpdated: 0,
+ serverToClientRemoved: 0,
+ clientToServerTotal: 0,
+ clientToServerAdded: 0,
+ clientToServerUpdated: 0,
+ clientToServerRemoved: 0
+ }];
+ p.stop_flag = false;
+ return;
+ }
+ name = p.profileName + "-" + p.serviceInfo[0].serviceType;
+ hereTotal = stats[name].hereAdd + stats[name].hereDel + stats[name].hereMod;
+ peerTotal = stats[name].peerAdd + stats[name].peerDel + stats[name].peerMod;
+ p.syncStatistics =[{
+ syncStatus: "SUCCESS",
+ serviceType: p.serviceInfo[0].serviceType,
+ lastSyncTime: new Date(),
+ serverToClientTotal: hereTotal,
+ serverToClientAdded: stats[name].hereAdd,
+ serverToClientUpdated: stats[name].hereMod,
+ serverToClientRemoved: stats[name].hereDel,
+ clientToServerTotal: peerTotal,
+ clientToServerAdded: stats[name].peerAdd,
+ clientToServerUpdated: stats[name].peerMod,
+ clientToServerRemoved: stats[name].peerDel
+ }];
+ p.stop_flag = false;
+
+ if (progressCallback) {
+ if (progressCallback.oncompleted) {
+ progressCallback.oncompleted(profileId);
+ }
}
+ });
+ };
+ _profile = _data.profiles[profileId];
+ _profile.context = new syncml.context.Context({prefix: "tizen-"});
+ _stores = [];
+ _routes = [];
+ utils.forEach(_profile.serviceInfo, function(service) {
+ var name = _profile.profileName + "-" + service.serviceType;
+ _stores.push({
+ uri: name,
+ displayName: name,
+ maxGuidSize: 64,
+ maxObjSize: 4000000,
+ agent: _data.agent
+ });
+ _routes.push([name, service.serverDatabaseUri]);
+ });
+ _profile.context.getEasyClientAdapter({
+ displayName: "Tizen syncML adapter",
+ devInfo: {
+ devID: "tizen-syncml-03",
+ devType: syncml.constant.DEVTYPE_WORKSTATION,
+ manufacturerName: "Tizen",
+ modelName: "tizen.syncml.client",
+ hierarchicalSync: false
+ },
+ stores: _stores,
+ peer: {
+ url: _profile.syncInfo.url,
+ username: _profile.syncInfo.id,
+ password: _profile.syncInfo.password
+ },
+ routes: _routes
+ }, function(err, adapter, stores, peer) {
+ if (err) {
+ console.log("[datasync.syncml] getEasyClientAdapter fail:", err);
return;
}
+ utils.forEach(stores, function(store) {
+ var args = {
+ data: _data.mode_table[_profile.syncInfo.type],
+ source: store.uri,
+ target: _profile.serviceInfo[0].serverDatabaseUri,
+ nextAnchor: syncml.common.ts()
+ };
+ if (args.data === _data.mode_table["SLOW"]) {
+ args.lastAnchor = null;
+ } else if (peer.getStore(args.target)) {
+ args.lastAnchor = peer.getStore(args.target)._getBinding().localAnchor;
+ }
- bluetoothDevice.isConnected = true;
- event.trigger("bt-device-connected-changed", [bluetoothDevice.address,
- true]);
- sockets[uuid].__defineGetter__("state", function () {
- return "OPEN";
+ db.saveObject("syncml-alert-args", args);
+ db.saveObject("syncml-first-flag", false);
+ sync_peer(adapter, store, peer, _data.type_table[_profile.syncInfo.type]);
});
- event.trigger("bt-service-state-changed", [bluetoothDevice.address,
- uuid, true]);
+ });
- successCallback(sockets[uuid]);
- }, 1);
- };
-};
+ }
-module.exports = BluetoothDevice;
+ function stopSync(profileId) {
+ if (!_security.stopSync) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-});
-define('ripple/platform/tizen/2.0/BluetoothServiceHandler', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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.
- */
+ t.DataSynchronizationManager("stopSync", arguments);
-var event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BluetoothServiceHandler,
- _security;
+ if (!_data.profiles[profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
-BluetoothServiceHandler = function (prop) {
- var bluetoothServiceHandler = {};
+ _data.profiles[profileId].stop_flag = true;
+ }
- _security = prop.metaData;
+ function getLastSyncStatistics(profileId) {
+ var s, statistics = [], i;
- bluetoothServiceHandler.uuid = prop.uuid || "";
- bluetoothServiceHandler.name = prop.name || "";
- bluetoothServiceHandler.isConnected = prop.isConnected || false;
- bluetoothServiceHandler.onconnect = null;
+ if (!_security.getLastSyncStatistics) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("uuid", function () {
- return bluetoothServiceHandler.uuid;
- });
+ t.DataSynchronizationManager("getLastSyncStatistics", arguments);
- this.__defineGetter__("name", function () {
- return bluetoothServiceHandler.name;
- });
+ if (!_data.profiles[profileId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- this.__defineGetter__("isConnected", function () {
- return bluetoothServiceHandler.isConnected;
- });
+ s = _data.profiles[profileId].syncStatistics;
- this.__defineGetter__("onconnect", function () {
- return bluetoothServiceHandler.onconnect;
- });
- this.__defineSetter__("onconnect", function (val) {
- try {
- bluetoothServiceHandler.onconnect =
- t.BluetoothSocketSuccessCallback(val, "?");
- } catch (e) {
+ for (i in s) {
+ statistics.push(
+ new SyncStatistics(s[i].syncStatus, s[i].serviceType, s[i].lastSyncTime,
+ s[i].serverToClientTotal, s[i].serverToClientAdded,
+ s[i].serverToClientUpdated, s[i].serverToClientRemoved,
+ s[i].clientToServerTotal, s[i].clientToServerAdded,
+ s[i].clientToServerUpdated, s[i].clientToServerRemoved)
+ );
}
- });
- this.unregister = function (successCallback, errorCallback) {
- if (!_security.unregister) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ return statistics;
+ }
- t.BluetoothServiceHandler("unregister", arguments);
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- event.trigger("bt-unregister-service", [bluetoothServiceHandler.uuid,
- successCallback, errorCallback]);
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
+
+ datasync = {
+ add: add,
+ update: update,
+ remove: remove,
+ getMaxProfilesNum: getMaxProfilesNum,
+ getProfilesNum: getProfilesNum,
+ get: get,
+ getAll: getAll,
+ startSync: startSync,
+ stopSync: stopSync,
+ getLastSyncStatistics: getLastSyncStatistics,
+ handleSubFeatures: handleSubFeatures
};
+
+ return datasync;
};
-module.exports = BluetoothServiceHandler;
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/BluetoothSocket', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/messageport', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2014 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var utils = require('ripple/utils'),
+var db = require('ripple/db'),
event = require('ripple/event'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
t = require('ripple/platform/tizen/2.0/typecast'),
WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BluetoothSocket,
- _security;
+ LocalMessagePort,
+ RemoteMessagePort,
+ MessagePortInternal,
+ _data = {
+ messagePorts: {},
+ nListener: 0
+ },
+ _self;
-BluetoothSocket = function (prop) {
- var bluetoothSocket = {}, buffer = [], that = this;
+function _get() {
+ return db.retrieveObject("tizen-messageport");
+}
- _security = prop.metaData;
+function _registerApplication(appId, certificate) {
+ if (_data.messagePorts[appId])
+ return;
- bluetoothSocket.uuid = prop.uuid;
- bluetoothSocket.state = prop.state;
- bluetoothSocket.peer = prop.peer;
- bluetoothSocket.onmessage = null;
- bluetoothSocket.onclose = null;
+ _data.messagePorts[appId] = {
+ local: {},
+ remote: {},
+ certificate: certificate
+ };
+}
- this.__defineGetter__("uuid", function () {
- return bluetoothSocket.uuid;
- });
+function _initialize() {
+ var appId, app, port, database = _get();
- this.__defineGetter__("state", function () {
- return bluetoothSocket.state;
- });
+ for (appId in database) {
+ app = database[appId];
- this.__defineGetter__("peer", function () {
- return bluetoothSocket.peer;
- });
+ _registerApplication(appId, app.certificate);
- this.__defineGetter__("onmessage", function () {
- return bluetoothSocket.onmessage;
- });
- this.__defineSetter__("onmessage", function (val) {
- try {
- bluetoothSocket.onmessage = t.SuccessCallback(val, "?");
- } catch (e) {
+ for (port in app.ports) {
+ _setMessagePort(appId, port, app.ports[port], false);
+ _data.messagePorts[appId].local[port].listeners
+ [++_data.nListener] = _remoteListener(appId, port);
}
- });
+ }
- this.__defineGetter__("onclose", function () {
- return bluetoothSocket.onclose;
- });
- this.__defineSetter__("onclose", function (val) {
- try {
- bluetoothSocket.onclose = t.SuccessCallback(val, "?");
- } catch (e) {
+ event.on("LocalMessagePortReceived", function (data, remotePort) {
+ var currentAppId = _getCurrentAppId(), appId, messagePortName, isTrusted;
+
+ appId = remotePort.appId;
+ messagePortName = remotePort.messagePortName;
+ isTrusted = remotePort.isTrusted;
+
+ if (!_getMessagePort(appId, messagePortName, true)) {
+ if (!_data.messagePorts[appId].remote[currentAppId]) {
+ _data.messagePorts[appId].remote[currentAppId] = {};
+ }
+ _data.messagePorts[appId].remote[currentAppId][messagePortName] =
+ new MessagePortInternal(currentAppId, appId, messagePortName,
+ true, isTrusted);
}
+
+ remotePort.appId = currentAppId;
+ _dispatchMessage(appId, remotePort, data, null);
});
+}
- this.writeData = function (data) {
- if (!_security.writeData) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+function _getCurrentAppId() {
+ return tizen.application.getCurrentApplication().appInfo.id;
+}
+
+function _remoteListener(appId, port) {
+ var remotePort = {
+ appId: appId,
+ messagePortName: port
+ };
+
+ return function (data, localMessagePort) {
+ event.trigger("RemoteMessagePortSent", [remotePort, data,
+ localMessagePort]);
+ };
+}
+
+function _setMessagePort(appId, messagePortName, isTrusted, isRemote) {
+ var messagePort, ports, currentAppId = "";
+
+ if (!isRemote) {
+ messagePort = new MessagePortInternal(currentAppId, appId,
+ messagePortName, isRemote, isTrusted);
+ ports = _data.messagePorts[appId].local;
+ } else {
+ currentAppId = _getCurrentAppId();
+ messagePort = new MessagePortInternal(currentAppId, appId,
+ messagePortName, isRemote, isTrusted);
+
+ if (!_data.messagePorts[currentAppId].remote[appId]) {
+ _data.messagePorts[currentAppId].remote[appId] = {};
}
+ ports = _data.messagePorts[currentAppId].remote[appId];
+ }
- t.BluetoothSocket("writeData", arguments);
+ ports[messagePortName] = messagePort;
- if (this.state === "CLOSED") {
- return;
+ return messagePort.external;
+}
+
+function _getMessagePort(appId, messagePortName, isRemote) {
+ var messagePort, currentAppId = _getCurrentAppId(),
+ app = _data.messagePorts[currentAppId];
+
+ messagePort = !isRemote ? app.local[messagePortName] :
+ (app.remote[appId] ? app.remote[appId][messagePortName] : null);
+
+ return !messagePort ? null : messagePort.external;
+}
+
+function _dispatchMessage(selfId, dest, data, repliedMessagePort) {
+ var app, watchId, listener, localPort, messagePort = null,
+ messagePortName = dest.messagePortName,
+ appId = dest.appId,
+ repliedName;
+
+ app = _data.messagePorts[appId];
+ localPort = app.local[messagePortName];
+
+ if (repliedMessagePort) {
+ repliedName = repliedMessagePort.messagePortName;
+ if (_data.messagePorts[appId].remote[selfId] &&
+ _data.messagePorts[appId].remote[selfId][repliedName]) {
+ messagePort = _data.messagePorts[appId].remote[selfId]
+ [repliedName].external;
}
+ }
- event.trigger("bt-service-write-msg", [bluetoothSocket.peer.address,
- bluetoothSocket.uuid, data]);
+ for (watchId in localPort.listeners) {
+ listener = localPort.listeners[watchId];
+ listener(data, messagePort);
+ }
+}
- return data.length;
- };
+_self = {
+ requestLocalMessagePort: function (localMessagePortName) {
+ var currentAppId, localMessagePort;
- this.readData = function () {
- var data;
+ t.MessagePortManager("requestLocalMessagePort", arguments);
- if (!_security.readData) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ currentAppId = _getCurrentAppId();
+ _registerApplication(currentAppId, true);
+
+ localMessagePort = _getMessagePort(currentAppId,
+ localMessagePortName, false);
+
+ if (localMessagePort) {
+ if (localMessagePort.isTrusted) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+ } else {
+ localMessagePort = _setMessagePort(currentAppId,
+ localMessagePortName, false, false);
+
+ event.trigger("LocalMessagePortAdded", [localMessagePortName,
+ false]);
}
- if (this.state === "CLOSED") {
- return;
+ return localMessagePort;
+ },
+
+ requestTrustedLocalMessagePort: function (localMessagePortName) {
+ var currentAppId, localMessagePort;
+
+ t.MessagePortManager("requestTrustedLocalMessagePort", arguments);
+
+ currentAppId = _getCurrentAppId();
+ _registerApplication(currentAppId, true);
+
+ localMessagePort = _getMessagePort(currentAppId,
+ localMessagePortName, false);
+
+ if (localMessagePort) {
+ if (!localMessagePort.isTrusted) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+ } else {
+ localMessagePort = _setMessagePort(currentAppId,
+ localMessagePortName, true, false);
+
+ event.trigger("LocalMessagePortAdded", [localMessagePortName,
+ true]);
}
- data = utils.copy(buffer);
- buffer = [];
+ return localMessagePort;
+ },
- return data;
- };
+ requestRemoteMessagePort: function (appId, remoteMessagePortName) {
+ var remoteMessagePort, app, currentAppId;
- this.close = function () {
- if (!_security.close) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ t.MessagePortManager("requestRemoteMessagePort", arguments);
+
+ currentAppId = _getCurrentAppId();
+ _registerApplication(currentAppId, true);
+
+ app = _data.messagePorts[appId];
+
+ if (!app || !app.local[remoteMessagePortName]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ if (app.local[remoteMessagePortName].isTrusted) {
+ throw new WebAPIException(errorcode.INVALID_ACCESS_ERR);
}
- this.__defineGetter__("state", function () {
- return "CLOSED";
- });
+ remoteMessagePort = _getMessagePort(appId,
+ remoteMessagePortName, true);
- event.trigger("bt-service-state-changed", [bluetoothSocket.peer.address,
- bluetoothSocket.uuid, false]);
- event.trigger("bt-device-connected-update",
- [bluetoothSocket.peer.address, false]);
+ if (remoteMessagePort) {
+ if (remoteMessagePort.isTrusted) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+ } else {
+ remoteMessagePort = _setMessagePort(appId,
+ remoteMessagePortName, false, true);
- if (bluetoothSocket.onclose) {
- bluetoothSocket.onclose();
+ event.trigger("RemoteMessagePortAdded", [appId,
+ remoteMessagePortName, false]);
}
- };
- event.on("bt-service-state-update", function (addr, state) {
- var stateStr = "CLOSED";
+ return remoteMessagePort;
+ },
- if (addr !== bluetoothSocket.peer.address) {
- return;
+ requestTrustedRemoteMessagePort: function (appId, remoteMessagePortName) {
+ var remoteMessagePort, app, currentAppId;
+
+ t.MessagePortManager("requestTrustedRemoteMessagePort", arguments);
+
+ currentAppId = _getCurrentAppId();
+ _registerApplication(currentAppId, true);
+
+ app = _data.messagePorts[appId];
+
+ if (!app) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
}
- if (state) {
- stateStr = "OPEN";
+ if (!app.certificate) {
+ throw new WebAPIException(errorcode.INVALID_ACCESS_ERR);
+ }
+ if (!app.local[remoteMessagePortName]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ if (!app.local[remoteMessagePortName].isTrusted) {
+ throw new WebAPIException(errorcode.INVALID_ACCESS_ERR);
}
- that.__defineGetter__("state", function () {
- return stateStr;
- });
+ remoteMessagePort = _getMessagePort(appId,
+ remoteMessagePortName, true);
- event.trigger("bt-service-state-changed",
- [bluetoothSocket.peer.address, bluetoothSocket.uuid,
- state]);
- event.trigger("bt-device-connected-update",
- [bluetoothSocket.peer.address, state]);
+ if (remoteMessagePort) {
+ if (!remoteMessagePort.isTrusted) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+ } else {
+ remoteMessagePort = _setMessagePort(appId,
+ remoteMessagePortName, true, true);
+
+ event.trigger("RemoteMessagePortAdded", [appId,
+ remoteMessagePortName, true]);
+ }
+
+ return remoteMessagePort;
+ }
+};
+
+LocalMessagePort = function (messagePortName, isTrusted, listeners) {
+ var messagePort = {};
+
+ messagePort.messagePortName = messagePortName || "";
+ messagePort.isTrusted = isTrusted || false;
+
+ this.__defineGetter__("messagePortName", function () {
+ return messagePort.messagePortName;
});
- event.on("bt-service-rawdata-received", function (addr, uuid, msg) {
- var i;
+ this.__defineGetter__("isTrusted", function () {
+ return messagePort.isTrusted;
+ });
- if ((addr !== bluetoothSocket.peer.address) ||
- (uuid !== bluetoothSocket.uuid)) {
+ this.addMessagePortListener = function (listener) {
+ var watchId;
+
+ t.LocalMessagePort("addMessagePortListener", arguments);
+
+ watchId = ++_data.nListener;
+ listeners[watchId] = listener;
+
+ return watchId;
+ };
+
+ this.removeMessagePortListener = function (watchId) {
+ t.LocalMessagePort("removeMessagePortListener", arguments);
+
+ if (!listeners[watchId]) {
+ // throw new WebAPIException(errorcode.NOT_FOUND_ERR);
return;
}
- buffer = [];
- for (i = 0; i < msg.length; i++) {
- buffer.push(msg.charCodeAt(i));
- }
- if (bluetoothSocket.onmessage) {
- bluetoothSocket.onmessage();
- }
- });
-};
-module.exports = BluetoothSocket;
+ delete listeners[watchId];
+ };
+};
-});
-define('ripple/platform/tizen/2.0/BookmarkFolder', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+RemoteMessagePort = function (selfId, appId, messagePortName, isTrusted) {
+ var messagePort = {};
-var t = require('ripple/platform/tizen/2.0/typecast'),
- BookmarkFolder;
+ messagePort.appId = appId || "";
+ messagePort.messagePortName = messagePortName || "";
+ messagePort.isTrusted = isTrusted || false;
-BookmarkFolder = function (title) {
- t.BookmarkFolder(arguments, this);
+ this.__defineGetter__("appId", function () {
+ return messagePort.appId;
+ });
- this.__defineGetter__("parent", function () {
- return undefined;
+ this.__defineGetter__("messagePortName", function () {
+ return messagePort.messagePortName;
});
- this.__defineGetter__("title", function () {
- return title;
+ this.__defineGetter__("isTrusted", function () {
+ return messagePort.isTrusted;
});
+
+ this.sendMessage = function (data, localMessagePort) {
+ t.RemoteMessagePort("sendMessage", arguments);
+
+ _dispatchMessage(selfId, messagePort, data, localMessagePort);
+ };
};
-module.exports = BookmarkFolder;
+MessagePortInternal = function (selfId, appId, messagePortName, isRemote,
+ isTrusted) {
+ this.isTrusted = isTrusted;
+
+ if (isRemote) {
+ this.external = new RemoteMessagePort(selfId, appId, messagePortName,
+ isTrusted);
+ } else {
+ this.listeners = {};
+ this.external = new LocalMessagePort(messagePortName, isTrusted,
+ this.listeners);
+ }
+};
+
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/BookmarkItem', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/errorcode', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 Intel Corporation.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
*
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- BookmarkItem;
+var _self = {};
-BookmarkItem = function (title, url) {
- t.BookmarkItem(arguments, this);
+_self.__defineGetter__("UNKNOWN_ERR", function () {
+ return 0;
+});
- this.__defineGetter__("parent", function () {
- return undefined;
- });
- this.__defineGetter__("title", function () {
- return title;
- });
- this.__defineGetter__("url", function () {
- return url;
- });
-};
+_self.__defineGetter__("INDEX_SIZE_ERR", function () {
+ return 1;
+});
-module.exports = BookmarkItem;
+_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
+ return 2;
+});
+
+_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
+ return 3;
+});
+_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
+ return 4;
});
-define('ripple/platform/tizen/2.0/CalendarAlarm', function (require, exports, module) {
+
+_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
+ return 5;
+});
+
+_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
+ return 6;
+});
+
+_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
+ return 7;
+});
+
+_self.__defineGetter__("NOT_FOUND_ERR", function () {
+ return 8;
+});
+
+_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
+ return 9;
+});
+
+_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
+ return 10;
+});
+
+_self.__defineGetter__("INVALID_STATE_ERR", function () {
+ return 11;
+});
+
+_self.__defineGetter__("SYNTAX_ERR", function () {
+ return 12;
+});
+
+_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
+ return 13;
+});
+
+_self.__defineGetter__("NAMESPACE_ERR", function () {
+ return 14;
+});
+
+_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
+ return 15;
+});
+
+_self.__defineGetter__("VALIDATION_ERR", function () {
+ return 16;
+});
+
+_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
+ return 17;
+});
+
+_self.__defineGetter__("SECURITY_ERR", function () {
+ return 18;
+});
+
+_self.__defineGetter__("NETWORK_ERR", function () {
+ return 19;
+});
+
+_self.__defineGetter__("ABORT_ERR", function () {
+ return 20;
+});
+
+_self.__defineGetter__("URL_MISMATCH_ERR", function () {
+ return 21;
+});
+
+_self.__defineGetter__("QUOTA_EXCEEDED_ERR", function () {
+ return 22;
+});
+
+_self.__defineGetter__("TIMEOUT_ERR", function () {
+ return 23;
+});
+
+_self.__defineGetter__("INVALID_NODE_TYPE_ERR", function () {
+ return 24;
+});
+
+_self.__defineGetter__("DATA_CLONE_ERR", function () {
+ return 25;
+});
+
+_self.__defineGetter__("INVALID_VALUES_ERR", function () {
+ return 99;
+});
+
+_self.__defineGetter__("IO_ERR", function () {
+ return 100;
+});
+
+_self.__defineGetter__("SERVICE_NOT_AVAILABLE_ERR", function () {
+ return 111;
+});
+
+module.exports = _self;
+
+
+});
+define('ripple/platform/tizen/2.0/POIBase', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- CalendarAlarm;
+var tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError');
-CalendarAlarm = function () {
- var voc, calendarAlarm = {};
- // private
- function construct() {
- this.__defineGetter__("absoluteDate", function () {
- return calendarAlarm.absoluteDate;
- });
- this.__defineSetter__("absoluteDate", function (val) {
- try {
- calendarAlarm.absoluteDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+module.exports = function (prop) {
+ var _self, i, copy, attr;
+ _self = {
+ name : null,
+ categories : [],
+ address : null,
+ phoneNumbers : [],
+ geometry : null,
+ urls : [],
+ rating : null,
+ tags : null,
+ toGeoJSON : function () {
+ throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
+ }
+ };
- this.__defineGetter__("before", function () {
- return calendarAlarm.before;
- });
- this.__defineSetter__("before", function (val) {
- try {
- calendarAlarm.before = t.TimeDuration(val, "?");
- } catch (e) {
- }
- });
+ _self.__defineGetter__("id", function () {
+ return null;
+ });
- this.__defineGetter__("method", function () {
- return calendarAlarm.method;
- });
- this.__defineSetter__("method", function (val) {
- try {
- calendarAlarm.method = t.AlarmMethod(val);
- } catch (e) {
- }
- });
+ _self.__defineGetter__("providerName", function () {
+ return null;
+ });
- this.__defineGetter__("description", function () {
- return calendarAlarm.description;
- });
- this.__defineSetter__("description", function (val) {
- try {
- calendarAlarm.description = t.DOMString(val, "?");
- } catch (e) {
+ if (prop) {
+ if (prop.name) {
+ _self.name = String(prop.name);
+ }
+ if (tizen1_utils.isValidArray(prop.categories)) {
+ _self.categories = [];
+ for (i in prop.categories) {
+ _self.categories.push(String(prop.categories[i]));
}
- });
+ }
+ if (prop.address) {
+ if (typeof prop.address === "string") {
+ _self.address = String(prop.address);
+ } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
+ copy = prop.address.constructor();
+ for (attr in prop.address) {
+ if (prop.address.hasOwnProperty(attr)) {
+ copy[attr] = prop.address[attr];
+ }
+ }
+ _self.address = copy;
+ }
+ }
+ if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
+ _self.phoneNumbers = [];
+ for (i in prop.phoneNumbers) {
+ _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
+ }
+ }
+ if (prop.geometry) {
+ _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
+ }
+ if (tizen1_utils.isValidArray(prop.urls)) {
+ _self.urls = [];
+ for (i in prop.urls) {
+ _self.urls.push(String(prop.urls[i]));
+ }
+ }
+ if (typeof prop.rating === "number") {
+ _self.rating = prop.rating;
+ }
+ if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
+ copy = prop.tags.constructor();
+ for (attr in prop.tags) {
+ if (prop.tags.hasOwnProperty(attr)) {
+ copy[attr] = prop.tags[attr];
+ }
+ }
+ _self.tags = copy;
+ }
}
- // Constructor
- function CalendarAlarm_TZDate_AlarmMethod_DOMString(absoluteDate, method,
- description) {
- construct.call(this);
+ return _self;
+};
- calendarAlarm.absoluteDate = absoluteDate;
- calendarAlarm.before = null;
- calendarAlarm.method = method;
- calendarAlarm.description = description || "";
- }
+});
+define('ripple/platform/tizen/2.0/NDEFRecordInternal', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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 CalendarAlarm_TimeDuration_AlarmMethod_DOMString(before, method,
- description) {
- construct.call(this);
+module.exports = function (tnf, type, payload, id) {
+ this.__defineGetter__("tnf", function () {
+ return tnf;
+ });
- calendarAlarm.absoluteDate = null;
- calendarAlarm.before = before;
- calendarAlarm.method = method;
- calendarAlarm.description = description || "";
- }
+ this.__defineGetter__("type", function () {
+ return type;
+ });
- voc = [CalendarAlarm_TZDate_AlarmMethod_DOMString,
- CalendarAlarm_TimeDuration_AlarmMethod_DOMString];
- t.CalendarAlarm(arguments, this, voc);
-};
+ this.__defineGetter__("id", function () {
+ return id;
+ });
-module.exports = CalendarAlarm;
+ this.__defineGetter__("payload", function () {
+ return payload;
+ });
+};
});
-define('ripple/platform/tizen/2.0/CalendarAttendee', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/EventBase', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- CalendarAttendee;
-
-CalendarAttendee = function (uri, attendeeInitDict) {
- var calendarAttendee = {}, attr;
-
- t.CalendarAttendee(arguments, this);
-
- calendarAttendee.uri = uri;
- calendarAttendee.name = undefined;
- calendarAttendee.role = "REQ_PARTICIPANT";
- calendarAttendee.status = "PENDING";
- calendarAttendee.RSVP = false;
- calendarAttendee.type = "INDIVIDUAL";
- calendarAttendee.group = undefined;
- calendarAttendee.delegatorURI = undefined;
- calendarAttendee.delegateURI = undefined;
- calendarAttendee.contactRef = null;
+module.exports = function () {
+ var _self = {
+ CAPTURING_PHASE: 1,
+ AT_TARGET: 2,
+ BUBBLING_PHASE: 3,
- if (attendeeInitDict) {
- for (attr in attendeeInitDict) {
- calendarAttendee[attr] = attendeeInitDict[attr];
- }
- }
+ type: '',
+ target: null, //new EventTarget(),
+ currentTarget: null, //new EventTarget(),
+ eventPhase: 0,
+ bubbles: false,
+ cancelable: false,
+ timeStamp: 0
+ };
- this.__defineGetter__("uri", function () {
- return calendarAttendee.uri;
- });
- this.__defineSetter__("uri", function (val) {
- try {
- calendarAttendee.uri = t.DOMString(val);
- } catch (e) {
- }
+ this.__defineGetter__("type", function () {
+ return _self.type;
});
- this.__defineGetter__("name", function () {
- return calendarAttendee.name;
- });
- this.__defineSetter__("name", function (val) {
- try {
- calendarAttendee.name = t.DOMString(val, "?");
- } catch (e) {
- }
+ this.__defineGetter__("target", function () {
+ return _self.target;
});
- this.__defineGetter__("role", function () {
- return calendarAttendee.role;
- });
- this.__defineSetter__("role", function (val) {
- try {
- calendarAttendee.role = t.AttendeeRole(val);
- } catch (e) {
- }
+ this.__defineGetter__("currentTarget", function () {
+ return _self.currentTarget;
});
- this.__defineGetter__("status", function () {
- return calendarAttendee.status;
- });
- this.__defineSetter__("status", function (val) {
- try {
- calendarAttendee.status = t.AttendeeStatus(val);
- } catch (e) {
- }
+ this.__defineGetter__("eventPhase", function () {
+ return _self.eventPhase;
});
- this.__defineGetter__("RSVP", function () {
- return calendarAttendee.RSVP;
- });
- this.__defineSetter__("RSVP", function (val) {
- try {
- calendarAttendee.RSVP = t.boolean(val);
- } catch (e) {
- }
+ this.__defineGetter__("bubbles", function () {
+ return _self.bubbles;
});
- this.__defineGetter__("type", function () {
- return calendarAttendee.type;
- });
- this.__defineSetter__("type", function (val) {
- try {
- calendarAttendee.type = t.AttendeeType(val);
- } catch (e) {
- }
+ this.__defineGetter__("cancelable", function () {
+ return _self.cancelable;
});
- this.__defineGetter__("group", function () {
- return calendarAttendee.group;
- });
- this.__defineSetter__("group", function (val) {
- try {
- calendarAttendee.group = t.DOMString(val, "?");
- } catch (e) {
- }
+ this.__defineGetter__("timeStamp", function () {
+ return _self.timeStamp;
});
- this.__defineGetter__("delegatorURI", function () {
- return calendarAttendee.delegatorURI;
- });
- this.__defineSetter__("delegatorURI", function (val) {
- try {
- calendarAttendee.delegatorURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ this.stopPropagation = function () {};
- this.__defineGetter__("delegateURI", function () {
- return calendarAttendee.delegateURI;
- });
- this.__defineSetter__("delegateURI", function (val) {
- try {
- calendarAttendee.delegateURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ this.preventDefault = function () {};
- this.__defineGetter__("contactRef", function () {
- return calendarAttendee.contactRef;
- });
- this.__defineSetter__("contactRef", function (val) {
- try {
- calendarAttendee.contactRef = t.ContactRef(val, "?");
- } catch (e) {
- }
- });
+ this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
+ _self.type = eventTypeArg;
+ _self.bubbles = canBubbleArg;
+ _self.cancelable = cancelableArg;
+
+ _self.timeStamp = (new Date()).getTime();
+ };
+
+ return _self;
};
-module.exports = CalendarAttendee;
});
-define('ripple/platform/tizen/2.0/CalendarEvent', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/messaging', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- typedef = require('ripple/platform/tizen/2.0/typedef'),
- CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
- CalendarEvent;
-
-CalendarEvent = function () {
- var voc, calendarEvent = {};
-
- // private
- function construct(eventInitDict) {
- CalendarItem.call(this, eventInitDict);
-
- this.status = "CONFIRMED";
-
- calendarEvent.convertToString = this.convertToString;
- calendarEvent.isDetached = false;
- calendarEvent.endDate = null;
- calendarEvent.availability = "BUSY";
- calendarEvent.recurrenceRule = null;
+var _self,
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ MessagingService = require('ripple/platform/tizen/2.0/MessagingService'),
+ t = require('ripple/platform/tizen/2.0/typedef'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ TIZEN_MESSAGING_SMS = "messaging.sms",
+ TIZEN_MESSAGING_MMS = "messaging.mms",
+ TIZEN_MESSAGING_EMAIL = "messaging.email",
+ _security_check = {read: false, write: false},
+ _sms_service = null,
+ _mms_service = null,
+ _email_service = null;
- this.__defineGetter__("isDetached", function () {
- return calendarEvent.isDetached;
- });
+_self = function () {
+ this.getMessageServices = function (messageServiceType, onSuccess, onError) {
+ var service;
- this.__defineGetter__("endDate", function () {
- return calendarEvent.endDate;
- });
- this.__defineSetter__("endDate", function (val) {
- try {
- calendarEvent.endDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+ if (!(new TypeCoerce(t.MessageServiceTag)).match(messageServiceType)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (!(new TypeCoerce(t.MessageServiceArraySuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- this.__defineGetter__("availability", function () {
- return calendarEvent.availability;
- });
- this.__defineSetter__("availability", function (val) {
- try {
- calendarEvent.availability = t.EventAvailability(val);
- } catch (e) {
+ switch (messageServiceType) {
+ case "messaging.sms":
+ if (_sms_service === null) {
+ _sms_service = [new MessagingService("Tizen SMS Service 1", TIZEN_MESSAGING_SMS, _security_check), new MessagingService("Tizen SMS Service 2", TIZEN_MESSAGING_SMS, _security_check)];
}
- });
-
- this.__defineGetter__("recurrenceRule", function () {
- return calendarEvent.recurrenceRule;
- });
- this.__defineSetter__("recurrenceRule", function (val) {
- try {
- calendarEvent.recurrenceRule = t.CalendarRecurrenceRule(val,
- "?");
- } catch (e) {
+ service = _sms_service;
+ break;
+ case "messaging.mms":
+ if (_mms_service === null) {
+ _mms_service = [new MessagingService("Tizen MMS Service", TIZEN_MESSAGING_MMS, _security_check)];
}
- });
-
- this.convertToString = convertToString;
- this.clone = clone(this);
- this.expandRecurrence = expandRecurrence;
- }
-
- function clone(self) {
- return function () {
- return new CalendarEvent(self);
- };
- }
-
- // public
- function convertToString(format) {
- var str;
-
- str = calendarEvent.convertToString.call(this, format);
- str = str.replace(/#TYPE#/g, "VEVENT");
-
- // TODO: endDate is not supported
- // TODO: recurrenceRule is not supported
- str = str.replace(/#AVAILABILITY#/g, "FREEBUSY;FBTYPE=" +
- calendarEvent.availability);
-
- str = str.replace(/#[^#]*#/g, "");
-
- return str;
- }
-
- function expandRecurrence(startDate, endDate, successCallback,
- errorCallback) {
- }
-
- // Constructor
- function CalendarEvent_CalendarEventInit(eventInitDict) {
- var attr;
-
- construct.call(this, eventInitDict);
-
- if (eventInitDict) {
- for (attr in eventInitDict) {
- if (attr in typedef.CalendarEventInit) {
- calendarEvent[attr] = eventInitDict[attr];
- }
+ service = _mms_service;
+ break;
+ case "messaging.email":
+ if (_email_service === null) {
+ _email_service = [new MessagingService("Tizen Email Service", TIZEN_MESSAGING_EMAIL, _security_check)];
}
+ service = _email_service;
+ break;
+ default:
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
}
- }
-
- function CalendarEvent_DOMString_CalendarTextFormat(stringRepresentation,
- format) {
- }
-
- voc = [CalendarEvent_CalendarEventInit,
- CalendarEvent_DOMString_CalendarTextFormat];
- t.CalendarEvent(arguments, this, voc);
+ setTimeout(function () {
+ onSuccess(service);
+ }, 1);
+ };
+ this.handleSubFeatures = function (subFeatures) {
+ if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.read')) {
+ _security_check.read = true;
+ }
+ if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.write')) {
+ _security_check.write = true;
+ }
+ };
};
-module.exports = CalendarEvent;
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/CalendarEventId', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/NDEFRecord', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2013 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
var t = require('ripple/platform/tizen/2.0/typecast'),
- CalendarEventId;
-
-CalendarEventId = function (uid, rid) {
- var calendarEventId = {};
-
- t.CalendarEventId(arguments, this);
-
- calendarEventId.uid = uid;
- calendarEventId.rid = rid || null;
+ NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
+ NDEFRecord;
- this.__defineGetter__("uid", function () {
- return calendarEventId.uid;
- });
- this.__defineSetter__("uid", function (val) {
- try {
- calendarEventId.uid = t.DOMString(val);
- } catch (e) {
+NDEFRecord = function () {
+ var voc = [
+ function (tnf, type, payload, id) {
+ NDEFRecordInternal.call(this, tnf, type, payload, id || []);
+ },
+ function (raw_data) {
+ NDEFRecordInternal.call(this, 0, [], [], []);
}
- });
+ ];
- this.__defineGetter__("rid", function () {
- return calendarEventId.rid;
- });
- this.__defineSetter__("rid", function (val) {
- try {
- calendarEventId.rid = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ t.NDEFRecord(arguments, this, voc);
};
-module.exports = CalendarEventId;
+module.exports = NDEFRecord;
});
-define('ripple/platform/tizen/2.0/CalendarItem', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/MessageStorage', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var t = require('ripple/platform/tizen/2.0/typecast'),
+var _self,
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ Message = require('ripple/platform/tizen/2.0/Message'),
+ Conversation = require('ripple/platform/tizen/2.0/Conversation'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
+ MessageFolder = require('ripple/platform/tizen/2.0/MessageFolder'),
+ msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- typedef = require('ripple/platform/tizen/2.0/typedef'),
- CalendarItem;
-
-CalendarItem = function (itemInitDict) {
- var calendarItem = {}, attr;
-
- // private
- function toDigit(number) {
- return ((number >= 10) ? "" : "0") + number;
- }
+ t = require('ripple/platform/tizen/2.0/typedef'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
+ "messaging.mms": "13572468",
+ "messaging.email": "tizen.simulator@tizen.org"};
- // public
- function convertToString(format) {
- var header = "BEGIN:VCALENDAR\r\nPRODID:-//Tizen.org//Tizen Calendar//EN\r\nVERSION:2.0\r\n",
- end = "END:VCALENDAR\r\n", str = "", pri, i, date, before, y, m, d,
- hh, mm, ss, dateStart = "", dateEnd = "";
+_self = function (messages, security_check) {
+ var message_storage = {},
+ _findMessage, _findConversation,
+ _processMessageChange, _processConversationChange,
+ _folders = {}, folderOpt = {},
+ _msgListeners = {},
+ _convListeners = {},
+ _folderListeners = {},
+ _security_check = security_check,
+ _messages = messages;
- t.CalendarItem("convertToString", arguments);
+ // init folders
+ folderOpt = {id: "INBOX", serviceId: _messages.id, contentType: _messages.type,
+ path: "inbox", type: "INBOX", synchronizable: true};
+ _folders.INBOX = new MessageFolder(folderOpt);
+ folderOpt = {id: "OUTBOX", serviceId: _messages.id, contentType: _messages.type,
+ path: "outbox", type: "OUTBOX", synchronizable: false};
+ _folders.OUTBOX = new MessageFolder(folderOpt);
+ folderOpt = {id: "DRAFT", serviceId: _messages.id, contentType: _messages.type,
+ path: "draft", type: "DRAFTS", synchronizable: false};
+ _folders.DRAFT = new MessageFolder(folderOpt);
+ folderOpt = {id: "SENTBOX", serviceId: _messages.id, contentType: _messages.type,
+ path: "sentbox", type: "SENTBOX", synchronizable: false};
+ _folders.SENTBOX = new MessageFolder(folderOpt);
- //TODO: vcalendar 1.0 doesn't support yet
- if (format === "VCALENDAR_10") {
+ event.on("MsgRecv", function (msg) {
+ // msg sent from panel to module
+ if (msg.priv.type !== _messages.type ||
+ msg.priv.serviceId !== _messages.id) {
return;
}
+ // trigger Message add
+ _processMessageChange([msg], "add");
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- str = header + "BEGIN:#TYPE#\r\n";
-
- if (this.isAllDay) {
- if (this.startDate) {
- date = this.startDate;
- y = date.getFullYear();
- m = toDigit(date.getMonth() + 1);
- d = toDigit(date.getDate());
- str += "DTSTART;VALUE=DATE:" + y + m + d + "\r\n";
- dateStart = "" + y + m + d + "T000000Z";
- if (this.duration) {
- date = date.addDuration(this.duration);
- y = date.getFullYear();
- m = toDigit(date.getMonth() + 1);
- d = toDigit(date.getDate());
- str += "DTEND;VALUE=DATE:" + y + m + d + "\r\n";
- dateEnd = "" + y + m + d + "T000000Z";
- }
- }
+ if (_messages.conv[msg.priv.conversationId].messageCount === 1) {
+ _processConversationChange([_messages.conv[msg.priv.conversationId]], "add");
} else {
- if (this.startDate) {
- date = this.startDate;
- y = date.getFullYear();
- m = toDigit(date.getMonth() + 1);
- d = toDigit(date.getDate());
- hh = toDigit(date.getHours());
- mm = toDigit(date.getMinutes());
- ss = toDigit(date.getSeconds());
- str += "DTSTART:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
- dateStart = "" + y + m + d + "T" + hh + mm + ss + "Z";
- if (this.duration && this.duration.length && this.duration.unit) {
- date = date.addDuration(this.duration);
- y = date.getFullYear();
- m = toDigit(date.getMonth() + 1);
- d = toDigit(date.getDate());
- hh = toDigit(date.getHours());
- mm = toDigit(date.getMinutes());
- ss = toDigit(date.getSeconds());
- str += "DTEND:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
- dateEnd = "" + y + m + d + "T" + hh + mm + ss + "Z";
- }
- }
+ _processConversationChange([_messages.conv[msg.priv.conversationId]], "update");
}
+ });
- if (this.description) {
- str += "DESCRIPTION:" + this.description + "\r\n";
- }
- if (this.summary) {
- str += "SUMMARY:" + this.summary + "\r\n";
- }
- if (this.location) {
- str += "LOCATION:" + this.location + "\r\n";
- }
- if (this.geolocation) {
- // Don't need to check latitude and longitude due to they are mandatory attributes
- str += "GEO:" + this.geolocation.latitude + "," + this.geolocation.longitude + "\r\n";
- }
- if (this.organizer) {
- str += "ORGANIZER:" + this.organizer + "\r\n";
- }
- if (this.visibility) {
- str += "CLASS:" + this.visibility + "\r\n";
+ event.on("OutsideMessageReceived", function (msg) {
+ // msg sent from module to panel
+ if (msg.msg.priv.type !== _messages.type ||
+ msg.msg.priv.serviceId !== _messages.id) {
+ return;
}
- if (this.status) {
- str += "STATUS:" + this.status + "\r\n";
+ // trigger conversation/Message add
+ _processMessageChange([msg.msg], "add");
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+
+ if (_messages.conv[msg.msg.priv.conversationId].messageCount === 1) {
+ _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "add");
+ } else {
+ _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "update");
}
- if (this.priority) {
- switch (this.priority) {
- case "HIGH":
- pri = 2;
- break;
- case "MEDIUM":
- pri = 5;
- break;
- case "LOW":
- pri = 7;
- break;
- }
- str += "PRIORITY:" + pri + "\r\n";
+ });
+
+ event.on("MsgSentRst", function (rst) {
+ // ACK from panel when module sent a msg to panel
+ if (rst.priv.type !== _messages.type ||
+ rst.priv.serviceId !== _messages.id) {
+ return;
}
- if (tizen1_utils.isValidArray(this.alarms)) {
- for (i = 0; i < this.alarms.length; i++) {
- str += "BEGIN:VALARM\r\n";
- // Don't need to check this.alarms[i].method due to it is a mandatory attribute
- str += "ACTION:" + this.alarms[i].method + "\r\n";
- if (this.alarms[i].description) {
- str += "DESCRIPTION:" + this.alarms[i].description + "\r\n";
- } else {
- // description property MUST included if action is DISPLAY (RFC5545 3.6.6)
- str += "DESCRIPTION:This is a reminder\r\n";
- }
- if (this.alarms[i].absoluteDate) {
- date = this.alarms[i].absoluteDate;
- y = date.getFullYear();
- m = toDigit(date.getMonth() + 1);
- d = toDigit(date.getDate());
- hh = toDigit(date.getHours());
- mm = toDigit(date.getMinutes());
- ss = toDigit(date.getSeconds());
- str += "TRIGGER;VALUE=DATE-TIME:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
- } else {
- //it must be included before attribute
- before = this.alarms[i].before;
- switch (before.unit) {
- case "DAYS":
- str += "TRIGGER:-P" + before.length + "D" + "\r\n";
- break;
- case "HOURS":
- str += "TRIGGER:-P0DT" + before.length + "H0M0S" + "\r\n";
- break;
- case "MINS":
- str += "TRIGGER:-P0DT0H" + before.length + "M0S" + "\r\n";
- break;
- case "SECS":
- str += "TRIGGER:-P0DT0H0M" + before.length + "S" + "\r\n";
- break;
- }
- }
- str += "END:VALARM\r\n";
+ // trigger conversation/Message Update
+ _processMessageChange([rst], "update");
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ _processConversationChange([_messages.conv[rst.priv.conversationId]], "update");
+ });
+
+ _findMessage = function (src, filter) {
+ var ret, foo = {};
+ switch (filter.attributeName) {
+ case "type":
+ foo[filter.attributeName] = _messages.type;
+ ret = tizen1_utils.matchAttributeFilter([foo],
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ if (ret.length === 0) {
+ ret = [];
+ } else {
+ // make an array
+ ret = utils.filter(src, function () { return true; });
}
- }
- if (tizen1_utils.isValidArray(this.categories)) {
- str += "CATEGORIES:";
- for (i = 0; i < this.categories.length; i++) {
- str += this.categories[i] + ",";
+ break;
+ case "id":
+ case "conversationId":
+ case "folderId":
+ case "from":
+ case "messageStatus":
+ ret = tizen1_utils.matchAttributeFilter(src,
+ "priv." + filter.attributeName,
+ filter.matchFlag, filter.matchValue);
+ break;
+ case "hasAttachment":
+ if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
}
- str = str.slice(0, -1);
- str += "\r\n";
- }
- if (tizen1_utils.isValidArray(this.attendees)) {
- for (i = 0; i < this.attendees.length; i++) {
- //TODO: basic implementation
- str += "ATTENDEE:mailto:" + this.attendees[i].uri + "\r\n";
+ ret = tizen1_utils.matchAttributeBooleanFilter(src,
+ "priv." + filter.attributeName, filter.matchValue);
+ break;
+ case "to":
+ case "cc":
+ case "bcc":
+ ret = tizen1_utils.matchAttributeArrayFilter(src,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
+ case "body":
+ ret = tizen1_utils.matchAttributeFilter(src,
+ filter.attributeName + ".plainBody",
+ filter.matchFlag, filter.matchValue);
+ break;
+ case "subject":
+ case "inResponseTo":
+ ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName,
+ filter.matchFlag, filter.matchValue);
+ break;
+ case "isRead":
+ case "isHighPriority":
+ if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
}
- }
+ ret = tizen1_utils.matchAttributeBooleanFilter(src,
+ filter.attributeName, filter.matchValue);
+ break;
+ case "timestamp":
+ ret = tizen1_utils.matchAttributeRangeFilter(src,
+ "priv." + filter.attributeName,
+ filter.initialValue, filter.endValue);
+ break;
- if ((dateStart !== "") && (dateEnd !== "")) {
- str += "#AVAILABILITY#:" + dateStart + "/" + dateEnd + "\r\n";
+ case "attachments":
+ throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR,
+ "not support find by " + filter.attributeName));
+ default:
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "invalid attributeName"));
}
+ return ret;
+ };
- str += "#ENDDATE##RECURRENCERULE#";
- str += "#DUEDATE##COMPLETEDDATE##PROGRESS#";
- str += "END:#TYPE#\r\n" + end;
-
- return str;
- }
-
- calendarItem.description = "";
- calendarItem.summary = "";
- calendarItem.isAllDay = false;
- calendarItem.startDate = null;
- calendarItem.duration = null;
- calendarItem.location = "";
- calendarItem.geolocation = null;
- calendarItem.organizer = "";
- calendarItem.visibility = "PUBLIC";
- calendarItem.status = "TENTATIVE";
- calendarItem.priority = "LOW";
- calendarItem.alarms = [];
- calendarItem.categories = [];
- calendarItem.attendees = [];
-
- if (itemInitDict) {
- for (attr in itemInitDict) {
- if (!(attr in typedef.CalendarItemInit))
- continue;
-
- switch (attr) {
- case "alarms":
- calendarItem.alarms = t.CalendarAlarm(itemInitDict.alarms,
- "[]+");
- break;
-
- case "categories":
- calendarItem.categories = t.DOMString(itemInitDict.categories,
- "[]+");
- break;
-
- case "attendees":
- calendarItem.attendees = t.CalendarAttendee(
- itemInitDict.attendees, "[]+");
- break;
+ _processMessageChange = function (messages, type) {
+ var i, j, ret = [], tmp,
+ operation = {"add": "messagesadded",
+ "remove": "messagesremoved",
+ "update": "messagesupdated"};
- default:
- calendarItem[attr] = itemInitDict[attr];
- break;
+ for (i in _msgListeners) {
+ ret = [];
+ if (_msgListeners[i].filter !== null) {
+ tmp = _findMessage(messages, _msgListeners[i].filter);
+ } else {
+ tmp = messages;
+ }
+ if (tmp.length !== 0) {
+ for (j = 0; j < tmp.length; j++) {
+ ret.push(new Message(tmp[j].priv.type, tmp[j]));
+ }
+ _msgListeners[i].callback[operation[type]](ret);
}
}
- }
-
- this.__defineGetter__("id", function () {
- return null;
- });
+ };
- this.__defineGetter__("calendarId", function () {
- return null;
- });
+ _findConversation = function (src, filter) {
+ var ret, foo = {};
+ switch (filter.attributeName) {
+ case "type":
+ foo[filter.attributeName] = _messages.type;
+ ret = tizen1_utils.matchAttributeFilter([foo], filter.attributeName, filter.matchFlag, filter.matchValue);
+ if (ret.length === 0) {
+ ret = [];
+ } else {
+ // make an array
+ ret = utils.filter(_messages.conv, function () { return true; });
+ }
+ break;
+ case "id":
+ case "preview":
+ case "subject":
+ case "from":
+ case "lastMessageId":
+ ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
+ case "to":
+ case "cc":
+ case "bcc":
+ ret = tizen1_utils.matchAttributeArrayFilter(src,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
+ case "isRead":
+ if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
+ }
+ ret = tizen1_utils.matchAttributeBooleanFilter(src,
+ filter.attributeName, filter.matchValue);
+ break;
+ case "timestamp":
+ case "messageCount":
+ case "unreadMessages":
+ ret = tizen1_utils.matchAttributeRangeFilter(src,
+ filter.attributeName,
+ filter.initialValue, filter.endValue);
+ break;
+ default:
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "invalid attributeName"));
+ }
+ return ret;
+ };
- this.__defineGetter__("lastModificationDate", function () {
- return null;
- });
+ _processConversationChange = function (conversations, type) {
+ var i, j, ret = [], tmp,
+ operation = {"add": "conversationsadded",
+ "remove": "conversationsremoved",
+ "update": "conversationsupdated"};
- this.__defineGetter__("description", function () {
- return calendarItem.description;
- });
- this.__defineSetter__("description", function (val) {
- try {
- calendarItem.description = t.DOMString(val, "?");
- } catch (e) {
+ for (i in _convListeners) {
+ ret = [];
+ if (_convListeners[i].filter !== null) {
+ tmp = _findConversation(conversations, _convListeners[i].filter);
+ } else {
+ tmp = conversations;
+ }
+ if (tmp.length !== 0) {
+ for (j = 0; j < tmp.length; j++) {
+ ret.push(new Conversation(tmp[j]));
+ }
+ _convListeners[i].callback[operation[type]](ret);
+ }
}
- });
+ };
- this.__defineGetter__("summary", function () {
- return calendarItem.summary;
- });
- this.__defineSetter__("summary", function (val) {
- try {
- calendarItem.summary = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ message_storage = {
+ addDraftMessage: function (_msg, onSuccess, onError) {
+ var m, msg = {}, opt = {};
- this.__defineGetter__("isAllDay", function () {
- return calendarItem.isAllDay;
- });
- this.__defineSetter__("isAllDay", function (val) {
- try {
- calendarItem.isAllDay = t.boolean(val);
- } catch (e) {
- }
- });
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (msg_utils.setMsg(_msg, msg) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ opt.id = Math.uuid(8, 16);
+ opt.serviceId = _messages.id;
+ if ((msg.inResponseTo !== null) &&
+ (_messages.msg[msg.inResponseTo] !== undefined)) {
+ opt.conversationId = _messages.msg[msg.inResponseTo].conversationId;
+ } else {
+ opt.conversationId = opt.id;
+ }
+ opt.folderId = "DRAFTS";
+ opt.type = _messages.type;
+ opt.timestamp = new Date();
+ opt.from = TIZEN_DEFAULT_MSG_FROM[_messages.type];
+ if (msg.attachments.length === 0) {
+ opt.hasAttachment = false;
+ } else {
+ opt.hasAttachment = true;
+ }
+ opt.messageStatus = "DRAFT";
- this.__defineGetter__("startDate", function () {
- return calendarItem.startDate;
- });
- this.__defineSetter__("startDate", function (val) {
- try {
- calendarItem.startDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+ m = new PrivMessage(msg, opt);
+ _messages.msg[m.priv.id] = m; // local
+ msg_utils.saveMsg(_messages.msg[m.priv.id]); // remote
+ // trigger message add
+ _processMessageChange([m], "add");
+ if (onSuccess) {
+ setTimeout(function () {
+ onSuccess(new Message(m.priv.type, m));
+ }, 1);
+ }
+ },
- this.__defineGetter__("duration", function () {
- return calendarItem.duration;
- });
- this.__defineSetter__("duration", function (val) {
- try {
- calendarItem.duration = t.TimeDuration(val, "?");
- } catch (e) {
- }
- });
+ removeMessages: function (messages, onSuccess, onError) {
+ var i, c, na_msg = "", msgToDel = [], convToDel = {}, delConv = [], updateConv = [];
- this.__defineGetter__("location", function () {
- return calendarItem.location;
- });
- this.__defineSetter__("location", function (val) {
- try {
- calendarItem.location = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (tizen1_utils.isValidArray(messages) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (messages.length === 0) {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
+ }
+ if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- this.__defineGetter__("geolocation", function () {
- return calendarItem.geolocation;
- });
- this.__defineSetter__("geolocation", function (val) {
- try {
- calendarItem.geolocation = t.SimpleCoordinates(val, "?");
- } catch (e) {
- }
- });
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ for (i = 0; i < messages.length; i++) {
+ if (_messages.msg[messages[i].id] === undefined) {
+ na_msg += messages[i].id + ", ";
+ } else {
+ msgToDel.push(utils.copy(_messages.msg[messages[i].id]));
+ }
+ if (_messages.conv[messages[i].conversationId] !== undefined) {
+ convToDel[messages[i].conversationId] = _messages.conv[messages[i].conversationId];
+ }
+ }
+ if (na_msg === "") {
+ for (i = 0; i < messages.length; i++) {
+ // conversation updated at remote when msg is deleted
+ msg_utils.delMsg(_messages.msg[messages[i].id]); // remote
+ delete _messages.msg[messages[i].id]; // local
+ }
+ // update conversation
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ for (c in convToDel) {
+ if (_messages.conv[c] === undefined) {
+ delConv.push(convToDel[c]);
+ } else {
+ updateConv.push(convToDel[c]);
+ }
+ }
+ if (onSuccess) {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ }
+ // trigger messages remove
+ _processMessageChange(msgToDel, "remove");
+ if (delConv.length > 0) {
+ _processConversationChange(delConv, "remove");
+ }
+ if (updateConv.length > 0) {
+ _processConversationChange(updateConv, "update");
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
+ na_msg + "not found !!"));
+ }, 1);
+ }
+ }
+ },
- this.__defineGetter__("organizer", function () {
- return calendarItem.organizer;
- });
- this.__defineSetter__("organizer", function (val) {
- try {
- calendarItem.organizer = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ updateMessages: function (messages, onSuccess, onError) {
+ var i, m, updateConv = {}, updateMsg = [], tmp,
+ na_msg = "", invalid_msg = "";
- this.__defineGetter__("visibility", function () {
- return calendarItem.visibility;
- });
- this.__defineSetter__("visibility", function (val) {
- try {
- calendarItem.visibility = t.CalendarItemVisibility(val);
- } catch (e) {
- }
- });
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (tizen1_utils.isValidArray(messages) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (messages.length === 0) {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
+ }
+ // update conversation
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ for (i = 0; i < messages.length; i++) {
+ m = _messages.msg[messages[i].id];
+ if (m === undefined) {
+ // msg not found
+ na_msg += messages[i].id + ", ";
+ } else {
+ if (m.priv.messageStatus === "DRAFT") {
+ tmp = {};
+ // allow update all writeable attr in draft
+ if (msg_utils.setMsg(messages[i], tmp) === false) {
+ invalid_msg += messages[i].id + ", ";
+ }
+ }
+ }
+ }
+ if (invalid_msg !== "") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR,
+ invalid_msg + "invalid values"));
+ }, 1);
+ }
+ return;
+ }
+ if (na_msg !== "") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
+ na_msg + "not found !!"));
+ }, 1);
+ }
+ return;
+ }
- this.__defineGetter__("status", function () {
- return calendarItem.status;
- });
- this.__defineSetter__("status", function (val) {
- try {
- calendarItem.status = t.CalendarItemStatus(val);
- } catch (e) {
- }
- });
+ for (i = 0; i < messages.length; i++) {
+ m = _messages.msg[messages[i].id];
+ if (m.priv.messageStatus === "DRAFT") {
+ msg_utils.setMsg(messages[i], m);
+ updateMsg.push(m);
+ } else {
+ // only allow update isRead in other folders
+ if (typeof messages[i].isRead === 'boolean') {
+ m.isRead = messages[i].isRead;
+ updateMsg.push(m);
+ updateConv[m.priv.conversationId] = _messages.conv[m.priv.conversationId];
+ }
+ }
+ msg_utils.saveMsg(m);
+ }
+ if (onSuccess) {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ }
- this.__defineGetter__("priority", function () {
- return calendarItem.priority;
- });
- this.__defineSetter__("priority", function (val) {
- try {
- calendarItem.priority = t.CalendarItemPriority(val);
- } catch (e) {
- }
- });
+ // trigger Message update
+ _processMessageChange(updateMsg, "update");
- this.__defineGetter__("alarms", function () {
- return calendarItem.alarms;
- });
- this.__defineSetter__("alarms", function (val) {
- try {
- calendarItem.alarms = t.CalendarAlarm(val, "[]");
- } catch (e) {
- }
- });
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ // trigger conversation update
+ _processConversationChange(updateConv, "update");
+ },
- this.__defineGetter__("categories", function () {
- return calendarItem.categories;
- });
- this.__defineSetter__("categories", function (val) {
- try {
- calendarItem.categories = t.DOMString(val, "[]");
- } catch (e) {
- }
- });
+ findMessages: function (filter, onSuccess, onError, sort, _limit, _offset) {
+ var i, tmp, offset, limit, ret = [];
- this.__defineGetter__("attendees", function () {
- return calendarItem.attendees;
- });
- this.__defineSetter__("attendees", function (val) {
- try {
- calendarItem.attendees = t.CalendarAttendee(val, "[]");
- } catch (e) {
- }
- });
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageArraySuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ tmp = _findMessage(_messages.msg, filter);
- this.convertToString = convertToString;
-};
+ if (_offset) {
+ offset = _offset;
+ } else {
+ offset = 0;
+ }
+ if (_limit) {
+ limit = Math.min(_limit + offset, tmp.length);
+ } else {
+ limit = tmp.length;
+ }
+ for (i = offset; i < limit; i++) {
+ ret.push(new Message(tmp[i].priv.type, tmp[i]));
+ }
+ setTimeout(function () {
+ onSuccess(ret);
+ }, 1);
+ },
-module.exports = CalendarItem;
+ findConversations: function (filter, onSuccess, onError, sort, _limit, _offset) {
+ var i, tmp, offset, limit, ret = [];
-});
-define('ripple/platform/tizen/2.0/CalendarRecurrenceRule', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageConversationArraySuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ // download conversation
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
-var t = require('ripple/platform/tizen/2.0/typecast'),
- CalendarRecurrenceRule;
+ tmp = _findConversation(_messages.conv, filter);
-CalendarRecurrenceRule = function (frequency, ruleInitDict) {
- var calendarRecurrenceRule = {}, attr;
+ if (_offset) {
+ offset = _offset;
+ } else {
+ offset = 0;
+ }
+ if (_limit) {
+ limit = Math.min(_limit + offset, tmp.length);
+ } else {
+ limit = tmp.length;
+ }
+ for (i = offset; i < limit; i++) {
+ ret.push(new Conversation(tmp[i]));
+ }
+ setTimeout(function () {
+ onSuccess(ret);
+ }, 1);
+ },
- t.CalendarRecurrenceRule(arguments, this);
+ removeConversations: function (conversations, onSuccess, onError) {
+ var i, m, na_msg = "", retConv = [], removeMsg = [];
- calendarRecurrenceRule.frequency = frequency;
- calendarRecurrenceRule.interval = 1;
- calendarRecurrenceRule.untilDate = null;
- calendarRecurrenceRule.occurrenceCount = -1;
- calendarRecurrenceRule.daysOfTheWeek = [];
- calendarRecurrenceRule.setPositions = [];
- calendarRecurrenceRule.exceptions = [];
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ // download conversation
+ _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- if (ruleInitDict) {
- for (attr in ruleInitDict) {
- switch (attr) {
- case "daysOfTheWeek":
- calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(
- ruleInitDict.daysOfTheWeek, "[]+");
- break;
+ if (tizen1_utils.isValidArray(conversations) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (conversations.length === 0) {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
+ }
+ if ((onSuccess && typeof onSuccess !== "function") ||
+ (onError && typeof onError !== "function")) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- case "setPositions":
- calendarRecurrenceRule.setPositions = t.short(
- ruleInitDict.setPositions, "[]+");
- break;
+ for (i = 0; i < conversations.length; i++) {
+ if (_messages.conv[conversations[i].id] === undefined) {
+ na_msg += conversations[i].id + ", ";
+ } else {
+ retConv.push(_messages.conv[conversations[i].id]);
+ for (m in _messages.msg) {
+ if (_messages.msg[m].priv.conversationId === conversations[i].id) {
+ removeMsg.push(_messages.msg[m]);
+ }
+ }
+ }
+ }
+ if (na_msg === "") {
+ for (i = 0; i < removeMsg.length; i++) {
+ // conversation updated at remote
+ msg_utils.delMsg(removeMsg[i]); // remote
+ delete _messages.msg[removeMsg[i].priv.id]; // local
+ }
+ // trigger msg(retMsg)/conv(retConv) delete update
+ _processMessageChange(removeMsg, "remove");
+ _processConversationChange(retConv, "remove");
+ if (onSuccess) {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
+ na_msg + "not found !!"));
+ }, 1);
+ }
+ }
+ },
- case "exceptions":
- calendarRecurrenceRule.exceptions = t.TZDate(
- ruleInitDict.exceptions, "[]+");
- break;
+ findFolders: function (filter, onSuccess, onError) {
+ var ret = [], tmp, i;
- default:
- calendarRecurrenceRule[attr] = ruleInitDict[attr];
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageFolderArraySuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ switch (filter.attributeName) {
+ case "id":
+ case "serviceId":
+ case "contentType":
+ case "name":
+ case "path":
+ case "type":
+ tmp = tizen1_utils.matchAttributeFilter(_folders,
+ filter.attributeName, filter.matchFlag,
+ filter.matchValue);
+ break;
+ case "synchronizable":
+ if (filter.matchFlag !== "EXACTLY" ||
+ typeof filter.matchValue !== "boolean") {
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
+ }
+ tmp = tizen1_utils.matchAttributeBooleanFilter(_folders,
+ filter.attributeName, filter.matchValue);
+ break;
+ case "parentId":
+ if (filter.matchValue === null) {
+ tmp = utils.filter(_folders, function (o) { return o.parentId === null; });
+ } else {
+ tmp = tizen1_utils.matchAttributeFilter(_folders,
+ filter.attributeName, filter.matchValue);
+ }
break;
+ default:
+ throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
+ "invalid attributeName"));
}
- }
- }
+ for (i = 0; i < tmp.length; i++) {
+ ret.push(new MessageFolder(tmp[i]));
+ }
+ setTimeout(function () {
+ onSuccess(ret);
+ }, 1);
+ },
- this.__defineGetter__("frequency", function () {
- return calendarRecurrenceRule.frequency;
- });
- this.__defineSetter__("frequency", function (val) {
- try {
- calendarRecurrenceRule.frequency = t.RecurrenceRuleFrequency(val);
- } catch (e) {
- }
- });
+ addMessagesChangeListener: function (msgCallback, filter) {
+ var watchId, msgListener = {};
- this.__defineGetter__("interval", function () {
- return calendarRecurrenceRule.interval;
- });
- this.__defineSetter__("interval", function (val) {
- try {
- calendarRecurrenceRule.interval = t.unsigned_short(val);
- } catch (e) {
- }
- });
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessagesChangeCallback)).match(msgCallback)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- this.__defineGetter__("untilDate", function () {
- return calendarRecurrenceRule.untilDate;
- });
- this.__defineSetter__("untilDate", function (val) {
- try {
- calendarRecurrenceRule.untilDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+ watchId = Number(Math.uuid(8, 10));
+ msgListener.callback = msgCallback;
+ msgListener.filter = filter || null;
+ _msgListeners[watchId] = msgListener;
+ return watchId;
+ },
- this.__defineGetter__("occurrenceCount", function () {
- return calendarRecurrenceRule.occurrenceCount;
- });
- this.__defineSetter__("occurrenceCount", function (val) {
- try {
- calendarRecurrenceRule.occurrenceCount = t.long(val);
- } catch (e) {
- }
- });
+ addConversationsChangeListener: function (convCallback, filter) {
+ var watchId, convListener = {};
- this.__defineGetter__("daysOfTheWeek", function () {
- return calendarRecurrenceRule.daysOfTheWeek;
- });
- this.__defineSetter__("daysOfTheWeek", function (val) {
- try {
- calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(val, "[]");
- } catch (e) {
- }
- });
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageConversationsChangeCallback)).match(convCallback)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- this.__defineGetter__("setPositions", function () {
- return calendarRecurrenceRule.setPositions;
- });
- this.__defineSetter__("setPositions", function (val) {
- try {
- calendarRecurrenceRule.setPositions = t.short(val, "[]");
- } catch (e) {
- }
- });
+ watchId = Number(Math.uuid(8, 10));
+ convListener.callback = convCallback;
+ convListener.filter = filter || null;
+ _convListeners[watchId] = convListener;
+ return watchId;
+ },
- this.__defineGetter__("exceptions", function () {
- return calendarRecurrenceRule.exceptions;
- });
- this.__defineSetter__("exceptions", function (val) {
- try {
- calendarRecurrenceRule.exceptions = t.TZDate(val, "[]");
- } catch (e) {
+ addFoldersChangeListener: function (callback, filter) {
+ var watchId, folderListener = {};
+
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageFoldersChangeCallback)).match(callback)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+
+ watchId = Number(Math.uuid(8, 10));
+ folderListener.callback = callback;
+ folderListener.filter = filter || null;
+ _folderListeners[watchId] = folderListener;
+ return watchId;
+ },
+
+ removeChangeListener: function (watchid) {
+ if (_security_check.read === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (_msgListeners[watchid] !== undefined) {
+ delete _msgListeners[watchid];
+ return;
+ }
+ if (_convListeners[watchid] !== undefined) {
+ delete _convListeners[watchid];
+ return;
+ }
+ if (_folderListeners[watchid] !== undefined) {
+ delete _folderListeners[watchid];
+ return;
+ }
}
- });
+
+ };
+ return message_storage;
};
-module.exports = CalendarRecurrenceRule;
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/CalendarTask', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/datacontrol', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2013 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- typedef = require('ripple/platform/tizen/2.0/typedef'),
- CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
- CalendarTask;
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ DataControlConsumerFactory,
+ DataControlConsumerObject,
+ SQLDataControlConsumer,
+ MappedDataControlConsumer,
+ SQLData,
+ MappedData,
+ _data = {
+ DB_DATACONTROL_KEY: "tizen1-db-datacontrol",
+ IDS_PROVIDER: ["http://tizen.org/datacontrol/provider/DictionaryDataControlProvider"],
+ IDS_DATA: ["Dictionary"],
+ PERSIST_DELAY: 1000,
+ SQL: null,
+ MAP: null,
+ dbStorage: null
+ },
+ _security = {
+ "http://tizen.org/privilege/datacontrol.consumer":
+ ["getDataControlConsumer", "insert", "update", "remove", "select",
+ "addValue", "removeValue", "getValue", "updateValue"]
+ },
+ _self;
-CalendarTask = function () {
- var voc, calendarTask = {};
+function _get() {
+ _data.dbStorage = db.retrieveObject(_data.DB_DATACONTROL_KEY) || {};
+}
- // private
- function construct(taskInitDict) {
- CalendarItem.call(this, taskInitDict);
+function _save() {
+ db.saveObject(_data.DB_DATACONTROL_KEY, _data.dbStorage);
+}
- this.status = "NEEDS_ACTION";
+function _load(type) {
+ if (!_data.dbStorage[type])
+ return;
- calendarTask.convertToString = this.convertToString;
- calendarTask.dueDate = null;
- calendarTask.completedDate = null;
- calendarTask.progress = 0;
+ _data[type] = {};
- this.__defineGetter__("dueDate", function () {
- return calendarTask.dueDate;
- });
- this.__defineSetter__("dueDate", function (val) {
- try {
- calendarTask.dueDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+ utils.forEach(_data.dbStorage[type], function (provider, id) {
+ var dataId;
- this.__defineGetter__("completedDate", function () {
- return calendarTask.completedDate;
- });
- this.__defineSetter__("completedDate", function (val) {
- try {
- calendarTask.completedDate = t.TZDate(val, "?");
- } catch (e) {
- }
- });
+ _data[type][id] = {};
- this.__defineGetter__("progress", function () {
- return calendarTask.progress;
- });
- this.__defineSetter__("progress", function (val) {
- try {
- calendarTask.progress = t.unsigned_short(val);
- } catch (e) {
- }
- });
+ for (dataId in provider) {
+ _data[type][id][dataId] = new DataControlConsumerFactory(type,
+ id, dataId, provider[dataId]);
+ }
+ });
+}
- this.convertToString = convertToString;
- this.clone = clone(this);
- }
+function _initialize() {
+ _get();
- function clone(self) {
- return function () {
- return new CalendarTask(self);
- };
- }
+ _load("SQL");
+ _load("MAP");
+}
- // public
- function convertToString(format) {
- var str;
+_self = function () {
+ var datacontrol;
- str = calendarTask.convertToString.call(this, format);
- str = str.replace(/#TYPE#/g, "VTASK");
+ // private
+ function initConsumer(type) {
+ var providers;
- // TODO: dueDate is not supported
- // TODO: completedDate is not supported
- if (this.progress) {
- str = str.replace(/#PROGRESS#/g, "PERCENT-COMPLETE:" +
- this.progress + "\r\n");
- }
+ _data.dbStorage[type] = {};
+ providers = _data.dbStorage[type];
- str = str.replace(/#AVAILABILITY#.*\r\n/g, "");
- str = str.replace(/#[^#]*#/g, "");
+ _data.IDS_PROVIDER.forEach(function (id) {
+ providers[id] = {};
- return str;
+ _data.IDS_DATA.forEach(function (dataId) {
+ providers[id][dataId] = {};
+ });
+ });
+
+ _load(type);
}
- // Constructor
- function CalendarTask_CalendarTaskInit(taskInitDict) {
- var attr;
+ // public
+ function getDataControlConsumer(providerId, dataId, type) {
+ if (!_security.getDataControlConsumer) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- construct.call(this, taskInitDict);
+ t.DataControlManager("getDataControlConsumer", arguments);
- if (taskInitDict) {
- for (attr in taskInitDict) {
- if (attr in typedef.CalendarTaskInit) {
- calendarTask[attr] = taskInitDict[attr];
- }
- }
+ if (_data[type] === null) {
+ initConsumer(type);
+ }
+ if (!_data[type][providerId] || !_data[type][providerId][dataId]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
}
- }
- function CalendarTask_DOMString_CalendarTextFormat(stringRepresentation,
- format) {
+ return _data[type][providerId][dataId];
}
- voc = [CalendarTask_CalendarTaskInit,
- CalendarTask_DOMString_CalendarTextFormat];
- t.CalendarTask(arguments, this, voc);
-};
-
-module.exports = CalendarTask;
-
-});
-define('ripple/platform/tizen/2.0/CompositeFilter', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 handleSubFeatures(subFeatures) {
+ var i, subFeature;
-var t = require('ripple/platform/tizen/2.0/typecast'),
- CompositeFilter;
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
-CompositeFilter = function (type, filters) {
- var compositeFilter = {};
+ datacontrol = {
+ getDataControlConsumer: getDataControlConsumer,
+ handleSubFeatures: handleSubFeatures
+ };
- t.CompositeFilter(arguments, this);
+ return datacontrol;
+};
+DataControlConsumerObject = function (type, providerId, dataId) {
this.__defineGetter__("type", function () {
- return compositeFilter.type;
- });
- this.__defineSetter__("type", function (val) {
- try {
- compositeFilter.type = t.CompositeFilterType(val);
- } catch (e) {
- }
+ return type;
});
- this.__defineGetter__("filters", function () {
- return compositeFilter.filters;
- });
- this.__defineSetter__("filters", function (val) {
- try {
- compositeFilter.filters = t.AbstractFilter(val, "[]");
- } catch (e) {
- }
+ this.__defineGetter__("providerId", function () {
+ return providerId;
});
- compositeFilter.type = type;
- compositeFilter.filters = filters || [];
+ this.__defineGetter__("dataId", function () {
+ return dataId;
+ });
};
-module.exports = CompositeFilter;
+SQLDataControlConsumer = function (providerId, dataId, dc) {
+ var self, privateData = new SQLData(dc);
-});
-define('ripple/platform/tizen/2.0/ContactAddress', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ // public
+ function insert(reqId, insertionData, successCallback, errorCallback) {
+ if (!_security.insert) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactAddress;
+ t.SQLDataControlConsumer("insert", arguments, true);
-ContactAddress = function (addressInitDict) {
- var contactAddress = {}, attr, arr, i;
+ privateData.insert(insertionData, function (rowId) {
+ if (successCallback) {
+ successCallback(reqId, rowId);
+ }
+ }, function (error) {
+ if (errorCallback) {
+ errorCallback(reqId, error);
+ }
+ });
+ }
- t.ContactAddress(arguments, this);
+ function update(reqId, updateData, where, successCallback, errorCallback) {
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- contactAddress.country = null;
- contactAddress.region = null;
- contactAddress.city = null;
- contactAddress.streetAddress = null;
- contactAddress.additionalInformation = null;
- contactAddress.postalCode = null;
- contactAddress.isDefault = false;
- contactAddress.types = ["HOME"];
+ t.SQLDataControlConsumer("update", arguments, true);
- this.__defineGetter__("country", function () {
- return contactAddress.country;
- });
- this.__defineSetter__("country", function (val) {
- try {
- contactAddress.country = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ privateData.update(updateData, where, function () {
+ if (successCallback) {
+ successCallback(reqId);
+ }
+ }, function (error) {
+ if (errorCallback) {
+ errorCallback(reqId, error);
+ }
+ });
+ }
- this.__defineGetter__("region", function () {
- return contactAddress.region;
- });
- this.__defineSetter__("region", function (val) {
- try {
- contactAddress.region = t.DOMString(val, "?");
- } catch (e) {
+ function remove(reqId, where, successCallback, errorCallback) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
- this.__defineGetter__("city", function () {
- return contactAddress.city;
- });
- this.__defineSetter__("city", function (val) {
- try {
- contactAddress.city = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ t.SQLDataControlConsumer("remove", arguments, true);
- this.__defineGetter__("streetAddress", function () {
- return contactAddress.streetAddress;
- });
- this.__defineSetter__("streetAddress", function (val) {
- try {
- contactAddress.streetAddress = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ privateData.remove(where, function () {
+ if (successCallback) {
+ successCallback(reqId);
+ }
+ }, function (error) {
+ if (errorCallback) {
+ errorCallback(reqId, error);
+ }
+ });
+ }
- this.__defineGetter__("additionalInformation", function () {
- return contactAddress.additionalInformation;
- });
- this.__defineSetter__("additionalInformation", function (val) {
- try {
- contactAddress.additionalInformation = t.DOMString(val, "?");
- } catch (e) {
+ function select(reqId, columns, where, successCallback, errorCallback, page,
+ maxNumberPerPage) {
+ if (!_security.select) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
- this.__defineGetter__("postalCode", function () {
- return contactAddress.postalCode;
- });
- this.__defineSetter__("postalCode", function (val) {
- try {
- contactAddress.postalCode = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ t.SQLDataControlConsumer("select", arguments, true);
- this.__defineGetter__("isDefault", function () {
- return contactAddress.isDefault;
- });
- this.__defineSetter__("isDefault", function (val) {
- try {
- contactAddress.isDefault = t.boolean(val);
- } catch (e) {
- }
- });
+ privateData.select(columns, where, function (rows) {
+ successCallback(rows, reqId);
+ }, function (error) {
+ if (errorCallback) {
+ errorCallback(reqId, error);
+ }
+ }, page, maxNumberPerPage);
+ }
- this.__defineGetter__("types", function () {
- return contactAddress.types;
- });
- this.__defineSetter__("types", function (val) {
- try {
- contactAddress.types = t.DOMString(val, "[]");
- } catch (e) {
- }
- });
+ self = new DataControlConsumerObject("SQL", providerId, dataId);
- if (addressInitDict) {
- for (attr in addressInitDict) {
- switch (attr) {
- case "types":
- arr = addressInitDict[attr];
- if (arr) {
- for (i in arr) {
- contactAddress[attr][i] = arr[i];
- }
- }
- break;
+ self.insert = insert;
+ self.update = update;
+ self.remove = remove;
+ self.select = select;
- default:
- contactAddress[attr] = addressInitDict[attr];
- break;
- }
- }
- }
+ return self;
};
-module.exports = ContactAddress;
+MappedDataControlConsumer = function (providerId, dataId, dc) {
+ var self, privateData = new MappedData(dc);
-});
-define('ripple/platform/tizen/2.0/ContactAnniversary', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 addValue(reqId, key, value, successCallback, errorCallback) {
+ if (!_security.addValue) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactAnniversary;
+ t.MappedDataControlConsumer("addValue", arguments);
-ContactAnniversary = function (date, label) {
- var contactAnniversary = {};
+ window.setTimeout(function () {
+ if (privateData.insert(key, value)) {
+ if (successCallback) {
+ successCallback(reqId);
+ }
+ } else if (errorCallback) {
+ errorCallback(reqId, new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ }, 1);
+ }
- t.ContactAnniversary(arguments, this);
+ function removeValue(reqId, key, value, successCallback, errorCallback) {
+ if (!_security.removeValue) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- contactAnniversary.date = date;
- contactAnniversary.label = label || null;
+ t.MappedDataControlConsumer("removeValue", arguments);
- this.__defineGetter__("date", function () {
- return contactAnniversary.date;
- });
- this.__defineSetter__("date", function (val) {
- try {
- contactAnniversary.date = t.Date(val);
- } catch (e) {
- }
- });
+ window.setTimeout(function () {
+ if (privateData.remove(key, value)) {
+ successCallback(reqId);
+ } else if (errorCallback) {
+ errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ }, 1);
+ }
- this.__defineGetter__("label", function () {
- return contactAnniversary.label;
- });
- this.__defineSetter__("label", function (val) {
- try {
- contactAnniversary.label = t.DOMString(val, "?");
- } catch (e) {
+ function getValue(reqId, key, successCallback, errorCallback) {
+ if (!_security.getValue) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
-};
-module.exports = ContactAnniversary;
+ t.MappedDataControlConsumer("getValue", arguments);
-});
-define('ripple/platform/tizen/2.0/ContactBase', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ window.setTimeout(function () {
+ var values;
-var decorator = require('ripple/platform/tizen/2.0/decorator'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- ContactName = require('ripple/platform/tizen/2.0/ContactName'),
- ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
- ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
- ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
- ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
- ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
- ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
- Contact;
+ values = privateData.search(key);
-Contact = function () {
- var voc;
+ if (values !== null) {
+ successCallback(values, reqId);
+ } else if (errorCallback) {
+ errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ }, 1);
+ }
- // private
- function construct() {
- this.name = null;
- this.addresses = [];
- this.photoURI = null;
- this.phoneNumbers = [];
- this.emails = [];
- this.birthday = null;
- this.anniversaries = [];
- this.organizations = [];
- this.notes = [];
- this.urls = [];
- this.ringtoneURI = null;
- this.groupIds = [];
+ function updateValue(reqId, key, oldValue, newValue, successCallback,
+ errorCallback) {
+ if (!_security.updateValue) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.MappedDataControlConsumer("updateValue", arguments);
+
+ window.setTimeout(function () {
+ if (privateData.update(key, oldValue, newValue)) {
+ successCallback(reqId);
+ } else if (errorCallback) {
+ errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ }, 1);
}
- // Constructor
- function Contact_ContactInit(contactInitDict) {
- var i, attr, arr;
+ self = new DataControlConsumerObject("MAP", providerId, dataId);
- construct.apply(this);
+ self.addValue = addValue;
+ self.removeValue = removeValue;
+ self.getValue = getValue;
+ self.updateValue = updateValue;
- for (attr in contactInitDict) {
- switch (attr) {
- case "name":
- this[attr] = new ContactName(contactInitDict[attr]);
- break;
+ return self;
+};
- case "addresses":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactAddress(arr[i]);
- }
- }
- break;
+DataControlConsumerFactory = function (type, providerId, dataId, dc) {
+ var self;
- case "phoneNumbers":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactPhoneNumber(arr[i].number,
- arr[i].types || null, arr[i].isDefault || null);
- }
- }
- break;
+ switch (type) {
+ case "SQL":
+ self = new SQLDataControlConsumer(providerId, dataId, dc);
+ break;
- case "emails":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactEmailAddress(arr[i].email,
- arr[i].types || null, arr[i].isDefault || null);
- }
- }
- break;
+ case "MAP":
+ self = new MappedDataControlConsumer(providerId, dataId, dc);
+ break;
+ }
- case "birthday":
- this[attr] = new Date(contactInitDict[attr]);
- break;
+ return self;
+};
- case "anniversaries":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactAnniversary(arr[i].date,
- arr[i].label || null);
- }
- }
- break;
+SQLData = function (dc) {
+ var self, data, columnNames, SQLErr2WebAPIErr;
- case "organizations":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactOrganization(arr[i]);
- }
- }
- break;
+ // private
+ function getDBTableName() {
+ return "DC_" + Math.uuid(8, 16);
+ }
- case "notes":
- case "groupIds":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = arr[i];
- }
- }
- break;
+ function getColumnNames(tx, results) {
+ columnNames = results.rows.item(0).sql
+ .replace(/^[^\(]+\(([^\)]+)\)/g, "$1")
+ .replace(/(^|(,) )([^ ,]+)([^,]*|$)/g, "$2$3")
+ .split(",");
+ }
- case "urls":
- arr = contactInitDict[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactWebSite(arr[i].url,
- arr[i].type || null);
- }
- }
- break;
+ function queryColumns(columns) {
+ return columns.join("=?,") + "=?";
+ }
- default:
- this[attr] = contactInitDict[attr];
- break;
- }
- }
+ function queryValues(n) {
+ return (new Array(n)).join("?,") + "?";
+ }
- decorator.Contact(this);
+ function shedQuotes(values) {
+ return values.every(function (value, i, arr) {
+ arr[i] = value.replace(/^('|")(.*)\1$/g, "$2");
+
+ return (arr[i] !== value);
+ });
}
- function Contact_DOMString(stringRepresentation) {
+ function isNull(p) {
+ return ((p === undefined) || (p === null));
}
- voc = [Contact_ContactInit, Contact_DOMString];
- t.Contact(arguments, this, voc);
-};
+ function initialize() {
+ SQLErr2WebAPIErr = [
+ 0, // 0: UNKNOWN_ERR 0: UNKNOWN_ERR
+ 100, // 1: DATABASE_ERR 100: IO_ERR
+ 100, // 2: VERSION_ERR 100: IO_ERR
+ 100, // 3: TOO_LARGE_ERR 100: IO_ERR
+ 22, // 4: QUOTA_ERR 22: QUOTA_EXCEEDED_ERR
+ 12, // 5: SYNTAX_ERR 12: SYNTAX_ERR
+ 100, // 6: CONSTRAINT_ERR 100: IO_ERR
+ 23 // 7: TIMEOUT_ERR 23: TIMEOUT_ERR
+ ];
-module.exports = Contact;
+ if (!("table" in dc)) {
+ dc.table = getDBTableName();
+ columnNames = ["id"];
+ _save();
+ }
-});
-define('ripple/platform/tizen/2.0/ContactEmailAddress', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ data = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence',
+ 2 * 1024 * 1024);
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactEmailAddress;
+ data.transaction(function (tx) {
+ tx.executeSql('CREATE TABLE IF NOT EXISTS ' + dc.table +
+ ' (id unique)');
+ tx.executeSql('SELECT sql FROM sqlite_master WHERE type="table" AND name=?',
+ [dc.table], getColumnNames);
+ });
+ }
-ContactEmailAddress = function (email, types, isDefault) {
- var contactEmailAddress = {};
+ // public
+ function insert(rowData, onSuccess, onError) {
+ if (rowData.columns.length > rowData.values.length) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ if (!shedQuotes(rowData.values)) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
- t.ContactEmailAddress(arguments, this);
+ data.transaction(function (tx) {
+ rowData.columns.forEach(function (column) {
+ if (columnNames.indexOf(column) !== -1)
+ return;
- contactEmailAddress.email = email;
- contactEmailAddress.isDefault = isDefault || false;
- contactEmailAddress.types = (types && types[0]) ? types : ["WORK"];
+ tx.executeSql('ALTER TABLE ' + dc.table + ' ADD ' + column +
+ ' TEXT', [], function () {
+ columnNames.push(column);
+ }, function (tx, error) {
+ onError(new WebAPIError(
+ SQLErr2WebAPIErr[error.code],
+ error.message));
+ });
+ });
- this.__defineGetter__("email", function () {
- return contactEmailAddress.email;
- });
- this.__defineSetter__("email", function (val) {
- try {
- contactEmailAddress.email = t.DOMString(val);
- } catch (e) {
+ tx.executeSql('INSERT INTO ' + dc.table + ' (' +
+ rowData.columns.join() + ') VALUES (' +
+ queryValues(rowData.values.length) + ')', rowData.values,
+ function (tx, results) {
+ onSuccess(results.insertId);
+ }, function (tx, error) {
+ onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
+ error.message));
+ });
+ });
+ }
+
+ function update(rowData, where, onSuccess, onError) {
+ if (rowData.columns.length > rowData.values.length) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ if (!shedQuotes(rowData.values)) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
}
- });
- this.__defineGetter__("isDefault", function () {
- return contactEmailAddress.isDefault;
- });
- this.__defineSetter__("isDefault", function (val) {
- try {
- contactEmailAddress.isDefault = t.boolean(val);
- } catch (e) {
+ data.transaction(function (tx) {
+ tx.executeSql('UPDATE ' + dc.table + ' SET ' +
+ queryColumns(rowData.columns) + ' WHERE ' + where,
+ rowData.values, onSuccess, function (tx, error) {
+ onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
+ error.message));
+ });
+ });
+ }
+
+ function remove(where, onSuccess, onError) {
+ data.transaction(function (tx) {
+ tx.executeSql('DELETE FROM ' + dc.table + ' WHERE ' + where, [],
+ onSuccess, function (tx, error) {
+ onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
+ error.message));
+ });
+ });
+ }
+
+ function select(columns, where, onSuccess, onError, page, maxNumberPerPage) {
+ if (isNull(page)) {
+ page = 1;
+ } else {
+ if (page <= 0) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ page = parseInt(page, 10);
}
- });
- this.__defineGetter__("types", function () {
- return contactEmailAddress.types;
- });
- this.__defineSetter__("types", function (val) {
- try {
- contactEmailAddress.types = t.DOMString(val, "[]");
- } catch (e) {
+ if (isNull(maxNumberPerPage)) {
+ if (page > 1) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ } else {
+ if (maxNumberPerPage <= 0) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ maxNumberPerPage = parseInt(maxNumberPerPage, 10);
}
- });
-};
-module.exports = ContactEmailAddress;
+ data.transaction(function (tx) {
+ tx.executeSql('SELECT ' + columns.join() + ' FROM ' + dc.table +
+ ' WHERE ' + where, [], function (tx, results) {
+ var rows = [], rowStart, rowData, r, c;
-});
-define('ripple/platform/tizen/2.0/ContactGroup', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ rowStart = maxNumberPerPage ?
+ (page - 1) * maxNumberPerPage : 0;
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactGroup;
+ for (r = rowStart; r < results.rows.length; ++r) {
+ rowData = {
+ columns: columns,
+ values: []
+ };
+ for (c in columns) {
+ rowData.values.push(results.rows
+ .item(r)[columns[c]]);
+ }
+ rows.push(rowData);
-ContactGroup = function (name, ringtoneURI, photoURI) {
- var contactGroup = {};
+ if (maxNumberPerPage && (--maxNumberPerPage === 0))
+ break;
+ }
- t.ContactGroup(arguments, this);
+ onSuccess(rows);
+ }, function (tx, error) {
+ onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
+ error.message));
+ });
+ });
+ }
- contactGroup.name = name;
- contactGroup.ringtoneURI = ringtoneURI || null;
- contactGroup.photoURI = photoURI || null;
+ initialize();
- this.__defineGetter__("id", function () {
- return null;
- });
+ self = {
+ insert: insert,
+ update: update,
+ remove: remove,
+ select: select
+ };
- this.__defineGetter__("addressBookId", function () {
- return null;
- });
+ return self;
+};
- this.__defineGetter__("name", function () {
- return contactGroup.name;
- });
- this.__defineSetter__("name", function (val) {
- try {
- contactGroup.name = t.DOMString(val);
- } catch (e) {
- }
- });
+MappedData = function (dc) {
+ var self, data = {}, ioStamp = 0;
- this.__defineGetter__("ringtoneURI", function () {
- return contactGroup.ringtoneURI;
- });
- this.__defineSetter__("ringtoneURI", function (val) {
- try {
- contactGroup.ringtoneURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ // private
+ function addNode(tree, arr, i) {
+ var key, value;
- this.__defineGetter__("photoURI", function () {
- return contactGroup.photoURI;
- });
- this.__defineSetter__("photoURI", function (val) {
- try {
- contactGroup.photoURI = t.DOMString(val, "?");
- } catch (e) {
+ if (typeof arr[i] === "string") {
+ key = arr[i];
+ value = 1;
+ } else {
+ key = arr[i][0];
+ value = arr[i][1];
}
- });
+ tree.insert(key, value);
+ }
- this.__defineGetter__("readOnly", function () {
- return false;
- });
-};
+ function bisearch(tree, arr, queue) {
+ var start, end, mid;
-module.exports = ContactGroup;
+ if (queue.length === 0)
+ return;
-});
-define('ripple/platform/tizen/2.0/ContactName', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ start = queue.shift();
+ end = queue.shift();
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactName;
+ if (start > end)
+ return;
-ContactName = function (nameInitDict) {
- var contactName = {}, attr;
+ mid = start + parseInt((end - start) / 2, 10);
+ addNode(tree, arr, mid);
+ queue.push(start, mid - 1);
+ queue.push(mid + 1, end);
+ }
- t.ContactName(arguments, this);
+ function build(arr) {
+ var tree, mid, lTree = [], rTree = [];
- contactName.prefix = null;
- contactName.suffix = null;
- contactName.firstName = null;
- contactName.middleName = null;
- contactName.lastName = null;
- contactName.nicknames = [];
- contactName.phoneticFirstName = null;
- contactName.phoneticLastName = null;
+ tree = redblack.tree();
+ mid = parseInt(arr.length / 2, 10);
+ addNode(tree, arr, mid);
- this.__defineGetter__("prefix", function () {
- return contactName.prefix;
- });
- this.__defineSetter__("prefix", function (val) {
- try {
- contactName.prefix = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ lTree.push(0, mid - 1);
+ rTree.push(mid + 1, arr.length - 1);
- this.__defineGetter__("suffix", function () {
- return contactName.suffix;
- });
- this.__defineSetter__("suffix", function (val) {
- try {
- contactName.suffix = t.DOMString(val, "?");
- } catch (e) {
+ while ((lTree.length > 0) || (rTree.length > 0)) {
+ bisearch(tree, arr, lTree);
+ bisearch(tree, arr, rTree);
}
- });
- this.__defineGetter__("firstName", function () {
- return contactName.firstName;
- });
- this.__defineSetter__("firstName", function (val) {
- try {
- contactName.firstName = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ return tree;
+ }
- this.__defineGetter__("middleName", function () {
- return contactName.middleName;
- });
- this.__defineSetter__("middleName", function (val) {
- try {
- contactName.middleName = t.DOMString(val, "?");
- } catch (e) {
+ function initialize() {
+ for (var key in dc) {
+ data[key] = build(dc[key]);
}
- });
+ }
- this.__defineGetter__("lastName", function () {
- return contactName.lastName;
- });
- this.__defineSetter__("lastName", function (val) {
- try {
- contactName.lastName = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ function traverse(tree, key) {
+ dc[key] = [];
+ tree.forEach(function (count, value) {
+ dc[key].push((count === 1) ? value : [value, count]);
+ });
+ }
- this.__defineGetter__("nicknames", function () {
- return contactName.nicknames;
- });
- this.__defineSetter__("nicknames", function (val) {
- try {
- contactName.nicknames = t.DOMString(val, "[]");
- } catch (e) {
+ function persist() {
+ if (ioStamp !== 0) {
+ window.clearTimeout(ioStamp);
}
- });
+ ioStamp = window.setTimeout(function () {
+ var key;
- this.__defineGetter__("phoneticFirstName", function () {
- return contactName.phoneticFirstName;
- });
- this.__defineSetter__("phoneticFirstName", function (val) {
- try {
- contactName.phoneticFirstName = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ for (key in data) {
+ traverse(data[key], key);
+ }
- this.__defineGetter__("phoneticLastName", function () {
- return contactName.phoneticLastName;
- });
- this.__defineSetter__("phoneticLastName", function (val) {
- try {
- contactName.phoneticLastName = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ _save();
- this.__defineGetter__("displayName", function () {
- return null;
- });
+ ioStamp = 0;
+ }, _data.PERSIST_DELAY);
+ }
- if (nameInitDict) {
- for (attr in nameInitDict) {
- contactName[attr] = nameInitDict[attr];
+ // public
+ function insert(key, value) {
+ var tree, count;
+
+ if (!(key in data)) {
+ data[key] = redblack.tree();
}
- }
-};
-module.exports = ContactName;
+ tree = data[key];
-});
-define('ripple/platform/tizen/2.0/ContactOrganization', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ if (!tree)
+ return false;
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactOrganization;
+ count = tree.get(value);
+ tree.insert(value, count ? (count + 1) : 1);
+ persist();
-ContactOrganization = function (orgInitDict) {
- var contactOrganization = {}, attr;
+ return true;
+ }
- t.ContactOrganization(arguments, this);
+ function remove(key, value) {
+ var tree, count;
- contactOrganization.name = null;
- contactOrganization.department = null;
- contactOrganization.title = null;
- contactOrganization.role = null;
- contactOrganization.logoURI = null;
+ if (!(key in data))
+ return false;
- this.__defineGetter__("name", function () {
- return contactOrganization.name;
- });
- this.__defineSetter__("name", function (val) {
- try {
- contactOrganization.name = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ tree = data[key];
+ count = tree.get(value);
+ if (count === null)
+ return false;
- this.__defineGetter__("department", function () {
- return contactOrganization.department;
- });
- this.__defineSetter__("department", function (val) {
- try {
- contactOrganization.department = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ tree.delete(value);
- this.__defineGetter__("title", function () {
- return contactOrganization.title;
- });
- this.__defineSetter__("title", function (val) {
- try {
- contactOrganization.title = t.DOMString(val, "?");
- } catch (e) {
+ if (tree.root === null) {
+ delete data[key];
+ if (key in dc) {
+ delete dc[key];
+ }
}
- });
- this.__defineGetter__("role", function () {
- return contactOrganization.role;
- });
- this.__defineSetter__("role", function (val) {
- try {
- contactOrganization.role = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ persist();
- this.__defineGetter__("logoURI", function () {
- return contactOrganization.logoURI;
- });
- this.__defineSetter__("logoURI", function (val) {
- try {
- contactOrganization.logoURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ return true;
+ }
- if (orgInitDict) {
- for (attr in orgInitDict) {
- contactOrganization[attr] = orgInitDict[attr];
- }
+ function search(key) {
+ var values = [], tree;
+
+ if (!(key in data))
+ return null;
+
+ tree = data[key];
+ tree.forEach(function (count, value) {
+ while (count--) {
+ values.push(value);
+ }
+ });
+
+ return values;
+ }
+
+ function update(key, oldValue, newValue) {
+ var tree, count, countNew;
+
+ if (!(key in data))
+ return false;
+
+ tree = data[key];
+ count = tree.get(oldValue);
+ if (count === null)
+ return false;
+
+ countNew = tree.get(newValue);
+ count += (countNew === null) ? 0 : countNew;
+ tree.delete(oldValue);
+ tree.insert(newValue, count);
+ persist();
+
+ return true;
}
+
+ initialize();
+
+ self = {
+ insert: insert,
+ remove: remove,
+ search: search,
+ update: update
+ };
+
+ return self;
};
-module.exports = ContactOrganization;
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/ContactPhoneNumber', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/CalendarAlarm', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
*/
var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactPhoneNumber;
+ CalendarAlarm;
-ContactPhoneNumber = function (number, types, isDefault) {
- var contactPhoneNumber = {};
+CalendarAlarm = function () {
+ var voc, calendarAlarm = {};
- t.ContactPhoneNumber(arguments, this);
+ // private
+ function construct() {
+ this.__defineGetter__("absoluteDate", function () {
+ return calendarAlarm.absoluteDate;
+ });
+ this.__defineSetter__("absoluteDate", function (val) {
+ try {
+ calendarAlarm.absoluteDate = t.TZDate(val, "?");
+ } catch (e) {
+ }
+ });
- contactPhoneNumber.number = number;
- contactPhoneNumber.isDefault = isDefault || false;
- contactPhoneNumber.types = (types && types[0]) ? types : ["VOICE"];
+ this.__defineGetter__("before", function () {
+ return calendarAlarm.before;
+ });
+ this.__defineSetter__("before", function (val) {
+ try {
+ calendarAlarm.before = t.TimeDuration(val, "?");
+ } catch (e) {
+ }
+ });
- this.__defineGetter__("number", function () {
- return contactPhoneNumber.number;
- });
- this.__defineSetter__("number", function (val) {
- try {
- contactPhoneNumber.number = t.DOMString(val);
- } catch (e) {
- }
- });
+ this.__defineGetter__("method", function () {
+ return calendarAlarm.method;
+ });
+ this.__defineSetter__("method", function (val) {
+ try {
+ calendarAlarm.method = t.AlarmMethod(val);
+ } catch (e) {
+ }
+ });
- this.__defineGetter__("isDefault", function () {
- return contactPhoneNumber.isDefault;
- });
- this.__defineSetter__("isDefault", function (val) {
- try {
- contactPhoneNumber.isDefault = t.boolean(val);
- } catch (e) {
- }
- });
+ this.__defineGetter__("description", function () {
+ return calendarAlarm.description;
+ });
+ this.__defineSetter__("description", function (val) {
+ try {
+ calendarAlarm.description = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+ }
- this.__defineGetter__("types", function () {
- return contactPhoneNumber.types;
- });
- this.__defineSetter__("types", function (val) {
- try {
- contactPhoneNumber.types = t.DOMString(val, "[]");
- } catch (e) {
- }
- });
+ // Constructor
+ function CalendarAlarm_TZDate_AlarmMethod_DOMString(absoluteDate, method,
+ description) {
+ construct.call(this);
+
+ calendarAlarm.absoluteDate = absoluteDate;
+ calendarAlarm.before = null;
+ calendarAlarm.method = method;
+ calendarAlarm.description = description || "";
+ }
+
+ function CalendarAlarm_TimeDuration_AlarmMethod_DOMString(before, method,
+ description) {
+ construct.call(this);
+
+ calendarAlarm.absoluteDate = null;
+ calendarAlarm.before = before;
+ calendarAlarm.method = method;
+ calendarAlarm.description = description || "";
+ }
+
+ voc = [CalendarAlarm_TZDate_AlarmMethod_DOMString,
+ CalendarAlarm_TimeDuration_AlarmMethod_DOMString];
+ t.CalendarAlarm(arguments, this, voc);
};
-module.exports = ContactPhoneNumber;
+module.exports = CalendarAlarm;
});
-define('ripple/platform/tizen/2.0/ContactRef', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/TZDate', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactRef;
+var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ tz = require('ripple/platform/tizen/2.0/timezone_info'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ _Month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
+ _Day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
-ContactRef = function (addressBookId, contactId) {
- var contactRef = {};
+function TZDate (dt) {
+ var d, UTCd, UTC_diff, tzid = "", target_diff, temp_date, localeTime_fmt = 'h:m:s', localeDate_fmt = 'D, d M y',
+ time = require('ripple/platform/tizen/2.0/time'),
+ hour = arguments[3] || 0, min = arguments[4] || 0,
+ sec = arguments[5] || 0, msec = arguments[6] || 0,
- t.ContactRef(arguments, this);
+ _checkTZDate = function (dat) {
+ var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
+ i, tzd;
+ if (typeof dat !== 'object' || dat === undefined || dat === null) {
+ return false;
+ }
+ tzd = new Tzdate();
+ for (i in tzd) {
+ if (dat.hasOwnProperty(i) === false) {
+ return false;
+ }
+ }
+ return true;
+ },
+ _d2UTCd_sync = function () {
+ UTCd = new Date(d.valueOf() - (UTC_diff * 1000 * 60 * 60));
+ },
+ _UTCd2d_sync = function () {
+ d = new Date(UTCd.valueOf() + (UTC_diff * 1000 * 60 * 60));
+ },
+ _getValue = function (o) {
+ var other;
+ other = new Date(o.getUTCFullYear(), o.getUTCMonth(), o.getUTCDate(),
+ o.getUTCHours(), o.getUTCMinutes(), o.getUTCSeconds(), o.getUTCMilliseconds());
+ return other.valueOf();
+ },
+ _formatDateString = function (fmt) {
+ var i, ret = '';
+ for (i = 0; i < fmt.length; i++) {
+ switch (fmt.charAt(i)) {
+ case 'd':
+ ret = ret + d.getDate();
+ break;
+ case 'y':
+ ret = ret + d.getFullYear();
+ break;
+ case 'm':
+ ret = ret + (d.getMonth() + 1);
+ break;
+ case 'M':
+ ret = ret + _Month[d.getMonth()];
+ break;
+ case 'D':
+ ret = ret + _Day[d.getDay()];
+ break;
+ default:
+ ret = ret + fmt.charAt(i);
+ }
+ }
+ return ret;
+ },
+ _formatTimeString = function (fmt) {
+ var i, hh, mm, ss, AP, ret = "";
+ if (fmt.search(/ap/) === -1) {
+ AP = false;
+ } else {
+ AP = true;
+ if (d.getHours() > 11) {
+ fmt = fmt.replace("ap", "PM");
+ } else {
+ fmt = fmt.replace("ap", "AM");
+ }
+ }
+ for (i = 0; i < fmt.length; i++) {
+ switch (fmt.charAt(i)) {
+ case 'h':
+ hh = d.getHours();
+ if (AP) {
+ hh = (hh > 12) ? hh - 12 : hh;
+ }
+ ret = ret + hh;
+ break;
+ case 'm':
+ mm = d.getMinutes();
+ mm = (mm < 10 ? "0" : "") + mm;
+ ret = ret + mm;
+ break;
+ case 's':
+ ss = d.getSeconds();
+ ss = (ss < 10 ? "0" : "") + ss;
+ ret = ret + ss;
+ break;
+ default:
+ ret = ret + fmt.charAt(i);
+ }
+ }
+ return ret;
+ };
- contactRef.addressBookId = addressBookId;
- contactRef.contactId = contactId;
+ if (arguments[7] !== undefined) {
+ tzid = arguments[7];
+ }
- this.__defineGetter__("addressBookId", function () {
- return contactRef.addressBookId;
- });
- this.__defineSetter__("addressBookId", function (val) {
- try {
- contactRef.addressBookId = t.AddressBookId(val);
- } catch (e) {
+ if (dt === null || dt === undefined) {
+ temp_date = new Date();
+ if (arguments[1] !== undefined) {
+ if (typeof arguments[1] !== 'string') {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (tz.isValidTimezone(arguments[1]) === false) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ tzid = arguments[1];
+ } else {
+ tzid = time.getLocalTimezone();
}
- });
+ target_diff = tz.getTimezoneDiff(tzid);
+ d = new Date(temp_date.valueOf() + (target_diff + temp_date.getTimezoneOffset() / 60) * 1000 * 60 * 60);
+ } else {
+ if (tizen1_utils.isValidDate(dt)) {
+ d = new Date(dt);
+ if (arguments[1] !== undefined) {
+ tzid = arguments[1];
+ } else {
+ tzid = time.getLocalTimezone();
+ }
+ } else {
+ if (arguments.length === 1) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ } else {
+ d = new Date(arguments[0], arguments[1], arguments[2], hour, min, sec, msec);
+ }
+ }
+ }
- this.__defineGetter__("contactId", function () {
- return contactRef.contactId;
- });
- this.__defineSetter__("contactId", function (val) {
- try {
- contactRef.contactId = t.ContactId(val);
- } catch (e) {
+ if (tz.isValidTimezone(tzid) === false) {
+ tzid = 'UTC';
+ }
+ UTC_diff = tz.getTimezoneDiff(tzid);
+ _d2UTCd_sync();
+
+ this.getDate = function () {
+ return d.getDate();
+ };
+ this.setDate = function (dt) {
+ d.setDate(dt);
+ _d2UTCd_sync();
+ };
+ this.getDay = function () {
+ return d.getDay();
+ };
+ this.getFullYear = function () {
+ return d.getFullYear();
+ };
+ this.setFullYear = function (yr) {
+ d.setFullYear(yr);
+ _d2UTCd_sync();
+ };
+ this.getHours = function () {
+ return d.getHours();
+ };
+ this.setHours = function (hr) {
+ d.setHours(hr);
+ _d2UTCd_sync();
+ };
+ this.getMilliseconds = function () {
+ return d.getMilliseconds();
+ };
+ this.setMilliseconds = function (msec) {
+ d.setMilliseconds(msec);
+ _d2UTCd_sync();
+ };
+ this.getMinutes = function () {
+ return d.getMinutes();
+ };
+ this.setMinutes = function (min) {
+ d.setMinutes(min);
+ _d2UTCd_sync();
+ };
+ this.getMonth = function () {
+ return d.getMonth();
+ };
+ this.setMonth = function (m) {
+ d.setMonth(m);
+ _d2UTCd_sync();
+ };
+ this.getSeconds = function () {
+ return d.getSeconds();
+ };
+ this.setSeconds = function (s) {
+ d.setSeconds(s);
+ _d2UTCd_sync();
+ };
+ this.getUTCDate = function () {
+ return UTCd.getDate();
+ };
+ this.setUTCDate = function (dt) {
+ UTCd.setDate(dt);
+ _UTCd2d_sync();
+ };
+ this.getUTCDay = function () {
+ return UTCd.getDay();
+ };
+ this.getUTCFullYear = function () {
+ return UTCd.getFullYear();
+ };
+ this.setUTCFullYear = function (yr) {
+ UTCd.setFullYear(yr);
+ _UTCd2d_sync();
+ };
+ this.getUTCHours = function () {
+ return UTCd.getHours();
+ };
+ this.setUTCHours = function (hr) {
+ UTCd.setHours(hr);
+ _UTCd2d_sync();
+ };
+ this.getUTCMilliseconds = function () {
+ return UTCd.getMilliseconds();
+ };
+ this.setUTCMilliseconds = function (msec) {
+ UTCd.setMilliseconds(msec);
+ _UTCd2d_sync();
+ };
+ this.getUTCMinutes = function () {
+ return UTCd.getMinutes();
+ };
+ this.setUTCMinutes = function (min) {
+ UTCd.setMinutes(min);
+ _UTCd2d_sync();
+ };
+ this.getUTCMonth = function () {
+ return UTCd.getMonth();
+ };
+ this.setUTCMonth = function (m) {
+ UTCd.setMonth(m);
+ _UTCd2d_sync();
+ };
+ this.getUTCSeconds = function () {
+ return UTCd.getSeconds();
+ };
+ this.setUTCSeconds = function (s) {
+ UTCd.setSeconds(s);
+ _UTCd2d_sync();
+ };
+ this.getTimezone = function () {
+ return tzid;
+ };
+ this.toTimezone = function (new_tzid) {
+ var diff,
+ Tzdate = require('ripple/platform/tizen/2.0/TZDate');
+ if (tz.isValidTimezone(String(new_tzid)) === true) {
+ diff = tz.getTimezoneDiff(new_tzid) - UTC_diff;
+ return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), new_tzid);
+ } else {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
}
- });
-};
+ };
+ this.toLocalTimezone = function () {
+ var diff,
+ localTzid,
+ Tzdate = require('ripple/platform/tizen/2.0/TZDate');
+ localTzid = time.getLocalTimezone();
-module.exports = ContactRef;
+ diff = tz.getTimezoneDiff(localTzid) - UTC_diff;
+ return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), localTzid);
+ };
+ this.toUTC = function () {
+ var Tzdate = require('ripple/platform/tizen/2.0/TZDate');
+ return new Tzdate(UTCd, "UTC");
+ };
+ this.difference = function (other) {
+ var diff,
+ TDur = require('ripple/platform/tizen/2.0/TimeDuration');
+ if (_checkTZDate(other) === false) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ diff = (UTCd.valueOf() - _getValue(other));
+ if (diff % 86400000 === 0) {
+ return new TDur(diff/86400000, 'DAYS');
+ } else {
+ return new TDur(diff);
+ }
+ };
+ this.equalsTo = function (other) {
+ if (_checkTZDate(other) === false) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ return (UTCd.valueOf() === _getValue(other));
+ };
+ this.earlierThan = function (other) {
+ if (_checkTZDate(other) === false) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ return (UTCd.valueOf() < _getValue(other));
+ };
+ this.laterThan = function (other) {
+ if (_checkTZDate(other) === false) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ return (UTCd.valueOf() > _getValue(other));
+ };
+ this.addDuration = function (dur) {
+ var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
+ Tunit = {"MSECS": 1,
+ "SECS": 1000,
+ "MINS": 60 * 1000,
+ "HOURS": 60 * 60 * 1000,
+ "DAYS": 24 * 60 * 60 * 1000
+ };
+ if (typeof dur !== 'object' || dur === undefined || dur === null) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (dur.length === undefined || dur.length === null ||
+ dur.unit === undefined || dur.unit === null) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((typeof dur.length) !== 'number') {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (Tunit[dur.unit] === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ return new Tzdate(new Date(d.valueOf() + (parseInt(dur.length, 10) * Tunit[dur.unit])), tzid);
+ };
+ this.toLocaleDateString = function () {
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ } else {
+ return _formatDateString(localeDate_fmt);
+ }
+ };
+ this.toLocaleTimeString = function () {
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ } else {
+ return _formatTimeString(localeTime_fmt);
+ }
+ };
+ this.toLocaleString = function () {
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ } else {
+ return (this.toLocaleDateString() + " " + this.toLocaleTimeString());
+ }
+ };
+ this.toDateString = function () {
+ var ret = "", fmt = time.getDateFormat();
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ }
+ ret = _formatDateString(fmt);
+ return ret;
+ };
+ this.toTimeString = function () {
+ var ret, fmt = time.getTimeFormat();
+
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ }
+
+ ret = _formatTimeString(fmt);
+ if (tz.getTimezoneDesc(tzid) !== null) {
+ return ret + " " + tz.getTimezoneDesc(tzid);
+ } else {
+ return ret + " " + tz.getTimezoneAbbr(tzid);
+ }
+ return ret;
+ };
+ this.toString = function () {
+ if (d.toString() === "Invalid Date") {
+ return d.toString();
+ } else {
+ return (this.toDateString() + " " + this.toTimeString());
+ }
+ };
+ this.getTimezoneAbbreviation = function () {
+ return tz.getTimezoneAbbr(tzid);
+ };
+ this.secondsFromUTC = function () {
+ return (-1 * UTC_diff * 60 * 60);
+ };
+ this.isDST = function () {
+ throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
+ };
+ this.getPreviousDSTTransition = function () {
+ throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
+ };
+ this.getNextDSTTransition = function () {
+ throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
+ };
+ return this;
+}
+
+module.exports = TZDate;
});
-define('ripple/platform/tizen/2.0/ContactWebSite', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/NotificationBase', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
*/
var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactWebSite;
+ Notification;
-ContactWebSite = function (url, type) {
- var contactWebSite = {};
+Notification = function (title, content) {
+ var notification = {};
- t.ContactWebSite(arguments, this);
+ notification.title = title;
+ notification.content = content || null;
- contactWebSite.url = url;
- contactWebSite.type = type || "HOMEPAGE";
+ this.__defineGetter__("id", function () {
+ return undefined;
+ });
- this.__defineGetter__("url", function () {
- return contactWebSite.url;
+ this.__defineGetter__("type", function () {
+ return "STATUS";
});
- this.__defineSetter__("url", function (val) {
+
+ this.__defineGetter__("postedTime", function () {
+ return undefined;
+ });
+
+ this.__defineGetter__("title", function () {
+ return notification.title;
+ });
+ this.__defineSetter__("title", function (val) {
try {
- contactWebSite.url = t.DOMString(val);
+ notification.title = t.DOMString(val);
} catch (e) {
}
});
- this.__defineGetter__("type", function () {
- return contactWebSite.type;
+ this.__defineGetter__("content", function () {
+ return notification.content;
});
- this.__defineSetter__("type", function (val) {
+ this.__defineSetter__("content", function (val) {
try {
- contactWebSite.type = t.DOMString(val);
+ notification.content = t.DOMString(val, "?");
} catch (e) {
}
});
};
-module.exports = ContactWebSite;
+module.exports = Notification;
});
-define('ripple/platform/tizen/2.0/Conversation', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/spec', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
- * Licensed under the Apache License, Version 2.0 (the "License"),
+ * 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
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils');
-module.exports = function (opt) {
- var conv = {}, priv = utils.copy(opt);
+module.exports = {
- conv.__defineGetter__("id", function () {
- return priv.id;
- });
- conv.__defineGetter__("type", function () {
- return priv.type;
- });
- conv.__defineGetter__("timestamp", function () {
- return priv.timestamp;
- });
- conv.__defineGetter__("messageCount", function () {
- return priv.messageCount;
- });
- conv.__defineGetter__("unreadMessages", function () {
- return priv.unreadMessages;
- });
- conv.__defineGetter__("preview", function () {
- return priv.preview;
- });
- conv.__defineGetter__("subject", function () {
- return priv.subject;
- });
- conv.__defineGetter__("isRead", function () {
- return priv.isRead;
- });
- conv.__defineGetter__("from", function () {
- return priv.from;
- });
- conv.__defineGetter__("to", function () {
- return priv.to;
- });
- conv.__defineGetter__("cc", function () {
- return priv.cc;
- });
- conv.__defineGetter__("bcc", function () {
- return priv.bcc;
- });
- conv.__defineGetter__("lastMessageId", function () {
- return priv.lastMessageId;
- });
- return conv;
+ id: "tizen",
+ version: "2.2",
+ name: "TIZEN",
+
+ persistencePrefix: "tizen1-",
+
+ config: require('ripple/platform/tizen/2.0/spec/config'),
+ ui: require('ripple/platform/tizen/2.0/spec/ui'),
+ device: require('ripple/platform/tizen/2.0/spec/device'),
+ sensor: require('ripple/platform/tizen/2.0/spec/sensor'),
+ DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
+ DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),
+
+ objects: {
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ SensorConnection: {
+ path: "w3c/1.0/SensorConnection"
+ },
+ navigator: {
+ path: "tizen/2.0/navigator",
+ children: {
+ geolocation: {
+ path: "wac/2.0/geolocation"
+ },
+ battery: {
+ path: "tizen/2.0/battery"
+ }
+ }
+ },
+ tizen: {
+ feature: "http://tizen.org/privilege/tizen",
+ children: {
+ AlarmAbsolute: {
+ path: "tizen/2.0/AlarmAbsolute"
+ },
+ AlarmRelative: {
+ path: "tizen/2.0/AlarmRelative"
+ },
+ ApplicationControl: {
+ path: "tizen/2.0/ApplicationControl"
+ },
+ ApplicationControlData: {
+ path: "tizen/2.0/ApplicationControlData"
+ },
+ AttributeFilter: {
+ path: "tizen/2.0/AttributeFilter"
+ },
+ AttributeRangeFilter: {
+ path: "tizen/2.0/AttributeRangeFilter"
+ },
+ BookmarkFolder: {
+ path: "tizen/2.0/BookmarkFolder"
+ },
+ BookmarkItem: {
+ path: "tizen/2.0/BookmarkItem"
+ },
+ CalendarAlarm: {
+ path: "tizen/2.0/CalendarAlarm"
+ },
+ CalendarAttendee: {
+ path: "tizen/2.0/CalendarAttendee"
+ },
+ CalendarEvent: {
+ path: "tizen/2.0/CalendarEvent"
+ },
+ CalendarEventId: {
+ path: "tizen/2.0/CalendarEventId"
+ },
+ CalendarRecurrenceRule: {
+ path: "tizen/2.0/CalendarRecurrenceRule"
+ },
+ CalendarTask: {
+ path: "tizen/2.0/CalendarTask"
+ },
+ CompositeFilter: {
+ path: "tizen/2.0/CompositeFilter"
+ },
+ Contact: {
+ path: "tizen/2.0/ContactBase"
+ },
+ ContactAddress: {
+ path: "tizen/2.0/ContactAddress"
+ },
+ ContactAnniversary: {
+ path: "tizen/2.0/ContactAnniversary"
+ },
+ ContactEmailAddress: {
+ path: "tizen/2.0/ContactEmailAddress"
+ },
+ ContactGroup: {
+ path: "tizen/2.0/ContactGroup"
+ },
+ ContactName: {
+ path: "tizen/2.0/ContactName"
+ },
+ ContactOrganization: {
+ path: "tizen/2.0/ContactOrganization"
+ },
+ ContactPhoneNumber: {
+ path: "tizen/2.0/ContactPhoneNumber"
+ },
+ ContactRef: {
+ path: "tizen/2.0/ContactRef"
+ },
+ ContactWebSite: {
+ path: "tizen/2.0/ContactWebSite"
+ },
+ DownloadRequest: {
+ path: "tizen/2.0/DownloadRequest"
+ },
+ Message: {
+ path: "tizen/2.0/Message"
+ },
+ NDEFMessage: {
+ path: "tizen/2.0/NDEFMessage"
+ },
+ NDEFRecord: {
+ path: "tizen/2.0/NDEFRecord"
+ },
+ NDEFRecordMedia: {
+ path: "tizen/2.0/NDEFRecordMedia"
+ },
+ NDEFRecordText: {
+ path: "tizen/2.0/NDEFRecordText"
+ },
+ NDEFRecordURI: {
+ path: "tizen/2.0/NDEFRecordURI"
+ },
+ NotificationDetailInfo: {
+ path: "tizen/2.0/NotificationDetailInfo"
+ },
+ SimpleCoordinates: {
+ path: "tizen/2.0/SimpleCoordinates"
+ },
+ SortMode: {
+ path: "tizen/2.0/SortMode"
+ },
+ StatusNotification: {
+ path: "tizen/2.0/StatusNotification"
+ },
+ SyncInfo: {
+ path: "tizen/2.0/SyncInfo"
+ },
+ SyncServiceInfo: {
+ path: "tizen/2.0/SyncServiceInfo"
+ },
+ SyncProfileInfo: {
+ path: "tizen/2.0/SyncProfileInfo"
+ },
+ TZDate: {
+ path: "tizen/2.0/TZDate"
+ },
+ TimeDuration: {
+ path: "tizen/2.0/TimeDuration"
+ },
+ alarm: {
+ path: "tizen/2.0/alarm",
+ feature: "http://tizen.org/privilege/alarm",
+ handleSubfeatures: true
+ },
+ application: {
+ path: "tizen/2.0/application",
+ feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
+ handleSubfeatures: true
+ },
+ bluetooth: {
+ path: "tizen/2.0/bluetooth",
+ feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
+ handleSubfeatures: true
+ },
+ bookmark: {
+ path: "tizen/2.0/bookmark",
+ feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
+ handleSubfeatures: true
+ },
+ callhistory: {
+ path: "tizen/2.0/callHistory",
+ feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
+ handleSubfeatures: true
+ },
+ calendar: {
+ path: "tizen/2.0/calendar",
+ feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
+ handleSubfeatures: true
+ },
+ contact: {
+ path: "tizen/2.0/contact",
+ feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
+ handleSubfeatures: true
+ },
+ content: {
+ path: "tizen/2.0/content",
+ feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
+ handleSubfeatures: true
+ },
+ datacontrol: {
+ path: "tizen/2.0/datacontrol",
+ feature: "http://tizen.org/privilege/datacontrol.consumer",
+ handleSubfeatures: true
+ },
+ datasync: {
+ path: "tizen/2.0/datasync",
+ feature: "http://tizen.org/privilege/datasync",
+ handleSubfeatures: true
+ },
+ download: {
+ path: "tizen/2.0/download",
+ feature: "http://tizen.org/privilege/download",
+ handleSubfeatures: true
+ },
+ filesystem: {
+ path: "tizen/2.0/filesystem",
+ feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
+ },
+ messageport: {
+ path: "tizen/2.0/messageport"
+ },
+ messaging: {
+ path: "tizen/2.0/messaging",
+ feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
+ handleSubfeatures: true
+ },
+ networkbearerselection: {
+ path: "tizen/2.0/networkbearerselection",
+ feature: "http://tizen.org/privilege/networkbearerselection",
+ handleSubfeatures: true
+ },
+ nfc: {
+ path: "tizen/2.0/nfc",
+ feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
+ handleSubfeatures: true
+ },
+ notification: {
+ path: "tizen/2.0/notification",
+ feature: "http://tizen.org/privilege/notification",
+ handleSubfeatures: true
+ },
+ package: {
+ path: "tizen/2.0/package",
+ feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
+ handleSubfeatures: true
+ },
+ power: {
+ path: "tizen/2.0/power",
+ feature: "http://tizen.org/privilege/power",
+ handleSubfeatures: true
+ },
+ push: {
+ path: "tizen/2.0/push",
+ feature: "http://tizen.org/privilege/push",
+ handleSubfeatures: true
+ },
+ systeminfo: {
+ path: "tizen/2.0/systeminfo",
+ feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
+ handleSubfeatures: true
+ },
+ systemsetting: {
+ path: "tizen/2.0/systemsetting",
+ feature: "http://tizen.org/privilege/setting",
+ handleSubfeatures: true
+ },
+ time: {
+ path: "tizen/2.0/time",
+ feature: "http://tizen.org/privilege/time",
+ handleSubfeatures: true
+ }
+ }
+ }
+ }
};
});
-define('ripple/platform/tizen/2.0/DeviceMotionEvent', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/routeBackend_local', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- Event = require('ripple/platform/tizen/2.0/EventBase');
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ lbs = require('ripple/platform/tizen/2.0/lbs'),
+ LocationServiceProvider = {},
+ RouteWaypoint,
+ RouteDistance,
+ RouteDuration,
+ RouteStep,
+ RouteSegment,
+ RouteRequestOptions,
+ RouteResultSummary,
+ RouteResult,
+ _data = {
+ DB_ROUTE_LOCATION_KEY: "tizen1-db-route",
+ DB_ROUTE_COLLEAGE_KEY: "tizen2-db-route",
+ routeProvider: {},
+ routes: [],
+ RouteDistanceUnit: ["M", "KM", "MI", "FT"],
+ providers: [],
+ path: []
+ },
+ _self;
-module.exports = function () {
- var _self = {
- acceleration: {
- x: null,
- y: null,
- z: null
- },
- accelerationIncludingGravity: {
- x: null,
- y: null,
- z: null
- },
- rotationRate: {
- alpha: null,
- beta: null,
- gamma: null
- },
- interval: 0
- };
+// The RouteWaypoint object
+RouteWaypoint = function () {
+ return {
+ position: {
+ latitude: 0,
+ longitude: 0
+ },
+ isStopover: true
+ };
+};
- Event.call(this);
+// The RouteDistance object
+RouteDistance = function () {
+ return {
+ text: "",
+ value: 0,
+ unit: "KM"
+ };
+};
- this.__defineGetter__("acceleration", function () {
- return _self.acceleration;
- });
+// The RouteDuration object
+RouteDuration = function () {
+ return {
+ text: "",
+ value: 0 // The duration in a seconds
+ };
+};
- this.__defineGetter__("accelerationIncludingGravity", function () {
- return _self.accelerationIncludingGravity;
- });
+// The RouteStep object
+RouteStep = function () {
+ var _self = {
+ mode: "", // The way of the travel, for example: car, bike, foot
+ instruction: "", // The instruction of this step
+ points: [] // The points of this step
+ };
- this.__defineGetter__("rotationRate", function () {
- return _self.rotationRate;
- });
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.distance = new RouteDistance();
+ _self.duration = new RouteDuration();
- this.__defineGetter__("interval", function () {
- return _self.interval;
- });
+ return _self;
+};
- this.initAccelerometerEvent = function (accelerometerType, accelerometerBubbles, accelerometerCancelable,
- accelerationData, accelerationGData, rotationRateData, intervalValue) {
- this.initEvent(accelerometerType, accelerometerBubbles, accelerometerCancelable);
+// The RouteSegment object
+RouteSegment = function () {
+ var _self = {
+ steps: []
+ };
- _self.acceleration = utils.copy(accelerationData);
- _self.accelerationIncludingGravity = utils.copy(accelerationGData);
- _self.rotationRate = utils.copy(rotationRateData);
- _self.interval = intervalValue;
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.distance = new RouteDistance();
+ _self.duration = new RouteDuration();
+
+ return _self;
+};
+
+// The RouteRequestOptions object
+RouteRequestOptions = function () {
+ return {
+ mode: "", // CAR, BIKE
+ unit: "KM",
+ routeGoal: "SHORTEST",
+ constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
+ wayPoints: [],
+ maxResults: 1
};
};
+// The RouteResultSummary object
+RouteResultSummary = function () {
+ var _self = {};
-});
-define('ripple/platform/tizen/2.0/DeviceOrientationEvent', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.totalDistance = new RouteDistance();
+ _self.totalDuration = new RouteDuration();
-var Event = require('ripple/platform/tizen/2.0/EventBase');
+ return _self;
+};
-module.exports = function () {
+// The RouteResult object
+RouteResult = function () {
var _self = {
- alpha: null,
- beta: null,
- gamma: null,
- absolute: false,
- };
+ segments: []
+ };
- Event.call(this);
+ _self.summary = new RouteResultSummary();
- this.__defineGetter__("alpha", function () {
- return _self.alpha;
- });
+ return _self;
+};
- this.__defineGetter__("beta", function () {
- return _self.beta;
- });
-
- this.__defineGetter__("gamma", function () {
- return _self.gamma;
- });
+// Floyd arithmetic in Mathematics, solving the optimal way
+function floyd(e, n, startIndex, endIndex) {
+ var MAX = Infinity,
+ a = new Array(n), i, j, k, p = new Array(n),
+ paths, pathWay = [];
- this.__defineGetter__("absolute", function () {
- return _self.absolute;
- });
+ for (i = 1; i < n + 1; i++) {
+ a[i] = new Array(n);
+ }
+ for (i = 1; i < n + 1; i++) {
+ p[i] = new Array(n);
+ }
+ for (i = 1; i < n + 1; i++) {
+ for (j = 1; j < n + 1; j++) {
+ if (i === j || e[i][j] === "MIN") {
+ a[i][j] = 0;
+ } else if (e[i][j] !== 0 && e[i][j] !== "MIN") {
+ a[i][j] = e[i][j];
+ } else {
+ a[i][j] = MAX;
+ }
+ p[i][j] = 0;
+ }
+ }
+ for (i = 1; i < n + 1; i++) {
+ a[i][i] = 0;
+ }
+ for (k = 1; k < n + 1; k++) {
+ for (i = 1; i < n + 1; i++) {
+ for (j = 1; j < n + 1; j++) {
+ if (parseInt(a[i][k], 10) + parseInt(a[k][j], 10) < a[i][j]) {
+ a[i][j] = parseInt(a[i][k], 10) + parseInt(a[k][j], 10);
+ p[i][j] = k;
+ }
+ }
+ }
+ }
+ _data.path = [];
+ paths = findPath(startIndex, endIndex, p);
+ pathWay = [];
+ pathWay.push(startIndex);
+ for (i = 0; i < paths.length; i++) {
+ pathWay.push(paths[i]);
+ }
+ pathWay.push(endIndex);
- this.initDeviceOrientationEvent = function (orientationType, orientationBubbles, orientationCancelable,
- alphaData, betaData, gammaData, isAbsolute) {
- this.initEvent(orientationType, orientationBubbles, orientationCancelable);
+ return pathWay;
+}
- _self.alpha = alphaData;
- _self.beta = betaData;
- _self.gamma = gammaData;
- _self.absolute = isAbsolute;
- };
-};
+// Find the best way in the locations
+function findPath(i, j, p) {
+ var k = p[i][j];
+ if (k === 0 || i === j) {
+ return _data.path;
+ }
+ findPath(i, k, p);
+ _data.path.push(k);
-});
-define('ripple/platform/tizen/2.0/DownloadRequest', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ return findPath(k, j, p);
+}
-var t = require('ripple/platform/tizen/2.0/typecast'),
- DownloadRequest;
+// Find the index in the locations by string
+function findIndexByStr(str, locations) {
+ for (var i in locations) {
+ if (locations[i].name === str) {
+ return parseInt(i, 10) + 1;
+ }
+ }
+ return -1;
+}
-DownloadRequest = function (url, destination, fileName, networkType,
- httpHeader) {
- var downloadRequest = {};
+// Find the index in the colleages by name1 and name2
+function findValueByStr(start, end, locations, colleages) {
+ for (var i in colleages) {
+ if (colleages[i].name1 === locations[start - 1].name && colleages[i].name2 === locations[end - 1].name) {
+ return parseInt(i, 10);
+ } else if (colleages[i].name2 === locations[start - 1].name && colleages[i].name1 === locations[end - 1].name) {
+ return parseInt(i, 10);
+ }
+ }
+ return -1;
+}
- t.DownloadRequest(arguments, this);
+// Find the index in the locations by latitude and longitude
+function searchIndexBycoodinates(latitude, longitude, locations) {
+ if (latitude !== null && longitude !== null) {
+ for (var i in locations) {
+ if (locations[i].latitude === latitude && locations[i].longitude === longitude) {
+ return parseInt(i, 10) + 1;
+ }
+ }
+ }
+ return -1;
+}
- this.__defineGetter__("url", function () {
- return downloadRequest.url;
- });
- this.__defineSetter__("url", function (val) {
- try {
- downloadRequest.url = t.DOMString(val);
- } catch (e) {
+// Get the relation among the locations
+function getRelation(n, colleages, locations, goal) {
+ var i, j, start, end, relation = new Array(n + 1);
+ for (i = 1; i < n + 2; i++) {
+ relation[i] = new Array(n + 1);
+ }
+ for (i = 1; i < n + 1; i++) {
+ for (j = 1; j < n + 1; j++) {
+ relation[i][j] = 0;
}
- });
+ }
+ for (i in colleages) {
+ start = findIndexByStr(colleages[i].name1, locations);
+ end = findIndexByStr(colleages[i].name2, locations);
+ if (start !== -1 && end !== -1 && start !== end) {
+ switch (goal) {
+ case "distance":
+ relation[start][end] = colleages[i].distance;
+ relation[end][start] = colleages[i].distance;
+ break;
- this.__defineGetter__("networkType", function () {
- return downloadRequest.networkType;
- });
- this.__defineSetter__("networkType", function (val) {
- try {
- downloadRequest.networkType = t.DownloadNetworkType(val, "?");
- } catch (e) {
+ case "duration":
+ relation[start][end] = colleages[i].duration;
+ relation[end][start] = colleages[i].duration;
+ break;
+
+ case "simple":
+ relation[start][end] = 1;
+ relation[end][start] = 1;
+ break;
+
+ case "scenic":
+ if (colleages[i].addition.scenic === "SCENIC") {
+ relation[start][end] = 1;
+ relation[start][end] = 1;
+ } else if (colleages[i].addition.scenic === "") {
+ relation[start][end] = "MIN";
+ relation[start][end] = "MIN";
+ }
+ break;
+
+ case "cheap":
+ if (colleages[i].addition.toll === "TOLL") {
+ relation[start][end] = 1;
+ relation[end][start] = 1;
+ } else if (colleages[i].addition.toll === "") {
+ relation[start][end] = "MIN";
+ relation[start][end] = "MIN";
+ }
+ break;
+
+ case "safe":
+ if (colleages[i].addition.hazardous === "HAZARDOUS") {
+ relation[start][end] = 1;
+ relation[end][start] = 1;
+ } else if (colleages[i].addition.hazardous === "") {
+ relation[start][end] = "MIN";
+ relation[end][start] = "MIN";
+ }
+ break;
+
+ default:
+ return null;
+ }
}
- });
+ }
- this.destination = destination || "";
- this.fileName = fileName || "";
- this.httpHeader = httpHeader || {};
+ return relation;
+}
- downloadRequest.url = url;
- downloadRequest.networkType = networkType || "ALL";
-};
+// Get the distance relationship among the locations
+function distanceRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "distance");
+}
-module.exports = DownloadRequest;
+// Get the duration relationship among the locations
+function durationRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "duration");
+}
-});
-define('ripple/platform/tizen/2.0/EventBase', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+// Get the simple relationship among the locations
+function simpleRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "simple");
+}
-module.exports = function () {
- var _self = {
- CAPTURING_PHASE: 1,
- AT_TARGET: 2,
- BUBBLING_PHASE: 3,
+// Get the cheap relationship among the locations
+function cheapRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "cheap");
+}
- type: '',
- target: null, //new EventTarget(),
- currentTarget: null, //new EventTarget(),
- eventPhase: 0,
- bubbles: false,
- cancelable: false,
- timeStamp: 0
- };
+// Get the safe relationship among the locations
+function safeRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "safe");
+}
- this.__defineGetter__("type", function () {
- return _self.type;
- });
+// Get the scenic relationship among the locations
+function scenicRelation(n, colleages, locations) {
+ return getRelation(n, colleages, locations, "scenic");
+}
- this.__defineGetter__("target", function () {
- return _self.target;
- });
+// Get the shortest way by origin, destination, locations and colleages
+function optimalWay(origin, destination, locations, colleages, relation) {
+ var n = locations.length, i, steps = [], step, relations, routeLocations,
+ originIndex, destinationIndex, startIndex, endIndex, colleageIndex,
+ originLatitude, originLongitude, destinationLatitude, destinationLongitude,
+ startLatitude, startLongitude, endLatitude, endLongitude,
+ originLocation, destinationLocation, segment, result;
- this.__defineGetter__("currentTarget", function () {
- return _self.currentTarget;
- });
+ originLatitude = origin.latitude;
+ originLongitude = origin.longitude;
+ originIndex = searchIndexBycoodinates(originLatitude, originLongitude, locations);
- this.__defineGetter__("eventPhase", function () {
- return _self.eventPhase;
- });
+ destinationLatitude = destination.latitude;
+ destinationLongitude = destination.longitude;
+ destinationIndex = searchIndexBycoodinates(destinationLatitude, destinationLongitude, locations);
- this.__defineGetter__("bubbles", function () {
- return _self.bubbles;
- });
+ relations = relation(n, colleages, locations);
- this.__defineGetter__("cancelable", function () {
- return _self.cancelable;
- });
+ if (originIndex !== -1 && destinationIndex !== -1) {
+ routeLocations = floyd(relations, n, parseInt(originIndex, 10), parseInt(destinationIndex, 10));
- this.__defineGetter__("timeStamp", function () {
- return _self.timeStamp;
- });
+ for (i = 0; i < routeLocations.length - 1; i++) {
+ colleageIndex = findValueByStr(routeLocations[i], routeLocations[i + 1], locations, colleages);
- this.stopPropagation = function () {};
+ if (colleageIndex !== -1) {
+ step = new RouteStep();
+ startIndex = parseInt(routeLocations[i], 10) - 1;
+ endIndex = parseInt(routeLocations[i + 1], 10) - 1;
- this.preventDefault = function () {};
+ startLatitude = locations[startIndex].latitude;
+ startLongitude = locations[startIndex].longitude;
+ originLocation = new SimpleCoordinates(startLatitude, startLongitude);
- this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
- _self.type = eventTypeArg;
- _self.bubbles = canBubbleArg;
- _self.cancelable = cancelableArg;
+ endLatitude = locations[endIndex].latitude;
+ endLongitude = locations[endIndex].longitude;
+ destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);
- _self.timeStamp = (new Date()).getTime();
- };
+ step.origin = originLocation;
+ step.destination = destinationLocation;
+ step.distance = colleages[colleageIndex].distance;
+ step.duration = colleages[colleageIndex].duration;
+ step.mode = colleages[colleageIndex].mode;
+ step.addition = colleages[colleageIndex].addition;
- return _self;
-};
+ steps.push(step);
+ } else if (colleageIndex === -1) {
+ return null;
+ }
+ }
+ segment = new RouteSegment();
+ segment.steps = steps;
+ result = new RouteResult();
+ result.segments[0] = segment;
-});
-define('ripple/platform/tizen/2.0/GeoCircleBounds', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ return result;
+ }
+ return null;
+}
-module.exports = function (_center, _radius) {
- var center, radius;
- center = _center || null;
- radius = _radius || 0;
+// Get the shortest way by origin, destination, locations and colleages
+function shortestWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, distanceRelation);
+}
- this.__defineGetter__("center", function () {
- return center;
- });
+// Get the fastest way by origin, destination, locations and colleages
+function fastestWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, durationRelation);
+}
- this.__defineGetter__("radius", function () {
- return radius;
- });
-};
+// Get the simplest way by origin, destination, locations and colleages
+function simplestWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, simpleRelation);
+}
-});
-define('ripple/platform/tizen/2.0/GeoPolyBounds', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+// Get the most scenic way by origin, destination, locations and colleages
+function mostScenicWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, scenicRelation);
+}
-module.exports = function (_points) {
- var points = _points || [];
+// Get the cheapest way by origin, destination, locations and colleages
+function cheapestWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, cheapRelation);
+}
- this.__defineGetter__("points", function () {
- return points;
- });
-};
+// Get the safest way by origin, destination, locations and colleages
+function safestWay(origin, destination, locations, colleages) {
+ return optimalWay(origin, destination, locations, colleages, safeRelation);
+}
-});
-define('ripple/platform/tizen/2.0/GeoRectBounds', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+// Uniquelize the array
+function uniquelize(array) {
+ var temp = {}, result = [], i;
+ for (i = array.length; i--;) {
+ temp[array[i]] = array[i];
+ }
+ for (i in temp) {
+ result.push(temp[i]);
+ }
+ return result;
+}
-module.exports = function (_southWest, _northEast) {
- var southWest, northEast;
- southWest = _southWest || null;
- northEast = _northEast || null;
+// Is it intersect between the Array a and b
+function intersect(a, b) {
+ var i, j;
- this.__defineGetter__("southWest", function () {
- return southWest;
- });
+ a = uniquelize(a);
+ if (a.length === 0 && b.length === 0) {
+ return true;
+ }
+ for (i in a) {
+ for (j in b) {
+ if (a[i] === b[j])
+ return true;
+ }
+ }
+ return false;
+}
- this.__defineGetter__("northEast", function () {
- return northEast;
+function getConstrains(result) {
+ var steps = result.segments[0].steps, constrains = [];
+
+ utils.forEach(steps, function (item, index) {
+ if (item.addition.highway === "HIGHWAY") {
+ constrains.push("HIGHWAY");
+ }
+ if (item.addition.toll === "TOLL") {
+ constrains.push("TOLL");
+ }
+ if (item.addition.bridge === "BRIDGE") {
+ constrains.push("BRIDGE");
+ }
+ if (item.addition.hazardous === "HAZARDOUS") {
+ constrains.push("HAZARDOUS");
+ }
+ if (item.addition.scenic === "SCENIC") {
+ constrains.push("SCENIC");
+ }
});
+ if (constrains.length > 0) {
+ return uniquelize(constrains);
+ }
+ return constrains;
+}
+
+module.exports = function (prop) {
+ var _self = new lbs.LocationServiceProvider(prop);
+ _self.find = function (origin, destination, successCallback, errorCallback, options) {
+ function _find() {
+ var locations, colleages, i, result = {}, emptyResult = [], modes = [], resultModes = [], constrains = [], resultconstrains = [];
+
+ locations = db.retrieveObject(_data.DB_ROUTE_LOCATION_KEY);
+ colleages = db.retrieveObject(_data.DB_ROUTE_COLLEAGE_KEY);
+
+ modes = options.modes;
+ constrains = options.constrains;
+ if (locations.length > 0 && colleages.length > 0) {
+ switch (options.routeGoal) {
+ case "SHORTEST":
+ result = shortestWay(origin, destination, locations, colleages);
+ break;
+
+ case "FASTEST":
+ result = fastestWay(origin, destination, locations, colleages);
+ break;
+
+ case "SIMPLEST":
+ result = simplestWay(origin, destination, locations, colleages);
+ break;
+
+ case "MOST_SCENIC":
+ result = mostScenicWay(origin, destination, locations, colleages);
+ break;
+
+ case "CHEAPEST":
+ result = cheapestWay(origin, destination, locations, colleages);
+ break;
+
+ case "SAFEST":
+ result = safestWay(origin, destination, locations, colleages);
+ break;
+
+ default:
+ result = shortestWay(origin, destination, locations, colleages);
+ break;
+ }
+ if (result !== null) {
+ for (i in result.segments[0].steps) {
+ resultModes.push(result.segments[0].steps[i].mode);
+ }
+ resultconstrains = getConstrains(result);
+ if (intersect(resultModes, modes) && intersect(resultconstrains, constrains)) {
+ successCallback(result);
+ } else {
+ successCallback(null);
+ }
+ }
+ } else {
+ successCallback(emptyResult);
+ }
+ }
+ tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
+ };
+ return _self;
};
});
-define('ripple/platform/tizen/2.0/GeocodeOptions', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/ReverseGeocodeOptions', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
SortMode = require('ripple/platform/tizen/2.0/SortMode');
-module.exports = function (_sortMode, _maxResults) {
+module.exports = function (_sortMode, _resultType, _maxResults) {
var _self;
if (_sortMode !== null && _sortMode !== undefined) {
if (typeof _sortMode !== "object") {
throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
}
+ if (_resultType !== null && _resultType !== undefined) {
+ if (_resultType !== "FORMATTED" && _resultType !== "STRUCTURED") {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ }
if (_maxResults !== null && _maxResults !== undefined) {
if (typeof _maxResults !== "number") {
throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
}
-
_self = {
sortMode : _sortMode,
+ resultType : _resultType || "FORMATTED",
maxResults : _maxResults || 0
};
});
-define('ripple/platform/tizen/2.0/GeocodeResult', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
+define('ripple/platform/tizen/2.0/BookmarkFolder', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
* 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.
* limitations under the License.
*/
-var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates');
-
-module.exports = function (lat, lon) {
- var _self, _coordinates, jsonStr, jsonObj;
-
- _coordinates = new SimpleCoordinates(lat, lon);
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ BookmarkFolder;
- jsonObj = {
- "type" : "Point",
- "coordinates" : [lat, lon]
- };
+BookmarkFolder = function (title) {
+ t.BookmarkFolder(arguments, this);
- jsonStr = JSON.stringify(jsonObj);
+ this.__defineGetter__("parent", function () {
+ return undefined;
+ });
- _self = {
- coordinates : _coordinates,
- toGeoJSON : function () {
- return jsonStr;
- }
- };
- return _self;
+ this.__defineGetter__("title", function () {
+ return title;
+ });
};
+module.exports = BookmarkFolder;
});
-define('ripple/platform/tizen/2.0/GeometryFilter', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/dbinit', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-module.exports = function (criteria, geometry) {
- var _self;
+var utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ dbfs = require('ripple/platform/tizen/2.0/dbfs'),
+ filesystem = require('ripple/platform/tizen/2.0/filesystem'),
+ DBBuilder,
+ Content,
+ FileSystem,
+ _data = {
+ dbBuilder: null
+ },
+ _self = {};
- _self = {
- criteria: criteria,
- geometry: geometry
+function _initialize() {
+ _data.dbBuilder = new DBBuilder();
+
+ _data.dbBuilder.register("FileSystem", "", FileSystem);
+ _data.dbBuilder.register("Content", "dbcontent.xml", Content);
+ _data.dbBuilder.register("Package", "dbpackage.xml");
+ _data.dbBuilder.register("Application", "dbapplication.xml");
+ _data.dbBuilder.register("Bluetooth", "dbbluetooth.xml");
+ _data.dbBuilder.register("MessagePort", "dbmessageport.json");
+
+ _data.FileSystem.initdb();
+}
+
+DBBuilder = function () {
+ var self;
+
+ // private
+ function formatString(str) {
+ return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, " ");
+ }
+
+ function getType(node) {
+ var type, reNum, reHexNum, reDate;
+
+ if (node.childNodes) {
+ return (node.childNodes[0].nodeName === "i") ? "Array" : "Object";
+ }
+
+ // Special case
+ if (node.nodeName === "version") {
+ return "DOMString";
+ }
+
+ reNum = /^(-?\d+)(\.\d+)?$/;
+ reHexNum = /^0[Xx][0-9A-Fa-f]+$/;
+ reDate = /^(\d{4})\-(\d{2})\-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/;
+
+ if (reNum.test(node.textContent)) {
+ type = "Number";
+ } else if (reHexNum.test(node.textContent)) {
+ type = "Number";
+ } else if (reDate.test(node.textContent)) {
+ type = "Date";
+ } else if (node.textContent === "true" || node.textContent === "false") {
+ type = "Boolean";
+ } else {
+ type = "DOMString";
+ }
+
+ return type;
+ }
+
+ function build(node) {
+ var i, value;
+
+ switch (getType(node)) {
+ case "Boolean":
+ value = (formatString(node.textContent) === "true");
+ break;
+
+ case "Date":
+ value = new Date(formatString(node.textContent));
+ break;
+
+ case "Number":
+ value = Number(formatString(node.textContent));
+ break;
+
+ case "Object":
+ value = {};
+ for (i in node.childNodes) {
+ value[node.childNodes[i].nodeName] = build(node.childNodes[i]);
+ }
+ break;
+
+ case "Array":
+ value = [];
+ for (i in node.childNodes) {
+ value.push(build(node.childNodes[i]));
+ }
+ break;
+
+ default: // "DOMString"
+ value = formatString(node.textContent);
+ break;
+ }
+
+ return value;
+ }
+
+ function parse(obj) {
+ var i, res = {};
+
+ res.nodeName = ("name" in obj.attributes) ?
+ obj.attributes["name"].value : obj.nodeName;
+
+ if (obj.childElementCount === 0) {
+ res.textContent = obj.textContent;
+ } else {
+ res.childNodes = [];
+
+ for (i in obj.childNodes) {
+ if (obj.childNodes[i].attributes) {
+ res.childNodes.push(parse(obj.childNodes[i]));
+ }
+ }
+ }
+
+ return res;
+ }
+
+ // public
+ function register(type, dbXml, Extension) {
+ _data[type] = Extension ? new Extension() : {};
+
+ if (!dbXml)
+ return;
+
+ _self.__defineGetter__(type, function () {
+ var fnInit;
+
+ if (!_data[type].db) {
+ fnInit = _data[type].initdb || initdb;
+ _data[type].db = fnInit(dbXml);
+ }
+
+ return _data[type].db;
+ });
+ }
+
+ function initdb(dbXml) {
+ var db = {}, xmlHttp, res;
+
+ try {
+ xmlHttp = new XMLHttpRequest();
+ xmlHttp.open("GET", "dbsamples/" + dbXml, false);
+ xmlHttp.send();
+ } catch (e) {
+ exception.handle(e);
+ }
+
+ if (/^(.+)\.json$/.test(dbXml)) {
+ if (!xmlHttp.responseText) {
+ return null;
+ }
+
+ db = JSON.parse(formatString(xmlHttp.responseText));
+ } else {
+ if (!xmlHttp.responseXML) {
+ return null;
+ }
+
+ res = parse(xmlHttp.responseXML.documentElement);
+ res.childNodes.forEach(function (node) {
+ db[node.nodeName] = build(node);
+ });
+ }
+
+ return db;
+ }
+
+ self = {
+ register: register,
+ initdb: initdb
};
- return _self;
+ return self;
};
-});
-define('ripple/platform/tizen/2.0/Message', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
+ * FileSystem
*/
-var msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
- MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');
+FileSystem = function () {
+ var self;
-module.exports = function (type, messageInit) {
- var _id = null, _serviceId = null, _conversationId = null,
- _folderId = null, _type = type, _timestamp = null,
- _from = null, _hasAttachment = false, _messageStatus = null,
- msg = {};
+ // private
+ function createPath(path) {
+ var parts = path.replace(/^\//, "").split("/"),
+ workflow = jWorkflow.order();
- if (messageInit !== undefined && messageInit !== null) {
- if (msg_utils.setMsg(messageInit, msg) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ parts.forEach(function (part, index) {
+ var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+
+ workflow.andThen(function (prev, baton) {
+ baton.take();
+ dbfs.mkdir(dir, baton.pass, baton.pass);
+ });
+ });
+
+ workflow.start();
+ }
+
+ // public
+ function initdb() {
+ filesystem.resolve("images", function () {});
+ filesystem.resolve("videos", function () {});
+ filesystem.resolve("music", function () {});
+ }
+
+ function createFile(uri) {
+ var directoryURI;
+
+ directoryURI = uri.slice(0, uri.lastIndexOf("/") + 1)
+ .replace(/file:\/\//, "");
+
+ dbfs.stat(directoryURI, function () {}, function () {
+ createPath(directoryURI);
+ });
+
+ uri = uri.replace(/file:\/\//, "");
+ dbfs.touch(uri, function () {});
+ }
+
+ self = {
+ initdb: initdb,
+ createFile: createFile
+ };
+
+ return self;
+};
+
+/*
+ * Content
+ */
+
+Content = function () {
+ var self, ContentStorage;
+
+ ContentStorage = function (contents, directories) {
+ var i, parentURI;
+
+ for (i in directories) {
+ directories[i].contents = {};
+ this[directories[i].directoryURI] = directories[i];
}
- if (messageInit.priv !== undefined) {
- /* secret constructor for PrivateMessage */
- _id = messageInit.priv.id;
- _serviceId = messageInit.priv.serviceId;
- _conversationId = messageInit.priv.conversationId;
- _folderId = messageInit.priv.folderId;
- _type = messageInit.priv.type;
- _timestamp = new Date(messageInit.priv.timestamp);
- _from = messageInit.priv.from;
- _hasAttachment = messageInit.priv.hasAttachment;
- _messageStatus = messageInit.priv.messageStatus;
+
+ for (i in contents) {
+ parentURI = contents[i].contentURI.slice(0,
+ contents[i].contentURI.lastIndexOf("/") + 1)
+ .replace(/file:\/\//, "");
+
+ if (parentURI in this) {
+ this[parentURI].contents[contents[i].contentURI] = contents[i];
+ }
}
- msg.body = new MessageBody(_id, msg.body.loaded, msg.body.plainBody, msg.body.htmlBody, []);
+ };
+
+ // public
+ function initdb(dbXml) {
+ var i, db;
+
+ db = _data.dbBuilder.initdb(dbXml);
+
+ if (!db)
+ return null;
+
+ for (i in db.contents) {
+ _data.FileSystem.createFile(db.contents[i].contentURI);
+ }
+
+ return new ContentStorage(db.contents, db.directories);
}
- msg.__defineGetter__("id", function () {
- return _id;
- });
- msg.__defineGetter__("conversationId", function () {
- return _conversationId;
- });
- msg.__defineGetter__("folderId", function () {
- return _folderId;
- });
- msg.__defineGetter__("type", function () {
- return _type;
- });
- msg.__defineGetter__("timestamp", function () {
- return _timestamp;
- });
- msg.__defineGetter__("from", function () {
- return _from;
- });
- msg.__defineGetter__("hasAttachment", function () {
- return _hasAttachment;
- });
- msg.__defineGetter__("messageStatus", function () {
- return _messageStatus;
- });
- return msg;
+ self = {
+ initdb: initdb
+ };
+
+ return self;
};
+_initialize();
+
+module.exports = _self;
+
});
-define('ripple/platform/tizen/2.0/MessageBody', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/pendingoperation', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-module.exports = function (id, isloaded, _plainbody, _htmlbody, inlineattachments) {
- var msgbody, _id = id, _loaded = isloaded;
- msgbody = {
- plainBody: _plainbody,
- htmlBody: _htmlbody,
- inlineAttachments: [] // TODO: not support attachment yet
+module.exports = function (pendingObj) {
+ var pending = true;
+ this.cancel = function () {
+ if (pending === true) {
+ if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
+ pending = false;
+ // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
+ clearTimeout(pendingObj.pendingID);
+ return false;
+ }
+ if (typeof (pendingObj.userCancel) === "function") {
+ pendingObj.userCancel();
+ }
+ clearTimeout(pendingObj.pendingID);
+ pending = false;
+ return true;
+ } else {
+ return false;
+ }
};
- msgbody.__defineGetter__("messageId", function () {
- return _id;
- });
- msgbody.__defineGetter__("loaded", function () {
- return _loaded;
- });
- return msgbody;
};
+
});
-define('ripple/platform/tizen/2.0/MessageFolder', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/navigator', function (require, exports, module) {
/*
+ * Copyright 2011 Research In Motion Limited.
* Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var _original = window.navigator,
+ utils = require('ripple/utils'),
+ devices = require('ripple/devices'),
+ constants = require('ripple/constants'),
+ vibration = require('ripple/platform/tizen/2.0/vibration'),
+ _self = {};
-module.exports = function (opt) {
- var folder = {}, _id = opt.id, _parentId = null, _serviceId = opt.serviceId,
- _contentType = opt.contentType, _name = opt.id, _path = opt.path,
- _type = opt.type, _synchronizable = opt.synchronizable;
+(function () {
+ var key,
+ nav = window.navigator;
- folder.name = _name;
- folder.synchronizable = _synchronizable;
-
- folder.__defineGetter__("id", function () {
- return _id;
- });
- folder.__defineGetter__("parentId", function () {
- return _parentId;
- });
- folder.__defineGetter__("serviceId", function () {
- return _serviceId;
- });
- folder.__defineGetter__("contentType", function () {
- return _contentType;
- });
- folder.__defineGetter__("path", function () {
- return _path;
- });
- folder.__defineGetter__("type", function () {
- return _type;
- });
- return folder;
-};
+ function _handle(obj, key) {
+ return typeof obj[key] !== "function" ? obj[key] : function () {
+ return obj[key].apply(obj, Array.prototype.slice.call(arguments));
+ };
+ }
+
+ for (key in nav) {
+ _self[key] = _handle(nav, key);
+ }
+}());
+
+_self.__defineGetter__('userAgent', function () {
+ var currentUserAgent = devices.getCurrentDevice().userAgent;
+ return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
+ _original.userAgent : currentUserAgent;
});
-define('ripple/platform/tizen/2.0/MessageStorage', function (require, exports, module) {
+
+_self.__defineGetter__('vibrate', function () {
+ return vibration.vibrate;
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/BluetoothDevice', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self,
- utils = require('ripple/utils'),
+
+var utils = require('ripple/utils'),
event = require('ripple/event'),
- Message = require('ripple/platform/tizen/2.0/Message'),
- Conversation = require('ripple/platform/tizen/2.0/Conversation'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
- MessageFolder = require('ripple/platform/tizen/2.0/MessageFolder'),
- msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- t = require('ripple/platform/tizen/2.0/typedef'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
- "messaging.mms": "13572468",
- "messaging.email": "tizen.simulator@tizen.org"};
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BluetoothClass = require('ripple/platform/tizen/2.0/BluetoothClass'),
+ BluetoothSocket = require('ripple/platform/tizen/2.0/BluetoothSocket'),
+ BluetoothDevice,
+ _security;
-_self = function (messages, security_check) {
- var message_storage = {},
- _findMessage, _findConversation,
- _processMessageChange, _processConversationChange,
- _folders = {}, folderOpt = {},
- _msgListeners = {},
- _convListeners = {},
- _folderListeners = {},
- _security_check = security_check,
- _messages = messages;
+BluetoothDevice = function (prop) {
+ var bluetoothDevice = {}, sockets = {}, self;
- // init folders
- folderOpt = {id: "INBOX", serviceId: _messages.id, contentType: _messages.type,
- path: "inbox", type: "INBOX", synchronizable: true};
- _folders.INBOX = new MessageFolder(folderOpt);
- folderOpt = {id: "OUTBOX", serviceId: _messages.id, contentType: _messages.type,
- path: "outbox", type: "OUTBOX", synchronizable: false};
- _folders.OUTBOX = new MessageFolder(folderOpt);
- folderOpt = {id: "DRAFT", serviceId: _messages.id, contentType: _messages.type,
- path: "draft", type: "DRAFTS", synchronizable: false};
- _folders.DRAFT = new MessageFolder(folderOpt);
- folderOpt = {id: "SENTBOX", serviceId: _messages.id, contentType: _messages.type,
- path: "sentbox", type: "SENTBOX", synchronizable: false};
- _folders.SENTBOX = new MessageFolder(folderOpt);
+ bluetoothDevice.name = prop.name || "";
+ bluetoothDevice.address = prop.address || "";
+ bluetoothDevice.deviceClass = new BluetoothClass(prop.deviceClass,
+ prop.metaData) || {};
+ bluetoothDevice.isBonded = prop.isBonded || false;
+ bluetoothDevice.isTrusted = prop.isTrusted || false;
+ bluetoothDevice.isConnected = prop.isConnected || false;
+ bluetoothDevice.services = prop.services;
+ bluetoothDevice.uuids = [];
- event.on("MsgRecv", function (msg) {
- // msg sent from panel to module
- if (msg.priv.type !== _messages.type ||
- msg.priv.serviceId !== _messages.id) {
- return;
- }
- // trigger Message add
- _processMessageChange([msg], "add");
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ this.__defineGetter__("name", function () {
+ return bluetoothDevice.name;
+ });
- if (_messages.conv[msg.priv.conversationId].messageCount === 1) {
- _processConversationChange([_messages.conv[msg.priv.conversationId]], "add");
- } else {
- _processConversationChange([_messages.conv[msg.priv.conversationId]], "update");
- }
+ this.__defineGetter__("address", function () {
+ return bluetoothDevice.address;
});
- event.on("OutsideMessageReceived", function (msg) {
- // msg sent from module to panel
- if (msg.msg.priv.type !== _messages.type ||
- msg.msg.priv.serviceId !== _messages.id) {
- return;
- }
- // trigger conversation/Message add
- _processMessageChange([msg.msg], "add");
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+ this.__defineGetter__("deviceClass", function () {
+ return bluetoothDevice.deviceClass;
+ });
- if (_messages.conv[msg.msg.priv.conversationId].messageCount === 1) {
- _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "add");
- } else {
- _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "update");
- }
+ this.__defineGetter__("isBonded", function () {
+ return bluetoothDevice.isBonded;
});
- event.on("MsgSentRst", function (rst) {
- // ACK from panel when module sent a msg to panel
- if (rst.priv.type !== _messages.type ||
- rst.priv.serviceId !== _messages.id) {
- return;
- }
- // trigger conversation/Message Update
- _processMessageChange([rst], "update");
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- _processConversationChange([_messages.conv[rst.priv.conversationId]], "update");
+ this.__defineGetter__("isTrusted", function () {
+ return bluetoothDevice.isTrusted;
});
- _findMessage = function (src, filter) {
- var ret, foo = {};
- switch (filter.attributeName) {
- case "type":
- foo[filter.attributeName] = _messages.type;
- ret = tizen1_utils.matchAttributeFilter([foo],
- filter.attributeName, filter.matchFlag, filter.matchValue);
- if (ret.length === 0) {
- ret = [];
- } else {
- // make an array
- ret = utils.filter(src, function () { return true; });
- }
- break;
- case "id":
- case "conversationId":
- case "folderId":
- case "from":
- case "messageStatus":
- ret = tizen1_utils.matchAttributeFilter(src,
- "priv." + filter.attributeName,
- filter.matchFlag, filter.matchValue);
- break;
- case "hasAttachment":
- if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
- }
- ret = tizen1_utils.matchAttributeBooleanFilter(src,
- "priv." + filter.attributeName, filter.matchValue);
- break;
- case "to":
- case "cc":
- case "bcc":
- ret = tizen1_utils.matchAttributeArrayFilter(src,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
- case "body":
- ret = tizen1_utils.matchAttributeFilter(src,
- filter.attributeName + ".plainBody",
- filter.matchFlag, filter.matchValue);
- break;
- case "subject":
- case "inResponseTo":
- ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName,
- filter.matchFlag, filter.matchValue);
- break;
- case "isRead":
- case "isHighPriority":
- if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
- }
- ret = tizen1_utils.matchAttributeBooleanFilter(src,
- filter.attributeName, filter.matchValue);
- break;
- case "timestamp":
- ret = tizen1_utils.matchAttributeRangeFilter(src,
- "priv." + filter.attributeName,
- filter.initialValue, filter.endValue);
- break;
+ this.__defineGetter__("isConnected", function () {
+ return bluetoothDevice.isConnected;
+ });
- case "attachments":
- throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR,
- "not support find by " + filter.attributeName));
- default:
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "invalid attributeName"));
+ this.__defineGetter__("uuids", function () {
+ return bluetoothDevice.uuids;
+ });
+
+ this.connectToServiceByUUID = function (uuid, successCallback,
+ errorCallback) {
+ if (!_security.all && !_security.connectToServiceByUUID) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- return ret;
- };
- _processMessageChange = function (messages, type) {
- var i, j, ret = [], tmp,
- operation = {"add": "messagesadded",
- "remove": "messagesremoved",
- "update": "messagesupdated"};
+ t.BluetoothDevice("connectToServiceByUUID", arguments);
- for (i in _msgListeners) {
- ret = [];
- if (_msgListeners[i].filter !== null) {
- tmp = _findMessage(messages, _msgListeners[i].filter);
- } else {
- tmp = messages;
- }
- if (tmp.length !== 0) {
- for (j = 0; j < tmp.length; j++) {
- ret.push(new Message(tmp[j].priv.type, tmp[j]));
+ window.setTimeout(function () {
+ if (bluetoothDevice.uuids.join(",").indexOf(uuid) === -1) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
}
- _msgListeners[i].callback[operation[type]](ret);
- }
- }
- };
-
- _findConversation = function (src, filter) {
- var ret, foo = {};
- switch (filter.attributeName) {
- case "type":
- foo[filter.attributeName] = _messages.type;
- ret = tizen1_utils.matchAttributeFilter([foo], filter.attributeName, filter.matchFlag, filter.matchValue);
- if (ret.length === 0) {
- ret = [];
- } else {
- // make an array
- ret = utils.filter(_messages.conv, function () { return true; });
- }
- break;
- case "id":
- case "preview":
- case "subject":
- case "from":
- case "lastMessageId":
- ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
- case "to":
- case "cc":
- case "bcc":
- ret = tizen1_utils.matchAttributeArrayFilter(src,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
- case "isRead":
- if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
+ return;
}
- ret = tizen1_utils.matchAttributeBooleanFilter(src,
- filter.attributeName, filter.matchValue);
- break;
- case "timestamp":
- case "messageCount":
- case "unreadMessages":
- ret = tizen1_utils.matchAttributeRangeFilter(src,
- filter.attributeName,
- filter.initialValue, filter.endValue);
- break;
- default:
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "invalid attributeName"));
- }
- return ret;
- };
- _processConversationChange = function (conversations, type) {
- var i, j, ret = [], tmp,
- operation = {"add": "conversationsadded",
- "remove": "conversationsremoved",
- "update": "conversationsupdated"};
+ bluetoothDevice.isConnected = true;
+ event.trigger("bt-device-connected-changed", [bluetoothDevice.address,
+ true]);
+ event.trigger("bt-service-state-changed", [bluetoothDevice.address,
+ uuid, true]);
- for (i in _convListeners) {
- ret = [];
- if (_convListeners[i].filter !== null) {
- tmp = _findConversation(conversations, _convListeners[i].filter);
- } else {
- tmp = conversations;
- }
- if (tmp.length !== 0) {
- for (j = 0; j < tmp.length; j++) {
- ret.push(new Conversation(tmp[j]));
- }
- _convListeners[i].callback[operation[type]](ret);
- }
- }
+ window.setTimeout(function () {
+ successCallback(sockets[uuid]);
+ }, 1);
+ }, 1);
};
- message_storage = {
- addDraftMessage: function (_msg, onSuccess, onError) {
- var m, msg = {}, opt = {};
+ event.on("bt-device-connected-update", function (addr, isConnected) {
+ if (addr !== bluetoothDevice.address)
+ return;
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (msg_utils.setMsg(_msg, msg) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- opt.id = Math.uuid(8, 16);
- opt.serviceId = _messages.id;
- if ((msg.inResponseTo !== null) &&
- (_messages.msg[msg.inResponseTo] !== undefined)) {
- opt.conversationId = _messages.msg[msg.inResponseTo].conversationId;
- } else {
- opt.conversationId = opt.id;
- }
- opt.folderId = "DRAFTS";
- opt.type = _messages.type;
- opt.timestamp = new Date();
- opt.from = TIZEN_DEFAULT_MSG_FROM[_messages.type];
- if (msg.attachments.length === 0) {
- opt.hasAttachment = false;
- } else {
- opt.hasAttachment = true;
- }
- opt.messageStatus = "DRAFT";
+ bluetoothDevice.isConnected = isConnected;
+ event.trigger("bt-device-connected-changed",
+ [bluetoothDevice.address, bluetoothDevice.isConnected]);
+ });
- m = new PrivMessage(msg, opt);
- _messages.msg[m.priv.id] = m; // local
- msg_utils.saveMsg(_messages.msg[m.priv.id]); // remote
- // trigger message add
- _processMessageChange([m], "add");
- if (onSuccess) {
- setTimeout(function () {
- onSuccess(new Message(m.priv.type, m));
- }, 1);
- }
- },
+ event.on("bt-device-bonded-changed", function (addr, isBonded) {
+ if (addr !== bluetoothDevice.address)
+ return;
- removeMessages: function (messages, onSuccess, onError) {
- var i, c, na_msg = "", msgToDel = [], convToDel = {}, delConv = [], updateConv = [];
+ bluetoothDevice.isBonded = isBonded;
+ });
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (tizen1_utils.isValidArray(messages) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if (messages.length === 0) {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
- }
- if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ _security = prop.metaData;
+ self = this;
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- for (i = 0; i < messages.length; i++) {
- if (_messages.msg[messages[i].id] === undefined) {
- na_msg += messages[i].id + ", ";
- } else {
- msgToDel.push(utils.copy(_messages.msg[messages[i].id]));
- }
- if (_messages.conv[messages[i].conversationId] !== undefined) {
- convToDel[messages[i].conversationId] = _messages.conv[messages[i].conversationId];
- }
- }
- if (na_msg === "") {
- for (i = 0; i < messages.length; i++) {
- // conversation updated at remote when msg is deleted
- msg_utils.delMsg(_messages.msg[messages[i].id]); // remote
- delete _messages.msg[messages[i].id]; // local
- }
- // update conversation
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- for (c in convToDel) {
- if (_messages.conv[c] === undefined) {
- delConv.push(convToDel[c]);
- } else {
- updateConv.push(convToDel[c]);
- }
- }
- if (onSuccess) {
- setTimeout(function () {
- onSuccess();
- }, 1);
- }
- // trigger messages remove
- _processMessageChange(msgToDel, "remove");
- if (delConv.length > 0) {
- _processConversationChange(delConv, "remove");
- }
- if (updateConv.length > 0) {
- _processConversationChange(updateConv, "update");
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
- na_msg + "not found !!"));
- }, 1);
- }
- }
- },
+ utils.forEach(bluetoothDevice.services, function (service) {
+ bluetoothDevice.uuids.push(service.uuid);
+ sockets[service.uuid] = new BluetoothSocket({
+ uuid: service.uuid,
+ protocol: service.protocol,
+ state: "CLOSED",
+ peer: self,
+ metaData: _security
+ });
+ });
+};
- updateMessages: function (messages, onSuccess, onError) {
- var i, m, updateConv = {}, updateMsg = [], tmp,
- na_msg = "", invalid_msg = "";
+module.exports = BluetoothDevice;
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (tizen1_utils.isValidArray(messages) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if (messages.length === 0) {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
- }
- // update conversation
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- for (i = 0; i < messages.length; i++) {
- m = _messages.msg[messages[i].id];
- if (m === undefined) {
- // msg not found
- na_msg += messages[i].id + ", ";
- } else {
- if (m.priv.messageStatus === "DRAFT") {
- tmp = {};
- // allow update all writeable attr in draft
- if (msg_utils.setMsg(messages[i], tmp) === false) {
- invalid_msg += messages[i].id + ", ";
- }
- }
- }
- }
- if (invalid_msg !== "") {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR,
- invalid_msg + "invalid values"));
- }, 1);
- }
- return;
- }
- if (na_msg !== "") {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
- na_msg + "not found !!"));
- }, 1);
- }
- return;
- }
+});
+define('ripple/platform/tizen/2.0/dbfs', function (require, exports, module) {
+/*
+ * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- for (i = 0; i < messages.length; i++) {
- m = _messages.msg[messages[i].id];
- if (m.priv.messageStatus === "DRAFT") {
- msg_utils.setMsg(messages[i], m);
- updateMsg.push(m);
- } else {
- // only allow update isRead in other folders
- if (typeof messages[i].isRead === 'boolean') {
- m.isRead = messages[i].isRead;
- updateMsg.push(m);
- updateConv[m.priv.conversationId] = _messages.conv[m.priv.conversationId];
- }
- }
- msg_utils.saveMsg(m);
- }
- if (onSuccess) {
- setTimeout(function () {
- onSuccess();
- }, 1);
- }
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _console = require('ripple/console'),
+ _cache = {},
+ _self;
- // trigger Message update
- _processMessageChange(updateMsg, "update");
+function _get(path) {
+ return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
+ return token === "" ? obj : ((obj && obj.children) ? obj.children[token] || null : null);
+ }, _cache);
+}
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
- // trigger conversation update
- _processConversationChange(updateConv, "update");
- },
+function _getInfo(path) {
+ var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
+ name = parent.splice(parent.length - 1, 1).join("");
- findMessages: function (filter, onSuccess, onError, sort, _limit, _offset) {
- var i, tmp, offset, limit, ret = [];
+ return {
+ name: name,
+ parent: parent.join("/") || "/"
+ };
+}
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageArraySuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- tmp = _findMessage(_messages.msg, filter);
+function _set(path, obj) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
- if (_offset) {
- offset = _offset;
- } else {
- offset = 0;
- }
- if (_limit) {
- limit = Math.min(_limit + offset, tmp.length);
- } else {
- limit = tmp.length;
- }
- for (i = offset; i < limit; i++) {
- ret.push(new Message(tmp[i].priv.type, tmp[i]));
- }
- setTimeout(function () {
- onSuccess(ret);
- }, 1);
- },
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
- findConversations: function (filter, onSuccess, onError, sort, _limit, _offset) {
- var i, tmp, offset, limit, ret = [];
+ parent.children = parent.children || {};
+ parent.children[child] = obj;
+}
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageConversationArraySuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- // download conversation
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+function _delete(path) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
- tmp = _findConversation(_messages.conv, filter);
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
- if (_offset) {
- offset = _offset;
- } else {
- offset = 0;
- }
- if (_limit) {
- limit = Math.min(_limit + offset, tmp.length);
- } else {
- limit = tmp.length;
- }
- for (i = offset; i < limit; i++) {
- ret.push(new Conversation(tmp[i]));
- }
- setTimeout(function () {
- onSuccess(ret);
- }, 1);
- },
+ delete parent.children[child];
+}
- removeConversations: function (conversations, onSuccess, onError) {
- var i, m, na_msg = "", retConv = [], removeMsg = [];
+function _save() {
+ db.saveObject("tizen1-db-filesystem", _cache);
+}
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- // download conversation
- _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
+function _walk(path, parent) {
+ _self.ls(path, function (entries) {
+ parent.children = parent.children || {};
- if (tizen1_utils.isValidArray(conversations) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if (conversations.length === 0) {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
- }
- if ((onSuccess && typeof onSuccess !== "function") ||
- (onError && typeof onError !== "function")) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ entries.forEach(function (entry) {
+ parent.children[entry.name] = entry;
- for (i = 0; i < conversations.length; i++) {
- if (_messages.conv[conversations[i].id] === undefined) {
- na_msg += conversations[i].id + ", ";
- } else {
- retConv.push(_messages.conv[conversations[i].id]);
- for (m in _messages.msg) {
- if (_messages.msg[m].priv.conversationId === conversations[i].id) {
- removeMsg.push(_messages.msg[m]);
- }
- }
- }
- }
- if (na_msg === "") {
- for (i = 0; i < removeMsg.length; i++) {
- // conversation updated at remote
- msg_utils.delMsg(removeMsg[i]); // remote
- delete _messages.msg[removeMsg[i].priv.id]; // local
- }
- // trigger msg(retMsg)/conv(retConv) delete update
- _processMessageChange(removeMsg, "remove");
- _processConversationChange(retConv, "remove");
- if (onSuccess) {
- setTimeout(function () {
- onSuccess();
- }, 1);
- }
+ if (entry.isDirectory) {
+ _walk(entry.fullPath, entry);
} else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
- na_msg + "not found !!"));
- }, 1);
- }
+ /* after getting Date out of DB, Date will become
+ a string, so need to recast it back to Date */
+ if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
+ entry.lastModifiedDate = new Date(entry.lastModifiedDate);
+ if (entry.createdDate !== null && entry.createdDate !== undefined)
+ entry.createdDate = new Date(entry.createdDate);
+
+ _self.read(entry.fullPath, function (data) {
+ parent.children[entry.name].data = data;
+ }, function (e) {
+ _console.error(e);
+ });
}
- },
+ });
+ }, function (e) {
+ _console.error(e);
+ });
+}
- findFolders: function (filter, onSuccess, onError) {
- var ret = [], tmp, i;
+function _createPath(path) {
+ var parts = path.replace(/^\//, '').split("/"),
+ workflow = jWorkflow.order();
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageFolderArraySuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- switch (filter.attributeName) {
- case "id":
- case "serviceId":
- case "contentType":
- case "name":
- case "path":
- case "type":
- tmp = tizen1_utils.matchAttributeFilter(_folders,
- filter.attributeName, filter.matchFlag,
- filter.matchValue);
- break;
- case "synchronizable":
- if (filter.matchFlag !== "EXACTLY" ||
- typeof filter.matchValue !== "boolean") {
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
- }
- tmp = tizen1_utils.matchAttributeBooleanFilter(_folders,
- filter.attributeName, filter.matchValue);
- break;
- case "parentId":
- if (filter.matchValue === null) {
- tmp = utils.filter(_folders, function (o) { return o.parentId === null; });
- } else {
- tmp = tizen1_utils.matchAttributeFilter(_folders,
- filter.attributeName, filter.matchValue);
- }
- break;
- default:
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
- "invalid attributeName"));
- }
- for (i = 0; i < tmp.length; i++) {
- ret.push(new MessageFolder(tmp[i]));
- }
- setTimeout(function () {
- onSuccess(ret);
- }, 1);
- },
+ parts.forEach(function (part, index) {
+ var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
- addMessagesChangeListener: function (msgCallback, filter) {
- var watchId, msgListener = {};
+ workflow.andThen(function (prev, baton) {
+ baton.take();
+ _self.mkdir(dir, baton.pass, baton.pass);
+ });
+ });
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessagesChangeCallback)).match(msgCallback)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ workflow.start();
+}
+
+_self = {
+ // The order is consistent with _virtualRoots in filesystem.js
+ roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
+ initialize: function () {
+ // TODO: Initialize at bootstrap and emulatorBridge.link
+ _cache = db.retrieveObject("tizen1-db-filesystem") || {};
+ // create real root paths if empty
+ _self.roots.every(function (root) {
+ _createPath(root);
+ return true;
+ });
+ // build the file system cache so that we could access information synchronously
+ _walk("/", _cache);
+ },
+ ls: function (path, success, error) {
+ try {
+ var dir = _get(path),
+ items = [];
+
+ if (dir) {
+ utils.forEach(dir.children, function (item) {
+ items.push(item);
+ });
}
- if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ else {
+ items = {};
}
- watchId = Number(Math.uuid(8, 10));
- msgListener.callback = msgCallback;
- msgListener.filter = filter || null;
- _msgListeners[watchId] = msgListener;
- return watchId;
- },
+ success(items);
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ rm: function (path, success, error, options) {
+ _delete(path);
+ _save();
+ success();
+ },
+ rmdir: function (path, success, error, options) {
+ _delete(path);
+ _save();
+ success();
+ },
+ mkdir: function (path, success, error) {
+ var entry = _get(path),
+ info = _getInfo(path);
- addConversationsChangeListener: function (convCallback, filter) {
- var watchId, convListener = {};
+ if (!entry) {
+ _set(path, {
+ lastModifiedDate: new Date(),
+ createdDate: new Date(),
+ name: info.name,
+ isDirectory: true,
+ fullPath: path
+ });
+ entry = _get(path);
+ _save();
+ }
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageConversationsChangeCallback)).match(convCallback)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ if (entry) {
+ success(entry);
+ }
+ else {
+ error({code: 1});
+ }
+ },
+ mv: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from),
+ toInfo = _getInfo(to);
- watchId = Number(Math.uuid(8, 10));
- convListener.callback = convCallback;
- convListener.filter = filter || null;
- _convListeners[watchId] = convListener;
- return watchId;
- },
+ fromEntry.fullPath = to;
+ fromEntry.name = toInfo.name;
- addFoldersChangeListener: function (callback, filter) {
- var watchId, folderListener = {};
+ _set(to, fromEntry);
+ _delete(from);
+ _save();
+ success();
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ touch: function (path, success, error) {
+ var entry = _get(path),
+ info = _getInfo(path);
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageFoldersChangeCallback)).match(callback)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ if (!entry) {
+ _set(path, {
+ lastModifiedDate: new Date(),
+ createdDate: new Date(),
+ name: info.name,
+ isDirectory: false,
+ fullPath: path,
+ data: ""
+ });
+ entry = _get(path);
+ }
+ _save();
+ success(entry);
+ },
+ cp: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from),
+ copied = utils.copy(fromEntry);
- watchId = Number(Math.uuid(8, 10));
- folderListener.callback = callback;
- folderListener.filter = filter || null;
- _folderListeners[watchId] = folderListener;
- return watchId;
- },
+ copied.name = _getInfo(to).name;
+ copied.fullPath = to;
+ _set(to, copied);
+ _save();
+ success();
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ stat: function (path, success, error) {
+ var entry = _get(path);
- removeChangeListener: function (watchid) {
- if (_security_check.read === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (_msgListeners[watchid] !== undefined) {
- delete _msgListeners[watchid];
- return;
- }
- if (_convListeners[watchid] !== undefined) {
- delete _convListeners[watchid];
- return;
- }
- if (_folderListeners[watchid] !== undefined) {
- delete _folderListeners[watchid];
- return;
- }
+ if (entry) {
+ success(entry);
+ } else {
+ error({code: 1});
}
+ },
+ write: function (path, contents, success, error, options) {
+ var entry = _get(path);
- };
- return message_storage;
+ if (entry) {
+ entry.lastModifiedDate = new Date();
+ entry.data = contents;
+ _save();
+ success();
+ } else {
+ error({code: 1});
+ }
+
+ },
+ read: function (path, success, error) {
+ var entry = _get(path);
+
+ if (entry) {
+ success(utils.copy(entry.data));
+ }
+ else {
+ error({code: 1});
+ }
+ }
};
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/MessagingService', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/spec/config', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants');
-var event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- deviceSettings = require('ripple/deviceSettings'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
- MessageStorage = require('ripple/platform/tizen/2.0/MessageStorage'),
- msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
- t = require('ripple/platform/tizen/2.0/typedef'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- _self,
- TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
- "messaging.mms": "13572468",
- "messaging.email": "tizen.simulator@tizen.org"},
- INCOMING_TYPE = {"messaging.sms": "sms",
- "messaging.mms": "mms",
- "messaging.email": "email"};
-
-_self = function (id, type, security_check) {
- var msg_service = {},
- pendingOperations = {},
- _msgSending = {},
- _receivedEmails = [],
- _id = id,
- _type = type,
- _security_check = security_check,
- _from = TIZEN_DEFAULT_MSG_FROM[_type],
- _incomingType = INCOMING_TYPE[_type],
- _messages = msg_utils.loadMsg(_type, _id),
- _messageStorage = new MessageStorage(_messages, _security_check);
+module.exports = {
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ // no xmlns:JIL in wac 2.0 spec
+ valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
- event.on("MessageSent", function (rst) {
- var i, rsp_ok = [], rsp_fail = [];
- // rst.msg is the real msg in module
- if (rst.msg.priv.type !== _type ||
- rst.msg.priv.serviceId !== _id) {
- // not my msg
- return;
- }
- if (_msgSending[rst.id] !== undefined) {
- for (i in rst) {
- if ((i !== "id") && (i !== "msg")) {
- if (rst[i] === true) {
- rsp_ok.push(i);
- } else {
- rsp_fail.push(i);
- }
- }
- }
- rst.msg.priv.folderId = "SENTBOX";
- if (rsp_fail.length === 0) {
- rst.msg.priv.messageStatus = "SENT";
- _msgSending[rst.id].onsuccess(rsp_ok);
- } else {
- rst.msg.priv.messageStatus = "FAILED";
- _msgSending[rst.id].onerror(rsp_fail);
- }
- msg_utils.saveMsg(rst.msg); // sync to remote
- event.trigger("MsgSentRst", [rst.msg]);
- delete _msgSending[rst.id];
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
}
- });
- event.on("MessageReceived", function (rst) {
- var m, opt = {}, msgInit = {}, msg = {};
+ var widgetInfo = {},
+ configFeatures,
+ configPreferences,
+ preferenceName,
+ platform, rst, i, j,
+ settingRst = {
+ 'screen-orientation': 'portrait',
+ 'context-menu': 'enable',
+ 'background-support': 'disable',
+ encryption: 'disable',
+ 'install-location': 'auto',
+ 'hwkey-event': 'enable'
+ };
- if (rst.type !== _incomingType) {
- // not my msg
- return;
- }
- msgInit.plainBody = rst.body;
- msgInit.to = [_from];
- // TODO: handle attachment
- if (msg_utils.setMsg(msgInit, msg) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR, "received message error"));
- }
- opt.id = Math.uuid(8, 16);
- opt.serviceId = _id;
- opt.conversationId = opt.id;
- opt.folderId = "INBOX";
- opt.type = _type;
- opt.timestamp = new Date();
- opt.from = rst.from;
- if (msg.attachments.length === 0) {
- opt.hasAttachment = false;
- } else {
- opt.hasAttachment = true;
- }
- opt.messageStatus = "RECEIVED";
- m = new PrivMessage(msg, opt);
- msg_utils.saveMsg(m); // save in server
- if (_type !== "messaging.email") {
- _messages.msg[m.priv.id] = m; // sync to local
- event.trigger("MsgRecv", [m]);
- } else {
- _receivedEmails.push(m); // don't sync to local yet
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+ if (configValidationObject.widget.children.application.validationResult[0].valid) {
+ widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
+ widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
}
- });
- msg_service = {
- sendMessage: function (_msg, onSuccess, onError) {
- var m, msg = {}, opt = {}, shortMsg = {}, rst = {};
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (_msg === null || _msg === undefined || _msg.id === undefined) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
+ widgetInfo.features = {};
- if (msg_utils.setMsg(_msg, msg) === false) {
- throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
- (_incomingType === 'sms' || _incomingType === 'mms')) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- return;
- }
- if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
- _incomingType === 'email') {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- return;
- }
- if (typeof _msg.id === 'string') {
- if (_messages.msg[_msg.id] === undefined) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return;
- }
- if (_messages.msg[_msg.id].priv.messageStatus === "DRAFT") {
- msg_utils.delMsg(_messages.msg[_msg.id]);
- delete _messages.msg[_msg.id];
- } else {
- // if msg found in storage, it can only be a draft.
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.UNKNOWN_ERR));
- }, 1);
+ if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
+ rst = configValidationObject.widget.children.setting.validationResult;
+ // the first one has higher priority per platform implementation
+ for (i = rst.length -1 ; i >= 0; i--) {
+ if (rst[i].valid === true) {
+ for (j in rst[i].attributes) {
+ if (rst[i].attributes[j].value !== undefined) {
+ settingRst[j] = rst[i].attributes[j].value;
+ }
}
- return;
}
}
- opt.id = Math.uuid(8, 16);
- opt.serviceId = _id;
- if ((msg.inResponseTo !== null) &&
- (_messages.msg[msg.inResponseTo] !== undefined) &&
- (_messages.msg[msg.inResponseTo].priv.messageStatus !== "DRAFT")) {
- opt.conversationId = _messages.msg[msg.inResponseTo].priv.conversationId;
- } else {
- opt.conversationId = opt.id;
- }
- opt.folderId = "OUTBOX";
- opt.type = _type;
- opt.timestamp = new Date();
- opt.from = _from;
- if (msg.attachments.length === 0) {
- opt.hasAttachment = false;
- } else {
- opt.hasAttachment = true;
- }
- opt.messageStatus = "SENDING";
-
- m = new PrivMessage(msg, opt);
- _messages.msg[m.priv.id] = m;
- msg_utils.saveMsg(m); // sync to remote
- shortMsg.msg = m; // pass by ref
- shortMsg.id = m.priv.id;
- shortMsg.body = m.body.plainBody;
- shortMsg.to = m.to.slice(0);
- shortMsg.cc = m.cc.slice(0);
- shortMsg.bcc = m.bcc.slice(0);
- event.trigger("OutsideMessageReceived", [shortMsg]);
- rst.onsuccess = onSuccess;
- rst.onerror = onError;
- _msgSending[m.priv.id] = rst;
- },
+ db.save("layout", settingRst["screen-orientation"]);
+ }
- loadMessageBody: function (msg, onSuccess, onError) {
- var pendingID;
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (_messages.msg[msg.id] === undefined) {
- throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
- }
- if (!(new TypeCoerce(t.MessageBodySuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ configFeatures = configValidationObject.widget.children.feature.validationResult;
+ utils.forEach(configFeatures, function (f) {
+ if (f.valid === true) {
+ var feature = {id: f.attributes.name.value,
+ required: f.attributes.required.valid};
+ widgetInfo.features[feature.id] = feature;
}
- pendingID = setTimeout(function () {
- if (pendingOperations.hasOwnProperty(pendingID) === false) {
- // has been cancelled/expired
- return;
- }
- delete pendingOperations[pendingID];
- onSuccess(_messages.msg[msg.id].body);
- }, 1);
- pendingOperations[pendingID] = onError;
- return pendingID;
- },
- loadMessageAttachment: function (msg, onSuccess, onError) {
- var pendingID;
+ });
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (_messages.msg[msg.id] === undefined) {
- throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
- }
- if (!(new TypeCoerce(t.MessageAttachmentSuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- pendingID = setTimeout(function () {
- if (pendingOperations.hasOwnProperty(pendingID) === false) {
- // has been cancelled/expired
- return;
- }
- delete pendingOperations[pendingID];
- onSuccess(_messages.msg[msg.id].attachments);
- }, 1);
- pendingOperations[pendingID] = onError;
- return pendingID;
- },
- sync: function (successCallback, errorCallback, limit) {
- var i, m, pendingID;
+ widgetInfo.preferences = {};
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if ((arguments.length > 0) && successCallback !== null && !(new TypeCoerce(t.SuccessCallback)).match(successCallback)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 1) && errorCallback !== null && !(new TypeCoerce(t.ErrorCallback)).match(errorCallback)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 2) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- pendingID = setTimeout(function () {
- if (pendingOperations.hasOwnProperty(pendingID) === false) {
- // has been cancelled/expired
- return;
- }
- delete pendingOperations[pendingID];
- for (i = 0; i < _receivedEmails.length; i++) {
- m = _receivedEmails[i];
- _messages.msg[m.priv.id] = m; // sync to local
- event.trigger("MsgRecv", [m]);
- }
- _receivedEmails = [];
- if (successCallback) {
- successCallback();
- }
- }, 1);
- pendingOperations[pendingID] = errorCallback;
- return pendingID;
- },
+ configPreferences = configValidationObject.widget.children.preference.validationResult;
- syncFolder: function (folder, onSuccess, onError, limit) {
- var i, m, pendingID;
+ platform = require('ripple/platform');
+ utils.forEach(configPreferences, function (preference) {
+ preferenceName = preference.attributes.name.value;
+ if (preferenceName) {
+ widgetInfo.preferences[preferenceName] = {
+ "key": preferenceName,
+ "value": preference.attributes.value.value || "",
+ "readonly": preference.attributes.readonly.value === "true"
+ };
- if (_security_check.write === false) {
- throw (new WebAPIException(errorcode.SECURITY_ERR));
- }
- if (!(new TypeCoerce(t.MessageFolder)).match(folder)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((arguments.length > 3) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ db.save(preferenceName,
+ widgetInfo.preferences[preferenceName].value,
+ platform.getPersistencePrefix(widgetInfo.id));
}
- pendingID = setTimeout(function () {
- if (pendingOperations.hasOwnProperty(pendingID) === false) {
- // has been cancelled/expired
- return;
- }
- delete pendingOperations[pendingID];
- if (folder.id === "INBOX") {
- for (i = 0; i < _receivedEmails.length; i++) {
- m = _receivedEmails[i];
- _messages.msg[m.priv.id] = m; // sync to local
- event.trigger("MsgRecv", [m]);
+ });
+
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:tizen": {
+ attributeName: "xmlns:tizen",
+ required: false,
+ type: "list",
+ listValues: ["http://tizen.org/ns/widgets"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
+ },
+ defaultlocale: {
+ attributeName: "defaultlocale",
+ required: false,
+ type: "iso-language"
+ },
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ "short": {
+ attributeName: "short",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.URL
+ },
+ email: {
+ attributeName: "email",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.EMAIL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ encoding: {
+ attributeName: "encoding",
+ required: false,
+ type: "string"
+ },
+ type: {
+ attributeName: "type",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ setting: {
+ nodeName: "tizen:setting",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ 'screen-orientation': {
+ attributeName: "screen-orientation",
+ required: false,
+ type: "list",
+ listValues: ['portrait', 'landscape', 'auto']
+ },
+ 'context-menu': {
+ attributeName: "context-menu",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'background-support': {
+ attributeName: "background-support",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'encryption': {
+ attributeName: "encryption",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'install-location': {
+ attributeName: "install-location",
+ required: false,
+ type: "list",
+ listValues: ['auto', 'internal-only', 'perfer-external']
+ },
+ 'hwkey-event': {
+ attributeName: "hwkey-event",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ }
+ }
+ },
+ application: {
+ nodeName: "tizen:application",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ },
+ required_version: {
+ attributeName: "required_version",
+ required: true,
+ type: "list",
+ listValues: ['1.0', '2.0', '2.1', '2.2']
+ },
+ package: {
+ attributeName: "package",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ "tizen:content": {
+ nodeName: "tizen:content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ control: {
+ nodeName: "tizen:app-control",
+ required: false,
+ occurrence: 0,
+ children: {
+ src: {
+ nodeName: "tizen:src",
+ required: true,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ operation: {
+ nodeName: "tizen:operation",
+ required: true,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ uri: {
+ nodeName: "tizen:uri",
+ required: false,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ mime: {
+ nodeName: "tizen:mime",
+ required: false,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ }
+ }
+ },
+ "app-widget": {
+ nodeName: "tizen:app-widget",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ },
+ primary: {
+ attributeName: "primary",
+ required: true,
+ type: "list",
+ listValues: ['true', 'false']
+ },
+ "auto-launch": {
+ attributeName: "auto-launch",
+ required: false,
+ type: "list",
+ listValues: ['true', 'false']
+ },
+ "update-period": {
+ attributeName: "update-period",
+ required: false,
+ type: "integer"
+ }
+ },
+ children: {
+ "box-label": {
+ nodeName: "tizen:box-label",
+ required: true,
+ occurence: 1
+ },
+ "box-icon": {
+ nodeName: "tizen:box-icon",
+ required: true,
+ occurence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ "box-content": {
+ nodeName: "tizen:box-content",
+ required: true,
+ occurence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ "mouse-event": {
+ attributeName: "mouse-event",
+ required: false,
+ type: "string"
+ },
+ "touch-event": {
+ attributeName: "touch-event",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ "box-size": {
+ nodeName: "tizen:box-size",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "preview": {
+ attributeName: "preview",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ pd: {
+ nodeName: "tizen:pd",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "src": {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ "width": {
+ attributeName: "width",
+ required: true,
+ type: "integer"
+ },
+ "height": {
+ attributeName: "height",
+ required: true,
+ type: "integer"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ account: {
+ nodeName: "tizen:account",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "multiple-account-support": {
+ attributeName: "multiple-account-support",
+ required: true,
+ type: "list",
+ listValues: ['true', 'false']
+ }
+ },
+ children: {
+ icon: {
+ nodeName: "tizen:icon",
+ required: false,
+ occurence: 1,
+ attributes: {
+ section: {
+ attributeName: "section",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ "display-name": {
+ nodeName: "tizen:display-name",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ capability: {
+ nodeName: "capability",
+ required: false,
+ occurence: 1
+ }
+ }
+ },
+ feature: {
+ nodeName: "tizen:privilege",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/TR/battery-status/",
+ "http://www.w3.org/TR/geolocation-API/",
+ "http://www.w3.org/TR/touch-events/",
+ "http://www.w3.org/TR/vibration/",
+ "http://tizen.org/privilege/tizen",
+ "http://tizen.org/privilege/alarm",
+ "http://tizen.org/privilege/application.launch",
+ "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
+ "http://tizen.org/privilege/bluetoothmanager", "http://tizen.org/privilege/bluetooth.admin",
+ "http://tizen.org/privilege/bluetooth.gap", "http://tizen.org/privilege/bluetooth.spp",
+ "http://tizen.org/privilege/bookmark.read", "http://tizen.org/privilege/bookmark.write",
+ "http://tizen.org/privilege/calendar.read", "http://tizen.org/privilege/calendar.write",
+ "http://tizen.org/privilege/callhistory.read", "http://tizen.org/privilege/callhistory.write",
+ "http://tizen.org/privilege/contact.read", "http://tizen.org/privilege/contact.write",
+ "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
+ "http://tizen.org/privilege/datacontrol.consumer",
+ "http://tizen.org/privilege/datasync",
+ "http://tizen.org/privilege/download",
+ "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
+ "http://tizen.org/privilege/messaging.read", "http://tizen.org/privilege/messaging.write",
+ "http://tizen.org/privilege/networkbearerselection",
+ "http://tizen.org/privilege/nfc.common", "http://tizen.org/privilege/nfc.admin",
+ "http://tizen.org/privilege/nfc.tag", "http://tizen.org/privilege/nfc.p2p",
+ "http://tizen.org/privilege/notification",
+ "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
+ "http://tizen.org/privilege/power",
+ "http://tizen.org/privilege/push",
+ "http://tizen.org/privilege/setting",
+ "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
+ "http://tizen.org/privilege/time"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ },
+ children: {
+ param: {
+ nodeName: "param",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string",
+ },
+ value: {
+ attributeName: "value",
+ required: true,
+ type: "string",
+ }
+ }
+ }
+ }
+ },
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string"
+ },
+ value: {
+ type: "string",
+ required: false,
+ attributeName: "value"
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
+ }
}
- _receivedEmails = [];
}
- onSuccess();
- }, 1);
- pendingOperations[pendingID] = onError;
- return pendingID;
- },
-
- stopSync: function (pendingID) {
- if (!(new TypeCoerce(t.long)).match(pendingID)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
}
- if (pendingOperations[pendingID] !== undefined) {
- clearTimeout(pendingID);
- pendingOperations[pendingID](new WebAPIError(errorcode.ABORT_ERR));
- }
- delete pendingOperations[pendingID];
}
- };
- msg_service.__defineGetter__("type", function () {
- return _type;
- });
- msg_service.__defineGetter__("messageStorage", function () {
- return _messageStorage;
- });
- return msg_service;
+ }
};
-module.exports = _self;
-
});
-define('ripple/platform/tizen/2.0/NDEFMessage', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/spec/device', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ StorageTypeTable = {
+ "UNKNOWN": "UNKNOWN",
+ "INTERNAL": "INTERNAL",
+ "MMC": "MMC",
+ "USB_HOST": "USB_HOST"
+ },
+ NetworkTypeTable = {
+ "NONE": "NONE",
+ "2G": "2G",
+ "2.5G": "2.5G",
+ "3G": "3G",
+ "4G": "4G",
+ "WIFI": "WIFI",
+ "ETHERNET": "ETHERNET",
+ "UNKNOWN": "UNKNOWN"
+ },
+ LocaleTable = {
+ "eng_USA": "eng_USA",
+ "eng_CAN": "eng_CAN",
+ "deu_DEU": "deu_DEU",
+ "jpn_JPN": "jpn_JPN",
+ "zho_CHN": "zho_CHN",
+ "UNKNOWN": "UNKNOWN"
+ },
+ SimStateTable = {
+ "ABSENT": "ABSENT",
+ "INITIALIZING": "INITIALIZING",
+ "READY": "READY",
+ "PIN_REQUIRED": "PIN_REQUIRED",
+ "PUK_REQUIRED":"PUK_REQUIRED",
+ "NETWORK_LOCKED": "NETWORK_LOCKED",
+ "SIM_LOCKED": "SIM_LOCKED",
+ "UNKNOWN": "UNKNOWN"
+ };
-var t = require('ripple/platform/tizen/2.0/typecast'),
- NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecord'),
- NDEFRecordText = require('ripple/platform/tizen/2.0/NDEFRecordText'),
- NDEFRecordURI = require('ripple/platform/tizen/2.0/NDEFRecordURI'),
- NDEFRecordMedia = require('ripple/platform/tizen/2.0/NDEFRecordMedia'),
- NDEFRecordFactory,
- NDEFMessage;
-
-NDEFRecordFactory = function (ndefRecord) {
- var record;
-
- if (ndefRecord instanceof NDEFRecordText) {
- record = new NDEFRecordText(ndefRecord.text, ndefRecord.languageCode,
- ndefRecord.encoding || null);
- } else if (ndefRecord instanceof NDEFRecordURI) {
- record = new NDEFRecordURI(ndefRecord.url);
- } else if (ndefRecord instanceof NDEFRecordMedia) {
- record = new NDEFRecordMedia(ndefRecord.mimeType, ndefRecord.payload);
- } else {
- record = new NDEFRecord(ndefRecord.tnf, ndefRecord.type,
- ndefRecord.payload, ndefRecord.id || null);
- }
-
- return record;
-};
-
-NDEFMessage = function () {
- var voc, records = [];
-
- // private
- function construct() {
- this.__defineGetter__("recordCount", function () {
- return this.records.length;
- });
-
- this.__defineGetter__("records", function () {
- return records;
- });
+function deviceStatusEventTrigger(setting) {
+ event.trigger("DeviceStatusChanged", [setting]);
+}
- this.__defineSetter__("records", function (val) {
- try {
- t.NDEFRecord(val, "[]");
- records = val;
- } catch (e) {
+module.exports = {
+ "Config": {
+ "vibratingMode": {
+ "name": "Vibrator",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("VibratingModeChanged", [setting]);
}
- });
-
- this.toByte = function () {
- var result = [], i, j, space = " ".charCodeAt(0);
-
- for (i in this.records) {
- for (j = 0; j < this.records[i].payload.length; j++) {
- result.push(this.records[i].payload.charCodeAt(j));
- }
- if (i < this.records.length - 1) {
- result.push(space);
- }
+ },
+ "lockScreen": {
+ "name": "Lock Screen",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "callback": function (setting) {
+ event.trigger("LockScreenChanged", [setting]);
}
-
- return result;
- };
- }
-
- // constructor
- function NDEFMessage_NDEFRecords(ndefRecords) {
- var i;
-
- construct.apply(this);
-
- for (i = 0; i < ndefRecords.length; i++) {
- records[i] = new NDEFRecordFactory(ndefRecords[i]);
}
- }
-
- function NDEFMessage_bytes(rawData) {
- //TODO: NDEFMessage doesn't support rawData constructor
- construct.apply(this);
- }
-
- function NDEFMessage_void() {
- construct.apply(this);
- }
-
- voc = [NDEFMessage_NDEFRecords, NDEFMessage_bytes, NDEFMessage_void];
- t.NDEFMessage(arguments, this, voc);
-};
-
-module.exports = NDEFMessage;
-
-});
-define('ripple/platform/tizen/2.0/NDEFRecord', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
- NDEFRecord;
-
-NDEFRecord = function () {
- var voc = [
- function (tnf, type, payload, id) {
- NDEFRecordInternal.call(this, tnf, type, payload, id || []);
+ },
+ "DEVICE_ORIENTATION": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "label",
+ "innertext": "PORTRAIT_PRIMARY",
+ "value": "PORTRAIT_PRIMARY"
+ },
+ "event": "LayoutChanged"
},
- function (raw_data) {
- NDEFRecordInternal.call(this, 0, [], [], []);
+ "isAutoRotation": {
+ "name": "Is Auto Rotation",
+ "control": {
+ "type": "label",
+ "value": false
+ }
}
- ];
-
- t.NDEFRecord(arguments, this, voc);
-};
-
-module.exports = NDEFRecord;
-
-});
-define('ripple/platform/tizen/2.0/NDEFRecordInternal', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 = function (tnf, type, payload, id) {
- this.__defineGetter__("tnf", function () {
- return tnf;
- });
-
- this.__defineGetter__("type", function () {
- return type;
- });
-
- this.__defineGetter__("id", function () {
- return id;
- });
-
- this.__defineGetter__("payload", function () {
- return payload;
- });
-};
-
-});
-define('ripple/platform/tizen/2.0/NDEFRecordMedia', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
- NDEFRecordMedia;
-
-NDEFRecordMedia = function (mimeType, data) {
- var i, type = [], payload;
-
- t.NDEFRecordMedia(arguments, this);
-
- for (i = 0; i < mimeType.length; i++) {
- type[i] = mimeType.charCodeAt(i);
- }
- payload = t.byte(data, "[]");
-
- // Normally, we can use prototype to inherit a class, for example:
- // NDEFRecordMedia.prototype = new NDEFRecord(2, [...], [...], [...]);
- // But the test case thinks that all the inherited property should be
- // the object's own property. So, we can only change the "this" point
- // of NDEFRecord constructor here.
- NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_MIME_MEDIA, type,
- payload, []);
-
- this.__defineGetter__("mimeType", function () {
- return mimeType;
- });
-};
-
-module.exports = NDEFRecordMedia;
-
-});
-define('ripple/platform/tizen/2.0/NDEFRecordText', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
- NDEFRecordText;
-
-NDEFRecordText = function (text, languageCode, encoding) {
- var payload = [], i;
-
- t.NDEFRecordText(arguments, this);
-
- encoding = encoding || "UTF8";
-
- // Store languageCode in payload
- payload.push(languageCode.length);
- for (i = 0; i < languageCode.length; i++) {
- payload.push(languageCode.charCodeAt(i));
- }
-
- // Store text in payload
- for (i = 0; i < text.length; i++) {
- payload.push(text.charCodeAt(i));
- }
-
- NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
- ["T".charCodeAt(0)], payload, []);
-
- this.__defineGetter__("text", function () {
- return text;
- });
-
- this.__defineGetter__("languageCode", function () {
- return languageCode;
- });
-
- this.__defineGetter__("encoding", function () {
- return encoding;
- });
-};
-
-module.exports = NDEFRecordText;
-
-});
-define('ripple/platform/tizen/2.0/NDEFRecordURI', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
- NDEFRecordURI;
-
-NDEFRecordURI = function (uri) {
- var payload = [], i;
-
- t.NDEFRecordURI(arguments, this);
-
- // Store uri in payload
- payload.push(0);
- for (i = 0; i < uri.length; i++) {
- payload.push(uri.charCodeAt(i));
- }
-
- NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
- ["U".charCodeAt(0)], payload, []);
-
- this.__defineGetter__("uri", function () {
- return uri;
- });
-};
-
-module.exports = NDEFRecordURI;
-
-});
-define('ripple/platform/tizen/2.0/NotificationBase', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- Notification;
-
-Notification = function (title, content) {
- var notification = {};
-
- notification.title = title;
- notification.content = content || null;
-
- this.__defineGetter__("id", function () {
- return undefined;
- });
-
- this.__defineGetter__("type", function () {
- return "STATUS";
- });
-
- this.__defineGetter__("postedTime", function () {
- return undefined;
- });
-
- this.__defineGetter__("title", function () {
- return notification.title;
- });
- this.__defineSetter__("title", function (val) {
- try {
- notification.title = t.DOMString(val);
- } catch (e) {
+ },
+ "CPU": {
+ "load": {
+ "name": "Load",
+ "control": {
+ "type": "number",
+ "value": 0.1
+ },
+ "event": "CpuLoadChanged",
+ "callback": function (setting) {
+ if (setting > 1) setting = 1;
+ if (setting < 0) setting = 0;
+ event.trigger("CpuLoadChanged", [setting]);
+ }
}
- });
+ },
+ "STORAGE": {
+ "type": {
+ "name": "Type",
+ "control": {
+ "type": "select",
+ "value": StorageTypeTable["INTERNAL"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(StorageTypeTable, function (key, value) {
+ optionList[key] = StorageTypeTable[value];
+ });
- this.__defineGetter__("content", function () {
- return notification.content;
- });
- this.__defineSetter__("content", function (val) {
- try {
- notification.content = t.DOMString(val, "?");
- } catch (e) {
+ return optionList;
+ }())
+ },
+ "capacity": {
+ "name": "Capacity(bytes)",
+ "control": {
+ "type": "label",
+ "value": 16000000000
+ },
+ },
+ "availableCapacity": {
+ "name": "AvailableCapacity(bytes)",
+ "control": {
+ "type": "number",
+ "value": 12000000000
+ },
+ "callback": function (setting) {
+ event.trigger("AvailCapacityChanged", [setting]);
+ }
+ },
+ "isRemovable": {
+ "name": "IsRemovable",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
}
- });
-};
-
-module.exports = Notification;
-
-});
-define('ripple/platform/tizen/2.0/NotificationDetailInfo', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 t = require('ripple/platform/tizen/2.0/typecast'),
- NotificationDetailInfo;
-
-NotificationDetailInfo = function (mainText, subText) {
- var notificationDetailInfo = {};
-
- t.NotificationDetailInfo(arguments, this);
+ },
+ "BUILD": {
+ "model": {
+ "name": "Model",
+ "control": {
+ "type": "label",
+ "innertext": "tizen-2.2 build",
+ "value": "tizen-2.2 build"
+ }
+ },
+ "manufacturer": {
+ "name": "Manufacturer",
+ "control": {
+ "type": "label",
+ "innertext": "Tizen",
+ "value": "Tizen"
+ }
+ },
+ "buildVersion": {
+ "name": "Build Version",
+ "control": {
+ "type": "label",
+ "innertext": "TIZEN_WEB_SIMULATOR_000001",
+ "value": "TIZEN_WEB_SIMULATOR_000001"
+ }
+ }
+ },
+ "LOCALE": {
+ "language": {
+ "name": "Language",
+ "control": {
+ "type": "select",
+ "value": LocaleTable["eng_USA"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(LocaleTable, function (key, value) {
+ optionList[key] = LocaleTable[value];
+ });
- notificationDetailInfo.mainText = mainText;
- notificationDetailInfo.subText = subText || null;
+ return optionList;
+ }())
+ },
+ "country": {
+ "name": "Country",
+ "control": {
+ "type": "select",
+ "value": LocaleTable["eng_USA"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(LocaleTable, function (key, value) {
+ optionList[key] = LocaleTable[value];
+ });
- this.__defineGetter__("mainText", function () {
- return notificationDetailInfo.mainText;
- });
- this.__defineSetter__("mainText", function (val) {
- try {
- notificationDetailInfo.mainText = t.DOMString(val);
- } catch (e) {
+ return optionList;
+ }())
}
- });
-
- this.__defineGetter__("subText", function () {
- return notificationDetailInfo.subText;
- });
- this.__defineSetter__("subText", function (val) {
- try {
- notificationDetailInfo.subText = t.DOMString(val, "?");
- } catch (e) {
+ },
+ "DISPLAY": {
+ "resolutionWidth": {
+ "name": "Resolution Width(pixels)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "resolutionHeight": {
+ "name": "Resolution Height(pixels)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "dotsPerInchWidth": {
+ "name": "DPI-X",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "dotsPerInchHeight": {
+ "name": "DPI-Y",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "physicalWidth": {
+ "name": "Physical Width(millimeters)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "physicalHeight": {
+ "name": "Physical Height(millimeters)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "brightness": {
+ "name": "Brightness",
+ "control": {
+ "type": "number",
+ "value": 1
+ },
+ "event": "DisplayBrightnessChanged",
+ "callback": function (setting) {
+ if (setting > 1) setting = 1;
+ if (setting < 0) setting = 0;
+ event.trigger("DisplayBrightnessChanged", [setting]);
+ }
}
- });
-};
-
-module.exports = NotificationDetailInfo;
-
-});
-define('ripple/platform/tizen/2.0/POIBase', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError');
-
+ },
+ "NETWORK": {
+ "networkType": {
+ "name": "Network Type",
+ "control" : {
+ "type": "select",
+ "value": NetworkTypeTable["NONE"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(NetworkTypeTable, function (key, value) {
+ optionList[key] = NetworkTypeTable[value];
+ });
-module.exports = function (prop) {
- var _self, i, copy, attr;
- _self = {
- name : null,
- categories : [],
- address : null,
- phoneNumbers : [],
- geometry : null,
- urls : [],
- rating : null,
- tags : null,
- toGeoJSON : function () {
- throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
+ return optionList;
+ }())
}
- };
-
- _self.__defineGetter__("id", function () {
- return null;
- });
+ },
+ "WIFI_NETWORK": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "event": "WiFiNetworkStatusChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiNetworkStatusChanged", [setting]);
+ }
+ },
+ "ssid": {
+ "name": "SSID",
+ "control": {
+ "type": "text",
+ "value": "Tizen WiFi"
+ }
+ },
+ "ipAddress": {
+ "name": "IP Address",
+ "control": {
+ "type": "text",
+ "value": "192.168.0.1"
+ }
+ },
+ "ipv6Address": {
+ "name": "IPv6 Address",
+ "control": {
+ "type": "text",
+ "value": "2001:db8:85a3:0:0:0:70:7334"
+ }
+ },
+ "signalStrength": {
+ "name": "Signal Strength",
+ "control": {
+ "type": "select",
+ "value": 0
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- _self.__defineGetter__("providerName", function () {
- return null;
- });
+ for (i = 0; i <= 10; i++) {
+ optionList[i] = i;
+ }
- if (prop) {
- if (prop.name) {
- _self.name = String(prop.name);
+ return optionList;
+ }())
}
- if (tizen1_utils.isValidArray(prop.categories)) {
- _self.categories = [];
- for (i in prop.categories) {
- _self.categories.push(String(prop.categories[i]));
+ },
+ "CELLULAR_NETWORK": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "CellularNetworkStatusChanged",
+ "callback": function (setting) {
+ event.trigger("CellularNetworkStatusChanged", [setting]);
}
- }
- if (prop.address) {
- if (typeof prop.address === "string") {
- _self.address = String(prop.address);
- } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
- copy = prop.address.constructor();
- for (attr in prop.address) {
- if (prop.address.hasOwnProperty(attr)) {
- copy[attr] = prop.address[attr];
- }
- }
- _self.address = copy;
+ },
+ "apn": {
+ "name": "APN",
+ "control": {
+ "type": "text",
+ "value": "Tizen"
}
- }
- if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
- _self.phoneNumbers = [];
- for (i in prop.phoneNumbers) {
- _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
+ },
+ "ipAddress": {
+ "name": "IP Address",
+ "control": {
+ "type": "text",
+ "value": "10.0.2.16"
}
- }
- if (prop.geometry) {
- _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
- }
- if (tizen1_utils.isValidArray(prop.urls)) {
- _self.urls = [];
- for (i in prop.urls) {
- _self.urls.push(String(prop.urls[i]));
+ },
+ "ipv6Address": {
+ "name": "IPv6 Address",
+ "control": {
+ "type": "text",
+ "value": "2001:db8:85a3:0:0:0:70:7334"
}
- }
- if (typeof prop.rating === "number") {
- _self.rating = prop.rating;
- }
- if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
- copy = prop.tags.constructor();
- for (attr in prop.tags) {
- if (prop.tags.hasOwnProperty(attr)) {
- copy[attr] = prop.tags[attr];
- }
+ },
+ "mcc": {
+ "name": "MCC",
+ "control": {
+ "type": "number",
+ "value": 460
+ }
+ },
+ "mnc": {
+ "name": "MNC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "cellId": {
+ "name": "Cell ID",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "lac": {
+ "name": "LAC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "isRoaming": {
+ "name": "Roaming",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "isFlightMode": {
+ "name": "Flight Mode",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "callback": function (setting) {
+ event.trigger("FlightModeChanged", [setting]);
+ }
+ },
+ "imei": {
+ "name": "IMEI",
+ "control": {
+ "type": "text",
+ "value": "012417005203000"
}
- _self.tags = copy;
}
- }
-
- return _self;
-};
-
-});
-define('ripple/platform/tizen/2.0/POIFilter', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 = function (attributeName, value) {
- var _self;
-
- _self = {
- attributeName: attributeName,
- value: value
- };
+ },
+ "SIM": {
+ "state": {
+ "name": "State",
+ "control": {
+ "type": "select",
+ "value": SimStateTable["READY"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(SimStateTable, function (key, value) {
+ optionList[key] = SimStateTable[value];
+ });
- return _self;
+ return optionList;
+ }())
+ },
+ "operatorName": {
+ "name": "Operator Name",
+ "control": {
+ "type": "text",
+ "value": "Tizen"
+ }
+ },
+ "msisdn": {
+ "name": "MSISDN",
+ "control": {
+ "type": "text",
+ "value": "088123456789"
+ }
+ },
+ "iccid": {
+ "name": "ICCID",
+ "control": {
+ "type": "text",
+ "value": "123000MFSSYYGXXXXXXP"
+ }
+ },
+ "mcc": {
+ "name": "MCC",
+ "control": {
+ "type": "number",
+ "value": 460
+ }
+ },
+ "mnc": {
+ "name": "MNC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "msin": {
+ "name": "MSIN",
+ "control": {
+ "type": "text",
+ "value": "H1 H2 H3 S 12345"
+ }
+ },
+ "spn": {
+ "name": "SPN",
+ "control": {
+ "type": "text",
+ "value": "TizenSPN"
+ }
+ }
+ },
+ "PERIPHERAL": {
+ "isVideoOutputOn": {
+ "name": "Video Output",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ }
+ }
};
+
});
-define('ripple/platform/tizen/2.0/POIGeometry', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/spec/sensor', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var event = require('ripple/event');
-var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- GeoRectBounds = require('ripple/platform/tizen/2.0/GeoRectBounds');
+function sensorStatusEventTrigger(setting) {
+ event.trigger("SensorStatusChanged", [setting]);
+}
-module.exports = function (position, viewport, wkt) {
- var _self, _position = null, _viewport = null, _wkt = "";
+module.exports = {
+ "Accelerometer": {
+ "resolution": 0.039239998906850815,
+ "minDelay": 20,
+ "range": 20.051639556884766,
+ "name": "Accelerometer",
+ "type": "Accelerometer"
+ },
+ "MagneticField": {
+ "x": {
+ "name": "X",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-xChanged", [setting]);
+ }
+ },
- if (position) {
- _position = new SimpleCoordinates(position.latitude, position.longitude);
- }
+ "y": {
+ "name": "Y",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-yChanged", [setting]);
+ }
+ },
- if (viewport) {
- _viewport = new GeoRectBounds(viewport.southWest, viewport.northEast);
- }
+ "z": {
+ "name": "Z",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-zChanged", [setting]);
+ }
+ },
- if (wkt) {
- _wkt = String(wkt);
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "MagneticField",
+ "type": "MagneticField"
+ },
+ "Rotation": {
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "Rotation",
+ "type": "Rotation"
+ },
+ "Orientation": {
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "Orientation",
+ "type": "Orientation"
}
-
- _self = {
- position : _position,
- viewport: _viewport,
- wkt: _wkt
- };
-
- return _self;
};
});
-define('ripple/platform/tizen/2.0/PackageInformation', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/spec/ui', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function (id, name, iconPath, version, totalSize,
- dataSize, lastModified, author, description, appIds) {
- var packageInformation = {}, _date = new Date(lastModified);
-
- packageInformation.__defineGetter__("id", function () {
- return id;
- });
- packageInformation.__defineGetter__("name", function () {
- return name;
- });
- packageInformation.__defineGetter__("iconPath", function () {
- return iconPath;
- });
- packageInformation.__defineGetter__("version", function () {
- return version;
- });
- packageInformation.__defineGetter__("totalSize", function () {
- return totalSize;
- });
- packageInformation.__defineGetter__("dataSize", function () {
- return dataSize;
- });
- packageInformation.__defineGetter__("lastModified", function () {
- return _date;
- });
- packageInformation.__defineGetter__("author", function () {
- return author;
- });
- packageInformation.__defineGetter__("description", function () {
- return description;
- });
- packageInformation.__defineGetter__("appIds", function () {
- return appIds;
- });
-
- return packageInformation;
+module.exports = {
+ plugins: [
+ "sensors",
+ "communication",
+ "geoView",
+ "widgetConfig",
+ "deviceSettings",
+ "application",
+ "network",
+ "power",
+ "download",
+ "notifications",
+ "package",
+ "messagePort"
+ ]
};
});
-define('ripple/platform/tizen/2.0/PrivMessage', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/AlarmBase', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
- * Licensed under the Apache License, Version 2.0 (the "License"),
+ * 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
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils');
-
-module.exports = function (m, opt) {
- return {
-// readonly begin
- priv: {id: opt.id,
- serviceId: opt.serviceId,
- conversationId: opt.conversationId,
- folderId: opt.folderId,
- type: opt.type,
- timestamp: new Date(opt.timestamp),
- from: opt.from,
- hasAttachment: opt.hasAttachment,
- messageStatus: opt.messageStatus
- },
-// readonly end
- to: m.to.slice(0),
- cc: m.cc.slice(0),
- bcc: m.bcc.slice(0),
- body: utils.copy(m.body),
- isRead: m.isRead,
- isHighPriority: m.isHighPriority,
- subject: m.subject,
- inResponseTo: m.inResponseTo,
- attachments: utils.copy(m.attachments)
- };
-};
-
-});
-define('ripple/platform/tizen/2.0/ReverseGeocodeOptions', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- SortMode = require('ripple/platform/tizen/2.0/SortMode');
-module.exports = function (_sortMode, _resultType, _maxResults) {
- var _self;
- if (_sortMode !== null && _sortMode !== undefined) {
- if (typeof _sortMode !== "object") {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- try {
- new SortMode(_sortMode.attributeName, _sortMode.order);
- } catch (e) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- }
- if (_resultType !== null && _resultType !== undefined) {
- if (_resultType !== "FORMATTED" && _resultType !== "STRUCTURED") {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- }
- if (_maxResults !== null && _maxResults !== undefined) {
- if (typeof _maxResults !== "number") {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- }
- _self = {
- sortMode : _sortMode,
- resultType : _resultType || "FORMATTED",
- maxResults : _maxResults || 0
- };
+module.exports = function (self) {
+ self = self || this;
- return _self;
+ self.__defineGetter__("id", function () {
+ return null;
+ });
};
-
});
-define('ripple/platform/tizen/2.0/SimpleCoordinates', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/CalendarRecurrenceRule', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
*/
var t = require('ripple/platform/tizen/2.0/typecast'),
- SimpleCoordinates;
+ CalendarRecurrenceRule;
-SimpleCoordinates = function (latitude, longitude) {
- var simpleCoordinates = {};
+CalendarRecurrenceRule = function (frequency, ruleInitDict) {
+ var calendarRecurrenceRule = {}, attr;
- t.SimpleCoordinates(arguments, this);
+ t.CalendarRecurrenceRule(arguments, this);
- this.__defineGetter__("latitude", function () {
- return simpleCoordinates.latitude;
+ calendarRecurrenceRule.frequency = frequency;
+ calendarRecurrenceRule.interval = 1;
+ calendarRecurrenceRule.untilDate = null;
+ calendarRecurrenceRule.occurrenceCount = -1;
+ calendarRecurrenceRule.daysOfTheWeek = [];
+ calendarRecurrenceRule.setPositions = [];
+ calendarRecurrenceRule.exceptions = [];
+
+ if (ruleInitDict) {
+ for (attr in ruleInitDict) {
+ switch (attr) {
+ case "daysOfTheWeek":
+ calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(
+ ruleInitDict.daysOfTheWeek, "[]+");
+ break;
+
+ case "setPositions":
+ calendarRecurrenceRule.setPositions = t.short(
+ ruleInitDict.setPositions, "[]+");
+ break;
+
+ case "exceptions":
+ calendarRecurrenceRule.exceptions = t.TZDate(
+ ruleInitDict.exceptions, "[]+");
+ break;
+
+ default:
+ calendarRecurrenceRule[attr] = ruleInitDict[attr];
+ break;
+ }
+ }
+ }
+
+ this.__defineGetter__("frequency", function () {
+ return calendarRecurrenceRule.frequency;
});
- this.__defineSetter__("latitude", function (val) {
+ this.__defineSetter__("frequency", function (val) {
try {
- simpleCoordinates.latitude = t.double(val);
+ calendarRecurrenceRule.frequency = t.RecurrenceRuleFrequency(val);
} catch (e) {
}
});
- this.__defineGetter__("longitude", function () {
- return simpleCoordinates.longitude;
+ this.__defineGetter__("interval", function () {
+ return calendarRecurrenceRule.interval;
});
- this.__defineSetter__("longitude", function (val) {
+ this.__defineSetter__("interval", function (val) {
try {
- simpleCoordinates.longitude = t.double(val);
+ calendarRecurrenceRule.interval = t.unsigned_short(val);
} catch (e) {
}
});
- simpleCoordinates.latitude = latitude;
- simpleCoordinates.longitude = longitude;
+ this.__defineGetter__("untilDate", function () {
+ return calendarRecurrenceRule.untilDate;
+ });
+ this.__defineSetter__("untilDate", function (val) {
+ try {
+ calendarRecurrenceRule.untilDate = t.TZDate(val, "?");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("occurrenceCount", function () {
+ return calendarRecurrenceRule.occurrenceCount;
+ });
+ this.__defineSetter__("occurrenceCount", function (val) {
+ try {
+ calendarRecurrenceRule.occurrenceCount = t.long(val);
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("daysOfTheWeek", function () {
+ return calendarRecurrenceRule.daysOfTheWeek;
+ });
+ this.__defineSetter__("daysOfTheWeek", function (val) {
+ try {
+ calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(val, "[]");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("setPositions", function () {
+ return calendarRecurrenceRule.setPositions;
+ });
+ this.__defineSetter__("setPositions", function (val) {
+ try {
+ calendarRecurrenceRule.setPositions = t.short(val, "[]");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("exceptions", function () {
+ return calendarRecurrenceRule.exceptions;
+ });
+ this.__defineSetter__("exceptions", function (val) {
+ try {
+ calendarRecurrenceRule.exceptions = t.TZDate(val, "[]");
+ } catch (e) {
+ }
+ });
};
-module.exports = SimpleCoordinates;
+module.exports = CalendarRecurrenceRule;
});
-define('ripple/platform/tizen/2.0/SortMode', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/systemsetting', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- SortMode;
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ _systemSettings = null,
+ DBSYSTEMSETTING_KEY = "tizen2-systemsetting",
+ _security = {
+ "http://tizen.org/privilege/setting": ["setProperty"]
+ },
+ _self;
-SortMode = function (attributeName, order) {
- var sortMode = {};
+function _initialize() {
+ _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
+ if (!_systemSettings) {
+ _systemSettings = {"HOME_SCREEN": "images/home_screen.jpg", "LOCK_SCREEN": "images/lock_screen.jpg", "INCOMING_CALL": "sounds/incoming.wav", "NOTIFICATION_EMAIL": "sounds/notification.wav"};
+ db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
+ event.trigger("SystemSettingChanged");
+ }
+}
- t.SortMode(arguments, this);
+_self = function () {
+ var systemSetting;
- this.__defineGetter__("attributeName", function () {
- return sortMode.attributeName;
- });
- this.__defineSetter__("attributeName", function (val) {
- try {
- sortMode.attributeName = t.DOMString(val);
- } catch (e) {
+ function setProperty(type, value, successCallback, errorCallback) {
+ if (!_security.setProperty) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
- this.__defineGetter__("order", function () {
- return sortMode.order;
- });
- this.__defineSetter__("order", function (val) {
- try {
- sortMode.order = t.SortModeOrder(val);
- } catch (e) {
+ t.SystemSettingManager("setProperty", arguments);
+
+ _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
+ _systemSettings[type] = value;
+ db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
+ event.trigger("SystemSettingChanged");
+ window.setTimeout(function () {
+ successCallback();
+ }, 1);
+ }
+
+ function getProperty(type, successCallback, errorCallback) {
+ t.SystemSettingManager("getProperty", arguments);
+
+ _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
+ window.setTimeout(function () {
+ successCallback(_systemSettings[type]);
+ }, 1);
+ }
+
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
}
- });
+ }
- sortMode.attributeName = attributeName;
- sortMode.order = order || "ASC";
+ systemSetting = {
+ setProperty: setProperty,
+ getProperty: getProperty,
+ handleSubFeatures: handleSubFeatures
+ };
+
+ return systemSetting;
};
-module.exports = SortMode;
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/StatusNotification', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/battery', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
- Notification = require('ripple/platform/tizen/2.0/NotificationBase'),
- NotificationDetailInfo = require('ripple/platform/tizen/2.0/NotificationDetailInfo'),
- StatusNotification;
-
-StatusNotification = function (statusType, title, notificationInitDict) {
- var statusNotification = {}, attr, i, info;
-
- t.StatusNotification(arguments, this);
-
- Notification.call(this, title, notificationInitDict ?
- notificationInitDict.content : null);
-
- statusNotification.statusType = statusType;
- statusNotification.iconPath = null;
- statusNotification.subIconPath = null;
- statusNotification.number = null;
- statusNotification.detailInfo = [];
- statusNotification.ledColor = null;
- statusNotification.ledOnPeriod = 0;
- statusNotification.ledOffPeriod = 0;
- statusNotification.backgroundImagePath = null;
- statusNotification.thumbnails = [];
- statusNotification.soundPath = null;
- statusNotification.vibration = false;
- statusNotification.appControl = null;
- statusNotification.appId = null;
- statusNotification.progressType = "PERCENTAGE";
- statusNotification.progressValue = null;
-
- for (attr in notificationInitDict) {
- switch (attr) {
- case "appControl":
- statusNotification.appControl = new ApplicationControl(
- notificationInitDict.appControl.operation,
- notificationInitDict.appControl.uri || null,
- notificationInitDict.appControl.mime || null,
- notificationInitDict.appControl.category || null,
- notificationInitDict.appControl.data || null);
- break;
-
- case "detailInfo":
- for (i in notificationInitDict.detailInfo) {
- info = notificationInitDict.detailInfo[i];
- info = new NotificationDetailInfo(info.mainText,
- info.subText);
+var event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ _data = {
+ charging: true,
+ chargingTime: 0,
+ level: 1.0,
+ dischargingTime: Infinity,
+ chargingchange: {},
+ chargingtimechange: {},
+ levelchange: {},
+ dischargingtimechange: {}
+ },
+ _self;
- statusNotification.detailInfo.push(info);
+_self = {
+ addEventListener: function (event, callback, capture) {
+ if (typeof callback !== "function" || event === undefined) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ switch (event) {
+ case "chargingchange":
+ case "chargingtimechange":
+ case "levelchange":
+ case "dischargingtimechange":
+ var isExist = false, item;
+ for (item in _data[event]) {
+ if (callback === item) {
+ isExist = true;
+ break;
+ }
+ }
+ if (!isExist) {
+ _data[event].add(callback);
}
break;
default:
- statusNotification[attr] = notificationInitDict[attr];
break;
}
- }
-
- this.__defineGetter__("statusType", function () {
- return statusNotification.statusType;
- });
-
- this.__defineGetter__("iconPath", function () {
- return statusNotification.iconPath;
- });
- this.__defineSetter__("iconPath", function (val) {
- try {
- statusNotification.iconPath = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ },
- this.__defineGetter__("subIconPath", function () {
- return statusNotification.subIconPath;
- });
- this.__defineSetter__("subIconPath", function (val) {
- try {
- statusNotification.subIconPath = t.DOMString(val, "?");
- } catch (e) {
+ removeEventListener: function (event, callback, capture) {
+ if (typeof callback !== "function" || event === undefined) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- });
+ _data[event].unbind(callback);
+ },
- this.__defineGetter__("number", function () {
- return statusNotification.number;
- });
- this.__defineSetter__("number", function (val) {
- try {
- statusNotification.number = t.long(val, "?");
- } catch (e) {
+ dispatchEvent: function (event) {
+ if (event === undefined) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- });
+ return _data[event].exec(event);
+ }
+};
- this.__defineGetter__("detailInfo", function () {
- return statusNotification.detailInfo;
- });
- this.__defineSetter__("detailInfo", function (val) {
- try {
- statusNotification.detailInfo = t.NotificationDetailInfo(val, "[]?");
- } catch (e) {
- }
- });
+_self.__defineGetter__("charging", function () {
+ return _data.charging;
+});
- this.__defineGetter__("ledColor", function () {
- return statusNotification.ledColor;
- });
- this.__defineSetter__("ledColor", function (val) {
- try {
- statusNotification.ledColor = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+_self.__defineGetter__("chargingTime", function () {
+ return _data.chargingTime;
+});
- this.__defineGetter__("ledOnPeriod", function () {
- return statusNotification.ledOnPeriod;
- });
- this.__defineSetter__("ledOnPeriod", function (val) {
- try {
- statusNotification.ledOnPeriod = t.unsigned_long(val);
- } catch (e) {
- }
- });
+_self.__defineGetter__("level", function () {
+ return _data.level;
+});
- this.__defineGetter__("ledOffPeriod", function () {
- return statusNotification.ledOffPeriod;
- });
- this.__defineSetter__("ledOffPeriod", function (val) {
- try {
- statusNotification.ledOffPeriod = t.unsigned_long(val);
- } catch (e) {
- }
- });
+_self.__defineGetter__("dischargingTime", function () {
+ return _data.dischargingTime;
+});
- this.__defineGetter__("backgroundImagePath", function () {
- return statusNotification.backgroundImagePath;
- });
- this.__defineSetter__("backgroundImagePath", function (val) {
- try {
- statusNotification.backgroundImagePath = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+function _initialize() {
+ var callback = [];
- this.__defineGetter__("thumbnails", function () {
- return statusNotification.thumbnails;
- });
- this.__defineSetter__("thumbnails", function (val) {
- try {
- statusNotification.thumbnails = t.DOMString(val, "[]?");
- } catch (e) {
- }
- });
+ function bind(name) {
+ _self.__defineGetter__(name, function () {
+ return callback;
+ });
- this.__defineGetter__("soundPath", function () {
- return statusNotification.soundPath;
- });
- this.__defineSetter__("soundPath", function (val) {
- try {
- statusNotification.soundPath = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ _self.__defineSetter__(name, function (cb) {
+ callback = cb;
+ });
- this.__defineGetter__("vibration", function () {
- return statusNotification.vibration;
- });
- this.__defineSetter__("vibration", function (val) {
- try {
- statusNotification.vibration = t.boolean(val);
- } catch (e) {
- }
- });
+ return {
+ get: function () {
+ return callback;
+ },
- this.__defineGetter__("appControl", function () {
- return statusNotification.appControl;
- });
- this.__defineSetter__("appControl", function (val) {
- try {
- statusNotification.appControl = t.ApplicationControl(val, "?");
- } catch (e) {
- }
- });
+ set: function (value) {
+ callback = value;
+ },
- this.__defineGetter__("appId", function () {
- return statusNotification.appId;
- });
- this.__defineSetter__("appId", function (val) {
- try {
- statusNotification.appId = t.ApplicationId(val, "?");
- } catch (e) {
- }
- });
+ add: function (value) {
+ callback.push(value);
+ },
- this.__defineGetter__("progressType", function () {
- return statusNotification.progressType;
- });
- this.__defineSetter__("progressType", function (val) {
- try {
- statusNotification.progressType = t.NotificationProgressType(val);
- } catch (e) {
- }
- });
+ exec: function (arg) {
+ callback.forEach(function (callback) {
+ return !callback || callback(arg);
+ });
+ },
- this.__defineGetter__("progressValue", function () {
- return statusNotification.progressValue;
- });
- this.__defineSetter__("progressValue", function (val) {
- try {
- val = t.unsigned_long(val, '?');
+ unbind: function (value) {
+ if (value === undefined) {
+ callback = [];
+ } else {
+ utils.forEach(callback, function (callback, index) {
+ if (callback === value) {
+ callback.splice(index, 1);
+ }
+ });
+ }
+ }
+ };
+ }
- if ((statusNotification.progressType === "PERCENTAGE") &&
- (val > 100))
- return;
+ _data.chargingchange = bind("onchargingchange");
+ _data.chargingtimechange = bind("onchargingtimechange");
+ _data.levelchange = bind("onlevelchange");
+ _data.dischargingtimechange = bind("ondischargingtimechange");
- statusNotification.progressValue = val;
- } catch (e) {
+ event.on("BatteryEvent", function (status) {
+ for (var ev in status) {
+ if ((status[ev] !== undefined) && (status[ev] !== _data[ev])) {
+ _data[ev] = status[ev];
+ }
}
+ _data[status.type].exec();
});
-};
+}
-module.exports = StatusNotification;
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/SyncInfo', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/CalendarTask', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var db = require('ripple/db'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- SyncInfo,
- _accounts = {},
- _counter = 0;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ typedef = require('ripple/platform/tizen/2.0/typedef'),
+ CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
+ CalendarTask;
-SyncInfo = function () {
- var voc, syncInfo = {}, index;
+CalendarTask = function () {
+ var voc, calendarTask = {};
- function save() {
- _accounts[index] = {
- id: syncInfo.id,
- password: syncInfo.password
- };
- db.saveObject("save-syncinfo", _accounts);
- }
+ // private
+ function construct(taskInitDict) {
+ CalendarItem.call(this, taskInitDict);
- function construct(url, id, password, mode) {
- syncInfo.url = url;
- syncInfo.id = id;
- syncInfo.password = password;
- syncInfo.mode = mode;
- syncInfo.type = null;
- syncInfo.interval = null;
+ this.status = "NEEDS_ACTION";
- this.__defineGetter__("url", function () {
- return syncInfo.url;
- });
- this.__defineSetter__("url", function (url) {
- try {
- syncInfo.url = t.DOMString(url);
- } catch (e) {
- }
- });
+ calendarTask.convertToString = this.convertToString;
+ calendarTask.dueDate = null;
+ calendarTask.completedDate = null;
+ calendarTask.progress = 0;
- this.__defineGetter__("id", function () {
- return null;
+ this.__defineGetter__("dueDate", function () {
+ return calendarTask.dueDate;
});
- this.__defineSetter__("id", function (id) {
+ this.__defineSetter__("dueDate", function (val) {
try {
- syncInfo.id = t.DOMString(id);
- save();
+ calendarTask.dueDate = t.TZDate(val, "?");
} catch (e) {
}
});
- this.__defineGetter__("password", function () {
- return null;
+ this.__defineGetter__("completedDate", function () {
+ return calendarTask.completedDate;
});
- this.__defineSetter__("password", function (password) {
+ this.__defineSetter__("completedDate", function (val) {
try {
- syncInfo.password = t.DOMString(password);
- save();
+ calendarTask.completedDate = t.TZDate(val, "?");
} catch (e) {
}
});
- this.__defineGetter__("mode", function () {
- return syncInfo.mode;
+ this.__defineGetter__("progress", function () {
+ return calendarTask.progress;
});
- this.__defineSetter__("mode", function (mode) {
+ this.__defineSetter__("progress", function (val) {
try {
- syncInfo.mode = t.SyncMode(mode);
+ calendarTask.progress = t.unsigned_short(val);
} catch (e) {
}
});
- this.__defineGetter__("type", function () {
- return syncInfo.type;
- });
- this.__defineSetter__("type", function (type) {
- if (mode !== "MANUAL") {
- return;
- }
- try {
- syncInfo.type = t.SyncType(type);
- } catch (e) {
- }
- });
+ this.convertToString = convertToString;
+ this.clone = clone(this);
+ }
- this.__defineGetter__("interval", function () {
- return syncInfo.interval;
- });
- this.__defineSetter__("interval", function (interval) {
- if (mode !== "PERIODIC") {
- return;
- }
- try {
- syncInfo.interval = t.SyncInterval(interval);
- } catch (e) {
- }
- });
+ function clone(self) {
+ return function () {
+ return new CalendarTask(self);
+ };
}
- voc = [
- function (url, id, password, mode, type) {
- construct.apply(this, arguments);
+ // public
+ function convertToString(format) {
+ var str;
- if (mode === "MANUAL") {
- syncInfo.type = type;
- }
- },
- function (url, id, password, mode, interval) {
- construct.apply(this, arguments);
+ str = calendarTask.convertToString.call(this, format);
+ str = str.replace(/#TYPE#/g, "VTASK");
- if (mode === "PERIODIC") {
- syncInfo.interval = interval;
+ // TODO: dueDate is not supported
+ // TODO: completedDate is not supported
+ if (this.progress) {
+ str = str.replace(/#PROGRESS#/g, "PERCENT-COMPLETE:" +
+ this.progress + "\r\n");
+ }
+
+ str = str.replace(/#AVAILABILITY#.*\r\n/g, "");
+ str = str.replace(/#[^#]*#/g, "");
+
+ return str;
+ }
+
+ // Constructor
+ function CalendarTask_CalendarTaskInit(taskInitDict) {
+ var attr;
+
+ construct.call(this, taskInitDict);
+
+ if (taskInitDict) {
+ for (attr in taskInitDict) {
+ if (attr in typedef.CalendarTaskInit) {
+ calendarTask[attr] = taskInitDict[attr];
+ }
}
- },
- function (url, id, password, mode) {
- construct.apply(this, arguments);
}
- ];
+ }
- t.SyncInfo(arguments, this, voc);
+ function CalendarTask_DOMString_CalendarTextFormat(stringRepresentation,
+ format) {
+ }
- index = _counter++;
- Object.defineProperty(this, "__syncInfoID__", {
- "configurable": false,
- "enumerable": false,
- "get": (function (_id_) {
- return function () { return _id_; };
- })(index)
+ voc = [CalendarTask_CalendarTaskInit,
+ CalendarTask_DOMString_CalendarTextFormat];
+ t.CalendarTask(arguments, this, voc);
+};
+
+module.exports = CalendarTask;
+
+});
+define('ripple/platform/tizen/2.0/pendingObject', function (require, exports, module) {
+/*
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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 = function (pendingObj) {
+ var cancelFlag = true;
+ this.setCancelFlag = function (flag) {
+ cancelFlag = flag;
+ };
+ this.getCancelFlag = function () {
+ return cancelFlag;
+ };
+ this.userCancel = null;
+ this.pendingID = null;
+};
+
+});
+define('ripple/platform/tizen/2.0/PackageInformation', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 = function (id, name, iconPath, version, totalSize,
+ dataSize, lastModified, author, description, appIds) {
+ var packageInformation = {}, _date = new Date(lastModified);
+
+ packageInformation.__defineGetter__("id", function () {
+ return id;
});
- save();
+ packageInformation.__defineGetter__("name", function () {
+ return name;
+ });
+ packageInformation.__defineGetter__("iconPath", function () {
+ return iconPath;
+ });
+ packageInformation.__defineGetter__("version", function () {
+ return version;
+ });
+ packageInformation.__defineGetter__("totalSize", function () {
+ return totalSize;
+ });
+ packageInformation.__defineGetter__("dataSize", function () {
+ return dataSize;
+ });
+ packageInformation.__defineGetter__("lastModified", function () {
+ return _date;
+ });
+ packageInformation.__defineGetter__("author", function () {
+ return author;
+ });
+ packageInformation.__defineGetter__("description", function () {
+ return description;
+ });
+ packageInformation.__defineGetter__("appIds", function () {
+ return appIds;
+ });
+
+ return packageInformation;
};
-module.exports = SyncInfo;
+});
+define('ripple/platform/tizen/2.0/POIFilter', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 = function (attributeName, value) {
+ var _self;
+
+ _self = {
+ attributeName: attributeName,
+ value: value
+ };
+
+ return _self;
+};
});
-define('ripple/platform/tizen/2.0/SyncProfileInfo', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/GeoPolyBounds', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- SyncProfileInfo;
-
-SyncProfileInfo = function (profileName, syncInfo, serviceInfo) {
- var syncProfileInfo = {};
-
- t.SyncProfileInfo(arguments, this);
-
- syncProfileInfo.profileName = profileName;
- syncProfileInfo.syncInfo = syncInfo;
- syncProfileInfo.serviceInfo = serviceInfo;
-
- this.__defineGetter__("profileId", function () {
- return null;
- });
-
- this.__defineGetter__("profileName", function () {
- return syncProfileInfo.profileName;
- });
- this.__defineSetter__("profileName", function (profileName) {
- try {
- syncProfileInfo.profileName = t.DOMString(profileName);
- } catch (e) {
- }
- });
-
- this.__defineGetter__("syncInfo", function () {
- return syncProfileInfo.syncInfo;
- });
- this.__defineSetter__("syncInfo", function (syncInfo) {
- try {
- t.SyncInfo(syncInfo);
- syncProfileInfo.syncInfo = syncInfo;
- } catch (e) {
- }
- });
+module.exports = function (_points) {
+ var points = _points || [];
- this.__defineGetter__("serviceInfo", function () {
- return syncProfileInfo.serviceInfo;
- });
- this.__defineSetter__("serviceInfo", function (serviceInfo) {
- try {
- t.SyncServiceInfo(serviceInfo, "[]?");
- syncProfileInfo.serviceInfo = serviceInfo;
- } catch (e) {
- }
+ this.__defineGetter__("points", function () {
+ return points;
});
};
-module.exports = SyncProfileInfo;
-
});
-define('ripple/platform/tizen/2.0/SyncServiceInfo', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/POIGeometry', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var db = require('ripple/db'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- SyncServiceInfo,
- _accounts = {},
- _counter = 0;
+var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ GeoRectBounds = require('ripple/platform/tizen/2.0/GeoRectBounds');
-SyncServiceInfo = function (enable, serviceType, serverDatabaseUri, id,
- password) {
- var syncServiceInfo = {}, index;
+module.exports = function (position, viewport, wkt) {
+ var _self, _position = null, _viewport = null, _wkt = "";
- function save() {
- _accounts[index] = {
- id: syncServiceInfo.id,
- password: syncServiceInfo.password
- };
- db.saveObject("save-syncserviceinfo", _accounts);
+ if (position) {
+ _position = new SimpleCoordinates(position.latitude, position.longitude);
}
- t.SyncServiceInfo(arguments, this);
-
- syncServiceInfo.enable = enable;
- syncServiceInfo.serviceType = serviceType;
- syncServiceInfo.serverDatabaseUri = serverDatabaseUri;
- syncServiceInfo.id = id || null;
- syncServiceInfo.password = password || null;
-
- this.__defineGetter__("enable", function () {
- return syncServiceInfo.enable;
- });
- this.__defineSetter__("enable", function (enable) {
- try {
- syncServiceInfo.enable = t.boolean(enable);
- } catch (e) {
- }
- });
-
- this.__defineGetter__("serviceType", function () {
- return syncServiceInfo.serviceType;
- });
- this.__defineSetter__("serviceType", function (serviceType) {
- try {
- syncServiceInfo.serviceType = t.SyncServiceType(serviceType);
- } catch (e) {
- }
- });
-
- this.__defineGetter__("serverDatabaseUri", function () {
- return syncServiceInfo.serverDatabaseUri;
- });
- this.__defineSetter__("serverDatabaseUri", function (serverDatabaseUri) {
- try {
- syncServiceInfo.serverDatabaseUri = t.DOMString(serverDatabaseUri);
- } catch (e) {
- }
- });
+ if (viewport) {
+ _viewport = new GeoRectBounds(viewport.southWest, viewport.northEast);
+ }
- this.__defineGetter__("id", function () {
- return null;
- });
- this.__defineSetter__("id", function (id) {
- try {
- syncServiceInfo.id = t.DOMString(id);
- save();
- } catch (e) {
- }
- });
+ if (wkt) {
+ _wkt = String(wkt);
+ }
- this.__defineGetter__("password", function () {
- return null;
- });
- this.__defineSetter__("password", function (password) {
- try {
- syncServiceInfo.password = t.DOMString(password);
- save();
- } catch (e) {
- }
- });
+ _self = {
+ position : _position,
+ viewport: _viewport,
+ wkt: _wkt
+ };
- index = _counter++;
- Object.defineProperty(this, "__syncServiceInfoID__", {
- "configurable": false,
- "enumerable": false,
- "get": (function (_id_) {
- return function () { return _id_; };
- })(index)
- });
- save();
+ return _self;
};
-module.exports = SyncServiceInfo;
-
});
-define('ripple/platform/tizen/2.0/SyncStatistics', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/BluetoothClass', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var SyncStatistics = function (syncStatus, serviceType, lastSyncTime,
- serverToClientTotal, serverToClientAdded, serverToClientUpdated,
- serverToClientRemoved, clientToServerTotal, clientToServerAdded,
- clientToServerUpdated, clientToServerRemoved) {
- this.__defineGetter__("syncStatus", function () {
- return syncStatus;
- });
+var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BluetoothClass,
+ _security;
- this.__defineGetter__("serviceType", function () {
- return serviceType;
- });
+BluetoothClass = function (prop, metaData) {
+ var bluetoothClass = {};
- this.__defineGetter__("lastSyncTime", function () {
- return lastSyncTime;
- });
+ _security = metaData;
- this.__defineGetter__("serverToClientTotal", function () {
- return serverToClientTotal;
- });
+ bluetoothClass.major = prop.major || 0;
+ bluetoothClass.minor = prop.minor || 0;
+ bluetoothClass.services = prop.services || [];
- this.__defineGetter__("serverToClientAdded", function () {
- return serverToClientAdded;
+ this.__defineGetter__("major", function () {
+ return bluetoothClass.major;
});
- this.__defineGetter__("serverToClientUpdated", function () {
- return serverToClientUpdated;
+ this.__defineGetter__("minor", function () {
+ return bluetoothClass.minor;
});
- this.__defineGetter__("serverToClientRemoved", function () {
- return serverToClientRemoved;
+ this.__defineGetter__("services", function () {
+ return bluetoothClass.services;
});
- this.__defineGetter__("clientToServerTotal", function () {
- return clientToServerTotal;
+ bluetoothClass.services.forEach(function (service, i) {
+ bluetoothClass.services.__defineGetter__(i, function () {
+ return service;
+ });
});
- this.__defineGetter__("clientToServerAdded", function () {
- return clientToServerAdded;
- });
+ this.hasService = function (service) {
+ if (!_security.hasService) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("clientToServerUpdated", function () {
- return clientToServerUpdated;
- });
+ t.BluetoothClass("hasService", arguments);
- this.__defineGetter__("clientToServerRemoved", function () {
- return clientToServerRemoved;
- });
+ return (bluetoothClass.services.join(",").indexOf(service) !== -1);
+ };
};
-module.exports = SyncStatistics;
+module.exports = BluetoothClass;
});
-define('ripple/platform/tizen/2.0/TZDate', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/NDEFRecordURI', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- tz = require('ripple/platform/tizen/2.0/timezone_info'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- _Month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
- _Day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
-
-function TZDate (dt) {
- var d, UTCd, UTC_diff, tzid = "", target_diff, temp_date, localeTime_fmt = 'h:m:s', localeDate_fmt = 'D, d M y',
- time = require('ripple/platform/tizen/2.0/time'),
- hour = arguments[3] || 0, min = arguments[4] || 0,
- sec = arguments[5] || 0, msec = arguments[6] || 0,
-
- _checkTZDate = function (dat) {
- var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
- i, tzd;
- if (typeof dat !== 'object' || dat === undefined || dat === null) {
- return false;
- }
- tzd = new Tzdate();
- for (i in tzd) {
- if (dat.hasOwnProperty(i) === false) {
- return false;
- }
- }
- return true;
- },
- _d2UTCd_sync = function () {
- UTCd = new Date(d.valueOf() - (UTC_diff * 1000 * 60 * 60));
- },
- _UTCd2d_sync = function () {
- d = new Date(UTCd.valueOf() + (UTC_diff * 1000 * 60 * 60));
- },
- _getValue = function (o) {
- var other;
- other = new Date(o.getUTCFullYear(), o.getUTCMonth(), o.getUTCDate(),
- o.getUTCHours(), o.getUTCMinutes(), o.getUTCSeconds(), o.getUTCMilliseconds());
- return other.valueOf();
- },
- _formatDateString = function (fmt) {
- var i, ret = '';
- for (i = 0; i < fmt.length; i++) {
- switch (fmt.charAt(i)) {
- case 'd':
- ret = ret + d.getDate();
- break;
- case 'y':
- ret = ret + d.getFullYear();
- break;
- case 'm':
- ret = ret + (d.getMonth() + 1);
- break;
- case 'M':
- ret = ret + _Month[d.getMonth()];
- break;
- case 'D':
- ret = ret + _Day[d.getDay()];
- break;
- default:
- ret = ret + fmt.charAt(i);
- }
- }
- return ret;
- },
- _formatTimeString = function (fmt) {
- var i, hh, mm, ss, AP, ret = "";
- if (fmt.search(/ap/) === -1) {
- AP = false;
- } else {
- AP = true;
- if (d.getHours() > 11) {
- fmt = fmt.replace("ap", "PM");
- } else {
- fmt = fmt.replace("ap", "AM");
- }
- }
- for (i = 0; i < fmt.length; i++) {
- switch (fmt.charAt(i)) {
- case 'h':
- hh = d.getHours();
- if (AP) {
- hh = (hh > 12) ? hh - 12 : hh;
- }
- ret = ret + hh;
- break;
- case 'm':
- mm = d.getMinutes();
- mm = (mm < 10 ? "0" : "") + mm;
- ret = ret + mm;
- break;
- case 's':
- ss = d.getSeconds();
- ss = (ss < 10 ? "0" : "") + ss;
- ret = ret + ss;
- break;
- default:
- ret = ret + fmt.charAt(i);
- }
- }
- return ret;
- };
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
+ NDEFRecordURI;
- if (arguments[7] !== undefined) {
- tzid = arguments[7];
- }
+NDEFRecordURI = function (uri) {
+ var payload = [], i;
- if (dt === null || dt === undefined) {
- temp_date = new Date();
- if (arguments[1] !== undefined) {
- if (typeof arguments[1] !== 'string') {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (tz.isValidTimezone(arguments[1]) === false) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- tzid = arguments[1];
- } else {
- tzid = time.getLocalTimezone();
- }
- target_diff = tz.getTimezoneDiff(tzid);
- d = new Date(temp_date.valueOf() + (target_diff + temp_date.getTimezoneOffset() / 60) * 1000 * 60 * 60);
- } else {
- if (tizen1_utils.isValidDate(dt)) {
- d = new Date(dt);
- if (arguments[1] !== undefined) {
- tzid = arguments[1];
- } else {
- tzid = time.getLocalTimezone();
- }
- } else {
- if (arguments.length === 1) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- } else {
- d = new Date(arguments[0], arguments[1], arguments[2], hour, min, sec, msec);
- }
- }
- }
+ t.NDEFRecordURI(arguments, this);
- if (tz.isValidTimezone(tzid) === false) {
- tzid = 'UTC';
+ // Store uri in payload
+ payload.push(0);
+ for (i = 0; i < uri.length; i++) {
+ payload.push(uri.charCodeAt(i));
}
- UTC_diff = tz.getTimezoneDiff(tzid);
- _d2UTCd_sync();
-
- this.getDate = function () {
- return d.getDate();
- };
- this.setDate = function (dt) {
- d.setDate(dt);
- _d2UTCd_sync();
- };
- this.getDay = function () {
- return d.getDay();
- };
- this.getFullYear = function () {
- return d.getFullYear();
- };
- this.setFullYear = function (yr) {
- d.setFullYear(yr);
- _d2UTCd_sync();
- };
- this.getHours = function () {
- return d.getHours();
- };
- this.setHours = function (hr) {
- d.setHours(hr);
- _d2UTCd_sync();
- };
- this.getMilliseconds = function () {
- return d.getMilliseconds();
- };
- this.setMilliseconds = function (msec) {
- d.setMilliseconds(msec);
- _d2UTCd_sync();
- };
- this.getMinutes = function () {
- return d.getMinutes();
- };
- this.setMinutes = function (min) {
- d.setMinutes(min);
- _d2UTCd_sync();
- };
- this.getMonth = function () {
- return d.getMonth();
- };
- this.setMonth = function (m) {
- d.setMonth(m);
- _d2UTCd_sync();
- };
- this.getSeconds = function () {
- return d.getSeconds();
- };
- this.setSeconds = function (s) {
- d.setSeconds(s);
- _d2UTCd_sync();
- };
- this.getUTCDate = function () {
- return UTCd.getDate();
- };
- this.setUTCDate = function (dt) {
- UTCd.setDate(dt);
- _UTCd2d_sync();
- };
- this.getUTCDay = function () {
- return UTCd.getDay();
- };
- this.getUTCFullYear = function () {
- return UTCd.getFullYear();
- };
- this.setUTCFullYear = function (yr) {
- UTCd.setFullYear(yr);
- _UTCd2d_sync();
- };
- this.getUTCHours = function () {
- return UTCd.getHours();
- };
- this.setUTCHours = function (hr) {
- UTCd.setHours(hr);
- _UTCd2d_sync();
- };
- this.getUTCMilliseconds = function () {
- return UTCd.getMilliseconds();
- };
- this.setUTCMilliseconds = function (msec) {
- UTCd.setMilliseconds(msec);
- _UTCd2d_sync();
- };
- this.getUTCMinutes = function () {
- return UTCd.getMinutes();
- };
- this.setUTCMinutes = function (min) {
- UTCd.setMinutes(min);
- _UTCd2d_sync();
- };
- this.getUTCMonth = function () {
- return UTCd.getMonth();
- };
- this.setUTCMonth = function (m) {
- UTCd.setMonth(m);
- _UTCd2d_sync();
- };
- this.getUTCSeconds = function () {
- return UTCd.getSeconds();
- };
- this.setUTCSeconds = function (s) {
- UTCd.setSeconds(s);
- _UTCd2d_sync();
- };
- this.getTimezone = function () {
- return tzid;
- };
- this.toTimezone = function (new_tzid) {
- var diff,
- Tzdate = require('ripple/platform/tizen/2.0/TZDate');
- if (tz.isValidTimezone(String(new_tzid)) === true) {
- diff = tz.getTimezoneDiff(new_tzid) - UTC_diff;
- return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), new_tzid);
- } else {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- };
- this.toLocalTimezone = function () {
- var diff,
- localTzid,
- Tzdate = require('ripple/platform/tizen/2.0/TZDate');
- localTzid = time.getLocalTimezone();
-
- diff = tz.getTimezoneDiff(localTzid) - UTC_diff;
- return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), localTzid);
- };
- this.toUTC = function () {
- var Tzdate = require('ripple/platform/tizen/2.0/TZDate');
- return new Tzdate(UTCd, "UTC");
- };
- this.difference = function (other) {
- var diff,
- TDur = require('ripple/platform/tizen/2.0/TimeDuration');
- if (_checkTZDate(other) === false) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- diff = (UTCd.valueOf() - _getValue(other));
- if (diff % 86400000 === 0) {
- return new TDur(diff/86400000, 'DAYS');
- } else {
- return new TDur(diff);
- }
- };
- this.equalsTo = function (other) {
- if (_checkTZDate(other) === false) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- return (UTCd.valueOf() === _getValue(other));
- };
- this.earlierThan = function (other) {
- if (_checkTZDate(other) === false) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- return (UTCd.valueOf() < _getValue(other));
- };
- this.laterThan = function (other) {
- if (_checkTZDate(other) === false) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- return (UTCd.valueOf() > _getValue(other));
- };
- this.addDuration = function (dur) {
- var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
- Tunit = {"MSECS": 1,
- "SECS": 1000,
- "MINS": 60 * 1000,
- "HOURS": 60 * 60 * 1000,
- "DAYS": 24 * 60 * 60 * 1000
- };
- if (typeof dur !== 'object' || dur === undefined || dur === null) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (dur.length === undefined || dur.length === null ||
- dur.unit === undefined || dur.unit === null) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if ((typeof dur.length) !== 'number') {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (Tunit[dur.unit] === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- return new Tzdate(new Date(d.valueOf() + (parseInt(dur.length, 10) * Tunit[dur.unit])), tzid);
- };
- this.toLocaleDateString = function () {
- if (d.toString() === "Invalid Date") {
- return d.toString();
- } else {
- return _formatDateString(localeDate_fmt);
- }
- };
- this.toLocaleTimeString = function () {
- if (d.toString() === "Invalid Date") {
- return d.toString();
- } else {
- return _formatTimeString(localeTime_fmt);
- }
- };
- this.toLocaleString = function () {
- if (d.toString() === "Invalid Date") {
- return d.toString();
- } else {
- return (this.toLocaleDateString() + " " + this.toLocaleTimeString());
- }
- };
- this.toDateString = function () {
- var ret = "", fmt = time.getDateFormat();
- if (d.toString() === "Invalid Date") {
- return d.toString();
- }
- ret = _formatDateString(fmt);
- return ret;
- };
- this.toTimeString = function () {
- var ret, fmt = time.getTimeFormat();
- if (d.toString() === "Invalid Date") {
- return d.toString();
- }
+ NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
+ ["U".charCodeAt(0)], payload, []);
- ret = _formatTimeString(fmt);
- if (tz.getTimezoneDesc(tzid) !== null) {
- return ret + " " + tz.getTimezoneDesc(tzid);
- } else {
- return ret + " " + tz.getTimezoneAbbr(tzid);
- }
- return ret;
- };
- this.toString = function () {
- if (d.toString() === "Invalid Date") {
- return d.toString();
- } else {
- return (this.toDateString() + " " + this.toTimeString());
- }
- };
- this.getTimezoneAbbreviation = function () {
- return tz.getTimezoneAbbr(tzid);
- };
- this.secondsFromUTC = function () {
- return (-1 * UTC_diff * 60 * 60);
- };
- this.isDST = function () {
- throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
- };
- this.getPreviousDSTTransition = function () {
- throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
- };
- this.getNextDSTTransition = function () {
- throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
- };
- return this;
-}
+ this.__defineGetter__("uri", function () {
+ return uri;
+ });
+};
-module.exports = TZDate;
+module.exports = NDEFRecordURI;
});
-define('ripple/platform/tizen/2.0/TimeDuration', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/StatusNotification', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
var t = require('ripple/platform/tizen/2.0/typecast'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- TimeDuration;
+ ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
+ Notification = require('ripple/platform/tizen/2.0/NotificationBase'),
+ NotificationDetailInfo = require('ripple/platform/tizen/2.0/NotificationDetailInfo'),
+ StatusNotification;
-TimeDuration = function (_length, _unit) {
- var timeDuration = {},
- TimeDurationUnit = {"MSECS": 1,
- "SECS": 1000,
- "MINS": 60 * 1000,
- "HOURS": 60 * 60 * 1000,
- "DAYS": 24 * 60 * 60 * 1000
- },
- _simplifyDuration = function (ms) {
- var TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
- uni = "MSECS";
- if ((ms % 1000) === 0) {
- ms = ms / 1000;
- uni = "SECS";
- if ((ms % 60) === 0) {
- ms = ms / 60;
- uni = "MINS";
- if ((ms % 60) === 0) {
- ms = ms / 60;
- uni = "HOURS";
- if ((ms % 24) === 0) {
- ms = ms / 24;
- uni = "DAYS";
- }
- }
- }
- }
- return (new TDur(ms, uni));
- },
- _toMSECS = function (unit) {
- if (TimeDurationUnit[unit] === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- } else {
- return TimeDurationUnit[unit];
+StatusNotification = function (statusType, title, notificationInitDict) {
+ var statusNotification = {}, attr, i, info;
+
+ t.StatusNotification(arguments, this);
+
+ Notification.call(this, title, notificationInitDict ?
+ notificationInitDict.content : null);
+
+ statusNotification.statusType = statusType;
+ statusNotification.iconPath = null;
+ statusNotification.subIconPath = null;
+ statusNotification.number = null;
+ statusNotification.detailInfo = [];
+ statusNotification.ledColor = null;
+ statusNotification.ledOnPeriod = 0;
+ statusNotification.ledOffPeriod = 0;
+ statusNotification.backgroundImagePath = null;
+ statusNotification.thumbnails = [];
+ statusNotification.soundPath = null;
+ statusNotification.vibration = false;
+ statusNotification.appControl = null;
+ statusNotification.appId = null;
+ statusNotification.progressType = "PERCENTAGE";
+ statusNotification.progressValue = null;
+
+ for (attr in notificationInitDict) {
+ switch (attr) {
+ case "appControl":
+ statusNotification.appControl = new ApplicationControl(
+ notificationInitDict.appControl.operation,
+ notificationInitDict.appControl.uri || null,
+ notificationInitDict.appControl.mime || null,
+ notificationInitDict.appControl.category || null,
+ notificationInitDict.appControl.data || null);
+ break;
+
+ case "detailInfo":
+ for (i in notificationInitDict.detailInfo) {
+ info = notificationInitDict.detailInfo[i];
+ info = new NotificationDetailInfo(info.mainText,
+ info.subText);
+
+ statusNotification.detailInfo.push(info);
}
- };
+ break;
- t.TimeDuration(arguments, this);
+ default:
+ statusNotification[attr] = notificationInitDict[attr];
+ break;
+ }
+ }
- this.__defineGetter__("length", function () {
- return timeDuration.length;
+ this.__defineGetter__("statusType", function () {
+ return statusNotification.statusType;
});
- this.__defineSetter__("length", function (val) {
+
+ this.__defineGetter__("iconPath", function () {
+ return statusNotification.iconPath;
+ });
+ this.__defineSetter__("iconPath", function (val) {
try {
- timeDuration.length = t.double(val);
+ statusNotification.iconPath = t.DOMString(val, "?");
} catch (e) {
}
});
- this.__defineGetter__("unit", function () {
- return timeDuration.unit;
+ this.__defineGetter__("subIconPath", function () {
+ return statusNotification.subIconPath;
});
- this.__defineSetter__("unit", function (val) {
+ this.__defineSetter__("subIconPath", function (val) {
try {
- timeDuration.unit = t.TimeDurationUnit(val);
+ statusNotification.subIconPath = t.DOMString(val, "?");
} catch (e) {
}
});
- timeDuration.length = _length;
- timeDuration.unit = _unit || "MSECS";
-
- this.difference = function (o) {
-
- t.TimeDuration("difference", arguments);
-
- var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
- otherMS = o.length * _toMSECS(o.unit);
- return _simplifyDuration(thisMS - otherMS);
- };
- this.equalsTo = function (o) {
-
- t.TimeDuration("equalsTo", arguments);
-
- var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
- otherMS = o.length * _toMSECS(o.unit);
- return (thisMS === otherMS);
- };
- this.lessThan = function (o) {
-
- t.TimeDuration("lessThan", arguments);
-
- var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
- otherMS = o.length * _toMSECS(o.unit);
- return (thisMS < otherMS);
- };
- this.greaterThan = function (o) {
+ this.__defineGetter__("number", function () {
+ return statusNotification.number;
+ });
+ this.__defineSetter__("number", function (val) {
+ try {
+ statusNotification.number = t.long(val, "?");
+ } catch (e) {
+ }
+ });
- t.TimeDuration("greaterThan", arguments);
+ this.__defineGetter__("detailInfo", function () {
+ return statusNotification.detailInfo;
+ });
+ this.__defineSetter__("detailInfo", function (val) {
+ try {
+ statusNotification.detailInfo = t.NotificationDetailInfo(val, "[]?");
+ } catch (e) {
+ }
+ });
- var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
- otherMS = o.length * _toMSECS(o.unit);
- return (thisMS > otherMS);
- };
-};
+ this.__defineGetter__("ledColor", function () {
+ return statusNotification.ledColor;
+ });
+ this.__defineSetter__("ledColor", function (val) {
+ try {
+ statusNotification.ledColor = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-module.exports = TimeDuration;
+ this.__defineGetter__("ledOnPeriod", function () {
+ return statusNotification.ledOnPeriod;
+ });
+ this.__defineSetter__("ledOnPeriod", function (val) {
+ try {
+ statusNotification.ledOnPeriod = t.unsigned_long(val);
+ } catch (e) {
+ }
+ });
-});
-define('ripple/platform/tizen/2.0/WebAPIError', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ this.__defineGetter__("ledOffPeriod", function () {
+ return statusNotification.ledOffPeriod;
+ });
+ this.__defineSetter__("ledOffPeriod", function (val) {
+ try {
+ statusNotification.ledOffPeriod = t.unsigned_long(val);
+ } catch (e) {
+ }
+ });
-var errorcode = require('ripple/platform/tizen/2.0/errorcode');
+ this.__defineGetter__("backgroundImagePath", function () {
+ return statusNotification.backgroundImagePath;
+ });
+ this.__defineSetter__("backgroundImagePath", function (val) {
+ try {
+ statusNotification.backgroundImagePath = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-var msg = {
- 0: "Generic Error",
- 1: "Index or size is negative, or greater than the allowed value.",
- 2: "Specified range of text does not fit into a DOMString.",
- 3: "Node is inserted somewhere it doesn't belong.",
- 4: "Node is used in a different document than the one that created it (that doesn't support it).",
- 5: "An invalid or illegal character is specified.",
- 6: "Data is specified for a Node which does not support data.",
- 7: "An attempt is made to modify an object where modifications are not allowed.",
- 8: "An attempt is made to reference a Node in a context where it does not exist.",
- 9: "The implementation does not support the requested type of object or operation.",
- 10: "An attempt is made to add an attribute that is already in use elsewhere.",
- 11: "An attempt is made to use an object that is not, or is no longer, usable.",
- 12: "An invalid or illegal string is specified.",
- 13: "An attempt is made to modify the type of the underlying object.",
- 14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
- 15: "A parameter or an operation is not supported by the underlying object.",
- 16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
- 17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
- 18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
- 19: "A network error occurs in synchronous requests.",
- 20: "The abort error occurs in asynchronous requests by user prompt.",
- 21: "The operation could not be completed because the URL does not match.",
- 22: "The quota has been exceeded.",
- 23: "The operation timed out.",
- 24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
- 25: "The object can not be cloned.",
- 99: "The content of an object does not include valid values.",
- 100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
- 111: "Requested service is not available."
-},
- errType = {
- 0: "UnknownError",
- 1: "IndexSizeError",
- 2: "DOMStringSizeError",
- 3: "HierarchyRequestError",
- 4: "WrongDocumentError",
- 5: "InvalidCharacterError",
- 6: "NoDataAllowedError",
- 7: "NoModificationAllowedError",
- 8: "NotFoundError",
- 9: "NotSupportedError",
- 10: "InuseAttributeError",
- 11: "InvalidStateError",
- 12: "SyntaxError",
- 13: "InvalidModificationError",
- 14: "NamespaceError",
- 15: "InvalidAccessError",
- 16: "ValidationError",
- 17: "TypeMismatchError",
- 18: "SecurityError",
- 19: "NetworkError",
- 20: "AbortError",
- 21: "URLMismatchError",
- 22: "QuotaExceededError",
- 23: "TimeoutError",
- 24: "InvalidNodeTypeError",
- 25: "DataCloneError",
- 99: "InvalidValuesError",
- 100: "IOError",
- 111: "ServiceNotAvailableError"
-};
+ this.__defineGetter__("thumbnails", function () {
+ return statusNotification.thumbnails;
+ });
+ this.__defineSetter__("thumbnails", function (val) {
+ try {
+ statusNotification.thumbnails = t.DOMString(val, "[]?");
+ } catch (e) {
+ }
+ });
-/*
- support 3 types of error:
- - WebAPIError()
- code = errorcode.UNKNOWN_ERR
- message = errorcode.message[UNKNOWN_ERR]
- - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
- code = 17
- message = errorcode.message[17]
- - WebAPIError(my_own_error_code, "This is my error message.")
- code = my_own_error_code(number)
- message = "This is my error message."
-*/
+ this.__defineGetter__("soundPath", function () {
+ return statusNotification.soundPath;
+ });
+ this.__defineSetter__("soundPath", function (val) {
+ try {
+ statusNotification.soundPath = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-module.exports = function (code, message, name) {
- var _code, _message, _name;
+ this.__defineGetter__("vibration", function () {
+ return statusNotification.vibration;
+ });
+ this.__defineSetter__("vibration", function (val) {
+ try {
+ statusNotification.vibration = t.boolean(val);
+ } catch (e) {
+ }
+ });
- if (typeof code !== 'number') {
- _code = errorcode.UNKNOWN_ERR;
- _message = msg[_code];
- _name = errType[_code];
- } else {
- _code = code;
- if (typeof message === 'string') {
- _message = message;
- } else {
- _message = msg[_code];
+ this.__defineGetter__("appControl", function () {
+ return statusNotification.appControl;
+ });
+ this.__defineSetter__("appControl", function (val) {
+ try {
+ statusNotification.appControl = t.ApplicationControl(val, "?");
+ } catch (e) {
}
- if (typeof name === 'string') {
- _name = name;
- } else {
- _name = errType[_code];
+ });
+
+ this.__defineGetter__("appId", function () {
+ return statusNotification.appId;
+ });
+ this.__defineSetter__("appId", function (val) {
+ try {
+ statusNotification.appId = t.ApplicationId(val, "?");
+ } catch (e) {
}
- }
+ });
- this.__defineGetter__("code", function () {
- return _code;
+ this.__defineGetter__("progressType", function () {
+ return statusNotification.progressType;
});
- this.__defineGetter__("message", function () {
- return _message;
+ this.__defineSetter__("progressType", function (val) {
+ try {
+ statusNotification.progressType = t.NotificationProgressType(val);
+ } catch (e) {
+ }
});
- this.__defineGetter__("name", function () {
- return _name;
+
+ this.__defineGetter__("progressValue", function () {
+ return statusNotification.progressValue;
+ });
+ this.__defineSetter__("progressValue", function (val) {
+ try {
+ val = t.unsigned_long(val, '?');
+
+ if ((statusNotification.progressType === "PERCENTAGE") &&
+ (val > 100))
+ return;
+
+ statusNotification.progressValue = val;
+ } catch (e) {
+ }
});
};
+module.exports = StatusNotification;
+
});
-define('ripple/platform/tizen/2.0/WebAPIException', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/WebAPIError', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
*/
module.exports = function (code, message, name) {
- var g, c, _code, _message, _name;
-
- for (c in errorcode) {
- g = errorcode.__lookupGetter__(c);
- if (g) {
- this.__defineGetter__(c, g);
- }
- }
+ var _code, _message, _name;
if (typeof code !== 'number') {
_code = errorcode.UNKNOWN_ERR;
};
});
-define('ripple/platform/tizen/2.0/account', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 db = require('ripple/db'),
- utils = require('ripple/utils'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- _data = {
- DB_ACCOUNT_KEY : "tizen1-db-accounts",
- accounts : {}
- },
- _self;
-
-function _checkAccount(account) {
- if (typeof account !== "object" ||
- typeof account.id !== "string" ||
- typeof account.appid !== "string" ||
- typeof account.userName !== "string" ||
- typeof account.displayName !== "string" ||
- typeof account.service !== "object") {
- return false;
- }
-
- return true;
-}
-
-function _checkCallback(successCallback, errorCallback) {
- tizen1_utils.validateArgumentType(successCallback, "function",
- new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- if (errorCallback) {
- tizen1_utils.validateArgumentType(errorCallback, "function",
- new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
-}
-
-_self = {
- getAccounts : function () {
- var results = [];
- utils.forEach(_data.accounts, function (account) {
- results.push(utils.copy(account));
- });
-
- return results;
- },
-
- getAccountById : function (id) {
- var acccount = null;
-
- if (typeof id !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- if (_data.accounts[id]) {
- account = utils.copy(_data.accounts[id]);
- }
-
- return account;
- },
-
- getAccountByUserName : function (userName) {
- var result = null;
-
- if (typeof userName !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- utils.forEach(_data.accounts, function (account) {
- if (userName === account.userName) {
- result = utils.copy(account);
- }
- });
-
- return result;
- },
-
- getAccountByappId : function (appId) {
- var result = null;
-
- if (typeof appId !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- utils.forEach(_data.accounts, function (account) {
- if (appId === account.appId) {
- result = utils.copy(account);
- }
- });
-
- return result;
- },
-
- getAccountByServiceId : function (serviceId) {
- var result = null;
-
- if (typeof serviceId !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- utils.forEach(_data.accounts, function (account) {
- if (serviceId === account.service.id) {
- result = utils.copy(account);
- }
- });
-
- return result;
- },
-
- getAccountByTag : function (tag) {
- var results = [], i;
-
- if (typeof tag !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- utils.forEach(_data.accounts, function (account) {
- for (i in account.service.tag) {
- if (tag === account.service.tag[i]) {
- results.push(utils.copy(account));
- break;
- }
- }
- });
-
- return results;
- },
-
- add : function (account, successCallback, errorCallback) {
- if (!_checkAccount(account)) {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- _checkCallback(successCallback, errorCallback);
-
- if (!_data.accounts[account.id]) {
- _data.accounts[account.id] = utils.copy(account);
- }
-
- successCallback();
- },
-
- update : function (account, successCallback, errorCallback) {
- if (!_checkAccount(account)) {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- _checkCallback(successCallback, errorCallback);
-
- if (!_data.accounts[account.id]) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- return;
- }
-
- _data.accounts[account.id] = utils.copy(account);
- successCallback();
- },
-
- remove : function (id, successCallback, errorCallback) {
- if (typeof id !== "string") {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
-
- _checkCallback(successCallback, errorCallback);
-
- if (!_data.accounts[id]) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- return;
- }
-
- delete _data.accounts[id];
- successCallback();
- },
-
- getAccountApplications : function () {
- var results = [];
- /* FIXME: wait for API update */
- return results;
- }
-};
-
-function _initialize() {
- _data.accounts = db.retrieveObject(_data.DB_ACCOUNT_KEY) || {};
-}
-
-_initialize();
-
-module.exports = _self;
-
-});
-define('ripple/platform/tizen/2.0/alarm', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/notification', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
var db = require('ripple/db'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- event = require('ripple/event'),
utils = require('ripple/utils'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- AlarmRelative = require('ripple/platform/tizen/2.0/AlarmRelative'),
- AlarmAbsolute = require('ripple/platform/tizen/2.0/AlarmAbsolute'),
- AlarmStore,
- _DB_ALARMS_KEY = "tizen1.0-db-alarms",
- PERIOD_MINUTE = 60,
- PERIOD_HOUR = 60 * PERIOD_MINUTE,
- PERIOD_DAY = 24 * PERIOD_HOUR,
- PERIOD_WEEK = 7 * PERIOD_DAY,
- _alarms = {}, _alarmStack = [],
- _security = {
- "http://tizen.org/privilege/alarm": ["add", "remove", "removeAll"]
- },
- _isInitialized = false, _self;
-
-function _initialize() {
- _alarms = db.retrieveObject(_DB_ALARMS_KEY);
- utils.forEach(_alarms, function (alarmStore) {
- alarmStore.date = new Date(alarmStore.date);
- _alarmStack.push(alarmStore);
- });
- _isInitialized = true;
-}
-
-function _get() {
- if (!_isInitialized) {
- _initialize();
- }
-}
-
-function _save() {
- db.saveObject(_DB_ALARMS_KEY, _alarmStack);
-}
-
-function _updateDB(alarmStore) {
- _alarmStack.push(alarmStore);
- _save();
-}
-
-function _getCurrentAppId() {
- return db.retrieve("current-url");
-}
-
-function _checkTriggerAlarm(alarm) {
- var remainingTime, nextTriggerDate;
-
- if (alarm.delay !== undefined) { // Alarm is relative
- if (alarm.period !== null)
- return false;
-
- remainingTime = alarm.getRemainingSeconds();
- if (remainingTime === null)
- return true; // This alarm is triggered, remove it
- } else if (alarm.period !== undefined) { // Alarm is absolute,no repeat
- nextTriggerDate = alarm.getNextScheduledDate();
- if (nextTriggerDate === null)
- return true; // Already triggered
- }
-
- return false; // Alarm is repeat, not expired
-}
-
-function _convertToAlarm(alarmStore) {
- var alarm, frequency;
-
- if (alarmStore.delay !== null) { // AlarmRelative
- alarm = new AlarmRelative(alarmStore.delay, alarmStore.period);
- alarm.date = alarmStore.date;
- } else { // AlarmAbsolute
- if (alarmStore.period !== null && alarmStore.period !== PERIOD_WEEK) {
- frequency = alarmStore.period;
- } else if (alarmStore.period === PERIOD_WEEK) {
- frequency = alarmStore.daysOfTheWeek;
- }
- alarm = new AlarmAbsolute(alarmStore.date, frequency);
- }
-
- alarm.__defineGetter__("id", function () {
- return alarmStore.id;
- });
-
- return alarm;
-}
-
-function _eventCheckAlarm(id) {
- var alarm, diff;
-
- _get();
- utils.forEach(_alarmStack, function (alarmStore) {
- if (alarmStore.id !== id)
- return;
-
- alarm = _convertToAlarm(alarmStore);
- if (alarm.delay !== undefined) {
- diff = alarm.getRemainingSeconds();
- if (0 < diff && diff < 2) {
- event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
- }
- } else {
- diff = (new Date()) - alarm.getNextScheduledDate();
- if (-2000 < diff && diff < 2000) {
- event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
- }
- }
- });
-}
-
-
-_self = function () {
- var currentAppId, alarm;
-
- alarm = {
- add: function (alarm, applicationId, appControl) {
- var id, alarmStore;
-
- if (!_security.add) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.AlarmManager("add", arguments);
-
- alarm.__defineGetter__("id", function () {
- return id;
- });
-
- id = Math.uuid(null, 16);
- currentAppId = _getCurrentAppId(); // Update The Current URL.
- alarmStore = new AlarmStore(alarm, applicationId, currentAppId, appControl);
- _updateDB(alarmStore);
- },
-
- remove: function (id) {
- var isFound = false, i;
-
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.AlarmManager("remove", arguments);
-
- for (i in _alarmStack) {
- if (_alarmStack[i].id !== id)
- continue;
-
- _alarmStack.splice(i, 1);
- _save();
- isFound = true;
- }
-
- if (!isFound) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- },
-
- removeAll: function () {
- var availableStack = [], i;
-
- if (!_security.removeAll)
- throw new WebAPIException(errorcode.SECURITY_ERR);
-
- t.AlarmManager("removeAll", arguments);
-
- for (i in _alarmStack) {
- if (_alarmStack[i].currentAppId === currentAppId)
- continue;
-
- availableStack.push(_alarmStack[i]);
- }
- _alarmStack = availableStack;
- _save();
- },
-
- get: function (id) {
- var isFound = false, item, isExpired, alarm;
-
- t.AlarmManager("get", arguments);
-
- for (item in _alarmStack) {
- if (_alarmStack[item].id === id) {
- alarm = _convertToAlarm(_alarmStack[item]);
- isExpired = _checkTriggerAlarm(alarm);
- if (isExpired) {
- _alarmStack.splice(item, 1);
- _save();
- } else {
- isFound = true;
- }
- break;
- }
- }
- if (!isFound) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
-
- return alarm;
- },
-
- getAll: function () {
- var availableStack = [], backAlarms = [], isExpired, alarm, i;
-
- t.AlarmManager("getAll", arguments);
-
- for (i in _alarmStack) {
- alarm = _convertToAlarm(_alarmStack[i]); // alarmStore --> alarm
- isExpired = _checkTriggerAlarm(alarm); // Check if the alarm is expired
- if (isExpired)
- continue;
-
- availableStack.push(_alarmStack[i]);
- if (_alarmStack[i].currentAppId === currentAppId)
- backAlarms.push(alarm);
- }
- _alarmStack = availableStack;
- _save();
- return backAlarms;
- },
-
- handleSubFeatures: function (subFeatures) {
- var i, subFeature;
-
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
- };
-
- currentAppId = _getCurrentAppId();
- _get();
-
- alarm.__defineGetter__("PERIOD_MINUTE", function () {
- return PERIOD_MINUTE;
- });
-
- alarm.__defineGetter__("PERIOD_HOUR", function () {
- return PERIOD_HOUR;
- });
-
- alarm.__defineGetter__("PERIOD_DAY", function () {
- return PERIOD_DAY;
- });
-
- alarm.__defineGetter__("PERIOD_WEEK", function () {
- return PERIOD_WEEK;
- });
-
- return alarm;
-};
-
-AlarmStore = function (alarmObject, applicationId, currentAppId, appControl) {
- var _self;
- _self = {
- id: alarmObject.id,
- delay: alarmObject.delay || null,
- date: alarmObject.date || null,
- period: alarmObject.period || null,
- daysOfTheWeek: alarmObject.daysOfTheWeek || null,
- applicationId: applicationId,
- currentAppId: currentAppId,
- appControl: appControl || null
- };
- return _self;
-};
-
-event.on("CheckAlarm", function (id) {
- _eventCheckAlarm(id);
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/tizen/2.0/application', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 utils = require('ripple/utils'),
event = require('ripple/event'),
- app = require('ripple/app'),
- db = require('ripple/db'),
- t = require('ripple/platform/tizen/2.0/typecast'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
- Application,
- ApplicationInformation,
- ApplicationContext,
- ApplicationCertificate,
- RequestedApplicationControl,
- _DB_APPLICATION_KEY = "tizen1-db-application",
- PSEUDO_PACKAGE_ID = "pseudopack00",
- PSEUDO_APP_ID = "pseudoapp00",
+ StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
+ _notificationStack,
_security = {
- "http://tizen.org/privilege/application.launch": ["launch", "launchAppControl"],
- "http://tizen.org/privilege/appmanager.kill": ["kill"],
- "http://tizen.org/privilege/appmanager.certificate": ["getAppCerts"]
- },
- _data = {
- applications : {},
- applicationContexts : {},
- activeApp : null,
- listeners : {}
- },
- _appDialogTemplate = jQuery("#app-dialog-template").html(),
- _appDialogTemplate_short = jQuery("#app-dialog2-template").html(),
- _appDialogTemplate_exit_hide = jQuery("#app-dialog3-template").html(),
- reasonable_mimetype = {
- "application" : true,
- "text" : true,
- "video" : true,
- "audio" : true,
- "image" : true
+ "http://tizen.org/privilege/notification": ["post", "update", "remove",
+ "removeAll"]
},
_self;
-function _setupCurrentApp() {
- var info, contextId, packageId, appId;
- info = app.getInfo();
- packageId = info.tizenPackageId || PSEUDO_PACKAGE_ID;
- appId = info.tizenAppId || PSEUDO_APP_ID;
- contextId = Math.uuid(null, 16);
- _data.applications[appId] = {
- id: appId,
- name: info.name,
- iconPath: info.icon,
- version: info.version,
- show: true,
- categories: [],
- installDate: new Date(),
- size: 1024,
- packageId: packageId,
- sharedURI: "/usr/local/share/",
- operation: "",
- appControl: {
- uri: "",
- mime: "",
- category: "",
- data: []
- },
- type: "AUTHOR_ROOT",
- value: ""
- };
- event.trigger("install-current-app", [_data.applications[appId]]);
- _data.applicationContexts[contextId] = {id: contextId, appId: appId};
- _data.activeApp = _data.applicationContexts[contextId];
-}
-
-function _translate(apps) {
- // translate string to Date after retrieving from DB,
- // it is a temporary sulusion
- var i;
- for (i in apps) {
- if (typeof apps[i].installDate === 'string') {
- apps[i].installDate = new Date(apps[i].installDate);
- }
- }
- return apps;
-}
-
-function _initialize() {
- _data = {
- applications : {},
- applicationContexts : {},
- activeApp : null,
- listeners : {}
- };
-
- if (!db.retrieveObject(_DB_APPLICATION_KEY))
- return;
-
- _data.applications = _translate(db.retrieveObject(_DB_APPLICATION_KEY).installedAppList);
- _setupCurrentApp();
- $("#app-dialog").dialog({
- resizable: false,
- draggable: false,
- modal: true,
- autoOpen: false,
- position: 'center',
- minWidth: '500',
- minHeight: '262',
- open: function () { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); }
- });
-}
-
_self = function () {
- // private
- function getHandle() {
- var handle;
- do {
- handle = Math.uuid(8, 10);
- } while (handle.toString().indexOf('0') === 0);
-
- return parseInt(handle, 10);
- }
-
- // public
- function getCurrentApplication() {
- var application, innerApp;
-
- t.ApplicationManager("getCurrentApplication", arguments);
-
- /* activeApp update (by WidgetInformationUpdate event) sometime will late after user calling getCurrentApplication()
- for example: load other application by omnibar */
- if (app.getInfo().id !== _data.activeApp.appId) {
- _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
- utils.forEach(_data.applications, function(item) {
- item.installDate = new Date(item.installDate);
- });
- _setupCurrentApp();
- }
- innerApp = _data.applications[_data.activeApp.appId];
- application = new Application(
- new ApplicationInformation(
- innerApp.id,
- innerApp.name,
- innerApp.iconPath,
- innerApp.version,
- innerApp.show,
- innerApp.categories,
- innerApp.installDate,
- innerApp.size,
- innerApp.packageId),
- _data.activeApp.id, innerApp);
- return application;
- }
-
- function kill(contextId, successCallback, errorCallback) {
- if (!_security.kill) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.ApplicationManager("kill", arguments);
-
- window.setTimeout(function () {
- if (!_data.applicationContexts[contextId]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
-
- if (_data.activeApp && (_data.activeApp.id === contextId)) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
-
- delete _data.applicationContexts[contextId];
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
-
- function launch(id, successCallback, errorCallback) {
- if (!_security.launch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.ApplicationManager("launch", arguments);
-
- window.setTimeout(function () {
- var htmlContent;
-
- if (!_data.applications[id]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
-
- htmlContent = _appDialogTemplate_short.replace(/#application-name/, _data.applications[id].name)
- .replace(/#application-id/, id);
- jQuery("#app-dialog-box").html(htmlContent);
- $("#app-dialog").dialog("open");
-
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
-
- function launchAppControl(appControl, id, successCallback, errorCallback, replyCallback) {
- if (!_security.launchAppControl) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.ApplicationManager("launchAppControl", arguments, true);
-
- window.setTimeout(function () {
- var isFound = false, appId, htmlContent;
-
- if (id) {
- if (!_data.applications[id]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- htmlContent = _appDialogTemplate.replace(/#application-name/, _data.applications[appId].name)
- .replace(/#appControl-operation/, _data.applications[appId].operation)
- .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
- .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
- .replace(/#appControl-category/, _data.applications[appId].appControl.category)
- .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
- jQuery("#app-dialog-box").html(htmlContent);
- $("#app-dialog").dialog("open");
-
- _data.activeApp.replyCallback = replyCallback;
-
- if (successCallback) {
- successCallback();
- }
- } else {
- utils.forEach(_data.applications, function (application) {
- if (application.operation === appControl.operation) {
- if (appControl.mime && (typeof appControl.mime === "string")) {
- if (!reasonable_mimetype[appControl.mime.split("/")[0]]) {
- return;
- }
- }
- appId = application.id;
- isFound = true;
- }
- });
-
- if (!isFound) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
-
- htmlContent = _appDialogTemplate.replace(/#application-name/,
- _data.applications[appId].name)
- .replace(/#appControl-operation/, _data.applications[appId].operation)
- .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
- .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
- .replace(/#appControl-category/, _data.applications[appId].appControl.category)
- .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
- jQuery("#app-dialog-box").html(htmlContent);
- $("#app-dialog").dialog("open");
-
- _data.activeApp.replyCallback = replyCallback;
-
- if (successCallback) {
- successCallback();
- }
- }
- }, 1);
- }
-
- function findAppControl(appControl, successCallback, errorCallback) {
- var appControlExternal = appControl;
-
- t.ApplicationManager("findAppControl", arguments, true);
-
- window.setTimeout(function () {
- var informationArray = [];
-
- utils.forEach(_data.applications, function (application) {
- if (application.operation === appControl.operation) {
- informationArray.push(new ApplicationInformation(
- application.id,
- application.name,
- application.iconPath,
- application.version,
- application.show,
- application.categories,
- application.installDate,
- application.size,
- application.packageId));
- }
- });
-
- successCallback(informationArray, appControlExternal);
- }, 1);
- }
-
- function getAppsContext(successCallback, errorCallback) {
- t.ApplicationManager("getAppsContext", arguments);
-
- window.setTimeout(function () {
- var contexts = [];
-
- utils.forEach(_data.applicationContexts, function (context) {
- contexts.push(new ApplicationContext(context.id, context.appId));
- });
-
- successCallback(contexts);
- }, 1);
- }
-
- function getAppContext(contextId) {
- var appContext;
-
- if (contextId === null || contextId === undefined) {
- appContext = new ApplicationContext(_data.activeApp.id, _data.activeApp.appId);
- return (appContext);
- }
-
- t.ApplicationManager("getAppContext", arguments);
-
- if (_data.applicationContexts[contextId]) {
- appContext = new ApplicationContext(contextId, _data.applicationContexts[contextId].appId);
- return (appContext);
- }
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
-
- function getAppsInfo(successCallback, errorCallback) {
- t.ApplicationManager("getAppsInfo", arguments);
-
- window.setTimeout(function () {
- var applications = [];
-
- utils.forEach(_data.applications, function (application) {
- applications.push(new ApplicationInformation(
- application.id,
- application.name,
- application.iconPath,
- application.version,
- application.show,
- application.categories,
- application.installDate,
- application.size,
- application.packageId));
- });
-
- successCallback(applications);
- }, 1);
- }
-
- function getAppInfo(id) {
- var appId, appInfo, theApp;
-
- t.ApplicationManager("getAppInfo", arguments);
-
- if (arguments.length === 0) {
- appId = _data.activeApp.appId;
- theApp = _data.applications[appId];
-
- appInfo = new ApplicationInformation(
- theApp.id,
- theApp.name,
- theApp.iconPath,
- theApp.version,
- theApp.show,
- theApp.categories,
- theApp.installDate,
- theApp.size,
- theApp.packageId);
- return appInfo;
- }
-
- if (!_data.applications[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
-
- theApp = _data.applications[id];
- appInfo = new ApplicationInformation(
- theApp.id,
- theApp.name,
- theApp.iconPath,
- theApp.version,
- theApp.show,
- theApp.categories,
- theApp.installDate,
- theApp.size,
- theApp.packageId);
- return appInfo;
- }
-
- function getAppCerts(id) {
- var certs = [];
+ function post(notification) {
+ var posted = {};
- if (!_security.getAppCerts) {
+ if (!_security.post) {
throw new WebAPIException(errorcode.SECURITY_ERR);
}
- t.ApplicationManager("getAppCerts", arguments);
-
- if (arguments.length === 0) {
- id = _data.activeApp.appId;
- certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
- return certs;
- }
-
- if (!_data.applications[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
- return certs;
- }
-
- function getAppSharedURI(id) {
- var appId;
-
- t.ApplicationManager("getAppSharedURI", arguments);
-
- if (id === null || id === undefined) {
- appId = _data.activeApp.appId;
- return _data.applications[appId].sharedURI;
- }
-
- if (!_data.applications[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
-
- return _data.applications[id].sharedURI;
- }
-
- function addAppInfoEventListener(eventCallback) {
- var handle;
-
- t.ApplicationManager("addAppInfoEventListener", arguments);
-
- handle = getHandle();
- _data.listeners[handle] = eventCallback;
-
- return handle;
- }
+ t.NotificationManager("post", arguments);
- function removeAppInfoEventListener(listenerID) {
- if (!_data.listeners[listenerID])
+ if (notification.id !== undefined) {
return;
-
- delete _data.listeners[listenerID];
- }
-
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
-
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
}
- }
-
- var application = {
- getCurrentApplication : getCurrentApplication,
- kill : kill,
- launch : launch,
- launchAppControl : launchAppControl,
- findAppControl : findAppControl,
- getAppsContext : getAppsContext,
- getAppContext : getAppContext,
- getAppsInfo : getAppsInfo,
- getAppInfo : getAppInfo,
- getAppCerts : getAppCerts,
- getAppSharedURI: getAppSharedURI,
- addAppInfoEventListener : addAppInfoEventListener,
- removeAppInfoEventListener : removeAppInfoEventListener,
- handleSubFeatures : handleSubFeatures
- };
-
- return application;
-};
-
-Application = function (appInfo, contextId, metaData) {
- var application = {}, requestedAppControl;
-
- application.appInfo = appInfo;
- application.contextId = contextId;
+ posted.id = Math.uuid(null, 16);
- requestedAppControl = new RequestedApplicationControl(
- new ApplicationControl(metaData.operation, metaData.appControl.uri,
- metaData.appControl.mime, metaData.appControl.category,
- metaData.appControl.data), application.appInfo.id);
+ notification.__defineGetter__("id", function () {
+ return posted.id;
+ });
- this.__defineGetter__("appInfo", function () {
- return application.appInfo;
- });
+ if (!_notificationStack[notification.id]) {
+ posted.postedTime = new Date();
- this.__defineGetter__("contextId", function () {
- return application.contextId;
- });
+ notification.__defineGetter__("postedTime", function () {
+ return posted.postedTime;
+ });
- this.exit = function () {
- event.trigger("tizen-application-exit", [contextId]);
- };
+ _notificationStack[notification.id] = t.Notification(notification,
+ "+");
+ db.saveObject("posted-notifications", _notificationStack);
+ event.trigger("refreshNotificationUI", [], true);
+ }
+ }
- this.hide = function () {
- event.trigger("tizen-application-hide", [contextId]);
- };
+ function update(notification) {
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this.getRequestedAppControl = function () {
- return requestedAppControl;
- };
-};
+ t.NotificationManager("update", arguments);
-ApplicationInformation = function (id, name, iconPath, version, show,
- categories, installDate, size, packageId) {
- this.__defineGetter__("id", function () {
- return id;
- });
+ if (!_notificationStack[notification.id]) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+ _notificationStack[notification.id] = t.Notification(notification,
+ "+");
+ db.saveObject("posted-notifications", _notificationStack);
+ event.trigger("refreshNotificationUI", [], true);
+ }
- this.__defineGetter__("name", function () {
- return name;
- });
+ function remove(id) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("iconPath", function () {
- return iconPath;
- });
+ t.NotificationManager("remove", arguments);
- this.__defineGetter__("version", function () {
- return version;
- });
+ if (!_notificationStack[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ delete _notificationStack[id];
+ db.saveObject("posted-notifications", _notificationStack);
+ event.trigger('refreshNotificationUI', [], true);
+ }
- this.__defineGetter__("show", function () {
- return show;
- });
+ function removeAll() {
+ if (!_security.removeAll) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("categories", function () {
- return categories;
- });
+ _notificationStack = {};
+ db.saveObject("posted-notifications", _notificationStack);
+ event.trigger('refreshNotificationUI', [], true);
+ }
- this.__defineGetter__("installDate", function () {
- return installDate;
- });
+ function get(id) {
+ var n, notification;
- this.__defineGetter__("size", function () {
- return size;
- });
+ t.NotificationManager("get", arguments);
- this.__defineGetter__("packageId", function () {
- return packageId;
- });
-};
+ if (!_notificationStack[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ n = _notificationStack[id];
+ notification = new StatusNotification(n.statusType, n.title, n);
-ApplicationContext = function (id, appId) {
- this.__defineGetter__("id", function () {
- return id;
- });
+ notification.__defineGetter__("id", function () {
+ return n.id;
+ });
- this.__defineGetter__("appId", function () {
- return appId;
- });
-};
+ notification.__defineGetter__("postedTime", function () {
+ return n.postedTime;
+ });
-RequestedApplicationControl = function (appControl, callerAppId) {
- this.__defineGetter__("appControl", function () {
- return appControl;
- });
+ return notification;
+ }
- this.__defineGetter__("callerAppId", function () {
- return callerAppId;
- });
+ function getAll() {
+ var notifications = [];
- this.replyResult = function (data) {
- t.RequestedApplicationControl("replyResult", arguments);
+ utils.forEach(_notificationStack, function (n) {
+ var notification;
- event.trigger("appServiceReplied", "Result: " + data);
- };
+ notification = new StatusNotification(n.statusType, n.title, n);
- this.replyFailure = function () {
- event.trigger("appServiceReplied", "Failure");
- };
-};
+ notification.__defineGetter__("id", function () {
+ return n.id;
+ });
-ApplicationCertificate = function (type, value) {
- this.__defineGetter__("type", function () {
- return type;
- });
+ notification.__defineGetter__("postedTime", function () {
+ return n.postedTime;
+ });
- this.__defineGetter__("value", function () {
- return value;
- });
-};
+ notifications.push(notification);
+ });
-jQuery("#app-dialog-return-btn").live("click", function () {
- $("#app-dialog").dialog("close");
-});
+ return notifications;
+ }
-jQuery("#app-dialog-reload-btn").live("click", function () {
- $("#app-dialog").dialog("close");
- window.tinyHipposReload = true;
- location.reload();
-});
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
-jQuery("#app-dialog-generate-reply").live("click", function () {
- var type, data, ret = [];
- type = jQuery('input:radio[name="app-dialog-reply-type"]:checked').val();
- data = jQuery("#app-dialog-reply-json").val();
- $("#app-dialog").dialog("close");
- if (_data.activeApp.replyCallback) {
- switch (type) {
- case "replyResult":
- if (_data.activeApp.replyCallback.onsuccess) {
- if (data === "") {
- _data.activeApp.replyCallback.onsuccess();
- } else {
- try {
- ret = JSON.parse(data);
- _data.activeApp.replyCallback.onsuccess(ret);
- } catch (e) {
- console.log("replyResult: JSON parsing error: " + e.message);
- _data.activeApp.replyCallback.onsuccess();
- }
- }
- }
- break;
- case "replyFailure":
- if (_data.activeApp.replyCallback.onfailure) {
- _data.activeApp.replyCallback.onfailure();
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
- break;
}
}
-});
-event.on("ApplicationLoad", function () {
- _initialize();
-});
+ var notification = {
+ post: post,
+ update: update,
+ remove: remove,
+ removeAll: removeAll,
+ get: get,
+ getAll: getAll,
+ handleSubFeatures: handleSubFeatures
+ };
-event.on("tizen-application-exit", function () {
- var htmlContent;
- htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
- .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
- .replace(/#application-operation/g, "exit")
- .replace(/#application-verb/, "launch")
- .replace(/#next-command/g, "Launch")
- .replace(/#application-btn/, "app-dialog-reload-btn");
- jQuery("#app-dialog-box").html(htmlContent);
- $("#app-dialog").dialog("open");
-});
+ return notification;
+};
-event.on("tizen-application-hide", function () {
- var htmlContent;
- htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
- .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
- .replace(/#application-operation/g, "hide")
- .replace(/#application-verb/, "show")
- .replace(/#next-command/g, "Show")
- .replace(/#application-btn/, "app-dialog-return-btn");
- jQuery("#app-dialog-box").html(htmlContent);
- $("#app-dialog").dialog("open");
-});
+function _initilize() {
+ _notificationStack = db.retrieveObject("posted-notifications") || {};
-event.on("programChanged", function (status, id) {
- var callback, data, innerApp;
- _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
- utils.forEach(_data.applications, function(item) {
- item.installDate = new Date(item.installDate);
+ utils.forEach(_notificationStack, function (n) {
+ n.postedTime = new Date(n.postedTime);
});
- _setupCurrentApp();
- switch (status) {
- case "installed":
- case "updated":
- innerApp = _data.applications[id];
- data = new ApplicationInformation(
- innerApp.id,
- innerApp.name,
- innerApp.iconPath,
- innerApp.version,
- innerApp.show,
- innerApp.categories,
- innerApp.installDate,
- innerApp.size,
- innerApp.packageId);
- break;
- case "uninstalled":
- data = id;
- break;
- default:
- return;
- }
- callback = "on" + status;
- utils.forEach(_data.listeners, function (listener) {
- listener[callback](data);
+ event.on("refreshNotificationStack", function () {
+ _notificationStack = db.retrieveObject("posted-notifications");
});
-});
+}
-_initialize();
+_initilize();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/battery', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/AttributeRangeFilter', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var event = require('ripple/event'),
- utils = require('ripple/utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- _data = {
- charging: true,
- chargingTime: 0,
- level: 1.0,
- dischargingTime: Infinity,
- chargingchange: {},
- chargingtimechange: {},
- levelchange: {},
- dischargingtimechange: {}
- },
- _self;
-
-_self = {
- addEventListener: function (event, callback, capture) {
- if (typeof callback !== "function" || event === undefined) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- switch (event) {
- case "chargingchange":
- case "chargingtimechange":
- case "levelchange":
- case "dischargingtimechange":
- var isExist = false, item;
- for (item in _data[event]) {
- if (callback === item) {
- isExist = true;
- break;
- }
- }
- if (!isExist) {
- _data[event].add(callback);
- }
- break;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ AttributeRangeFilter;
- default:
- break;
- }
- },
+AttributeRangeFilter = function (attributeName, initialValue, endValue) {
+ var attributeRangeFilter = {};
- removeEventListener: function (event, callback, capture) {
- if (typeof callback !== "function" || event === undefined) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- _data[event].unbind(callback);
- },
+ t.AttributeRangeFilter(arguments, this);
- dispatchEvent: function (event) {
- if (event === undefined) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ this.__defineGetter__("attributeName", function () {
+ return attributeRangeFilter.attributeName;
+ });
+ this.__defineSetter__("attributeName", function (val) {
+ try {
+ attributeRangeFilter.attributeName = t.DOMString(val);
+ } catch (e) {
}
- return _data[event].exec(event);
- }
-};
+ });
-_self.__defineGetter__("charging", function () {
- return _data.charging;
-});
+ attributeRangeFilter.attributeName = attributeName;
-_self.__defineGetter__("chargingTime", function () {
- return _data.chargingTime;
-});
+ this.initialValue = initialValue || null;
+ this.endValue = endValue || null;
+};
-_self.__defineGetter__("level", function () {
- return _data.level;
-});
+module.exports = AttributeRangeFilter;
-_self.__defineGetter__("dischargingTime", function () {
- return _data.dischargingTime;
});
+define('ripple/platform/tizen/2.0/SyncStatistics', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 _initialize() {
- var callback = [];
+var SyncStatistics = function (syncStatus, serviceType, lastSyncTime,
+ serverToClientTotal, serverToClientAdded, serverToClientUpdated,
+ serverToClientRemoved, clientToServerTotal, clientToServerAdded,
+ clientToServerUpdated, clientToServerRemoved) {
+ this.__defineGetter__("syncStatus", function () {
+ return syncStatus;
+ });
- function bind(name) {
- _self.__defineGetter__(name, function () {
- return callback;
- });
+ this.__defineGetter__("serviceType", function () {
+ return serviceType;
+ });
- _self.__defineSetter__(name, function (cb) {
- callback = cb;
- });
+ this.__defineGetter__("lastSyncTime", function () {
+ return lastSyncTime;
+ });
- return {
- get: function () {
- return callback;
- },
+ this.__defineGetter__("serverToClientTotal", function () {
+ return serverToClientTotal;
+ });
- set: function (value) {
- callback = value;
- },
+ this.__defineGetter__("serverToClientAdded", function () {
+ return serverToClientAdded;
+ });
- add: function (value) {
- callback.push(value);
- },
+ this.__defineGetter__("serverToClientUpdated", function () {
+ return serverToClientUpdated;
+ });
- exec: function (arg) {
- callback.forEach(function (callback) {
- return !callback || callback(arg);
- });
- },
+ this.__defineGetter__("serverToClientRemoved", function () {
+ return serverToClientRemoved;
+ });
- unbind: function (value) {
- if (value === undefined) {
- callback = [];
- } else {
- utils.forEach(callback, function (callback, index) {
- if (callback === value) {
- callback.splice(index, 1);
- }
- });
- }
- }
- };
- }
+ this.__defineGetter__("clientToServerTotal", function () {
+ return clientToServerTotal;
+ });
- _data.chargingchange = bind("onchargingchange");
- _data.chargingtimechange = bind("onchargingtimechange");
- _data.levelchange = bind("onlevelchange");
- _data.dischargingtimechange = bind("ondischargingtimechange");
+ this.__defineGetter__("clientToServerAdded", function () {
+ return clientToServerAdded;
+ });
- event.on("BatteryEvent", function (status) {
- for (var ev in status) {
- if ((status[ev] !== undefined) && (status[ev] !== _data[ev])) {
- _data[ev] = status[ev];
- }
- }
- _data[status.type].exec();
+ this.__defineGetter__("clientToServerUpdated", function () {
+ return clientToServerUpdated;
});
-}
-_initialize();
+ this.__defineGetter__("clientToServerRemoved", function () {
+ return clientToServerRemoved;
+ });
+};
-module.exports = _self;
+module.exports = SyncStatistics;
});
-define('ripple/platform/tizen/2.0/bluetooth', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/typedef', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- db = require('ripple/db'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BluetoothDevice = require('ripple/platform/tizen/2.0/BluetoothDevice'),
- BluetoothClassDeviceMajor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor'),
- BluetoothClassDeviceMinor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor'),
- BluetoothClassDeviceService = require('ripple/platform/tizen/2.0/BluetoothClassDeviceService'),
- BluetoothServiceHandler = require('ripple/platform/tizen/2.0/BluetoothServiceHandler'),
- BluetoothAdapter,
- _data = {
- DB_BLUETOOTH_KEY: "tizen1-db-bluetooth_adapter-name",
- DEFAULT_ADAPTER_NAME: "Tizen BT Adapter",
- DEFAULT_ADAPTER_ADDRESS: "12:34:56:78:90:AB",
- availableDevsChanging: false,
- DEFAULT_VISIBLE_TIME: 180000,
- DISCOVER_TIME: 10000,
- DISCOVER_INTERVAL: 1000,
- bluetoothClassDeviceMajor: {},
- bluetoothClassDeviceMinor: {},
- bluetoothClassDeviceService: {},
- adapter: {},
- historyDevs: {},
- availableDevs: {},
- localServices: {}
- },
- _security = {
- "http://tizen.org/privilege/bluetoothmanager": ["setVisible"],
- "http://tizen.org/privilege/bluetooth.admin": ["setName", "setPowered"],
- "http://tizen.org/privilege/bluetooth.gap": ["getDefaultAdapter",
- "discoverDevices", "stopDiscovery", "getKnownDevices",
- "getDevice", "createBonding", "destroyBonding", "hasService"],
- "http://tizen.org/privilege/bluetooth.spp":
- ["registerRFCOMMServiceByUUID", "connectToServiceByUUID",
- "writeData", "readData", "close", "unregister"]
- },
- _self;
-
-function _initialize() {
- var adapterName, devs;
+var _t, _c, _i;
- _data.bluetoothClassDeviceMajor = new BluetoothClassDeviceMajor();
- _data.bluetoothClassDeviceMinor = new BluetoothClassDeviceMinor();
- _data.bluetoothClassDeviceService = new BluetoothClassDeviceService();
- adapterName = db.retrieveObject(_data.DB_BLUETOOTH_KEY) ||
- _data.DEFAULT_ADAPTER_NAME;
- _data.adapter = new BluetoothAdapter(adapterName,
- _data.DEFAULT_ADAPTER_ADDRESS);
+/*
+ * Primitive type definition
+ */
- // get defalt nearby devices
- devs = db.retrieveObject("bt-simulated-devices");
- utils.forEach(devs, function (item) {
- if (!_data.availableDevs[item.address]) {
- _data.availableDevs[item.address] = new BluetoothDevice({
- name: item.name,
- address: item.address,
- deviceClass: item.deviceClass,
- isBonded: false,
- isTrusted: item.isTrusted,
- isConnected: false,
- services: item.services,
- metaData: _security
- });
- }
- });
-}
+_t = {
+ // Basic
+ Callback: "Callback",
+ DOMString: "",
+ Date: new Date(),
+ Function: function () {},
+ TZDate: "TZDate",
+ any: "any",
+ boolean: false,
+ byte: "byte",
+ double: "double",
+ float: "float",
+ long: "long",
+ octet: "octet",
+ short: "short",
+ long_long: "long long",
+ unsigned_long: "unsigned long",
+ unsigned_long_long: "unsigned long long",
+ unsigned_short: "unsigned short",
-BluetoothAdapter = function (devName, devAddress) {
- var adapter,
- timeoutVar,
- _devName = devName,
- _devAddress = devAddress,
- _devPowered = false,
- _devVisible = false,
- _isDiscovering = false,
- discoverInterval;
+ // Common
+ FilterMatchFlag: ["EXACTLY", "FULLSTRING", "CONTAINS",
+ "STARTSWITH", "ENDSWITH", "EXISTS"],
+ SortModeOrder: ["ASC", "DESC"],
+ CompositeFilterType: ["UNION", "INTERSECTION"],
- // private
- function updateVisibleStatus(status, time) {
- if (!_devPowered)
- return;
+ // Bluetooth
+ BluetoothSocketState: ["CLOSED", "OPEN"],
+ BluetoothProfileType: ["HEALTH", "HEALTH"],
+ BluetoothHealthChannelType: ["RELIABLE", "STREAMING"],
- _devVisible = status;
- event.trigger("bt-adapter-visible-changed", [_devVisible]);
- if (_devVisible) {
- if (time > 0) {
- timeoutVar = window.setTimeout(function () {
- _devVisible = false;
- event.trigger("bt-adapter-visible-changed", [_devVisible]);
- }, time);
- }
- } else {
- window.clearTimeout(timeoutVar);
- }
- }
+ // Calendar
+ CalendarType: ["EVENT", "TASK"],
+ CalendarTextFormat: ["ICALENDAR_20", "VCALENDAR_10"],
+ AlarmMethod: ["SOUND", "DISPLAY"],
+ RecurrenceRuleFrequency: ["DAILY", "WEEKLY", "MONTHLY",
+ "YEARLY"],
+ ByDayValue: ["MO", "TU", "WE", "TH", "FR", "SA",
+ "SU"],
+ EventAvailability: ["BUSY", "FREE"],
+ AttendeeType: ["INDIVIDUAL", "GROUP", "RESOURCE",
+ "ROOM", "UNKNOWN"],
+ AttendeeStatus: ["PENDING", "ACCEPTED", "DECLINED",
+ "TENTATIVE", "DELEGATED", "COMPLETED",
+ "IN_PROCESS"],
+ AttendeeRole: ["REQ_PARTICIPANT", "OPT_PARTICIPANT",
+ "NON_PARTICIPANT", "CHAIR"],
+ CalendarItemPriority: ["HIGH", "MEDIUM", "LOW"],
+ CalendarItemVisibility: ["PUBLIC", "PRIVATE", "CONFIDENTIAL"],
+ CalendarItemStatus: ["TENTATIVE", "CONFIRMED", "CANCELLED",
+ "NEEDS_ACTION", "IN_PROCESS",
+ "COMPLETED"],
- function updatePowerStatus(status) {
- if (_devPowered === status) {
- return;
- }
- if (!status) {
- updateVisibleStatus(false);
- utils.forEach(_data.historyDevs, function (dev) {
- event.trigger("bt-service-state-update", [dev.address, false]);
- dev.__defineGetter__("isBonded", function () {
- return false;
- });
- event.trigger("bt-device-bonded-changed", [dev.address, false]);
- jQuery("#service-transfer-textarea-" + dev.address.replace(/:/g, "")).val("");
- jQuery("#service-receive-textarea-" + dev.address.replace(/:/g, "")).html("");
- });
- }
- _devPowered = status;
- event.trigger("bt-adapter-power-changed", [_devPowered]);
- }
+ // Contact
+ ContactTextFormat: ["VCARD_30", "VCARD_30"], // Enum must has more than one value
- // public
- function setName(name, successCallback, errorCallback) {
- if (!_security.setName) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Content
+ ContentDirectoryStorageType: ["INTERNAL", "EXTERNAL"],
+ ContentType: ["IMAGE", "VIDEO", "AUDIO", "OTHER"],
+ AudioContentLyricsType: ["SYNCHRONIZED", "UNSYNCHRONIZED"],
+ ImageContentOrientation: ["NORMAL", "FLIP_HORIZONTAL",
+ "ROTATE_180", "FLIP_VERTICAL",
+ "TRANSPOSE", "ROTATE_90", "TRANSVERSE",
+ "ROTATE_270"],
- t.BluetoothAdapter("setName", arguments);
+ // Data Control
+ DataType: ["MAP", "SQL"],
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+ // Data Synchronization
+ SyncMode: ["MANUAL", "PERIODIC", "PUSH"],
+ SyncType: ["TWO_WAY", "SLOW",
+ "ONE_WAY_FROM_CLIENT",
+ "REFRESH_FROM_CLIENT",
+ "ONE_WAY_FROM_SERVER",
+ "REFRESH_FROM_SERVER"],
+ SyncInterval: ["5_MINUTES", "15_MINUTES", "1_HOUR",
+ "4_HOURS", "12_HOURS", "1_DAY",
+ "1_WEEK", "1_MONTH"],
+ SyncServiceType: ["CONTACT", "EVENT"],
+ SyncStatus: ["SUCCESS", "FAIL", "STOP", "NONE"],
- _devName = name;
- db.saveObject(_data.DB_BLUETOOTH_KEY, _devName);
- event.trigger("bt-adapter-name-changed", [_devName]);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+ // Download
+ DownloadState: ["QUEUED", "DOWNLOADING", "PAUSED",
+ "CANCELED", "COMPLETED", "FAILED"],
+ DownloadNetworkType: ["CELLULAR", "WIFI", "ALL"],
- function setPowered(state, successCallback, errorCallback) {
- if (!_security.setPowered) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Messaging
+ MessageServiceTag: ["messaging.sms", "messaging.mms",
+ "messaging.email"],
- t.BluetoothAdapter("setPowered", arguments);
+ // Network Bearer Selection
+ NetworkType: ["CELLULAR", "UNKNOWN"],
- window.setTimeout(function () {
- updatePowerStatus(state);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+ // NFC
+ NDEFRecordTextEncoding: ["UTF8", "UTF16"],
+ NFCTagType: ["GENERIC_TARGET", "ISO14443_A",
+ "ISO14443_4A", "ISO14443_3A",
+ "MIFARE_MINI", "MIFARE_1K",
+ "MIFARE_4K", "MIFARE_ULTRA",
+ "MIFARE_DESFIRE", "ISO14443_B",
+ "ISO14443_4B", "ISO14443_BPRIME",
+ "FELICA", "JEWEL", "ISO15693",
+ "UNKNOWN_TARGET"],
- function setVisible(mode, successCallback, errorCallback, timeout) {
- if (!_security.setVisible) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Notification
+ NotificationType: ["STATUS", "STATUS"],
+ StatusNotificationType: ["SIMPLE", "THUMBNAIL", "ONGOING",
+ "PROGRESS"],
+ NotificationProgressType: ["PERCENTAGE", "BYTE"],
- t.BluetoothAdapter("setVisible", arguments);
+ // System Info
+ SystemInfoPropertyId: ["BATTERY", "CPU", "STORAGE", "DISPLAY",
+ "DEVICE_ORIENTATION", "BUILD",
+ "LOCALE", "NETWORK", "WIFI_NETWORK",
+ "CELLULAR_NETWORK", "SIM",
+ "PERIPHERAL"],
+ SystemInfoNetworkType: ["NONE", "2G", "2.5G", "3G", "4G",
+ "WIFI", "ETHERNET", "UNKNOWN"],
+ SystemInfoDeviceOrientationStatus: ["PORTRAIT_PRIMARY",
+ "PORTRAIT_SECONDARY",
+ "LANDSCAPE_PRIMARY",
+ "LANDSCAPE_SECONDARY"],
+ SystemInfoSimState: ["ABSENT", "INITIALIZING", "READY",
+ "PIN_REQUIRED", "PUK_REQUIRED",
+ "NETWORK_LOCKED", "SIM_LOCKED",
+ "UNKNOWN"],
+ SystemInfoProfile: ["MOBILE_FULL", "MOBILE_WEB"],
- window.setTimeout(function () {
- var time;
+ // System Setting
+ SystemSettingType: ["HOME_SCREEN", "LOCK_SCREEN",
+ "INCOMING_CALL", "NOTIFICATION_EMAIL"],
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+ // Time
+ TimeDurationUnit: ["MSECS", "SECS", "MINS", "HOURS",
+ "DAYS"]
+};
- if (typeof timeout === "number") {
- if (timeout < 0) {
- time = _data.DEFAULT_VISIBLE_TIME;
- } else {
- time = timeout * 1000;
- }
- } else {
- time = _data.DEFAULT_VISIBLE_TIME;
- }
- updateVisibleStatus(mode, time);
+/*
+ * Derivative type definition
+ */
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+/*
+ * Object
+ *
+ * attributes
+ * Specify a type for each attribute.
+ *
+ * _optional
+ * Optional attributes table, which consists of two types of attributes,
+ *
+ * nullable
+ * Nullable attributes, marked as '?' in IDL.
+ *
+ * undefined
+ * Array type attributes, that not definitely specified to be
+ * initialized as an empty array, i.e., undefined-initialized array.
+ *
+ * _derived
+ * Subtype list, which consists of derived subtypes. It exists in the
+ * definition of a base type.
+ *
+ * _dictionary
+ * Dictionary type, which indicates that the object is a dictionary type.
+ */
- function discoverDevices(successCallback, errorCallback) {
- if (!_security.discoverDevices) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Union types
+ * An array consists of two or more other types.
+ */
- t.BluetoothAdapter("discoverDevices", arguments);
+/*
+ * Common
+ */
- window.setTimeout(function () {
- var interval;
+_t.AttributeFilter = {
+ attributeName: _t.DOMString,
+ matchFlag: _t.FilterMatchFlag,
+ matchValue: _t.any,
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+ _optional: {
+ // nullable
+ matchValue: true
+ }
+};
- // already discovering
- if (_isDiscovering) {
- return;
- }
+_t.AttributeRangeFilter = {
+ attributeName: _t.DOMString,
+ initialValue: _t.any,
+ endValue: _t.any,
- _isDiscovering = true;
- _data.historyDevs = {};
+ _optional: {
+ // nullable
+ initialValue: true,
+ endValue: true
+ }
+};
- successCallback.onstarted();
+_t.CompositeFilter = {
+ type: _t.CompositeFilterType,
+ filters: ["AbstractFilter"] // Recursive expansion
+};
- _data.availableDevsChanging = false;
- utils.forEach(_data.availableDevs, function (item) {
- _data.historyDevs[item.address] = item;
- successCallback.ondevicefound(item);
- });
+_t.AbstractFilter = {
+ _derived: [_t.AttributeFilter, _t.AttributeRangeFilter, _t.CompositeFilter]
+};
- discoverInterval = window.setTimeout(function () {
- var devs = [];
+_t.SortMode = {
+ attributeName: _t.DOMString,
+ order: _t.SortModeOrder
+};
- window.clearInterval(interval);
- utils.forEach(_data.historyDevs, function (item) {
- devs.push(item);
- });
- successCallback.onfinished(devs);
- _isDiscovering = false;
- }, _data.DISCOVER_TIME);
+_t.SimpleCoordinates = {
+ latitude: _t.double,
+ longitude: _t.double
+};
- interval = window.setInterval(function () {
- var removeList = [], i;
+_t.SuccessCallback = _t.Function;
+_t.ErrorCallback = _t.Function;
- if (!_isDiscovering) {
- window.clearInterval(interval);
- return;
- }
+/*
+ * Time
+ */
- if (_data.availableDevsChanging) {
- _data.availableDevsChanging = false;
- utils.forEach(_data.historyDevs, function (item) {
- if (!_data.availableDevs[item.address]) {
- removeList.push(item.address);
- }
- });
- for (i in removeList) {
- successCallback.ondevicedisappeared(removeList[i]);
- delete _data.historyDevs[removeList[i]];
- }
- utils.forEach(_data.availableDevs, function (item) {
- if (!_data.historyDevs[item.address]) {
- _data.historyDevs[item.address] = item;
- successCallback.ondevicefound(item);
- }
- });
- }
- }, _data.DISCOVER_INTERVAL);
- }, 1);
- }
+_t.TimeDuration = {
+ length: _t.long_long,
+ unit: _t.TimeDurationUnit,
+ difference: _t.Function,
+ equalsTo: _t.Function,
+ lessThan: _t.Function,
+ greaterThan: _t.Function
+};
- function stopDiscovery(successCallback, errorCallback) {
- if (!_security.stopDiscovery) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Alarm
+ */
- t.BluetoothAdapter("stopDiscovery", arguments);
+_t.AlarmId = _t.DOMString;
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+_t.AlarmRelative = {
+ delay: _t.unsigned_long_long,
+ period: _t.unsigned_long_long,
+ getRemainingSeconds: _t.Function,
- if (_isDiscovering) {
- window.clearTimeout(discoverInterval);
- }
- _isDiscovering = false;
- if (successCallback) {
- successCallback();
- }
- }, 1);
+ _optional: {
+ // nullable
+ period: true,
+ getRemainingSeconds: true
}
+};
- function getKnownDevices(successCallback, errorCallback) {
- if (!_security.getKnownDevices) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.BluetoothAdapter("getKnownDevices", arguments);
-
- window.setTimeout(function () {
- var devs = [];
+_t.AlarmAbsolute = {
+ date: _t.Date,
+ period: _t.unsigned_long_long,
+ daysOfTheWeek: [_t.ByDayValue],
+ getNextScheduledDate: _t.Function,
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
- utils.forEach(_data.historyDevs, function (item) {
- devs.push(new BluetoothDevice({
- name: item.name,
- address: item.address,
- deviceClass: item.deviceClass,
- isBonded: false,
- isTrusted: item.isTrusted,
- isConnected: false,
- services: item.services,
- metaData: _security
- }));
- });
- successCallback(devs);
- }, 1);
+ _optional: {
+ // nullable
+ period: true,
+ getNextScheduledDate: true
}
+};
- function getDevice(address, successCallback, errorCallback) {
- if (!_security.getDevice) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.BluetoothAdapter("getDevice", arguments);
-
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+_t.Alarm = {
+ id: _t.AlarmId,
- if (!_data.historyDevs[address]) {
- if (!_data.availableDevs[address]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- _data.historyDevs[address] = _data.availableDevs[address];
- }
+ _optional: {
+ // nullable
+ id: true
+ },
- successCallback(_data.historyDevs[address]);
- }, 1);
- }
+ _derived: [_t.AlarmRelative, _t.AlarmAbsolute]
+};
- function createBonding(address, successCallback, errorCallback) {
- if (!_security.createBonding) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Application
+ */
- t.BluetoothAdapter("createBonding", arguments);
+_t.ApplicationId = _t.DOMString;
+_t.ApplicationContextId = _t.DOMString;
+_t.ApplicationInformationArraySuccessCallback = _t.Function;
+_t.FindAppControlSuccessCallback = _t.Function;
+_t.ApplicationContextArraySuccessCallback = _t.Function;
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+_t.ApplicationControlData = {
+ key: _t.DOMString,
+ value: [_t.DOMString]
+};
- if (!_data.historyDevs[address]) {
- if (!_data.availableDevs[address]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- _data.historyDevs[address] = _data.availableDevs[address];
- }
+_t.ApplicationControl = {
+ operation: _t.DOMString,
+ uri: _t.DOMString,
+ mime: _t.DOMString,
+ category: _t.DOMString,
+ data: [_t.ApplicationControlData],
- _data.historyDevs[address].__defineGetter__("isBonded", function () {
- return true;
- });
- event.trigger("bt-device-bonded-changed", [address, true]);
- successCallback(_data.historyDevs[address]);
- }, 1);
+ _optional: {
+ // nullable
+ uri: true,
+ mime: true,
+ category: true
}
+};
- function destroyBonding(address, successCallback, errorCallback) {
- if (!_security.destroyBonding) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.BluetoothAdapter("destroyBonding", arguments);
+_t.ApplicationControlDataArrayReplyCallback = {
+ onsuccess: _t.Callback,
+ onfailure: _t.Callback
+};
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+_t.ApplicationInformationEventCallback = {
+ oninstalled: _t.Callback,
+ onupdated: _t.Callback,
+ onuninstalled: _t.Callback
+};
- if (!_data.historyDevs[address]) {
- if (!_data.availableDevs[address]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- _data.historyDevs[address] = _data.availableDevs[address];
- }
+/*
+ * Bluetooth
+ */
- event.trigger("bt-service-state-update", [address, false]);
- _data.historyDevs[address].__defineGetter__("isBonded", function () {
- return false;
- });
- event.trigger("bt-device-bonded-changed", [address, false]);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+_t.BluetoothAddress = _t.DOMString;
+_t.BluetoothUUID = _t.DOMString;
+_t.BluetoothDeviceSuccessCallback = _t.Function;
+_t.BluetoothDeviceArraySuccessCallback = _t.Function;
+_t.BluetoothSocketSuccessCallback = _t.Function;
+_t.BluetoothServiceSuccessCallback = _t.Function;
+_t.BluetoothHealthApplicationSuccessCallback = _t.Function;
+_t.BluetoothHealthChannelSuccessCallback = _t.Function;
- function registerRFCOMMServiceByUUID(uuid, name, successCallback,
- errorCallback, securityLevel) {
- if (!_security.registerRFCOMMServiceByUUID) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_t.BluetoothClass = {
+ major: _t.octet,
+ minor: _t.octet,
+ services: [_t.unsigned_short],
+ hasService: _t.Function
+};
- t.BluetoothAdapter("registerRFCOMMServiceByUUID", arguments);
+_t.BluetoothDevice = {
+ name: _t.DOMString,
+ address: _t.BluetoothAddress,
+ deviceClass: _t.BluetoothClass,
+ isBonded: _t.boolean,
+ isTrusted: _t.boolean,
+ isConnected: _t.boolean,
+ uuids: [_t.BluetoothUUID],
+ connectToServiceByUUID: _t.Function
+};
- window.setTimeout(function () {
- if (!_devPowered) {
- if (errorCallback) {
- errorCallback(new WebAPIError(
- errorcode.SERVICE_NOT_AVAILABLE_ERR));
- }
- return;
- }
+_t.BluetoothHealthApplication = {
+ dataType: _t.unsigned_short,
+ name: _t.DOMString,
+ onconnect: _t.BluetoothHealthChannelSuccessCallback,
+ unregister: _t.Function,
- _data.localServices[uuid] = new BluetoothServiceHandler({
- uuid: uuid,
- name: name,
- isConnected: false,
- metaData: _security
- });
- successCallback(_data.localServices[uuid]);
- }, 1);
+ _optional: {
+ onconnect: true
}
+};
- event.on("bt-simulated-devices-changed", function () {
- var devs = db.retrieveObject("bt-simulated-devices");
- utils.forEach(_data.availableDevs, function (item) {
- if (!devs[item.address]) {
- delete _data.availableDevs[item.address];
- }
- });
- utils.forEach(devs, function (item) {
- if (!_data.availableDevs[item.address]) {
- _data.availableDevs[item.address] = new BluetoothDevice({
- name: item.name,
- address: item.address,
- deviceClass: item.deviceClass,
- isBonded: false,
- isTrusted: item.isTrusted,
- isConnected: false,
- services: item.services,
- metaData: _security
- });
- }
- });
- _data.availableDevsChanging = true;
- });
-
- event.on("bt-unregister-service", function (uuid, successCallback, errorCallback) {
- if (!_data.localServices[uuid]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
- delete _data.localServices[uuid];
- if (successCallback) {
- successCallback();
- }
- });
+_t.BluetoothAdapterChangeCallback = {
+ onstatechanged: _t.Callback,
+ onnamechanged: _t.Callback,
+ onvisibilitychanged: _t.Callback
+};
- event.on("bt-power-setting", function (status) {
- updatePowerStatus(status);
- });
+_t.BluetoothDiscoverDevicesSuccessCallback = {
+ onstarted: _t.Callback,
+ ondevicefound: _t.Callback,
+ ondevicedisappeared: _t.Callback,
+ onfinished: _t.Callback
+};
- adapter = {
- setName: setName,
- setPowered: setPowered,
- setVisible: setVisible,
- discoverDevices: discoverDevices,
- stopDiscovery: stopDiscovery,
- getKnownDevices: getKnownDevices,
- getDevice: getDevice,
- createBonding: createBonding,
- destroyBonding: destroyBonding,
- registerRFCOMMServiceByUUID: registerRFCOMMServiceByUUID
- };
+_t.BluetoothHealthChannelChangeCallback = {
+ onmessage: _t.Callback,
+ onclose: _t.Callback
+};
- adapter.__defineGetter__("name", function () {
- return _devName;
- });
+/*
+ * Bookmark
+ */
- adapter.__defineGetter__("address", function () {
- return _devAddress;
- });
+_t.BookmarkFolder = {
+ parent: "BookmarkFolder",
+ title: _t.DOMString,
- adapter.__defineGetter__("powered", function () {
- return _devPowered;
- });
+ _optional: {
+ // nullable
+ parent: true
+ }
+};
- adapter.__defineGetter__("visible", function () {
- return _devVisible;
- });
+_t.BookmarkItem = {
+ parent: _t.BookmarkFolder,
+ title: _t.DOMString,
+ url: _t.DOMString,
- return adapter;
+ _optional: {
+ // nullable
+ parent: true
+ }
};
-_self = function () {
- var bluetooth;
+_t.Bookmark = [_t.BookmarkItem, _t.BookmarkFolder];
- function getDefaultAdapter() {
- if (!_security.getDefaultAdapter) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Contact
+ */
- if (!_data.adapter) {
- throw new WebAPIException(errorcode.UNKNOWN_ERR);
- }
+_t.AddressBookId = _t.DOMString;
+_t.ContactId = _t.DOMString;
+_t.PersonId = _t.DOMString;
+_t.ContactGroupId = _t.DOMString;
- return _data.adapter;
+_t.Person = {
+ id: _t.PersonId,
+ displayName: _t.DOMString,
+ contactCount: _t.long,
+ hasPhoneNumber: _t.boolean,
+ hasEmail: _t.boolean,
+ isFavorite: _t.boolean,
+ photoURI: _t.DOMString,
+ ringtoneURI: _t.DOMString,
+ displayContactId: _t.ContactId,
+
+ _optional: {
+ // nullable
+ photoURI: true,
+ ringtoneURI: true
}
+};
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+_t.ContactRef = {
+ addressBookId: _t.AddressBookId,
+ contactId: _t.ContactId
+};
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+_t.ContactName = {
+ prefix: _t.DOMString,
+ suffix: _t.DOMString,
+ firstName: _t.DOMString,
+ middleName: _t.DOMString,
+ lastName: _t.DOMString,
+ nicknames: [_t.DOMString],
+ phoneticFirstName: _t.DOMString,
+ phoneticLastName: _t.DOMString,
+ displayName: _t.DOMString,
- bluetooth = {
- getDefaultAdapter: getDefaultAdapter,
- handleSubFeatures: handleSubFeatures
- };
+ _optional: {
+ // nullable
+ prefix: true,
+ suffix: true,
+ firstName: true,
+ middleName: true,
+ lastName: true,
+ phoneticFirstName: true,
+ phoneticLastName: true,
+ displayName: true
+ }
+};
- bluetooth.__defineGetter__("deviceMajor", function () {
- return _data.bluetoothClassDeviceMajor;
- });
+_t.ContactOrganization = {
+ name: _t.DOMString,
+ department: _t.DOMString,
+ title: _t.DOMString,
+ role: _t.DOMString,
+ logoURI: _t.DOMString,
- bluetooth.__defineGetter__("deviceMinor", function () {
- return _data.bluetoothClassDeviceMinor;
- });
+ _optional: {
+ // nullable
+ name: true,
+ department: true,
+ title: true,
+ role: true,
+ logoURI: true
+ }
+};
- bluetooth.__defineGetter__("deviceService", function () {
- return _data.bluetoothClassDeviceService;
- });
+_t.ContactWebSite = {
+ url: _t.DOMString,
+ type: _t.DOMString,
- return bluetooth;
+ _optional: {
+ // nullable
+ type: true
+ }
};
-_initialize();
+_t.ContactAnniversary = {
+ date: _t.Date,
+ label: _t.DOMString,
-module.exports = _self;
+ _optional: {
+ // nullable
+ label: true
+ }
+};
-});
-define('ripple/platform/tizen/2.0/bookmark', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+_t.ContactAddress = {
+ country: _t.DOMString,
+ region: _t.DOMString,
+ city: _t.DOMString,
+ streetAddress: _t.DOMString,
+ additionalInformation: _t.DOMString,
+ postalCode: _t.DOMString,
+ isDefault: _t.boolean,
+ types: [_t.DOMString],
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- BookmarkFolder = require('ripple/platform/tizen/2.0/BookmarkFolder'),
- BookmarkItem = require('ripple/platform/tizen/2.0/BookmarkItem'),
- BookmarkExternal,
- BookmarkInternal,
- BookmarkStorage,
- _data = {
- DB_BOOKMARK_KEY: "tizen1-bookmark",
- bookmarks: [],
- dbStorage: []
- },
- _security = {
- "http://tizen.org/privilege/bookmark.read": ["get"],
- "http://tizen.org/privilege/bookmark.write": ["add", "remove"]
- },
- _self;
+ _optional: {
+ // nullable
+ country: true,
+ region: true,
+ city: true,
+ streetAddress: true,
+ additionalInformation: true,
+ postalCode: true,
+ // undefined
+ types: true
+ }
+};
-function _get() {
- _data.dbStorage = db.retrieveObject(_data.DB_BOOKMARK_KEY) || [];
-}
+_t.ContactPhoneNumber = {
+ number: _t.DOMString,
+ isDefault: _t.boolean,
+ types: [_t.DOMString],
-function _save() {
- db.saveObject(_data.DB_BOOKMARK_KEY, _data.dbStorage);
-}
+ _optional: {
+ // undefined
+ types: true
+ }
+};
-function _initialize() {
- _get();
+_t.ContactEmailAddress = {
+ email: _t.DOMString,
+ isDefault: _t.boolean,
+ types: [_t.DOMString],
- utils.forEach(_data.dbStorage, function (bookmark) {
- _data.bookmarks.push(new BookmarkInternal(bookmark, null));
- });
-}
+ _optional: {
+ // undefined
+ types: true
+ }
+};
-function _persist() {
- _data.dbStorage = [];
+_t.Contact = {
+ id: _t.ContactId,
+ personId: _t.PersonId,
+ addressBookId: _t.AddressBookId,
+ lastUpdated: _t.Date,
+ isFavorite: _t.boolean,
+ name: _t.ContactName,
+ addresses: [_t.ContactAddress],
+ photoURI: _t.DOMString,
+ phoneNumbers: [_t.ContactPhoneNumber],
+ emails: [_t.ContactEmailAddress],
+ birthday: _t.Date,
+ anniversaries: [_t.ContactAnniversary],
+ organizations: [_t.ContactOrganization],
+ notes: [_t.DOMString],
+ urls: [_t.ContactWebSite],
+ ringtoneURI: _t.DOMString,
+ groupIds: [_t.ContactGroupId],
+ convertToString: _t.Function,
+ clone: _t.Function,
- utils.forEach(_data.bookmarks, function (bookmark) {
- _data.dbStorage.push(new BookmarkStorage(bookmark));
- });
+ _optional: {
+ // nullable
+ id: true,
+ personId: true,
+ addressBookId: true,
+ lastUpdated: true,
+ name: true,
+ photoURI: true,
+ birthday: true,
+ ringtoneURI: true
+ }
+};
- _save();
-}
+_t.ContactGroup = {
+ id: _t.ContactGroupId,
+ addressBookId: _t.AddressBookId,
+ name: _t.DOMString,
+ ringtoneURI: _t.DOMString,
+ photoURI: _t.DOMString,
+ readOnly: _t.boolean,
-function _isFolder(bookmark) {
- return !bookmark.url;
-}
+ _optional: {
+ // nullable
+ id: true,
+ addressBookId: true,
+ ringtoneURI: true,
+ photoURI: true
+ }
+};
-function _isExternal(bookmark) {
- return !("children" in bookmark);
-}
+_t.PersonArraySuccessCallback = _t.Function;
+_t.ContactArraySuccessCallback = _t.Function;
+_t.AddressBookArraySuccessCallback = _t.Function;
-function _getChildren(bookmark, BookmarkType, parent) {
- var i, children = [];
+_t.AddressBookChangeCallback = {
+ oncontactsadded: _t.Callback,
+ oncontactsupdated: _t.Callback,
+ oncontactsremoved: _t.Callback
+};
- if (!_isExternal(bookmark)) {
- for (i in bookmark.children) {
- children.push(new BookmarkType(bookmark.children[i], parent));
- }
- }
+_t.PersonsChangeCallback = {
+ onpersonsadded: _t.Callback,
+ onpersonsupdated: _t.Callback,
+ onpersonsremoved: _t.Callback
+};
- return children;
-}
+_t.ContactInit = {
+ name: _t.ContactName,
+ addresses: [_t.ContactAddress],
+ photoURI: _t.DOMString,
+ phoneNumbers: [_t.ContactPhoneNumber],
+ emails: [_t.ContactEmailAddress],
+ birthday: _t.Date,
+ anniversaries: [_t.ContactAnniversary],
+ organizations: [_t.ContactOrganization],
+ notes: [_t.DOMString],
+ urls: [_t.ContactWebSite],
+ ringtoneURI: _t.DOMString,
+ groupIds: [_t.ContactGroupId],
-_self = function () {
- var bookmark;
+ _dictionary: null
+};
- // private
- /*
- * map
- * Map the external bookmark to the internal one in the tree
- *
- * bookmarkExternal
- * External bookmark Object
- *
- * callback
- * callback(index, peers). Optional.
- *
- * Root Bookmark Not Found
- * ------------------------------------------
- * index 0 index -1
- * peers null peers null
- *
- * Return null peers[index] undefined
- */
+_t.ContactNameInit = {
+ prefix: _t.DOMString,
+ suffix: _t.DOMString,
+ firstName: _t.DOMString,
+ middleName: _t.DOMString,
+ lastName: _t.DOMString,
+ nicknames: [_t.DOMString],
+ phoneticFirstName: _t.DOMString,
+ phoneticLastName: _t.DOMString,
- function map(bookmarkExternal, callback) {
- var trace = [], it, i, peers = null;
+ _dictionary: null
+};
- if (!bookmarkExternal) {
- if (callback) {
- callback(0, null);
- }
- return null;
- }
+_t.ContactOrganizationInit = {
+ name: _t.DOMString,
+ department: _t.DOMString,
+ title: _t.DOMString,
+ role: _t.DOMString,
+ logoURI: _t.DOMString,
- for (it = bookmarkExternal; it; it = it.parent) {
- trace.push(it);
- }
+ _dictionary: null
+};
- for (it = _data.bookmarks; trace.length !== 0; it = it[i].children) {
- bookmarkExternal = trace.pop();
- peers = null;
+_t.ContactAddressInit = {
+ country: _t.DOMString,
+ region: _t.DOMString,
+ city: _t.DOMString,
+ streetAddress: _t.DOMString,
+ additionalInformation: _t.DOMString,
+ postalCode: _t.DOMString,
+ isDefault: _t.boolean,
+ types: [_t.DOMString],
- if (it.length === 0)
- break;
+ _dictionary: null
+};
- for (i in it) {
- if (it[i].external === bookmarkExternal) {
- peers = it;
- break;
- }
- }
- }
+/*
+ * Calendar
+ */
- if (callback) {
- return callback((peers !== null) ? i : -1, peers);
- }
+_t.CalendarId = _t.DOMString;
+_t.CalendarTaskId = _t.DOMString;
+_t.CalendarEventArraySuccessCallback = _t.Function;
+_t.CalendarItemArraySuccessCallback = _t.Function;
+_t.CalendarArraySuccessCallback = _t.Function;
- return (peers !== null) ? peers[i] : undefined;
+_t.CalendarEventId = {
+ uid: _t.DOMString,
+ rid: _t.DOMString,
+
+ _optional: {
+ // nullable
+ rid: true
}
+};
- function traverse(bookmarks, trace, level) {
- for (var i in bookmarks) {
- trace.push(bookmarks[i].external);
- if ((level !== 0) && bookmarks[i].children) {
- traverse(bookmarks[i].children, trace, --level);
- }
- }
+_t.CalendarItemId = [_t.CalendarEventId, _t.CalendarTaskId];
+
+_t.CalendarAlarm = {
+ absoluteDate: _t.TZDate,
+ before: _t.TimeDuration,
+ method: _t.AlarmMethod,
+ description: _t.DOMString,
+
+ _optional: {
+ // nullable
+ absoluteDate: true,
+ before: true,
+ description: true
}
+};
- function findUrl(bookmarks, url) {
- var i, isFound = false;
+_t.CalendarAttendee = {
+ uri: _t.DOMString,
+ name: _t.DOMString,
+ role: _t.AttendeeRole,
+ status: _t.AttendeeStatus,
+ RSVP: _t.boolean,
+ type: _t.AttendeeType,
+ group: _t.DOMString,
+ delegatorURI: _t.DOMString,
+ delegateURI: _t.DOMString,
+ contactRef: _t.ContactRef,
- for (i in bookmarks) {
- if (_isFolder(bookmarks[i])) {
- isFound = findUrl(bookmarks[i].children, url);
- } else {
- isFound = (bookmarks[i].url === url);
- }
+ _optional: {
+ // nullable
+ name: true,
+ group: true,
+ delegatorURI: true,
+ delegateURI: true,
+ contactRef: true
+ }
+};
- if (isFound)
- break;
- }
+_t.CalendarRecurrenceRule = {
+ frequency: _t.RecurrenceRuleFrequency,
+ interval: _t.unsigned_short,
+ untilDate: _t.TZDate,
+ occurrenceCount: _t.long,
+ daysOfTheWeek: [_t.ByDayValue],
+ setPositions: [_t.short],
+ exceptions: [_t.TZDate],
- return isFound;
+ _optional: {
+ // nullable
+ untilDate: true
}
+};
- function isExisting(bookmark, peers) {
- var i;
+_t.CalendarTask = {
+ dueDate: _t.TZDate,
+ completedDate: _t.TZDate,
+ progress: _t.unsigned_short,
- if (!_isFolder(bookmark)) {
- return findUrl(_data.bookmarks, bookmark.url);
- }
+ _optional: {
+ // nullable
+ dueDate: true,
+ completedDate: true
+ }
+};
- for (i in peers) {
- if (_isFolder(peers[i]) && (peers[i].title === bookmark.title)) {
- return true;
- }
- }
+_t.CalendarEvent = {
+ isDetached: _t.boolean,
+ endDate: _t.TZDate,
+ availability: _t.EventAvailability,
+ recurrenceRule: _t.CalendarRecurrenceRule,
+ expandRecurrence: _t.Function,
- return false;
+ _optional: {
+ // nullable
+ endDate: true,
+ recurrenceRule: true
}
+};
- // public
- function get(parentFolder, recursive) {
- var bookmarks = [], parent, peers;
+_t.CalendarItem = {
+ id: _t.CalendarItemId,
+ calendarId: _t.CalendarId,
+ lastModificationDate: _t.TZDate,
+ description: _t.DOMString,
+ summary: _t.DOMString,
+ isAllDay: _t.boolean,
+ startDate: _t.TZDate,
+ duration: _t.TimeDuration,
+ location: _t.DOMString,
+ geolocation: _t.SimpleCoordinates,
+ organizer: _t.DOMString,
+ visibility: _t.CalendarItemVisibility,
+ status: _t.CalendarItemStatus,
+ priority: _t.CalendarItemPriority,
+ alarms: [_t.CalendarAlarm],
+ categories: [_t.DOMString],
+ attendees: [_t.CalendarAttendee],
+ convertToString: _t.Function,
+ clone: _t.Function,
- if (!_security.get) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _optional: {
+ // nullable
+ id: true,
+ calendarId: true,
+ lastModificationDate: true,
+ description: true,
+ summary: true,
+ startDate: true,
+ duration: true,
+ location: true,
+ geolocation: true,
+ organizer: true
+ },
- t.BookmarkManager("get", arguments);
+ _derived: [_t.CalendarTask, _t.CalendarEvent]
+};
- parent = map(parentFolder);
- if ((parent === undefined) || (parent && !_isFolder(parent))) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- peers = parent ? parent.children : _data.bookmarks;
- traverse(peers, bookmarks, recursive ? -1 : 0);
+_t.CalendarItemInit = {
+ description: _t.DOMString,
+ summary: _t.DOMString,
+ isAllDay: _t.boolean,
+ startDate: _t.TZDate,
+ duration: _t.TimeDuration,
+ location: _t.DOMString,
+ geolocation: _t.SimpleCoordinates,
+ organizer: _t.DOMString,
+ visibility: _t.CalendarItemVisibility,
+ status: _t.CalendarItemStatus,
+ priority: _t.CalendarItemPriority,
+ alarms: [_t.CalendarAlarm],
+ categories: [_t.DOMString],
+ attendees: [_t.CalendarAttendee],
- return bookmarks;
- }
+ _dictionary: null
+};
- function add(bookmark, parentFolder) {
- var parent, peers;
+_t.CalendarTaskInit = {
+ dueDate: _t.TZDate,
+ completedDate: _t.TZDate,
+ progress: _t.short,
- if (!_security.add) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _dictionary: _t.CalendarItemInit
+};
- t.BookmarkManager("add", arguments);
+_t.CalendarEventInit = {
+ endDate: _t.TZDate,
+ availability: _t.EventAvailability,
+ recurrenceRule: _t.CalendarRecurrenceRule,
- parent = map(parentFolder);
- if ((parent === undefined) || (parent && !_isFolder(parent))) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- peers = parent ? parent.children : _data.bookmarks;
- if (isExisting(bookmark, peers)) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
+ _dictionary: _t.CalendarItemInit
+};
- peers.push(new BookmarkInternal(bookmark));
+_t.CalendarAttendeeInit = {
+ name: _t.DOMString,
+ role: _t.AttendeeRole,
+ status: _t.AttendeeStatus,
+ RSVP: _t.boolean,
+ type: _t.AttendeeType,
+ group: _t.DOMString,
+ delegatorURI: _t.DOMString,
+ delegateURI: _t.DOMString,
+ contactRef: _t.ContactRef,
- _persist();
+ _dictionary: null
+};
- bookmark.__defineGetter__("parent", function () {
- return parent ? parent.external : null;
- });
- }
+_t.CalendarRecurrenceRuleInit = {
+ interval: _t.short,
+ untilDate: _t.TZDate,
+ occurrenceCount: _t.long,
+ daysOfTheWeek: [_t.ByDayValue],
+ setPositions: [_t.short],
+ exceptions: [_t.TZDate],
- function remove(bookmark) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _dictionary: null
+};
- t.BookmarkManager("remove", arguments);
+_t.CalendarChangeCallback = {
+ onitemsadded: _t.Callback,
+ onitemsupdated: _t.Callback,
+ onitemsremoved: _t.Callback
+};
- if (!bookmark) {
- _data.bookmarks = [];
- } else {
- map(bookmark, function (index, peers) {
- if (index === -1) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- peers.splice(index, 1);
- });
+/*
+ * CallHistory
+ */
- bookmark.__defineGetter__("parent", function () {
- return undefined;
- });
- }
+_t.CallHistoryEntryArraySuccessCallback = _t.Function;
- _persist();
+_t.RemoteParty = {
+ remoteParty: _t.DOMString,
+ personId: _t.PersonId,
+
+ _optional: {
+ // nullable
+ remoteParty: true,
+ personId: true
}
+};
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+_t.CallHistoryEntry = {
+ uid: _t.DOMString,
+ type: _t.DOMString,
+ features: [_t.DOMString],
+ remoteParties: [_t.RemoteParty],
+ startTime: _t.Date,
+ duration: _t.unsigned_long,
+ direction: _t.DOMString,
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
+ _optional: {
+ // nullable
+ features: true
}
+};
- bookmark = {
- get: get,
- add: add,
- remove: remove,
- handleSubFeatures: handleSubFeatures
- };
-
- return bookmark;
+_t.CallHistoryChangeCallback = {
+ onadded: _t.Callback,
+ onchanged: _t.Callback,
+ onremoved: _t.Callback
};
/*
- * BookmarkInternal BookmarkStorage BookmarkExternal
- * ---------------------------------------------------------
- * title title title
- * url url url/-
- * children children -
- * external - -
- * - - parent
+ * Content
*/
-BookmarkInternal = function (bookmark, parent) {
- this.title = bookmark.title;
- this.url = _isFolder(bookmark) ? null : bookmark.url;
- this.children = _isFolder(bookmark) ?
- _getChildren(bookmark, BookmarkInternal, this) : null;
- this.external = _isExternal(bookmark) ? bookmark :
- new BookmarkExternal(bookmark, parent);
-};
+_t.ContentId = _t.DOMString;
+_t.ContentDirectoryId = _t.DOMString;
+_t.ContentArraySuccessCallback = _t.Function;
+_t.ContentDirectoryArraySuccessCallback = _t.Function;
+_t.ContentScanSuccessCallback = _t.Function;
-BookmarkStorage = function (bookmark) {
- this.title = bookmark.title;
- this.url = _isFolder(bookmark) ? null : bookmark.url;
- this.children = _isFolder(bookmark) ?
- _getChildren(bookmark, BookmarkStorage) : null;
+_t.ContentChangeCallback = {
+ oncontentadded: _t.Callback,
+ oncontentupdated: _t.Callback,
+ oncontentremoved: _t.Callback
};
-BookmarkExternal = function (bookmark, parent) {
- var self;
+_t.VideoContent = {
+ geolocation: _t.SimpleCoordinates,
+ album: _t.DOMString,
+ artists: [_t.DOMString],
+ duration: _t.unsigned_long,
+ width: _t.unsigned_long,
+ height: _t.unsigned_long,
- if (_isFolder(bookmark)) {
- self = new BookmarkFolder(bookmark.title);
- } else {
- self = new BookmarkItem(bookmark.title, bookmark.url);
+ _optional: {
+ // nullable
+ geolocation: true,
+ album: true,
+ artists: true
}
+};
- self.__defineGetter__("parent", function () {
- return parent ? parent.external : null;
- });
+_t.AudioContentLyrics = {
+ type: _t.AudioContentLyricsType,
+ timestamps: [_t.unsigned_long],
+ texts: [_t.DOMString],
- return self;
+ _optional: {
+ // undefined
+ timestamps: true
+ }
};
-_initialize();
+_t.AudioContent = {
+ album: _t.DOMString,
+ genres: [_t.DOMString],
+ artists: [_t.DOMString],
+ composers: [_t.DOMString],
+ lyrics: _t.AudioContentLyrics,
+ copyright: _t.DOMString,
+ bitrate: _t.unsigned_long,
+ trackNumber: _t.unsigned_short,
+ duration: _t.unsigned_long,
-module.exports = _self;
+ _optional: {
+ // nullable
+ album: true,
+ genres: true,
+ artists: true,
+ composers: true,
+ lyrics: true,
+ copyright: true,
+ trackNumber: true
+ }
+};
-});
-define('ripple/platform/tizen/2.0/calendar', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+_t.ImageContent = {
+ geolocation: _t.SimpleCoordinates,
+ width: _t.unsigned_long,
+ height: _t.unsigned_long,
+ orientation: _t.ImageContentOrientation,
-var utils = require('ripple/utils'),
- db = require('ripple/db'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- TZDate = require('ripple/platform/tizen/2.0/TZDate'),
- TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
- CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
- CalendarEvent = require('ripple/platform/tizen/2.0/CalendarEvent'),
- CalendarEventId = require('ripple/platform/tizen/2.0/CalendarEventId'),
- CalendarTask = require('ripple/platform/tizen/2.0/CalendarTask'),
- Calendar,
- CalendarStorage,
- CalendarItemsStorage,
- _DB_CALENDARS_KEY = "tizen1-db-calendars",
- _watchers = [],
- _calendars = {
- EVENT: {},
- TASK: {}
- },
- _calendarsStorage,
- _security = {
- "http://tizen.org/privilege/calendar.read": ["getCalendars",
- "getUnifiedCalendar", "getDefaultCalendar", "getCalendar",
- "get", "find", "addChangeListener", "removeChangeListener",
- "expandRecurrence", "convertToString", "clone"],
- "http://tizen.org/privilege/calendar.write": ["add", "addBatch",
- "update", "updateBatch", "remove", "removeBatch"]
+ _optional: {
+ // nullable
+ geolocation: true
+ }
+};
+
+_t.Content = {
+ editableAttributes: [_t.DOMString],
+ id: _t.ContentId,
+ name: _t.DOMString,
+ type: _t.ContentType,
+ mimeType: _t.DOMString,
+ title: _t.DOMString,
+ contentURI: _t.DOMString,
+ thumbnailURIs: [_t.DOMString],
+ releaseDate: _t.Date,
+ modifiedDate: _t.Date,
+ size: _t.unsigned_long,
+ description: _t.DOMString,
+ rating: _t.float,
+
+ _optional: {
+ // nullable
+ thumbnailURIs: true,
+ releaseDate: true,
+ modifiedDate: true,
+ description: true
},
- _self;
-function _isValidId(id) {
- return (/[a-z]|[A-Z]|[0-9]|[\-]/).test(id);
-}
+ _derived: [_t.VideoContent, _t.AudioContent, _t.ImageContent]
+};
-function retrieveCalendars() {
- _calendarsStorage = db.retrieveObject(_DB_CALENDARS_KEY) || {EVENT: {}, TASK: {}};
-}
+/*
+ * Data Control
+ */
-function saveCalendars() {
- db.saveObject(_DB_CALENDARS_KEY, _calendarsStorage);
-}
+_t.DataControlSuccessCallback = _t.Function;
+_t.DataControlErrorCallback = _t.Function;
+_t.DataControlInsertSuccessCallback = _t.Function;
+_t.DataControlSelectSuccessCallback = _t.Function;
+_t.DataControlGetValueSuccessCallback = _t.Function;
-_self = function () {
- var calendarManager;
+_t.RowData = {
+ columns: [_t.DOMString],
+ values: [_t.DOMString]
+};
- // private
- function loadCalendars(type) {
- var calsStorage, defCalendar, id, i, item;
+/*
+ * Data Synchronization
+ */
- retrieveCalendars();
- calsStorage = _calendarsStorage[type];
+_t.SyncProfileId = _t.DOMString;
- if (tizen1_utils.isEmptyObject(calsStorage)) {
- defCalendar = new Calendar(type, "Default " + type.toLowerCase() + " calendar");
+_t.SyncInfo = {
+ url: _t.DOMString,
+ id: _t.DOMString,
+ password: _t.DOMString,
+ mode: _t.SyncMode,
+ type: _t.SyncType,
+ interval: _t.SyncInterval,
- _calendars[type][defCalendar.id] = defCalendar;
- calsStorage[defCalendar.id] = new CalendarStorage(defCalendar);
- } else {
- for (id in calsStorage) {
- for (i in calsStorage[id].items) {
- item = calsStorage[id].items[i];
- }
- _calendars[type][id] = new Calendar(type, calsStorage[id].name,
- calsStorage[id].items, id);
- }
- }
+ _optional: {
+ // nullable
+ id: true,
+ password: true,
+ type: true,
+ interval: true
}
+};
- // public
- function getCalendars(type, successCallback, errorCallback) {
- if (!_security.getCalendars) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.CalendarManager("getCalendars", arguments);
+_t.SyncServiceInfo = {
+ enable: _t.boolean,
+ serviceType: _t.SyncServiceType,
+ serverDatabaseUri: _t.DOMString,
+ id: _t.DOMString,
+ password: _t.DOMString,
- window.setTimeout(function () {
- var i, result = [];
+ _optional: {
+ // nullable
+ id: true,
+ password: true
+ }
+};
- if (tizen1_utils.isEmptyObject(_calendars[type])) {
- loadCalendars(type);
- }
+_t.SyncProfileInfo = {
+ profileId: _t.SyncProfileId,
+ profileName: _t.DOMString,
+ syncInfo: _t.SyncInfo,
+ serviceInfo: [_t.SyncServiceInfo],
- if (_calendars.length !== 0) {
- for (i in _calendars[type]) {
- result.push(_calendars[type][i]);
- }
- successCallback(result);
- } else if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- }, 1);
+ _optional: {
+ // nullable
+ profileId: true,
+ serviceInfo: true
}
+};
- function getUnifiedCalendar(type) {
- var id, calendar;
+_t.SyncProgressCallback = {
+ onprogress: _t.Callback,
+ oncompleted: _t.Callback,
+ onstopped: _t.Callback,
+ onfailed: _t.Callback
+};
- if (!_security.getUnifiedCalendar) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Download
+ */
- t.CalendarManager("getUnifiedCalendar", arguments);
+_t.DownloadHTTPHeaderFields = {};
- if (tizen1_utils.isEmptyObject(_calendars[type])) {
- loadCalendars(type);
- }
+_t.DownloadRequest = {
+ url: _t.DOMString,
+ destination: _t.DOMString,
+ fileName: _t.DOMString,
+ networkType: _t.DownloadNetworkType,
+ httpHeader: _t.DownloadHTTPHeaderFields,
- for (id in _calendars[type]) {
- calendar = _calendars[type][id];
- break;
- }
+ _optional: {
+ destination: true,
+ fileName: true,
+ networkType: true,
+ httpHeader: true
+ }
+};
- if (calendar === undefined)
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+_t.DownloadCallback = {
+ onprogress: _t.Callback,
+ onpaused: _t.Callback,
+ oncanceled: _t.Callback,
+ oncompleted: _t.Callback,
+ onfailed: _t.Callback
+};
- return calendar;
+/*
+ * Messaging
+ */
+
+_t.MessageId = _t.DOMString;
+_t.MessageAttachmentId = _t.DOMString;
+_t.MessageConvId = _t.DOMString;
+_t.MessageFolderId = _t.DOMString;
+_t.MessageServiceArraySuccessCallback = _t.Function;
+_t.MessageRecipientsCallback = _t.Function;
+_t.MessageBodySuccessCallback = _t.Function;
+_t.MessageAttachmentSuccessCallback = _t.Function;
+_t.MessageArraySuccessCallback = _t.Function;
+_t.MessageConversationArraySuccessCallback = _t.Function;
+_t.MessageFolderArraySuccessCallback = _t.Function;
+
+_t.MessageFolder = {
+ id: _t.MessageFolderId,
+ parentId: _t.MessageFolderId,
+ serviceId: _t.DOMString,
+ contentType: _t.MessageServiceTag,
+ name: _t.DOMString,
+ path: _t.DOMString,
+ type: _t.DOMString,
+ synchronizable: _t.boolean,
+
+ _optional: {
+ // nullable
+ parentId: true
}
+};
- function getDefaultCalendar(type) {
- var id, calendar;
+_t.MessagesChangeCallback = {
+ messagesadded: _t.Callback,
+ messagesupdated: _t.Callback,
+ messagesremoved: _t.Callback
+};
- if (!_security.getDefaultCalendar) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_t.MessageConversationsChangeCallback = {
+ conversationsadded: _t.Callback,
+ conversationsupdated: _t.Callback,
+ conversationsremoved: _t.Callback
+};
- t.CalendarManager("getDefaultCalendar", arguments);
+_t.MessageFoldersChangeCallback = {
+ foldersadded: _t.Callback,
+ foldersupdated: _t.Callback,
+ foldersremoved: _t.Callback
+};
- if (tizen1_utils.isEmptyObject(_calendars[type])) {
- loadCalendars(type);
- }
+/*
+ * Message Port
+ */
- for (id in _calendars[type]) {
- calendar = _calendars[type][id];
- break;
- }
+_t.MessagePortCallback = _t.Function;
- if (calendar === undefined)
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+_t.LocalMessagePort = {
+ messagePortName: _t.DOMString,
+ isTrusted: _t.boolean,
+ addMessagePortListener: _t.Function,
+ removeMessagePortListener: _t.Function
+};
- return calendar;
- }
+_t.MessagePortDataItem = {
+ key: _t.DOMString,
+ value: _t.DOMString,
- function getCalendar(type, id) {
- var calendar;
+ _dictionary: null
+};
- if (!_security.getCalendar) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Network Bearer Selection
+ */
- t.CalendarManager("getCalendar", arguments);
+_t.NetworkSuccessCallback = {
+ onsuccess: _t.Callback,
+ ondisconnected: _t.Callback
+};
- if (tizen1_utils.isEmptyObject(_calendars[type])) {
- loadCalendars(type);
- }
+/*
+ * NFC
+ */
- calendar = _calendars[type][id];
- if (calendar === undefined)
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+_t.NDEFMessageReadCallback = _t.Function;
+_t.ByteArraySuccessCallback = _t.Function;
- return calendar;
- }
+_t.NFCTagDetectCallback = {
+ onattach: _t.Callback,
+ ondetach: _t.Callback
+};
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+_t.NFCPeerDetectCallback = {
+ onattach: _t.Callback,
+ ondetach: _t.Callback
+};
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+_t.NDEFRecordText = {
+ text: _t.DOMString,
+ languageCode: _t.DOMString,
+ encoding: _t.NDEFRecordTextEncoding
+};
- calendarManager = {
- getCalendars: getCalendars,
- getUnifiedCalendar: getUnifiedCalendar,
- getDefaultCalendar: getDefaultCalendar,
- getCalendar: getCalendar,
- handleSubFeatures: handleSubFeatures
- };
+_t.NDEFRecordURI = {
+ uri: _t.DOMString
+};
- return calendarManager;
+_t.NDEFRecordMedia = {
+ mimeType: _t.DOMString
};
-Calendar = function (type, name, storageItems, calendarId) {
- var privateItems = {},
- defaultWatchId = 0;
- calendarId = calendarId || Math.uuid(null, 16);
+_t.NDEFRecord = {
+ tnf: _t.short,
+ type: [_t.byte],
+ id: [_t.byte],
+ payload: [_t.byte],
- // private
- function createCalendarItem() {
- var calendarItem = null;
+ _derived: [_t.NDEFRecordText, _t.NDEFRecordURI, _t.NDEFRecordMedia]
+};
- switch (type) {
- case "EVENT":
- calendarItem = new CalendarEvent();
- break;
+_t.NDEFMessage = {
+ recordCount: _t.long,
+ records: [_t.NDEFRecord],
+ toByte: _t.Function
+};
- case "TASK":
- calendarItem = new CalendarTask();
- break;
+/*
+ * Notification
+ */
- default:
- break;
- }
+_t.NotificationId = _t.DOMString;
- return calendarItem;
+_t.NotificationDetailInfo = {
+ mainText: _t.DOMString,
+ subText: _t.DOMString,
+
+ _optional: {
+ // nullable
+ subText: true
}
+};
- function isValidCalendarItemId(itemId) {
- var i;
+_t.StatusNotificationInit = {
+ content: _t.DOMString,
+ iconPath: _t.DOMString,
+ soundPath: _t.DOMString,
+ vibration: _t.boolean,
+ appControl: _t.ApplicationControl,
+ appId: _t.ApplicationId,
+ progressType: _t.NotificationProgressType,
+ progressValue: _t.unsigned_long,
+ number: _t.long,
+ subIconPath: _t.DOMString,
+ detailInfo: [_t.NotificationDetailInfo],
+ ledColor: _t.DOMString,
+ ledOnPeriod: _t.unsigned_long,
+ ledOffPeriod: _t.unsigned_long,
+ backgroundImagePath: _t.DOMString,
+ thumbnails: [_t.DOMString],
- if (!_isValidId(itemId))
- return false;
+ _dictionary: null
+};
- for (i in privateItems) {
- if (i === itemId)
- return true;
- }
+_t.StatusNotification = {
+ statusType: _t.StatusNotificationType,
+ iconPath: _t.DOMString,
+ subIconPath: _t.DOMString,
+ number: _t.long,
+ detailInfo: [_t.NotificationDetailInfo],
+ ledColor: _t.DOMString,
+ ledOnPeriod: _t.unsigned_long,
+ ledOffPeriod: _t.unsigned_long,
+ backgroundImagePath: _t.DOMString,
+ thumbnails: [_t.DOMString],
+ soundPath: _t.DOMString,
+ vibration: _t.boolean,
+ appControl: _t.ApplicationControl,
+ appId: _t.ApplicationId,
+ progressType: _t.NotificationProgressType,
+ progressValue: _t.unsigned_long,
- return false;
+ _optional: {
+ // nullable
+ iconPath: true,
+ subIconPath: true,
+ number: true,
+ detailInfo: true,
+ ledColor: true,
+ backgroundImagePath: true,
+ thumbnails: true,
+ soundPath: true,
+ appControl: true,
+ appId: true,
+ progressValue: true
}
+};
- function loadCalendarItemInit(calendarItem, storageItem) {
- calendarItem.description = utils.copy(storageItem.description);
- calendarItem.summary = utils.copy(storageItem.summary);
- calendarItem.isAllDay = utils.copy(storageItem.isAllDay);
- calendarItem.startDate = storageItem.startDate;
- if (storageItem.startDate instanceof TZDate) {
- calendarItem.startDate = storageItem.startDate.addDuration(new TDur(0, 'MSECS'));
- }
- if (typeof storageItem.startDate === 'string') {
- calendarItem.startDate = new TZDate(new Date(storageItem.startDate));
- }
+_t.Notification = {
+ id: _t.NotificationId,
+ type: _t.NotificationType,
+ postedTime: _t.Date,
+ title: _t.DOMString,
+ content: _t.DOMString,
- calendarItem.duration = utils.copy(storageItem.duration);
- calendarItem.location = utils.copy(storageItem.location);
- calendarItem.geolocation = utils.copy(storageItem.geolocation);
- calendarItem.organizer = utils.copy(storageItem.organizer);
- calendarItem.visibility = utils.copy(storageItem.visibility);
- calendarItem.status = utils.copy(storageItem.status);
- calendarItem.priority = utils.copy(storageItem.priority);
- calendarItem.alarms = utils.copy(storageItem.alarms);
- calendarItem.categories = utils.copy(storageItem.categories);
- calendarItem.attendees = utils.copy(storageItem.attendees);
- }
+ _optional: {
+ // nullable
+ id: true,
+ postedTime: true,
+ content: true
+ },
- function loadCalendarEventInit(calendarItem, storageItem) {
- loadCalendarItemInit(calendarItem, storageItem);
+ _derived: [_t.StatusNotification]
+};
- calendarItem.endDate = storageItem.endDate;
- if (storageItem.endDate instanceof TZDate) {
- calendarItem.endDate = storageItem.endDate.addDuration(new TDur(0, 'MSECS'));
- }
- if (typeof storageItem.endDate === 'string') {
- calendarItem.endDate = new TZDate(new Date(storageItem.endDate));
- }
- calendarItem.availability = utils.copy(storageItem.availability);
- calendarItem.recurrenceRule = utils.copy(storageItem.recurrenceRule);
- calendarItem.expandRecurrence = function (startDate, endDate, successCallback, errorCallback) {
- if (!_security.expandRecurrence) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Push
+ */
- calendarItem.startDate = startDate;
- calendarItem.endDate = endDate;
+_t.PushRegistrationId = _t.DOMString;
+_t.PushRegisterSuccessCallback = _t.Function;
+_t.PushNotificationCallback = _t.Function;
- if (errorCallback) {
- window.setTimeout(function () {
- errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
- }, 1);
- }
- };
- calendarItem.frequency = utils.copy(storageItem.frequency);
- calendarItem.interval = utils.copy(storageItem.interval);
- calendarItem.untilDate = storageItem.untilDate;
- if (storageItem.untilDate instanceof TZDate) {
- calendarItem.untilDate = storageItem.untilDate.addDuration(new TDur(0, 'MSECS'));
- }
- if (typeof storageItem.untilDate === 'string') {
- calendarItem.untilDate = new TZDate(new Date(storageItem.untilDate));
- }
- calendarItem.occurrenceCount = utils.copy(storageItem.occurrenceCount);
- calendarItem.daysOfTheWeek = utils.copy(storageItem.daysOfTheWeek);
- calendarItem.setPositions = utils.copy(storageItem.setPositions);
- calendarItem.exceptions = utils.copy(storageItem.exceptions);
- }
+/*
+ * Package
+ */
- function loadCalendarTaskInit(calendarItem, storageItem) {
- loadCalendarItemInit(calendarItem, storageItem);
+_t.PackageId = _t.DOMString;
+_t.PackageInformationArraySuccessCallback = _t.Function;
- calendarItem.dueDate = storageItem.dueDate;
- if (storageItem.dueDate instanceof TZDate) {
- calendarItem.dueDate = storageItem.dueDate.addDuration(new TDur(0, 'MSECS'));
- }
- if (typeof storageItem.dueDate === 'string') {
- calendarItem.dueDate = new TZDate(new Date(storageItem.dueDate));
- }
- calendarItem.completeDate = storageItem.completeDate;
- if (storageItem.completeDate instanceof TZDate) {
- calendarItem.completeDate = storageItem.completeDate.addDuration(new TDur(0, 'MSECS'));
- }
- if (typeof storageItem.completeDate === 'string') {
- calendarItem.completeDate = new TZDate(new Date(storageItem.completeDate));
- }
- calendarItem.progress = utils.copy(storageItem.progress);
- }
+_t.PackageProgressCallback = {
+ onprogress: _t.Callback,
+ oncomplete: _t.Callback
+};
- function loadCalendarItems() {
- var i, calendarItem;
+_t.PackageInfomationEventCallback = {
+ oninstalled: _t.Callback,
+ onupdated: _t.Callback,
+ onuninstalled: _t.Callback
+};
- if (storageItems === undefined)
- return;
+/*
+ * System Info
+ */
- for (i in storageItems) {
- calendarItem = new CalendarItem(type, i, storageItems[i].lastModificationDate? new TZDate(new Date(storageItems[i].lastModificationDate)) : null, _security);
+_t.SystemInfoPropertySuccessCallback = _t.Callback;
- if (type === "EVENT") {
- loadCalendarEventInit(calendarItem, storageItems[i]);
- } else {
- loadCalendarTaskInit(calendarItem, storageItems[i]);
- }
+_t.SystemInfoOptions = {
+ timeout: _t.unsigned_long,
+ highThreshold: _t.double,
+ lowThreshold: _t.double,
- privateItems[i] = calendarItem;
- }
- }
+ _dictionary: null
+};
- function saveCalendarItems() {
- _calendarsStorage[type][calendarId] || (_calendarsStorage[type][calendarId] = {});
- _calendarsStorage[type][calendarId].items = new CalendarItemsStorage(privateItems);
- saveCalendars();
- }
+/*
+ * System Setting
+ */
- // public
- function get(id) {
- var item, uid, CalendarItemType, external = {};
+_t.SystemSettingSuccessCallback = _t.Function;
- if (!_security.get) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Vehicle
+ */
+_t.SupportedPropertiesSuccessCallback = _t.Function;
- t.Calendar("get", arguments);
+_t.VehiclePropertyErrorCallback = _t.Function;
- if (type === "EVENT") {
- if (typeof id !== "object") {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- uid = id.uid;
- CalendarItemType = CalendarEvent;
- } else {
- uid = id;
- CalendarItemType = CalendarTask;
- }
+/*
+ * Constructor list definition
+ */
- if (!isValidCalendarItemId(uid))
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+/*
+ * Generic constructor
+ * Construct a prototype of constructor. A fake array of arguments type is
+ * specified for constructor.
+ *
+ * Overloaded constructors
+ * Construct an array of prototype of constructor. Each array element is
+ * specified for one of constructors. The constructor with extra arguments
+ * are recommended to be defined ahead of the one with fewer same arguments
+ * for exact match.
+ */
- item = new CalendarItemType(privateItems[uid]);
- external.id = privateItems[uid].id;
- external.lastModificationDate = privateItems[uid].lastModificationDate;
+_c = {
+ // Alarm
+ AlarmAbsolute: [],
- item.__defineGetter__("calendarId", function () {
- return calendarId;
- });
+ // Calendar
+ CalendarTask: [],
+ CalendarEvent: [],
+ CalendarAlarm: [],
- item.__defineGetter__("id", function () {
- return external.id;
- });
+ // Contact
+ Contact: [],
- item.__defineGetter__("lastModificationDate", function () {
- return external.lastModificationDate;
- });
+ // NFC
+ NDEFMessage: [],
+ NDEFRecord: [],
- return item;
- }
+ // Data Synchronization
+ SyncInfo: [],
- function add(item) {
- var uid, external = {};
+ // Time
+ TZDate: []
+};
- if (!_security.add) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+/*
+ * Common
+ */
- t.Calendar("add", arguments);
+// AttributeFilter
+_c.AttributeFilter = {
+ 0: _t.DOMString,
+ 1: _t.FilterMatchFlag,
+ 2: _t.any,
- uid = Math.uuid(null, 16);
- privateItems[uid] = t.CalendarItem(item, "+");
- if (type === "EVENT") {
- privateItems[uid].id = new CalendarEventId(uid);
- } else {
- privateItems[uid].id = uid;
- }
- privateItems[uid].lastModificationDate = new TZDate();
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- external.id = privateItems[uid].id;
- external.lastModificationDate = privateItems[uid].lastModificationDate;
+// AttributeRangeFilter
+_c.AttributeRangeFilter = {
+ 0: _t.DOMString,
+ 1: _t.any,
+ 2: _t.any,
- saveCalendarItems();
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- // set the calendarId of the item
- item.__defineGetter__("calendarId", function () {
- return calendarId;
- });
+// CompositeFilter
+_c.CompositeFilter = {
+ 0: _t.CompositeFilterType,
+ 1: [_t.AbstractFilter],
- item.__defineGetter__("id", function () {
- return external.id;
- });
+ _optional: {
+ 1: true
+ }
+};
- item.__defineGetter__("lastModificationDate", function () {
- return external.lastModificationDate;
- });
+// SortMode
+_c.SortMode = {
+ 0: _t.DOMString,
+ 1: _t.SortModeOrder,
- window.setTimeout(function () {
- for (var i in _watchers) {
- _watchers[i].onitemsadded([item]);
- }
- }, 1);
+ _optional: {
+ 1: true
}
+};
- function addBatch(items, successCallback, errorCallback) {
- if (!_security.addBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// SimpleCoordinates
+_c.SimpleCoordinates = {
+ 0: _t.double,
+ 1: _t.double
+};
- t.Calendar("addBatch", arguments, true);
+/*
+ * Alarm
+ */
- window.setTimeout(function () {
- var i, j, uid, external = [];
+// AlarmRelative
+_c.AlarmRelative = {
+ 0: _t.long,
+ 1: _t.long,
- for (i in items) {
- uid = Math.uuid(null, 16);
- privateItems[uid] = utils.copy(items[i]);
+ _optional: {
+ 1: true
+ }
+};
- if (type === "EVENT") {
- privateItems[uid].id = new CalendarEventId(uid);
- } else {
- privateItems[uid].id = uid;
- }
+// AlarmAbsolute
+_c.AlarmAbsolute[0] = {
+ 0: _t.Date,
+ 1: [_t.ByDayValue]
+};
- external[i] = {};
- external[i].id = privateItems[uid].id;
- external[i].lastModificationDate = new TZDate();
+_c.AlarmAbsolute[1] = {
+ 0: _t.Date,
+ 1: _t.long
+};
- items[i].__defineGetter__("calendarId", function () {
- return calendarId;
- });
+_c.AlarmAbsolute[2] = {
+ 0: _t.Date
+};
- items[i].__defineGetter__("id", function () {
- return external[i].id;
- });
+/*
+ * Application
+ */
- items[i].__defineGetter__("lastModificationDate", function () {
- return external[i].lastModificationDate;
- });
- }
+// ApplicationControlData
+_c.ApplicationControlData = {
+ 0: _t.DOMString,
+ 1: [_t.DOMString]
+};
- saveCalendarItems();
+// ApplicationControl
+_c.ApplicationControl = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.DOMString,
+ 4: [_t.ApplicationControlData],
- if (successCallback) {
- successCallback(items);
- }
- for (j in _watchers) {
- _watchers[j].onitemsadded(items);
- }
- }, 1);
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true,
+ 4: true
}
+};
- function update(item, updateAllInstances) {
- var calendarItem, attr, uid;
+/*
+ * Bookmark
+ */
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// BookmarkItem
+_c.BookmarkItem = {
+ 0: _t.DOMString,
+ 1: _t.DOMString
+};
- t.Calendar("update", arguments);
+// BookmarkFolder
+_c.BookmarkFolder = {
+ 0: _t.DOMString
+};
- uid = (type === "EVENT") ? item.id.uid : item.id;
- if (!isValidCalendarItemId(uid))
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+/*
+ * Calendar
+ */
- if (updateAllInstances === undefined || updateAllInstances === null) {
- updateAllInstances = true;
- }
+// CalendarTask
+_c.CalendarTask[0] = {
+ 0: _t.CalendarTaskInit,
- if ((type === "EVENT") && !updateAllInstances) {
- calendarItem = createCalendarItem();
+ _optional: {
+ // nullable
+ 0: true
+ }
+};
- for (attr in privateItems[uid]) {
- if (attr !== "id" && attr !== "lastModificationDate") {
- if (item[attr] !== undefined)
- calendarItem[attr] = utils.copy(item[attr]);
- else
- calendarItem[attr] = utils.copy(privateItems[uid][attr]);
- }
- }
+_c.CalendarTask[1] = {
+ 0: _t.DOMString,
+ 1: _t.CalendarTextFormat
+};
- add(calendarItem);
- } else {
- for (attr in privateItems[uid]) {
- if ((attr !== "id") && (attr !== "lastModificationDate") && (item[attr] !== undefined))
- privateItems[uid][attr] = utils.copy(item[attr]);
- }
- window.setTimeout(function () {
- var i;
+// CalendarEvent
+_c.CalendarEvent[0] = {
+ 0: _t.CalendarEventInit,
- for (i in _watchers) {
- _watchers[i].onitemsupdated([utils.copy(privateItems[uid])]);
- }
- }, 1);
- }
- saveCalendarItems();
+ _optional: {
+ // nullable
+ 0: true
}
+};
- function updateBatch(items, successCallback, errorCallback,
- updateAllInstances) {
- if (!_security.updateBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.Calendar("updateBatch", arguments, true);
+_c.CalendarEvent[1] = {
+ 0: _t.DOMString,
+ 1: _t.CalendarTextFormat
+};
- window.setTimeout(function () {
- var i, j, attr, calendarItem, updatedItems = [], uid;
+// CalendarAttendee
+_c.CalendarAttendee = {
+ 0: _t.DOMString,
+ 1: _t.CalendarAttendeeInit,
- for (i in items) {
- uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
- if (!uid || !privateItems[uid]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
+ _optional: {
+ 1: true
+ }
+};
- if (updateAllInstances) {
- for (i in privateItems) {
- for (j in items) {
- uid = (type === "EVENT") ? items[j].id.uid : items[j].id;
- if (i === uid) {
- for (attr in privateItems[i]) {
- if (attr !== "id" && attr !== "lastModificationDate" && items[j][attr] !== undefined)
- privateItems[i][attr] = utils.copy(items[j][attr]);
- }
- saveCalendarItems();
- updatedItems.push(utils.copy(privateItems[i]));
- }
- }
- }
- } else {
- for (i in items) {
- calendarItem = createCalendarItem();
+// CalendarRecurrenceRule
+_c.CalendarRecurrenceRule = {
+ 0: _t.RecurrenceRuleFrequency,
+ 1: _t.CalendarRecurrenceRuleInit,
- uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
- for (attr in privateItems[uid]) {
- if (attr !== "id" && attr !== "lastModificationDate") {
- if (items[i][attr] !== undefined)
- calendarItem[attr] = utils.copy(items[i][attr]);
- else
- calendarItem[attr] = utils.copy(privateItems[uid][attr]);
- }
- }
+ _optional: {
+ 1: true
+ }
+};
- add(calendarItem);
- updatedItems.push(utils.copy(calendarItem));
- }
- }
+// CalendarEventId
+_c.CalendarEventId = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
- saveCalendarItems();
- if (successCallback) {
- successCallback();
- }
- for (i in _watchers) {
- _watchers[i].onitemsupdated(utils.copy(updatedItems));
- }
- }, 1);
+ _optional: {
+ 1: true
}
+};
- function remove(id) {
- var isFound = false, i, uid;
-
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// CalendarAlarm
+_c.CalendarAlarm[0] = {
+ 0: _t.TZDate,
+ 1: _t.AlarmMethod,
+ 2: _t.DOMString,
- t.Calendar("remove", arguments);
+ _optional: {
+ 2: true
+ }
+};
- uid = (type === "EVENT") ? id.uid : id;
- for (i in privateItems) {
- if (i === uid) {
- delete privateItems[i];
- isFound = true;
- break;
- }
- }
+_c.CalendarAlarm[1] = {
+ 0: _t.TimeDuration,
+ 1: _t.AlarmMethod,
+ 2: _t.DOMString,
- if (!isFound)
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ _optional: {
+ 2: true
+ }
+};
- saveCalendarItems();
+/*
+ * Contact
+ */
- window.setTimeout(function () {
- var i;
+// Contact
+_c.Contact[0] = {
+ 0: _t.ContactInit,
- for (i in _watchers) {
- _watchers[i].onitemsremoved([id]);
- }
- }, 1);
+ _optional: {
+ 0: true
}
+};
- function removeBatch(ids, successCallback, errorCallback) {
- if (!_security.removeBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_c.Contact[1] = {
+ 0: _t.DOMString
+};
- t.Calendar("removeBatch", arguments, true);
+// ContactRef
+_c.ContactRef = {
+ 0: _t.AddressBookId,
+ 1: _t.ContactId
+};
- window.setTimeout(function () {
- var i, uid;
+// ContactName
+_c.ContactName = {
+ 0: _t.ContactNameInit,
- for (i in ids) {
- uid = (type === "EVENT") ? ids[i].uid : ids[i];
+ _optional: {
+ 0: true
+ }
+};
- if (!privateItems[uid]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
+// ContactOrganization
+_c.ContactOrganization = {
+ 0: _t.ContactOrganizationInit,
- for (i in ids) {
- uid = (type === "EVENT") ? ids[i].uid : ids[i];
- delete privateItems[uid];
- }
- saveCalendarItems();
- if (successCallback) {
- successCallback();
- }
+ _optional: {
+ 0: true
+ }
+};
+
+// ContactWebSite
+_c.ContactWebSite = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
- for (i in _watchers) {
- _watchers[i].onitemsremoved(utils.copy(ids));
- }
- }, 1);
+ _optional: {
+ 1: true
}
+};
- function find(successCallback, errorCallback, filter, sortMode) {
- if (!_security.find) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// ContactAnniversary
+_c.ContactAnniversary = {
+ 0: _t.Date,
+ 1: _t.DOMString,
- t.Calendar("find", arguments, true);
+ _optional: {
+ 1: true
+ }
+};
- window.setTimeout(function () {
- var i, calendarItems = [], result = [];
+// ContactAddress
+_c.ContactAddress = {
+ 0: _t.ContactAddressInit,
- for (i in privateItems) {
- calendarItems.push(privateItems[i]);
- }
- if (calendarItems.length > 0) {
- result = tizen1_utils.query(calendarItems, filter, sortMode);
- }
- successCallback(result);
- }, 1);
+ _optional: {
+ 0: true
}
+};
- function addChangeListener(successCallback) {
- var watchId;
-
- if (!_security.addChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// ContactPhoneNumber
+_c.ContactPhoneNumber = {
+ 0: _t.DOMString,
+ 1: [_t.DOMString],
+ 2: _t.boolean,
- t.Calendar("addChangeListener", arguments);
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- watchId = ++defaultWatchId;
- _watchers[watchId] = successCallback;
+// ContactEmailAddress
+_c.ContactEmailAddress = {
+ 0: _t.DOMString,
+ 1: [_t.DOMString],
+ 2: _t.boolean,
- return watchId;
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function removeChangeListener(watchId) {
- if (!_security.removeChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- if (!_watchers[watchId])
- return;
+// ContactGroup
+_c.ContactGroup = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
- delete _watchers[watchId];
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- loadCalendarItems(type, privateItems, storageItems);
-
- this.__defineGetter__("id", function () {
- return calendarId;
- });
- this.__defineGetter__("name", function () {
- return name;
- });
+/*
+ * Data Synchronization
+ */
- this.get = get;
- this.add = add;
- this.addBatch = addBatch;
- this.update = update;
- this.updateBatch = updateBatch;
- this.remove = remove;
- this.removeBatch = removeBatch;
- this.find = find;
- this.addChangeListener = addChangeListener;
- this.removeChangeListener = removeChangeListener;
+// SyncInfo
+_c.SyncInfo[0] = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.SyncMode,
+ 4: _t.SyncType
};
-CalendarStorage = function (calendar) {
- this.id = calendar.id;
- this.name = calendar.name;
+_c.SyncInfo[1] = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.SyncMode,
+ 4: _t.SyncInterval
};
-CalendarItemsStorage = function (privateItems) {
- var itemsStorage = {}, i, attr;
+_c.SyncInfo[2] = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.SyncMode
+};
- for (i in privateItems) {
- itemsStorage[i] = {};
- for (attr in privateItems[i]) {
- //TODO: should be
- // if (privateItems[i][attr] instanceof TZDate) {
- //But, we used "utils.copy" before store the item to privateItems list.
- //So the constructor information all lost
- if ((attr === "startDate" || attr === "endDate" || attr === "dueDate" || attr === "completedDate" || attr === "lastModificationDate") &&
- (privateItems[i][attr])) {
+// SyncServiceInfo
+_c.SyncServiceInfo = {
+ 0: _t.boolean,
+ 1: _t.SyncServiceType,
+ 2: _t.DOMString,
+ 3: _t.DOMString,
+ 4: _t.DOMString,
- itemsStorage[i][attr] = privateItems[i][attr].toString();
- } else if (typeof privateItems[i] !== "function") {
- itemsStorage[i][attr] = privateItems[i][attr];
- }
- }
+ _optional: {
+ 3: true,
+ 4: true
}
-
- return itemsStorage;
};
-module.exports = _self;
+// SyncProfileInfo
+_c.SyncProfileInfo = {
+ 0: _t.DOMString,
+ 1: _t.SyncInfo,
+ 2: [_t.SyncServiceInfo],
+
+ _optional: {
+ 2: true
+ }
+};
-});
-define('ripple/platform/tizen/2.0/callHistory', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
+ * Download
*/
-var utils = require('ripple/utils'),
- db = require('ripple/db'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- _DB_CALL_KEY = "tizen1-db-callhistory",
- _data = {
- observers: {},
- callHistory: []
- },
- _security = {
- "http://tizen.org/privilege/callhistory.read": ["find", "addChangeListener", "removeChangeListener"],
- "http://tizen.org/privilege/callhistory.write": ["remove", "removeBatch", "removeAll"]
- },
- _self;
-
-function _getValue(inputValue, key) {
- var keys = key.split("."),
- value = inputValue[keys[0]],
- index;
+// DownloadRequest
+_c.DownloadRequest = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.DownloadNetworkType,
+ 4: _t.DownloadHTTPHeaderFields,
- for (index = 1; index < keys.length; index++) {
- if (value[keys[index]]) {
- value = value[keys[index]];
- }
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true,
+ 4: true
}
+};
- return value;
-}
+/*
+ * NFC
+ */
-function _filter(inputArray, filter) {
- var index, filterResults = [], compositeResultArray;
+// NDEFMessage
+_c.NDEFMessage[0] = {
+ 0: [_t.NDEFRecord]
+};
- if (filter === null || filter === undefined) {
- return inputArray;
- }
+_c.NDEFMessage[1] = {
+ 0: [_t.byte]
+};
- if (filter.type && filter.filters) {
- filterResults = _filter(inputArray, filter.filters[0]);
- for (index = 1; index < filter.filters.length; index++) {
- compositeResultArray = _filter(inputArray, filter.filters[index]);
+_c.NDEFMessage[2] = null;
- filterResults = tizen1_utils.arrayComposite(filter.type, filterResults, compositeResultArray);
- }
- return filterResults;
- }
+// NDEFRecord
+_c.NDEFRecord[0] = {
+ 0: _t.short,
+ 1: [_t.byte],
+ 2: [_t.byte],
+ 3: [_t.byte],
- if (filter.attributeName === null || filter.attributeName === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ _optional: {
+ 3: true
}
+};
- if (filter.matchFlag) {
- if (filter.attributeName === 'features') {
- filterResults = tizen1_utils.matchAttributeArrayFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
- } else {
- filterResults = tizen1_utils.matchAttributeFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
- }
- }
- else if (filter.initialValue || filter.endValue) {
- filterResults = tizen1_utils.matchAttributeRangeFilter(inputArray, filter.attributeName, filter.initialValue, filter.endValue);
- }
+_c.NDEFRecord[1] = {
+ 0: [_t.byte]
+};
- return filterResults;
-}
+// NDEFRecordText
+_c.NDEFRecordText = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
-function _sort(inputArray, sortMode) {
- if (sortMode.attributeName === null || sortMode.attributeName === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ _optional: {
+ 2: true
}
+};
- inputArray.sort(function (a, b) {
- return sortMode.order === "ASC" ? _getValue(a, sortMode.attributeName) - _getValue(b, sortMode.attributeName) :
- _getValue(b, sortMode.attributeName) - _getValue(a, sortMode.attributeName);
- });
-
- return inputArray;
-}
+// NDEFRecordURI
+_c.NDEFRecordURI = {
+ 0: _t.DOMString
+};
-function _save() {
- db.saveObject(_DB_CALL_KEY, _data.callHistory);
-}
+// NDEFRecordMedia
+_c.NDEFRecordMedia = {
+ 0: _t.DOMString,
+ 1: [_t.byte]
+};
-function _retrieve() {
- var index;
+/*
+ * Notification
+ */
- _data.callHistory = db.retrieveObject(_DB_CALL_KEY) || [];
+// StatusNotification
+_c.StatusNotification = {
+ 0: _t.StatusNotificationType,
+ 1: _t.DOMString,
+ 2: _t.StatusNotificationInit,
- for (index = 0; index < _data.callHistory.length; index++) {
- _data.callHistory[index].startTime = new Date(_data.callHistory[index].startTime);
+ _optional: {
+ 2: true
}
-}
-
-function _isValidCallHistoryEntry(arg) {
- return arg && arg.hasOwnProperty("uid") && arg.hasOwnProperty("type") &&
- arg.hasOwnProperty("features") && arg.hasOwnProperty("remoteParties") &&
- arg.hasOwnProperty("startTime") && arg.hasOwnProperty("duration") &&
- arg.hasOwnProperty("direction");
-}
-
-function _rtnRmtPty(pty) {
- var _remoteParty = pty.remoteParty,
- _personId = pty.personId,
- _self = {};
- _self.__defineGetter__("remoteParty", function () {
- return _remoteParty;
- });
- _self.__defineGetter__("personId", function () {
- return _personId;
- });
- return _self;
-}
+};
-function _rtnEntry(entry) {
- var _uid = entry.uid,
- _type = entry.type,
- _features = tizen1_utils.copy(entry.features),
- _remoteParties = [],
- _startTime = new Date(entry.startTime),
- _duration = entry.duration,
- _direction = entry.direction,
- _self = {}, i;
+// NotificationDetailInfo
+_c.NotificationDetailInfo = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
- for (i = 0; i < entry.remoteParties.length; i++) {
- _remoteParties.push(_rtnRmtPty(entry.remoteParties[i]));
+ _optional: {
+ 1: true
}
- _self.__defineGetter__("uid", function () {
- return _uid;
- });
- _self.__defineGetter__("type", function () {
- return _type;
- });
- _self.__defineGetter__("features", function () {
- return _features;
- });
- _self.__defineGetter__("remoteParties", function () {
- return _remoteParties;
- });
- _self.__defineGetter__("startTime", function () {
- return _startTime;
- });
- _self.__defineGetter__("duration", function () {
- return _duration;
- });
- _self.direction = _direction;
-
- return _self;
-}
-
-function _initialize() {
- _retrieve();
-
- event.on("CallInProgress", function () {
- });
-
- event.on("CallRecorded", function (record) {
- var historyEntry = tizen1_utils.copy(record);
- historyEntry.uid = Math.uuid(8, 16);
+};
- _data.callHistory.push(historyEntry);
- _save();
+/*
+ * Time
+ */
- utils.forEach(_data.observers, function (observer) {
- observer.onadded([historyEntry]);
- });
- });
-}
+// TZDate
+_c.TZDate[0] = {
+ 0: _t.Date,
+ 1: _t.DOMString,
-_self = function () {
- this.find = function (successCallback, errorCallback, filter, sortMode, limit, offset) {
- var i, rtn = [],
- filterResults,
- limitValue = limit | 0,
- offsetValue = offset | 0;
+ _optional: {
+ // nullable
+ 0: true,
+ 1: true
+ }
+};
- if (!_security.find) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_c.TZDate[1] = {
+ 0: _t.long,
+ 1: _t.long,
+ 2: _t.long,
+ 3: _t.long,
+ 4: _t.long,
+ 5: _t.long,
+ 6: _t.long,
+ 7: _t.DOMString,
- t.CallHistory("find", arguments);
+ _optional: {
+ // nullable
+ 3: true,
+ 4: true,
+ 5: true,
+ 6: true,
+ 7: true
+ }
+};
- filterResults = tizen1_utils.copy(_data.callHistory);
- if (filter !== null && filter !== undefined) {
- filterResults = _filter(filterResults, filter);
- }
+// TimeDuration
+_c.TimeDuration = {
+ 0: _t.long_long,
+ 1: _t.TimeDurationUnit,
- if (sortMode !== null && sortMode !== undefined) {
- _sort(filterResults, sortMode);
- }
+ _optional: {
+ // nullable
+ 1: true
+ }
+};
- setTimeout(function () {
- if (limitValue > 0) {
- offsetValue = offsetValue > 0 ? offsetValue : 0;
- filterResults = filterResults.slice(offsetValue, limitValue);
- }
+/*
+ * Interface prototype definition
+ */
- for (i = 0; i < filterResults.length; i++) {
- rtn.push(_rtnEntry(filterResults[i]));
- }
- successCallback(rtn);
- }, 1);
- };
- this.remove = function (entry) {
- var isFound = false, rtn = [];
+_i = {
+ // Alarm
+ AlarmManager: {},
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Application
+ ApplicationManager: {},
+ Application: {},
+ RequestedApplicationControl: {},
- t.CallHistory("remove", arguments);
+ // Bluetooth
+ BluetoothManager: {},
+ BluetoothAdapter: {},
+ BluetoothDevice: {},
+ BluetoothSocket: {},
+ BluetoothClass: {},
+ BluetoothServiceHandler: {},
+ BluetoothHealthProfileHandler: {},
+ BluetoothHealthApplication: {},
+ BluetoothHealthChannel: {},
- _data.callHistory = _data.callHistory.filter(function (element) {
- return utils.some(element, function (value, key) {
- if (tizen1_utils.isEqual(entry[key], value)) {
- isFound = true;
- return false;
- }
- return true;
- });
- });
+ // Bookmark
+ BookmarkManager: {},
- if (!isFound) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+ // Calendar
+ CalendarManager: {},
+ Calendar: {},
+ CalendarItem: {},
+ CalendarEvent: {},
- _save();
- rtn.push(_rtnEntry(entry));
- utils.forEach(_data.observers, function (observer) {
- observer.onchanged(rtn);
- });
+ // Call History
+ CallHistory: {},
- };
- this.removeBatch = function (entries, successCallback, errorCallback) {
- var isFound = false, i, rtn = [];
+ // Contact
+ ContactManager: {},
+ AddressBook: {},
+ Person: {},
+ Contact: {},
- if (!_security.removeBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Content
+ ContentManager: {},
- t.CallHistory("removeBatch", arguments);
+ // Data Control
+ DataControlManager: {},
+ SQLDataControlConsumer: {},
+ MappedDataControlConsumer: {},
- setTimeout(function () {
- isFound = entries.every(function (element) {
- return _data.callHistory.some(function (callHistory) {
- return element.uid === callHistory.uid;
- });
- });
+ // Data Synchronization
+ DataSynchronizationManager: {},
- if (!isFound) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
+ // Download
+ DownloadManager: {},
- _data.callHistory = _data.callHistory.filter(function (element) {
- return !entries.some(function (entryValue, entryIndex) {
- return tizen1_utils.isEqual(element, entryValue);
- });
- });
+ // Network Bearer Selection
+ NetworkBearerSelection: {},
- _save();
+ // NFC
+ NFCManager: {},
+ NFCAdapter: {},
+ NFCTag: {},
+ NFCPeer: {},
+ NDEFMessage: {},
- if (successCallback) {
- successCallback();
- }
- for (i = 0; i < entries.length; i++) {
- rtn.push(_rtnEntry(entries[i]));
- }
- utils.forEach(_data.observers, function (observer) {
- observer.onchanged(rtn);
- });
- }, 1);
- };
- this.removeAll = function (successCallback, errorCallback) {
- var i, rtn = [];
+ // Notification
+ NotificationManager: {},
- if (!_security.removeAll) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Message
+ Messaging: {},
+ MessageService: {},
+ MessageStorage: {},
- t.CallHistory("removeAll", arguments);
+ // Message Port
+ MessagePortManager: {},
+ LocalMessagePort: {},
+ RemoteMessagePort: {},
- for (i = 0; i < _data.callHistory.length; i++) {
- rtn.push(_rtnEntry(_data.callHistory[i]));
- }
+ // Package
+ PackageManager: {},
- _data.callHistory = [];
- _save();
+ // Push
+ PushManager: {},
- utils.forEach(_data.observers, function (observer) {
- observer.onchanged(rtn);
- });
+ // System Info
+ SystemInfo: {},
- if (successCallback) {
- setTimeout(function () {
- successCallback();
- }, 1);
- }
+ // System Setting
+ SystemSettingManager: {},
- };
- this.addChangeListener = function (observerObj) {
- var handle = Number(Math.uuid(8, 10));
+ // Time
+ TimeUtil: {},
+ TZDate: {},
+ TimeDuration: {},
- if (!_security.addChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Vehicle
+ Vehicle: {}
+};
- t.CallHistory("addChangeListener", arguments);
+/*
+ * Alarm
+ */
- _data.observers[handle] = observerObj;
+// AlarmManager
+_i.AlarmManager.add = {
+ 0: _t.Alarm,
+ 1: _t.ApplicationId,
+ 2: _t.ApplicationControl,
- return handle;
- };
- this.removeChangeListener = function (handle) {
- if (!_security.removeChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _optional: {
+ 2: true
+ }
+};
- if (!_data.observers[handle])
- return;
+_i.AlarmManager.remove = {
+ 0: _t.AlarmId
+};
- delete _data.observers[handle];
- };
- this.handleSubFeatures = function (subFeatures) {
- function setSecurity(method) {
- _security[method] = true;
- }
+_i.AlarmManager.removeAll = null;
- for (var subFeature in subFeatures) {
- utils.forEach(_security[subFeature], setSecurity);
- }
- };
+_i.AlarmManager.get = {
+ 0: _t.AlarmId
};
-_initialize();
-
-module.exports = _self;
+_i.AlarmManager.getAll = null;
-});
-define('ripple/platform/tizen/2.0/contact', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
+ * Application
*/
-var db = require('ripple/db'),
- decorator = require('ripple/platform/tizen/2.0/decorator'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- utils = require('ripple/utils'),
- ContactName = require('ripple/platform/tizen/2.0/ContactName'),
- ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
- ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
- ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
- ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
- ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
- ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- AddressBook,
- AddressBookData,
- AddressBookStorage,
- Contact,
- ContactData,
- ContactInternal,
- ContactGroup,
- Person,
- PersonBuilder,
- _data = {
- DB_CONTACT_KEY: "tizen1-contact",
- addressBooks: [],
- contacts: {},
- persons: {},
- contactData: {},
- dbStorage: {}
- },
- _security = {
- "http://tizen.org/privilege/contact.read": ["getAddressBooks",
- "getUnifiedAddressBook", "getDefaultAddressBook",
- "getAddressBook", "get", "find", "addChangeListener",
- "removeChangeListener", "getGroup", "getGroups", "clone"],
- "http://tizen.org/privilege/contact.write": ["add", "addBatch",
- "update", "updateBatch", "remove", "removeBatch", "addGroup",
- "updateGroup", "removeGroup", "link", "unlink"]
- },
- _self;
+// ApplicationManager
+_i.ApplicationManager.getCurrentApplication = null;
-function _get() {
- _data.dbStorage = db.retrieveObject(_data.DB_CONTACT_KEY) ||
- {addressBooks: [], persons: {}};
-}
+_i.ApplicationManager.kill = {
+ 0: _t.ApplicationContextId,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
-function _save() {
- db.saveObject(_data.DB_CONTACT_KEY, _data.dbStorage);
-}
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
-function _serialize(obj) {
- var i, dbObj = {};
+_i.ApplicationManager.launch = {
+ 0: _t.ApplicationId,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- for (i in obj) {
- if (typeof obj[i] !== "function")
- dbObj[i] = utils.copy(obj[i]);
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- return dbObj;
-}
-
-/* check filter type (it's a recursive function)
- 0: It is not a filter
- 1: CompositeFilter
- 2: AttributeFilter
- 3: AttributeRangeFilter
- */
-function _filterType(filter) {
- var i = 0, ret;
+_i.ApplicationManager.launchAppControl = {
+ 0: _t.ApplicationControl,
+ 1: _t.ApplicationId,
+ 2: _t.SuccessCallback,
+ 3: _t.ErrorCallback,
+ 4: _t.ApplicationControlDataArrayReplyCallback,
- if (Object.prototype.toString.call(filter) !== "[object Object]") {
- return 0; // 0: it is not a filter
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true,
+ 4: true
}
+};
- /* check if it is CompositFilter or not */
- if (filter.type !== null && filter.type !== undefined) {
- /* attribute 'type' of CompositeFilter must be "UNION" or "INTERSECTION" */
- if (filter.type === "UNION" || filter.type === "INTERSECTION") {
- /*attribute 'filters' of CompositeFilter must be AbstractFilter array */
- if (tizen1_utils.isValidArray(filter.filters)) {
- for (i = 0; i < filter.filters.length; i++) {
- /* recursive call */
- if (_filterType(filter.filters[i]) === 0) {
- return 0; // 0: it is not a filter
- }
- }
- } else {
- return 0; // 0: it is not a filter
- }
- } else {
- return 0; // 0: it is not a filter
- }
- return 1; // CompositeFilter
- }
+_i.ApplicationManager.findAppControl = {
+ 0: _t.ApplicationControl,
+ 1: _t.FindAppControlSuccessCallback,
+ 2: _t.ErrorCallback,
- /* AttributeFilter or AttributeRangeFilter must have attributeName */
- if (filter.attributeName === null || filter.attributeName === undefined) {
- return 0; // 0: it is not a filter
- } else {
- ret = 2; // assume it is an AttributeFilter
- if ((filter.initialValue !== null && filter.initialValue !== undefined) ||
- (filter.endValue !== null && filter.endValue !== undefined)) {
- ret = 3; // AttributeRangeFilter
- }
- return ret;
+ _optional: {
+ 2: true
}
-}
-
-function _sort(objects, sortMode) {
- function getValue(obj, key) {
- var keys = key.split("."),
- value = obj[keys[0]],
- i;
+};
- for (i = 1; i < keys.length; i++) {
- if (value[keys[i]]) {
- value = value[keys[i]];
- }
- }
+_i.ApplicationManager.getAppsContext = {
+ 0: _t.ApplicationContextArraySuccessCallback,
+ 1: _t.ErrorCallback,
- return value;
+ _optional: {
+ 1: true
}
+};
- objects.sort(function (a, b) {
- return (sortMode.order === "ASC") ?
- (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
- (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
- });
+_i.ApplicationManager.getAppContext = {
+ 0: _t.ApplicationContextId,
- return objects;
-}
+ _optional: {
+ 0: true
+ }
+};
-function _replacePerson(oldId, newId) {
- var contact, dbAddressBook, idab, idc, i;
+_i.ApplicationManager.getAppsInfo = {
+ 0: _t.ApplicationInformationArraySuccessCallback,
+ 1: _t.ErrorCallback,
- for (idab in _data.contacts) {
- for (idc in _data.contacts[idab]) {
- contact = _data.contacts[idab][idc];
- if (contact.personId === oldId) {
- if (newId === null) {
- delete _data.contacts[idab][idc];
- } else {
- contact.personId = newId;
- }
- }
- }
+ _optional: {
+ 1: true
}
+};
- if (_data.persons[oldId]) {
- delete _data.persons[oldId];
+_i.ApplicationManager.getAppInfo = {
+ 0: _t.ApplicationId,
+
+ _optional: {
+ 0: true
}
+};
- for (i in _data.dbStorage.addressBooks) {
- dbAddressBook = _data.dbStorage.addressBooks[i];
- for (idc in dbAddressBook.contacts) {
- contact = dbAddressBook.contacts[idc];
- if (contact.personId === oldId) {
- if (newId === null) {
- delete dbAddressBook.contacts[idc];
- } else {
- contact.personId = newId;
- }
- }
- }
+_i.ApplicationManager.getAppCerts = {
+ 0: _t.ApplicationId,
+
+ _optional: {
+ 0: true
}
+};
- if (_data.dbStorage.persons[oldId]) {
- delete _data.dbStorage.persons[oldId];
+_i.ApplicationManager.getAppSharedURI = {
+ 0: _t.ApplicationId,
+
+ _optional: {
+ 0: true
}
-}
+};
-_self = function () {
- var contact;
+_i.ApplicationManager.getAppMetaData = {
+ 0: _t.ApplicationId,
- // private
- function loadAddressBooks() {
- var i;
+ _optional: {
+ 0: true
+ }
+};
- _get();
+_i.ApplicationManager.addAppInfoEventListener = {
+ 0: _t.ApplicationInformationEventCallback
+};
- if (_data.dbStorage.addressBooks.length === 0) {
- // Initialize default address books if database is empty
- _data.dbStorage.addressBooks = [
- new AddressBookStorage(Math.uuid(null, 16), "Phone address book", false, {}, []),
- new AddressBookStorage(Math.uuid(null, 16), "SIM address book", false, {}, [])
- ];
- }
+_i.ApplicationManager.removeAppInfoEventListener = {
+ 0: _t.long
+};
- utils.forEach(_data.dbStorage.addressBooks, function (addressBook) {
- _data.addressBooks.push(new AddressBook(addressBook.id, addressBook.name,
- addressBook.readOnly, addressBook.contacts, addressBook.groups));
- });
+// Application
+_i.Application.exit = null;
+_i.Application.hide = null;
+_i.Application.getRequestedAppControl = null;
- for (i in _data.dbStorage.persons) {
- _data.persons[i] = new Person(_data.dbStorage.persons[i]);
- }
+// RequestedApplicationControl
+_i.RequestedApplicationControl.replyResult = {
+ 0: [_t.ApplicationControlData],
+
+ _optional: {
+ 0: true
}
+};
- // public
- // Address Book Methods
- function getAddressBooks(successCallback, errorCallback) {
- if (!_security.getAddressBooks) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.RequestedApplicationControl.replyFailure = null;
- t.ContactManager("getAddressBooks", arguments);
+/*
+ * Bluetooth
+ */
- window.setTimeout(function () {
- if (_data.addressBooks.length === 0) {
- loadAddressBooks();
- }
- successCallback(_data.addressBooks);
- }, 1);
+// BluetoothManager
+_i.BluetoothManager.getDefaultAdapter = null;
+
+// BluetoothAdapter
+_i.BluetoothAdapter.setName = {
+ 0: _t.DOMString,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function getUnifiedAddressBook() {
- if (!_security.getUnifiedAddressBook) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (_data.addressBooks.length === 0) {
- loadAddressBooks();
- }
- return _data.addressBooks[0];
+_i.BluetoothAdapter.setPowered = {
+ 0: _t.boolean,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function getDefaultAddressBook() {
- if (!_security.getDefaultAddressBook) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (_data.addressBooks.length === 0) {
- loadAddressBooks();
- }
- return _data.addressBooks[0];
+_i.BluetoothAdapter.setVisible = {
+ 0: _t.boolean,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+ 3: _t.unsigned_short,
+
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true
}
+};
- function getAddressBook(addressBookId) {
- var i;
+_i.BluetoothAdapter.setChangeListener = {
+ 0: _t.BluetoothAdapterChangeCallback
+};
+
+_i.BluetoothAdapter.unsetChangeListener = null;
+
+_i.BluetoothAdapter.discoverDevices = {
+ 0: _t.BluetoothDiscoverDevicesSuccessCallback,
+ 1: _t.ErrorCallback,
+
+ _optional: {
+ 1: true
+ }
+};
- if (!_security.getAddressBook) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.BluetoothAdapter.stopDiscovery = {
+ 0: _t.SuccessCallback,
+ 1: _t.ErrorCallback,
- t.ContactManager("getAddressBook", arguments);
+ _optional: {
+ 0: true,
+ 1: true
+ }
+};
- if (_data.addressBooks.length === 0) {
- loadAddressBooks();
- }
- for (i in _data.addressBooks) {
- if (_data.addressBooks[i].id === addressBookId) {
- return _data.addressBooks[i];
- }
- }
+_i.BluetoothAdapter.getKnownDevices = {
+ 0: _t.BluetoothDeviceArraySuccessCallback,
+ 1: _t.ErrorCallback,
- /* Cannot found */
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ _optional: {
+ 1: true
}
+};
- // Person Methods
- function get(personId) {
- if (!_security.get) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.BluetoothAdapter.getDevice = {
+ 0: _t.BluetoothAddress,
+ 1: _t.BluetoothDeviceSuccessCallback,
+ 2: _t.ErrorCallback,
- t.ContactManager("get", arguments);
+ _optional: {
+ 2: true
+ }
+};
- if (_data.persons[personId] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+_i.BluetoothAdapter.createBonding = {
+ 0: _t.BluetoothAddress,
+ 1: _t.BluetoothDeviceSuccessCallback,
+ 2: _t.ErrorCallback,
- return new Person(_data.persons[personId]);
+ _optional: {
+ 2: true
}
+};
- function update(person) {
- var updated;
+_i.BluetoothAdapter.destroyBonding = {
+ 0: _t.BluetoothAddress,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- t.ContactManager("update", arguments);
+_i.BluetoothAdapter.registerRFCOMMServiceByUUID = {
+ 0: _t.BluetoothUUID,
+ 1: _t.DOMString,
+ 2: _t.BluetoothServiceSuccessCallback,
+ 3: _t.ErrorCallback,
- if (!person.id) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- if (_data.persons[person.id] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+ _optional: {
+ 3: true
+ }
+};
- updated = new Person(person);
+_i.BluetoothAdapter.getBluetoothProfileHandler = {
+ 0: _t.BluetoothProfileType
+};
- _data.persons[updated.id] = updated;
- _data.dbStorage.persons[updated.id] = _serialize(updated);
- _save();
+// BluetoothDevice
+_i.BluetoothDevice.connectToServiceByUUID = {
+ 0: _t.BluetoothUUID,
+ 1: _t.BluetoothSocketSuccessCallback,
+ 2: _t.ErrorCallback,
- window.setTimeout(function () {
- utils.forEach(_data.contactData.listeners, function (listener) {
- listener.onpersonsupdated([new Person(updated)]);
- });
- }, 1);
+ _optional: {
+ 2: true
}
+};
- function updateBatch(persons, successCallback, errorCallback) {
- if (!_security.updateBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.ContactManager("updateBatch", arguments, true);
+// BluetoothSocket
+_i.BluetoothSocket.readData = null;
+_i.BluetoothSocket.close = null;
- window.setTimeout(function () {
- var i, updated;
+_i.BluetoothSocket.writeData = {
+ 0: [_t.byte]
+};
- if (persons.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+// BluetoothClass
+_i.BluetoothClass.hasService = {
+ 0: _t.unsigned_short
+};
- for (i in persons) {
- if (!persons[i].id) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- if (_data.persons[persons[i].id] === undefined) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
- for (i in persons) {
- updated = new Person(persons[i]);
+// BluetoothServiceHandler
+_i.BluetoothServiceHandler.unregister = {
+ 0: _t.SuccessCallback,
+ 1: _t.ErrorCallback,
- _data.persons[updated.id] = updated;
- _data.dbStorage.persons[updated.id] = _serialize(updated);
- }
- _save();
- if (successCallback) {
- successCallback();
- }
+ _optional: {
+ 0: true,
+ 1: true
+ }
+};
- utils.forEach(_data.contactData.listeners, function (listener) {
- var i, watched = [];
+// BluetoothHealthProfileHandler
+_i.BluetoothHealthProfileHandler.registerSinkApplication = {
+ 0: _t.unsigned_short,
+ 1: _t.DOMString,
+ 2: _t.BluetoothHealthApplicationSuccessCallback,
+ 3: _t.ErrorCallback,
- for (i in persons) {
- watched.push(new Person(_data.persons[persons[i].id]));
- }
- listener.onpersonsupdated(watched);
- });
- }, 1);
+ _optional: {
+ 3: true
}
+};
- function remove(personId) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.BluetoothHealthProfileHandler.connectToSource = {
+ 0: _t.BluetoothDevice,
+ 1: _t.BluetoothHealthApplication,
+ 2: _t.BluetoothHealthChannelSuccessCallback,
+ 3: _t.ErrorCallback,
- t.ContactManager("remove", arguments);
+ _optional: {
+ 3: true
+ }
+};
- if (_data.persons[personId] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- _replacePerson(personId, null);
- _save();
+// BluetoothHealthApplication
+_i.BluetoothHealthApplication.unregister = {
+ 0: _t.SuccessCallback,
+ 1: _t.ErrorCallback,
- window.setTimeout(function () {
- utils.forEach(_data.contactData.listeners, function (listener) {
- listener.onpersonsremoved([personId]);
- });
- }, 1);
+ _optional: {
+ 0: true,
+ 1: true
}
+};
- function removeBatch(personIds, successCallback, errorCallback) {
- if (!_security.removeBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// BluetoothHealthChannel
+_i.BluetoothHealthChannel.close = null;
+_i.BluetoothHealthChannel.unsetListener = null;
- t.ContactManager("removeBatch", arguments, true);
+_i.BluetoothHealthChannel.sendData = {
+ 0: [_t.byte]
+};
- window.setTimeout(function () {
- var i;
+_i.BluetoothHealthChannel.setListener = {
+ 0: _t.BluetoothHealthChannelChangeCallback
+};
- if (personIds.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+/*
+ * Bookmark
+ */
- for (i in personIds) {
- if (!personIds[i]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- if (_data.persons[personIds[i]] === undefined) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
- for (i in personIds) {
- _replacePerson(personIds[i], null);
- }
- _save();
- if (successCallback) {
- successCallback();
- }
+// BookmarkManager
+_i.BookmarkManager.get = {
+ 0: _t.BookmarkFolder,
+ 1: _t.boolean,
- utils.forEach(_data.contactData.listeners, function (listener) {
- listener.onpersonsremoved(utils.copy(personIds));
- });
- }, 1);
+ _optional: {
+ 0: true,
+ 1: true
}
+};
- function find(successCallback, errorCallback, filter, sortMode) {
- if (!_security.find) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.BookmarkManager.add = {
+ 0: _t.Bookmark,
+ 1: _t.BookmarkFolder,
- t.ContactManager("find", arguments, true);
+ _optional: {
+ 1: true
+ }
+};
- window.setTimeout(function () {
- var i, matched = [], result = [];
+_i.BookmarkManager.remove = {
+ 0: _t.Bookmark,
- if (filter) {
- switch (_filterType(filter)) {
- case 0:
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
+ _optional: {
+ 0: true
+ }
+};
- case 1:
- //TODO:
- //"compositeFilter doesn't support"
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
- }
- return;
+/*
+ * Calendar
+ */
- case 2:
- case 3:
- break;
- }
- }
+// CalendarManager
+_i.CalendarManager.getCalendars = {
+ 0: _t.CalendarType,
+ 1: _t.CalendarArraySuccessCallback,
+ 2: _t.ErrorCallback,
- if (filter === null || filter === undefined) {
- utils.forEach(_data.persons, function (person) {
- matched.push(person);
- });
- } else {
- switch (filter.attributeName) {
- case "id":
- case "displayName":
- case "photoURI":
- case "ringtoneURI":
- case "displayContactId":
- matched = tizen1_utils.matchAttributeFilter(_data.persons,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
+ _optional: {
+ 2: true
+ }
+};
- case "contactCount":
- if ((filter.matchFlag !== "EXACTLY") ||
- (typeof filter.matchValue !== "number")) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- matched = tizen1_utils.matchAttributeFilter(_data.persons,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
+_i.CalendarManager.getUnifiedCalendar = {
+ 0: _t.CalendarType
+};
- case "hasPhoneNumber":
- case "hasEmail":
- case "isFavorite":
- if ((filter.matchFlag !== "EXACTLY") ||
- (typeof filter.matchValue !== "boolean")) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- matched = tizen1_utils.matchAttributeBooleanFilter(_data.persons,
- filter.attributeName, filter.matchValue);
- break;
+_i.CalendarManager.getDefaultCalendar = {
+ 0: _t.CalendarType
+};
- default:
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- }
+_i.CalendarManager.getCalendar = {
+ 0: _t.CalendarType,
+ 1: _t.CalendarId
+};
- if (sortMode) {
- _sort(matched, sortMode);
- }
+// Calendar
+_i.Calendar.get = {
+ 0: _t.CalendarItemId
+};
- for (i in matched) {
- result.push(new Person(matched[i]));
- }
+_i.Calendar.add = {
+ 0: _t.CalendarItem
+};
- successCallback(result);
- }, 1);
- }
+_i.Calendar.addBatch = {
+ 0: [_t.CalendarItem],
+ 1: _t.CalendarItemArraySuccessCallback,
+ 2: _t.ErrorCallback,
- function addChangeListener(successCallback) {
- var id;
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- if (!_security.addChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.Calendar.update = {
+ 0: _t.CalendarItem,
+ 1: _t.boolean,
- t.ContactManager("addChangeListener", arguments);
+ _optional: {
+ 1: true
+ }
+};
- id = ++_data.contactData.nListener;
- _data.contactData.listeners[id] = successCallback;
+_i.Calendar.updateBatch = {
+ 0: [_t.CalendarItem],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+ 3: _t.boolean,
- return id;
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true
}
+};
- function removeChangeListener(watchId) {
- if (!_security.removeChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.Calendar.remove = {
+ 0: _t.CalendarItemId
+};
- if (!_data.contactData.listeners[watchId])
- return;
+_i.Calendar.removeBatch = {
+ 0: [_t.CalendarItemId],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- delete _data.contactData.listeners[watchId];
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+_i.Calendar.find = {
+ 0: _t.CalendarItemArraySuccessCallback,
+ 1: _t.ErrorCallback,
+ 2: _t.AbstractFilter,
+ 3: _t.SortMode,
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true
}
+};
- _data.contactData = new ContactData();
-
- contact = {
- getAddressBooks: getAddressBooks,
- getUnifiedAddressBook: getUnifiedAddressBook,
- getDefaultAddressBook: getDefaultAddressBook,
- getAddressBook: getAddressBook,
-
- get: get,
- update: update,
- updateBatch: updateBatch,
- remove: remove,
- removeBatch: removeBatch,
- find: find,
- addChangeListener: addChangeListener,
- removeChangeListener: removeChangeListener,
- handleSubFeatures: handleSubFeatures
- };
+_i.Calendar.addChangeListener = {
+ 0: _t.CalendarChangeCallback
+};
- return contact;
+_i.Calendar.removeChangeListener = {
+ 0: _t.long
};
-AddressBook = function (id, name, readOnly, dbContacts, dbGroups) {
- var addressBook,
- privateData = new AddressBookData(dbContacts, dbGroups);
+// CalendarItem
+_i.CalendarItem.convertToString = {
+ 0: _t.CalendarTextFormat
+};
- // private
- function addNewContact(contact, external) {
- var added, person;
+_i.CalendarItem.clone = null;
- added = new ContactInternal(contact);
- privateData.contacts[added.id] = added;
+// CalendarEvent
+_i.CalendarEvent.expandRecurrence = {
+ 0: _t.TZDate,
+ 1: _t.TZDate,
+ 2: _t.CalendarEventArraySuccessCallback,
+ 3: _t.ErrorCallback,
- person = new PersonBuilder(added);
- _data.persons[person.id] = person;
+ _optional: {
+ 3: true
+ }
+};
- added.personId = person.id;
- added.addressBookId = id;
+/*
+ * Call History
+ */
- dbContacts[added.id] = _serialize(added);
- _data.dbStorage.persons[person.id] = _serialize(_data.persons[person.id]);
+// CallHistory
+_i.CallHistory.find = {
+ 0: _t.CallHistoryEntryArraySuccessCallback,
+ 1: _t.ErrorCallback,
+ 2: _t.AbstractFilter,
+ 3: _t.SortMode,
+ 4: _t.unsigned_long,
+ 5: _t.unsigned_long,
- decorator.Contact(external, added);
+ _optional: {
+ // nullable
+ 1: true,
+ 2: true,
+ 3: true,
+ 4: true,
+ 5: true
}
+};
- // public
- function get(id) {
- if (!_security.get) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.CallHistory.remove = {
+ 0: _t.CallHistoryEntry
+};
- t.AddressBook("get", arguments);
+_i.CallHistory.removeBatch = {
+ 0: [_t.CallHistoryEntry],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- if (privateData.contacts[id] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- return new Contact(privateData.contacts[id]);
+ _optional: {
+ // nullable
+ 1: true,
+ 2: true
}
+};
- function add(contact) {
- var external = contact;
+_i.CallHistory.removeAll = {
+ 0: _t.SuccessCallback,
+ 1: _t.ErrorCallback,
- if (!_security.add) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ _optional: {
+ // nullable
+ 0: true,
+ 1: true
+ }
+};
- t.AddressBook("add", arguments, true);
+_i.CallHistory.addChangeListener = {
+ 0: _t.CallHistoryChangeCallback
+};
- addNewContact(contact, external);
- _save();
+_i.CallHistory.removeChangeListener = {
+ 0: _t.long
+};
- window.setTimeout(function () {
- utils.forEach(privateData.listeners, function (listener) {
- listener.oncontactsadded([new Contact(external)]);
- });
- utils.forEach(_data.contactData.listeners, function (listener) {
- listener.onpersonsadded([new Person(_data.persons[external.personId])]);
- });
- }, 1);
- }
+/*
+ * Contact
+ */
- function addBatch(contacts, successCallback, errorCallback) {
- var external = contacts;
- if (!_security.addBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// ContactManager
+_i.ContactManager.getAddressBooks = {
+ 0: _t.AddressBookArraySuccessCallback,
+ 1: _t.ErrorCallback,
- t.AddressBook("addBatch", arguments, true);
+ _optional: {
+ 1: true
+ }
+};
- window.setTimeout(function () {
- var i, personIds = [];
+_i.ContactManager.getUnifiedAddressBook = null;
+_i.ContactManager.getDefaultAddressBook = null;
- if (contacts.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+_i.ContactManager.getAddressBook = {
+ 0: _t.AddressBookId
+};
- for (i in contacts) {
- addNewContact(contacts[i], external[i]);
- personIds.push(external[i].personId);
- }
- _save();
- if (successCallback) {
- successCallback(external);
- }
+_i.ContactManager.get = {
+ 0: _t.PersonId
+};
- utils.forEach(privateData.listeners, function (listener) {
- var i, watched = [];
+_i.ContactManager.update = {
+ 0: _t.Person
+};
- for (i in contacts) {
- watched.push(new Contact(external[i]));
- }
- listener.oncontactsadded(watched);
- });
- utils.forEach(_data.contactData.listeners, function (listener) {
- var i, watched = [];
+_i.ContactManager.updateBatch = {
+ 0: [_t.Person],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- for (i in personIds) {
- watched.push(new Person(_data.persons[personIds[i]]));
- }
- listener.onpersonsadded(watched);
- });
- }, 1);
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function update(contact) {
- var updated;
-
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.AddressBook("update", arguments);
+_i.ContactManager.remove = {
+ 0: _t.PersonId
+};
- if (!contact.id) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- if (privateData.contacts[contact.id] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+_i.ContactManager.removeBatch = {
+ 0: [_t.PersonId],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- updated = new ContactInternal(contact);
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- privateData.contacts[updated.id] = updated;
- dbContacts[updated.id] = _serialize(updated);
- _save();
+_i.ContactManager.find = {
+ 0: _t.PersonArraySuccessCallback,
+ 1: _t.ErrorCallback,
+ 2: _t.AbstractFilter,
+ 3: _t.SortMode,
- window.setTimeout(function () {
- utils.forEach(privateData.listeners, function (listener) {
- listener.oncontactsupdated([new Contact(updated)]);
- });
- }, 1);
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true
}
+};
- function updateBatch(contacts, successCallback, errorCallback) {
- if (!_security.updateBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.ContactManager.addChangeListener = {
+ 0: _t.PersonsChangeCallback
+};
- t.AddressBook("updateBatch", arguments, true);
+_i.ContactManager.removeChangeListener = {
+ 0: _t.long
+};
- window.setTimeout(function () {
- var i, updated;
+// AddressBook
+_i.AddressBook.get = {
+ 0: _t.ContactId
+};
- if (contacts.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+_i.AddressBook.add = {
+ 0: _t.Contact
+};
- for (i in contacts) {
- if (!contacts[i].id) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- if (privateData.contacts[contacts[i].id] === undefined) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
- for (i in contacts) {
- updated = new ContactInternal(contacts[i]);
+_i.AddressBook.addBatch = {
+ 0: [_t.Contact],
+ 1: _t.ContactArraySuccessCallback,
+ 2: _t.ErrorCallback,
- privateData.contacts[updated.id] = updated;
- dbContacts[updated.id] = _serialize(updated);
- }
- _save();
- if (successCallback) {
- successCallback();
- }
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- utils.forEach(privateData.listeners, function (listener) {
- var i, watched = [];
+_i.AddressBook.update = {
+ 0: _t.Contact
+};
- for (i in contacts) {
- watched.push(new Contact(
- privateData.contacts[contacts[i].id]));
- }
- listener.oncontactsupdated(watched);
- });
- }, 1);
+_i.AddressBook.updateBatch = {
+ 0: [_t.Contact],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- function remove(id) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.AddressBook.remove = {
+ 0: _t.ContactId
+};
- t.AddressBook("remove", arguments);
+_i.AddressBook.removeBatch = {
+ 0: [_t.ContactId],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- if (privateData.contacts[id] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- delete privateData.contacts[id];
- if (dbContacts[id]) {
- delete dbContacts[id];
- }
- _save();
+_i.AddressBook.find = {
+ 0: _t.ContactArraySuccessCallback,
+ 1: _t.ErrorCallback,
+ 2: _t.AbstractFilter,
+ 3: _t.SortMode,
- window.setTimeout(function () {
- utils.forEach(privateData.listeners, function (listener) {
- listener.oncontactsremoved([id]);
- });
- }, 1);
+ _optional:{
+ 1: true,
+ 2: true,
+ 3: true
}
+};
- function removeBatch(ids, successCallback, errorCallback) {
- if (!_security.removeBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- if (addressBook.readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.AddressBook.addChangeListener = {
+ 0: _t.AddressBookChangeCallback,
+ 1: _t.ErrorCallback,
- t.AddressBook("removeBatch", arguments, true);
+ _optional: {
+ 1: true
+ }
+};
- window.setTimeout(function () {
- var i;
+_i.AddressBook.removeChangeListener = {
+ 0: _t.long
+};
- if (ids.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+_i.AddressBook.getGroup = {
+ 0: _t.ContactGroupId
+};
- for (i in ids) {
- if (!ids[i]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- if (privateData.contacts[ids[i]] === undefined) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- }
- for (i in ids) {
- delete privateData.contacts[ids[i]];
- if (dbContacts[ids[i]]) {
- delete dbContacts[ids[i]];
- }
- }
- _save();
- if (successCallback) {
- successCallback();
- }
+_i.AddressBook.addGroup = {
+ 0: _t.ContactGroup
+};
- utils.forEach(privateData.listeners, function (listener) {
- listener.oncontactsremoved(utils.copy(ids));
- });
- }, 1);
- }
+_i.AddressBook.updateGroup = {
+ 0: _t.ContactGroup
+};
- function find(successCallback, errorCallback, filter, sortMode) {
- if (!_security.find) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.AddressBook.removeGroup = {
+ 0: _t.ContactGroupId
+};
- t.AddressBook("find", arguments, true);
+_i.AddressBook.getGroups = null;
- window.setTimeout(function () {
- var result = [], begin, end, i, atr, _re, errFlag = false,
- _rangeMatch, low, high, matched, _existMatch, _arrayMatch;
+// Person
+_i.Person.link = {
+ 0: _t.PersonId
+};
- if (filter) {
- switch (_filterType(filter)) {
- case 0:
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
+_i.Person.unlink = {
+ 0: _t.ContactId
+};
- case 1:
- //TODO:
- //"compositeFilter doesn't support"
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
- }
- return;
+// Contact
+_i.Contact.convertToString = {
+ 0: _t.ContactTextFormat,
- case 2:
- case 3:
- break;
- }
- }
+ _optional: {
+ 0: true
+ }
+};
- /* return all contacts if no filter argument */
- if (filter === null || filter === undefined) {
- utils.forEach(privateData.contacts, function (contact) {
- result.push(new Contact(contact));
- });
+_i.Contact.clone = null;
- successCallback(result);
- return;
- }
+/*
+ * Content
+ */
- /* check composition of filter.attributeName */
- switch (filter.attributeName) {
- case "id" :
- case "personId" :
- case "addressBookId" :
- case "name.prefix" :
- case "name.suffix" :
- case "name.firstName" :
- case "name.middleName" :
- case "name.lastName" :
- case "name.phoneticFirstName" :
- case "name.phoneticLastName" :
- case "name.displayName" :
- case "account.accountServiceId" :
- case "account.contactURI" :
- case "photoURI" :
- case "ringtoneURI" :
- matched = tizen1_utils.matchAttributeFilter(privateData.contacts,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
+// ContentManager
+_i.ContentManager.update = {
+ 0: _t.Content
+};
- case "name.nicknames" :
- case "notes" :
- case "groupIds" :
- matched = tizen1_utils.matchAttributeArrayFilter(privateData.contacts,
- filter.attributeName, filter.matchFlag, filter.matchValue);
- break;
+_i.ContentManager.updateBatch = {
+ 0: [_t.Content],
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- case "addresses.country" :
- case "addresses.region" :
- case "addresses.city" :
- case "addresses.streetAddress" :
- case "addresses.additionalInformation" :
- case "addresses.postalCode" :
- case "phoneNumbers.number" :
- case "emails.email" :
- case "anniversaries.label" :
- case "organizations.name" :
- case "organizations.department" :
- case "organizations.title" :
- case "organizations.role" :
- case "organizations.logoURI" :
- case "urls.url" :
- case "urls.type" :
- atr = filter.attributeName.split(".");
- _existMatch = function (obj) {
- return (obj[atr[0]] !== undefined);
- };
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
- matched = utils.filter(privateData.contacts, _existMatch);
- break;
- }
+_i.ContentManager.getDirectories = {
+ 0: _t.ContentDirectoryArraySuccessCallback,
+ 1: _t.ErrorCallback,
+
+ _optional: {
+ 1: true
+ }
+};
- errFlag = false;
+_i.ContentManager.find = {
+ 0: _t.ContentArraySuccessCallback,
+ 1: _t.ErrorCallback,
+ 2: _t.ContentDirectoryId,
+ 3: _t.AbstractFilter,
+ 4: _t.SortMode,
+ 5: _t.unsigned_long,
+ 6: _t.unsigned_long,
- switch (filter.matchFlag)
- {
- case "EXACTLY":
- _re = new RegExp("^" + filter.matchValue + "$");
- break;
- case "FULLSTRING":
- _re = new RegExp("^" + filter.matchValue + "$", "i");
- break;
- case "CONTAINS":
- _re = new RegExp(filter.matchValue, "i");
- break;
- case "STARTSWITH":
- _re = new RegExp("^" + filter.matchValue, "i");
- break;
- case "ENDSWITH":
- _re = new RegExp(filter.matchValue + "$", "i");
- break;
- default:
- errFlag = true;
- }
+ _optional: {
+ 1: true,
+ 2: true,
+ 3: true,
+ 4: true,
+ 5: true,
+ 6: true
+ }
+};
- if (errFlag) {
- matched = [];
- break;
- }
+_i.ContentManager.scanFile = {
+ 0: _t.DOMString,
+ 1: _t.ContentScanSuccessCallback,
+ 2: _t.ErrorCallback,
- _arrayMatch = function (obj) {
- return (obj[atr[0]].some(function (o) {
- if (typeof o[atr[1]] !== "string") {
- return false;
- } else {
- return (o[atr[1]].search(_re) !== -1);
- }
- }));
- };
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- matched = utils.filter(privateData.contacts, _arrayMatch);
- break;
+_i.ContentManager.setChangeListener = {
+ 0: _t.ContentChangeCallback
+};
- case "addresses.types" :
- case "phoneNumbers.types" :
- case "emails.types" :
- atr = filter.attributeName.split(".");
- _existMatch = function (obj) {
- return (obj[atr[0]].some(function (o) {
- return (o[atr[1]] !== undefined);
- }));
- };
+_i.ContentManager.unsetChangeListener = null;
- if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
- matched = utils.filter(privateData.contacts, _existMatch);
- break;
- }
+/*
+ * Data Control
+ */
- errFlag = false;
+// DataControlManager
+_i.DataControlManager.getDataControlConsumer = {
+ 0: _t.DOMString,
+ 1: _t.DOMString,
+ 2: _t.DataType
+};
- switch (filter.matchFlag) {
- case "EXACTLY":
- _re = new RegExp("^" + filter.matchValue + "$");
- break;
- case "FULLSTRING":
- _re = new RegExp("^" + filter.matchValue + "$", "i");
- break;
- case "CONTAINS":
- _re = new RegExp(filter.matchValue, "i");
- break;
- case "STARTSWITH":
- _re = new RegExp("^" + filter.matchValue, "i");
- break;
- case "ENDSWITH":
- _re = new RegExp(filter.matchValue + "$", "i");
- break;
- default:
- errFlag = true;
- }
+// SQLDataControlConsumer
+_i.SQLDataControlConsumer.insert = {
+ 0: _t.unsigned_long,
+ 1: _t.RowData,
+ 2: _t.DataControlInsertSuccessCallback,
+ 3: _t.DataControlErrorCallback,
- if (errFlag) {
- matched = [];
- break;
- }
+ _optional: {
+ 2: true,
+ 3: true
+ }
+};
- _arrayMatch = function (obj) {
- return (obj[atr[0]].some(function (o) {
- if (!tizen1_utils.isValidArray(o[atr[1]])) {
- return false;
- } else {
- return (o[atr[1]].some(function (t) {
- return (t.search(_re) !== -1);
- }));
- }
- }));
- };
+_i.SQLDataControlConsumer.update = {
+ 0: _t.unsigned_long,
+ 1: _t.RowData,
+ 2: _t.DOMString,
+ 3: _t.DataControlSuccessCallback,
+ 4: _t.DataControlErrorCallback,
- matched = utils.filter(privateData.contacts, _arrayMatch);
- break;
+ _optional: {
+ 3: true,
+ 4: true
+ }
+};
- case "anniversaries.date" :
- low = filter.initialValue;
- high = filter.endValue;
- atr = filter.attributeName.split(".");
+_i.SQLDataControlConsumer.remove = {
+ 0: _t.unsigned_long,
+ 1: _t.DOMString,
+ 2: _t.DataControlSuccessCallback,
+ 3: _t.DataControlErrorCallback,
- _rangeMatch = function (obj) {
- var isMatched = true;
- if (low !== null && low !== undefined) {
- if (!tizen1_utils.isValidArray(obj[atr[0]])) {
- isMatched = false;
- } else {
- isMatched = (obj[atr[0]].some(function (o) {
- return (o[atr[1]] >= low);
- }));
- }
- }
- if (isMatched && (high !== null && high !== undefined)) {
- if (!tizen1_utils.isValidArray(obj[atr[0]])) {
- isMatched = false;
- } else {
- isMatched = (obj[atr[0]].some(function (o) {
- return (o[atr[1]] <= high);
- }));
- }
- }
- return isMatched;
- };
+ _optional: {
+ 2: true,
+ 3: true
+ }
+};
- matched = utils.filter(privateData.contacts, _rangeMatch);
- break;
+_i.SQLDataControlConsumer.select = {
+ 0: _t.unsigned_long,
+ 1: [_t.DOMString],
+ 2: _t.DOMString,
+ 3: _t.DataControlSelectSuccessCallback,
+ 4: _t.DataControlErrorCallback,
+ 5: _t.unsigned_long,
+ 6: _t.unsigned_long,
- case "addresses.isDefault" :
- case "phoneNumbers.isDefault" :
- case "emails.isDefault" :
- break;
+ _optional: {
+ 4: true,
+ 5: true,
+ 6: true
+ }
+};
- case "isFavorite" :
- if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- } else {
- matched = tizen1_utils.matchAttributeBooleanFilter(privateData.contacts,
- filter.attributeName, filter.matchValue);
- }
- break;
+// MappedDataControlConsumer
+_i.MappedDataControlConsumer.addValue = {
+ 0: _t.unsigned_long,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.DataControlSuccessCallback,
+ 4: _t.DataControlErrorCallback,
- case "birthday" :
- begin = filter.initialValue;
- end = filter.endValue;
+ _optional: {
+ 3: true,
+ 4: true
+ }
+};
- matched = tizen1_utils.matchAttributeRangeFilter(privateData.contacts,
- filter.attributeName, begin, end);
- break;
+_i.MappedDataControlConsumer.removeValue = {
+ 0: _t.unsigned_long,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.DataControlSuccessCallback,
+ 4: _t.DataControlErrorCallback,
- default:
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+ _optional: {
+ 4: true
+ }
+};
- if (sortMode) {
- _sort(matched, sortMode);
- }
+_i.MappedDataControlConsumer.getValue = {
+ 0: _t.unsigned_long,
+ 1: _t.DOMString,
+ 2: _t.DataControlGetValueSuccessCallback,
+ 3: _t.DataControlErrorCallback,
- for (i in matched) {
- result.push(new Contact(matched[i]));
- }
+ _optional: {
+ 3: true
+ }
+};
- successCallback(result);
- }, 1);
+_i.MappedDataControlConsumer.updateValue = {
+ 0: _t.unsigned_long,
+ 1: _t.DOMString,
+ 2: _t.DOMString,
+ 3: _t.DOMString,
+ 4: _t.DataControlSuccessCallback,
+ 5: _t.DataControlErrorCallback,
+
+ _optional: {
+ 5: true
}
+};
- function addChangeListener(successCallback, errorCallback) {
- var id;
+/*
+ * Data Synchronization
+ */
- if (!_security.addChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// DataSynchronizationManager
+_i.DataSynchronizationManager.getMaxProfilesNum = null;
+_i.DataSynchronizationManager.getProfilesNum = null;
+_i.DataSynchronizationManager.getAll = null;
- t.AddressBook("addChangeListener", arguments);
+_i.DataSynchronizationManager.add = {
+ 0: _t.SyncProfileInfo
+};
- id = ++privateData.nListener;
- privateData.listeners[id] = successCallback;
+_i.DataSynchronizationManager.update = {
+ 0: _t.SyncProfileInfo
+};
- return id;
- }
+_i.DataSynchronizationManager.remove = {
+ 0: _t.SyncProfileId
+};
- function removeChangeListener(watchId) {
- if (!_security.removeChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.DataSynchronizationManager.get = {
+ 0: _t.SyncProfileId
+};
- if (!privateData.listeners[watchId])
- return;
+_i.DataSynchronizationManager.startSync = {
+ 0: _t.SyncProfileId,
+ 1: _t.SyncProgressCallback,
- delete privateData.listeners[watchId];
+ _optional: {
+ 1: true
}
+};
- function getGroup(groupId) {
- var i;
+_i.DataSynchronizationManager.stopSync = {
+ 0: _t.SyncProfileId
+};
- if (!_security.getGroup) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.DataSynchronizationManager.getLastSyncStatistics = {
+ 0: _t.SyncProfileId
+};
- t.AddressBook("getGroup", arguments);
+/*
+ * Download
+ */
- for (i in privateData.groups) {
- if (privateData.groups[i].id === groupId)
- break;
- }
- if (privateData.groups[i] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+// DownloadManager
+_i.DownloadManager.start = {
+ 0: _t.DownloadRequest,
+ 1: _t.DownloadCallback,
- return new ContactGroup(privateData.groups[i]);
+ _optional: {
+ 1: true
}
+};
- function addGroup(group) {
- var external = group;
+_i.DownloadManager.cancel = {
+ 0: _t.long
+};
- if (!_security.addGroup) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_i.DownloadManager.pause = {
+ 0: _t.long
+};
- t.AddressBook("addGroup", arguments, true);
+_i.DownloadManager.resume = {
+ 0: _t.long
+};
- group.id = Math.uuid(null, 16);
- group.addressBookId = id;
+_i.DownloadManager.getState = {
+ 0: _t.long
+};
- external.__defineGetter__("id", function () {
- return group.id;
- });
+_i.DownloadManager.getDownloadRequest = {
+ 0: _t.long
+};
- external.__defineGetter__("addressBookId", function () {
- return group.addressBookId;
- });
+_i.DownloadManager.getMIMEType = {
+ 0: _t.long
+};
- privateData.groups.push(group);
- _save();
- }
+_i.DownloadManager.setListener = {
+ 0: _t.long,
+ 1: _t.DownloadCallback
+};
- function updateGroup(group) {
- var i;
+/*
+ * Message Port
+ */
- if (!_security.updateGroup) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// MessagePortManager
+_i.MessagePortManager.requestLocalMessagePort = {
+ 0: _t.DOMString
+};
- t.AddressBook("updateGroup", arguments);
+_i.MessagePortManager.requestTrustedLocalMessagePort = {
+ 0: _t.DOMString
+};
- if (!group.id) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- for (i in privateData.groups) {
- if (privateData.groups[i].id === group.id)
- break;
- }
- if (privateData.groups[i].id === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- if (privateData.groups[i].readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- privateData.groups[i] = utils.copy(group);
- _save();
- }
+_i.MessagePortManager.requestRemoteMessagePort = {
+ 0: _t.ApplicationId,
+ 1: _t.DOMString
+};
- function removeGroup(groupId) {
- var i;
+_i.MessagePortManager.requestTrustedRemoteMessagePort = {
+ 0: _t.ApplicationId,
+ 1: _t.DOMString
+};
- if (!_security.removeGroup) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// LocalMessagePort
+_i.LocalMessagePort.addMessagePortListener = {
+ 0: _t.MessagePortCallback
+};
- t.AddressBook("removeGroup", arguments);
+_i.LocalMessagePort.removeMessagePortListener = {
+ 0: _t.long
+};
- for (i in privateData.groups) {
- if (privateData.groups[i].id === groupId)
- break;
- }
- if (privateData.groups[i].id === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- if (privateData.groups[i].readOnly) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// RemoteMessagePort
+_i.RemoteMessagePort.sendMessage = {
+ 0: [_t.MessagePortDataItem],
+ 1: _t.LocalMessagePort,
- privateData.groups.splice(i, 1);
- _save();
+ _optional: {
+ 1: true
}
+};
- function getGroups() {
- var groups = [], i;
+/*
+ * Network Bearer Selection
+ */
- if (!_security.getGroups) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+// NetworkBearerSelection
+_i.NetworkBearerSelection.requestRouteToHost = {
+ 0: _t.NetworkType,
+ 1: _t.DOMString,
+ 2: _t.NetworkSuccessCallback,
+ 3: _t.ErrorCallback,
- for (i in privateData.groups) {
- groups.push(new ContactGroup(privateData.groups[i]));
- }
- return groups;
+ _optional: {
+ 3: true
}
+};
- privateData.load();
- // Make private contacts accessible for Person methods
- _data.contacts[id] = privateData.contacts;
-
- addressBook = {
- get: get,
- add: add,
- addBatch: addBatch,
- update: update,
- updateBatch: updateBatch,
- remove: remove,
- removeBatch: removeBatch,
- find: find,
- addChangeListener: addChangeListener,
- removeChangeListener: removeChangeListener,
+_i.NetworkBearerSelection.releaseRouteToHost = {
+ 0: _t.NetworkType,
+ 1: _t.DOMString,
+ 2: _t.SuccessCallback,
+ 3: _t.ErrorCallback,
- getGroup: getGroup,
- addGroup: addGroup,
- updateGroup: updateGroup,
- removeGroup: removeGroup,
- getGroups: getGroups
- };
+ _optional: {
+ 3: true
+ }
+};
- addressBook.__defineGetter__("id", function () {
- return id;
- });
+/*
+ * NFC
+ */
- addressBook.__defineGetter__("name", function () {
- return name;
- });
+// NFCManager
+_i.NFCManager.getDefaultAdapter = null;
+_i.NFCManager.setExclusiveMode = {
+ 0: _t.boolean
+};
- addressBook.__defineGetter__("readOnly", function () {
- return readOnly;
- });
+// NFCAdapter
+_i.NFCAdapter.setPowered = {
+ 0: _t.boolean,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- return addressBook;
+ _optional: {
+ 1: true,
+ 2: true
+ }
};
-AddressBookData = function (contacts, groups) {
- var addressBookData;
+_i.NFCAdapter.setTagListener = {
+ 0: _t.NFCTagDetectCallback,
+ 1: [_t.NFCTagType],
- // private
- function loadContacts() {
- for (var i in contacts) {
- addressBookData.contacts[i] = new ContactInternal(contacts[i]);
- }
+ _optional: {
+ 1: true
}
+};
- function loadGroups() {
- addressBookData.groups = groups;
+_i.NFCAdapter.setPeerListener = {
+ 0: _t.NFCPeerDetectCallback
+};
+
+_i.NFCAdapter.unsetTagListener = null;
+_i.NFCAdapter.unsetPeerListener = null;
+_i.NFCAdapter.getCachedMessage = null;
+
+// NFCTag
+_i.NFCTag.readNDEF = {
+ 0: _t.NDEFMessageReadCallback,
+ 1: _t.ErrorCallback,
+
+ _optional: {
+ 1: true
}
+};
- // public
- function load() {
- loadContacts();
- loadGroups();
+_i.NFCTag.writeNDEF = {
+ 0: _t.NDEFMessage,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 1: true,
+ 2: true
}
+};
- addressBookData = {
- contacts: {},
- groups: [],
- listeners: {},
- nListener: 0,
- load: load
- };
+_i.NFCTag.transceive = {
+ 0: [_t.byte],
+ 1: _t.ByteArraySuccessCallback,
+ 2: _t.ErrorCallback,
- return addressBookData;
+ _optional: {
+ 2: true
+ }
};
-AddressBookStorage = function (id, name, readOnly, contacts, groups) {
- this.id = id;
- this.name = name;
- this.readOnly = readOnly;
- this.contacts = contacts;
- this.groups = groups;
+// NFCPeer
+_i.NFCPeer.setReceiveNDEFListener = {
+ 0: _t.NDEFMessageReadCallback
};
-Contact = function (contact) {
- var i, attr, arr;
+_i.NFCPeer.unsetReceiveNDEFListener = null;
- this.name = null;
- this.addresses = [];
- this.photoURI = null;
- this.phoneNumbers = [];
- this.emails = [];
- this.birthday = null;
- this.anniversaries = [];
- this.organizations = [];
- this.notes = [];
- this.urls = [];
- this.ringtoneURI = null;
- this.groupIds = [];
+_i.NFCPeer.sendNDEF = {
+ 0: _t.NDEFMessage,
+ 1: _t.SuccessCallback,
+ 2: _t.ErrorCallback,
- for (attr in contact) {
- switch (attr) {
- case "name":
- this[attr] = new ContactName(contact[attr]);
- break;
+ _optional: {
+ 1: true,
+ 2: true
+ }
+};
- case "addresses":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactAddress(arr[i]);
- }
- }
- break;
+// NDEFMessage
+_i.NDEFMessage.toByte = null;
- case "phoneNumbers":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactPhoneNumber(arr[i].number,
- arr[i].types || null, arr[i].isDefault || null);
- }
- }
- break;
+/*
+ * Notification
+ */
- case "emails":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactEmailAddress(arr[i].email,
- arr[i].types || null, arr[i].isDefault || null);
- }
- }
- break;
+// NotificationManager
+_i.NotificationManager.post = {
+ 0: _t.Notification
+};
- case "birthday":
- this[attr] = new Date(contact[attr]);
- break;
+_i.NotificationManager.update = {
+ 0: _t.Notification
+};
- case "anniversaries":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- if (!tizen1_utils.isValidDate(arr[i].date)) {
- arr[i].date = new Date(arr[i].date);
- }
- this[attr][i] = new ContactAnniversary(arr[i].date,
- arr[i].label || null);
- }
- }
- break;
+_i.NotificationManager.remove = {
+ 0: _t.NotificationId
+};
- case "organizations":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactOrganization(arr[i]);
- }
- }
- break;
+_i.NotificationManager.get = {
+ 0: _t.NotificationId
+};
- case "notes":
- case "groupIds":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = arr[i];
- }
- }
- break;
+_i.NotificationManager.removeAll = null;
+_i.NotificationManager.getAll = null;
- case "urls":
- arr = contact[attr];
- if (arr) {
- for (i in arr) {
- this[attr][i] = new ContactWebSite(arr[i].url,
- arr[i].type || null);
- }
- }
- break;
+/*
+ * Package
+ */
- default:
- this[attr] = contact[attr];
- break;
- }
+// PackageManager
+_i.PackageManager.install = {
+ 0: _t.DOMString,
+ 1: _t.PackageProgressCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 2: true
}
+};
- decorator.Contact(this, contact);
- this.__proto__ = tizen.Contact.prototype;
+_i.PackageManager.uninstall = {
+ 0: _t.PackageId,
+ 1: _t.PackageProgressCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 2: true
+ }
};
-ContactInternal = function (contact) {
- var attr;
+_i.PackageManager.getPackagesInfo = {
+ 0: _t.PackageInformationArraySuccessCallback,
+ 1: _t.ErrorCallback,
- for (attr in contact) {
- this[attr] = contact[attr];
+ _optional: {
+ 1: true
}
+};
- if (!contact.id) {
- this.id = Math.uuid(null, 16);
- this.lastUpdated = new Date();
- } else {
- this.lastUpdated = new Date(contact.lastUpdated);
+_i.PackageManager.getPackageInfo = {
+ 0: _t.PackageId,
+
+ _optional: {
+ 0: true
}
+};
- if (this.name) {
- this.name.__defineGetter__("displayName", function () {
- var displayName = "";
+_i.PackageManager.setPackageInfoEventListener = {
+ 0: _t.PackageInfomationEventCallback
+};
- if (!this)
- return "";
+_i.PackageManager.unsetPackageInfoEventListener = null;
- if ((this.firstName !== null) &&
- (this.lastName !== null)) {
- displayName = [this.firstName, this.middleName, this.lastName];
- displayName = displayName.join(" ").replace(/ +/g, " ").trim();
- } else if (this.nicknames.length !== 0) {
- this.nicknames.some(function (nickname) {
- displayName = nickname;
- return displayName;
- });
- }
+/*
+ * Push
+ */
- return displayName;
- });
+// PushManager
+_i.PushManager.registerService = {
+ 0: _t.ApplicationControl,
+ 1: _t.PushRegisterSuccessCallback,
+ 2: _t.ErrorCallback,
+
+ _optional: {
+ 2: true
}
};
-ContactData = function () {
- this.listeners = {};
- this.nListener = 0;
+_i.PushManager.unregisterService = {
+ 0: _t.SuccessCallback,
+ 1: _t.ErrorCallback,
+
+ _optional: {
+ 0: true,
+ 1: true
+ }
};
-ContactGroup = function (groupInitDict) {
- var id, addressBookId, readOnly;
+_i.PushManager.connectService = {
+ 0: _t.PushNotificationCallback
+};
- this.__defineGetter__("id", function () {
- return id;
- });
+_i.PushManager.disconnectService = null;
+_i.PushManager.getRegistrationId = null;
- this.__defineGetter__("addressBookId", function () {
- return addressBookId;
- });
+/*
+ * System Info
+ */
- this.__defineGetter__("readOnly", function () {
- return readOnly;
- });
+// SystemInfo
+_i.SystemInfo.getCapabilities = null;
- id = groupInitDict.id || null;
- addressBookId = groupInitDict.addressBookId || null;
- readOnly = groupInitDict.readOnly || false;
+_i.SystemInfo.getPropertyValue = {
+ 0: _t.SystemInfoPropertyId,
+ 1: _t.SystemInfoPropertySuccessCallback,
+ 2: _t.ErrorCallback,
- this.name = groupInitDict.name || "";
- this.ringtoneURI = groupInitDict.ringtoneURI || null;
- this.photoURI = groupInitDict.photoURI || null;
+ _optional: {
+ 2: true
+ }
+};
- this.__proto__ = tizen.ContactGroup.prototype;
+_i.SystemInfo.addPropertyValueChangeListener = {
+ 0: _t.SystemInfoPropertyId,
+ 1: _t.SystemInfoPropertySuccessCallback,
+ 2: _t.SystemInfoOptions,
+
+ _optional: {
+ 2: true
+ }
};
-Person = function (personInitDict) {
- var person = {};
+_i.SystemInfo.removePropertyValueChangeListener = {
+ 0: _t.unsigned_long
+};
- function hasContactMethod(method) {
- var idab, idc, contact, count = 0;
+/*
+ * System Setting
+ */
- for (idab in _data.contacts) {
- for (idc in _data.contacts[idab]) {
- contact = _data.contacts[idab][idc];
- if (contact.personId === person.id) {
- count += contact[method].length;
- }
- }
- }
+// SystemSettingManager
+_i.SystemSettingManager.setProperty = {
+ 0: _t.SystemSettingType,
+ 1: _t.DOMString,
+ 2: _t.SuccessCallback,
+ 3: _t.ErrorCallback,
- return (count !== 0);
+ _optional: {
+ 3: true
}
+};
- person.id = personInitDict.id || Math.uuid(null, 16);
- person.isFavorite = personInitDict.isFavorite || false;
- person.photoURI = personInitDict.photoURI || null;
- person.ringtoneURI = personInitDict.ringtoneURI || null;
- person.displayContactId = personInitDict.displayContactId;
+_i.SystemSettingManager.getProperty = {
+ 0: _t.SystemSettingType,
+ 1: _t.SystemSettingSuccessCallback,
+ 2: _t.ErrorCallback,
- this.__defineGetter__("id", function () {
- return person.id;
- });
+ _optional: {
+ 2: true
+ }
+};
- this.__defineGetter__("displayName", function () {
- var idab, contact, displayName = "";
+/*
+ * Time
+ */
- for (idab in _data.contacts) {
- contact = _data.contacts[idab][this.displayContactId];
+// TimeUtil
+_i.TimeUtil.getCurrentDateTime = null;
+_i.TimeUtil.getLocalTimezone = null;
+_i.TimeUtil.getAvailableTimezones = null;
+_i.TimeUtil.getTimeFormat = null;
- if (contact !== undefined) {
- if (contact.name && contact.name.displayName) {
- displayName = contact.name.displayName;
- }
- break;
- }
- }
+_i.TimeUtil.getDateFormat = {
+ 0: _t.boolean,
- return displayName;
- });
+ _optional: {
+ 0: true
+ }
+};
- this.__defineGetter__("contactCount", function () {
- var idab, idc, contactCount = 0;
+_i.TimeUtil.isLeapYear = {
+ 0: _t.long
+};
- for (idab in _data.contacts) {
- for (idc in _data.contacts[idab]) {
- if (_data.contacts[idab][idc].personId === person.id) {
- ++contactCount;
- }
- }
- }
+// TimeDuration
+_i.TimeDuration.difference = {
+ 0: _t.TimeDuration
+};
- return contactCount;
- });
+_i.TimeDuration.equalsTo = {
+ 0: _t.TimeDuration
+};
- this.__defineGetter__("hasPhoneNumber", function () {
- return hasContactMethod("phoneNumbers");
- });
+_i.TimeDuration.lessThan = {
+ 0: _t.TimeDuration
+};
- this.__defineGetter__("hasEmail", function () {
- return hasContactMethod("emails");
- });
+_i.TimeDuration.greaterThan = {
+ 0: _t.TimeDuration
+};
- this.__defineGetter__("isFavorite", function () {
- return person.isFavorite;
- });
- this.__defineSetter__("isFavorite", function (val) {
- try {
- person.isFavorite = t.boolean(val);
- } catch (e) {
- }
- });
+_i.Vehicle.getSupported = {
+ 0: _t.SupportedPropertiesSuccessCallback,
+ 1: _t.VehiclePropertyErrorCallback
+}
- this.__defineGetter__("photoURI", function () {
- return person.photoURI;
- });
- this.__defineSetter__("photoURI", function (val) {
- try {
- person.photoURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+// Exports
+_t.constructor = _c;
+_t.interface = _i;
- this.__defineGetter__("ringtoneURI", function () {
- return person.ringtoneURI;
- });
- this.__defineSetter__("ringtoneURI", function (val) {
- try {
- person.ringtoneURI = t.DOMString(val, "?");
- } catch (e) {
+module.exports = _t;
+
+});
+define('ripple/platform/tizen/2.0/geoBackend_nominatim', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult');
+
+function _concatAddrString(addr) {
+ var ret = "", i, pieces;
+ if (typeof addr === "string") {
+ pieces = addr.split(" ");
+ for (i = 0; i < pieces.length; i++) {
+ ret = ret + pieces[i] + "+";
+ }
+ } else if (typeof addr === "object") {
+ if (addr.premises !== null && addr.premises !== undefined) {
+ ret = ret + addr.premises + "+";
+ }
+ if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
+ ret = ret + addr.streetNumber + "+";
+ }
+ if (addr.street !== null && addr.street !== undefined) {
+ ret = ret + addr.street + "+";
+ }
+ if (addr.city !== null && addr.city !== undefined) {
+ ret = ret + addr.city + "+";
+ }
+ if (addr.county !== null && addr.county !== undefined) {
+ ret = ret + addr.county + "+";
}
- });
-
- this.__defineGetter__("displayContactId", function () {
- return person.displayContactId;
- });
- this.__defineSetter__("displayContactId", function (val) {
- try {
- person.displayContactId = t.ContactId(val);
- } catch (e) {
+ if (addr.region !== null && addr.region !== undefined) {
+ ret = ret + addr.region + "+";
}
- });
-
- this.link = function (personId) {
- if (!_security.link) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (addr.postalCode !== null && addr.postalCode !== undefined) {
+ ret = ret + addr.postalCode + "+";
}
-
- t.Person("link", arguments);
-
- if (_data.persons[personId] === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ if (addr.country !== null && addr.country !== undefined) {
+ ret = ret + addr.country + "+";
}
+ } else {
+ return undefined;
+ }
+ ret = ret.slice(0, -1);
+ return ret;
+}
- _replacePerson(personId, person.id);
- _save();
- };
-
- this.unlink = function (contactId) {
- var idab, contact, separated, i, dbAddressBook;
-
- if (!_security.unlink) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+module.exports = function (prop) {
+ var _self = new lbs.LocationServiceProvider(prop);
- t.Person("unlink", arguments);
+ _self.geocode = function (address, successCB, errorCB, options) {
+ function _geocode() {
+ var i, searchStr, coordinates = [], result;
- for (idab in _data.contacts) {
- if (_data.contacts[idab][contactId] !== undefined) {
- contact = _data.contacts[idab][contactId];
- break;
+ searchStr = _concatAddrString(address);
+ if (searchStr === undefined) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- }
+ searchStr = "http://nominatim.openstreetmap.org/search?q=" + searchStr + "&format=json&polygon=1&addressdetails=1";
- if (contact === undefined) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- if (contact.personId !== person.id) {
- throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
+ $.getJSON(searchStr, function (data) {
+ for (i = 0; i < data.length; i++) {
+ result = new GeocodeResult(parseFloat(data[i].lat), parseFloat(data[i].lon));
+ coordinates.push(result);
+ }
+ successCB(coordinates);
+ }).error(function () {
+ if (errorCB) {
+ setTimeout(function () {
+ errorCB(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
+ }
+ });
}
- separated = new PersonBuilder(contact);
- _data.persons[separated.id] = separated;
- contact.personId = separated.id;
+ tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
+ };
- _data.dbStorage.persons[separated.id] = _serialize(separated);
- for (i in _data.dbStorage.addressBooks) {
- dbAddressBook = _data.dbStorage.addressBooks[i];
- if (dbAddressBook.id === idab) {
- dbAddressBook.contacts[contact.id].personId = separated.id;
- break;
+ _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
+ function _reverseGeocode() {
+ var searchStr = "";
+ if (typeof coordinates !== "object" ||
+ typeof coordinates.latitude !== "number" ||
+ typeof coordinates.longitude !== "number") {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- }
- _save();
+ searchStr = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" +
+ coordinates.latitude + "&lon=" + coordinates.longitude + "&zoom=18&addressdetails=1";
- return separated;
- };
-};
+ /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
+ $.getJSON(searchStr, function (data) {
+ var addr;
-PersonBuilder = function (contact) {
- var person, personInitDict = {};
+ if (options && options.resultType === "STRUCTURED") {
+ addr = new lbs.StructuredAddress({
+ country : data.address.country,
+ region : data.address.state,
+ county : data.address.county,
+ city : data.address.city,
+ street : data.address.road,
+ streetNumber : data.address.streetNumber,
+ postalCode : data.address.postcode
+ });
+ } else {
+ addr = data.display_name;
+ }
+ successCB([addr]);
+ }).error(function () {
+ if (errorCB) {
+ setTimeout(function () {
+ errorCB(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
+ }
+ });
+ }
- personInitDict.displayContactId = contact.id;
- person = new Person(personInitDict);
+ tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
+ };
- return person;
+ return _self;
};
-module.exports = _self;
});
-define('ripple/platform/tizen/2.0/content', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/route', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- dbfs = require('ripple/platform/tizen/2.0/dbfs'),
- dbinit = require('ripple/platform/tizen/2.0/dbinit'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- Content,
- ContentDirectory,
- ContentFactory,
- ContentStorage,
- AudioContent,
- ImageContent,
- VideoContent,
- ContentInternal,
- ContentDirectoryInternal,
- AudioContentInternal,
- ImageContentInternal,
- VideoContentInternal,
- AudioContentLyrics,
- _data = {
- DB_CONTENT_KEY: "tizen1-db-content",
- content: {},
- listener: null,
- dbStorage: null
- },
- _security = {
- "http://tizen.org/privilege/content.read": ["find",
- "setChangeListener", "unsetChangeListener"],
- "http://tizen.org/privilege/content.write": ["update", "updateBatch",
- "scanFile"]
- },
+ SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ ProviderNominatim = require('ripple/platform/tizen/2.0/routeBackend_navigation'), // navigation route service
+ _getProviders,
+ _providers,
_self;
-function _get() {
- _data.dbStorage = db.retrieveObject(_data.DB_CONTENT_KEY) || dbinit.Content;
+function _initialize() {
+ _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})];
}
-function _save() {
- db.saveObject(_data.DB_CONTENT_KEY, _data.dbStorage);
-}
+_initialize();
-function _initialize() {
- _get();
+_self = {
+ getDefaultProvider : function () {
+ if (arguments.length !== 0) {
+ throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return _providers[0];
+ },
+ getProviders : function () {
+ if (arguments.length !== 0) {
+ throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return _providers;
+ }
+};
- if (!_data.dbStorage)
- return;
+module.exports = _self;
- utils.forEach(_data.dbStorage, function (content) {
- _data.content[content.directoryURI] = new ContentStorage(content);
- });
+});
+define('ripple/platform/tizen/2.0/time', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- _data.dbStorage = _data.content;
- _save();
-}
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ TZDate = require('ripple/platform/tizen/2.0/TZDate'),
+ db = require('ripple/db'),
+ tz = require('ripple/platform/tizen/2.0/timezone_info'),
+ _timeFormat = "h:m:s ap", _shortDateFormat = "d/m/y",
+ _longDateFormat = "D, M d, y", _self;
-_self = function () {
- var content;
+_self = {
+ getCurrentDateTime: function () {
+ t.TimeUtil("getCurrentDateTime", arguments);
+ return new TZDate();
+ },
+ getLocalTimezone: function () {
+ t.TimeUtil("getLocalTimezone", arguments);
+ var localtz = db.retrieve("tizen-timezone") || "UTC";
+ return localtz;
+ },
+ getAvailableTimezones: function () {
+ t.TimeUtil("getAvailableTimezones", arguments);
+ var ret = tz.getAllTimezone();
+ return ret;
+ },
+ getDateFormat: function (shortformat) {
+ t.TimeUtil("getDateFormat", arguments);
- // private
- function getType(file) {
- var extName, type;
+ if (shortformat) {
+ return _shortDateFormat;
+ } else {
+ return _longDateFormat;
+ }
+ },
+ getTimeFormat: function () {
+ t.TimeUtil("getTimeFormat", arguments);
+ return _timeFormat;
+ },
+ isLeapYear: function (year) {
+ t.TimeUtil("isLeapYear", arguments);
+ return ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0));
+ }
+};
- extName = file.substr(file.lastIndexOf(".") + 1).toLowerCase();
+module.exports = _self;
- switch (extName) {
- case "bmp":
- case "gif":
- case "jpeg":
- case "jpg":
- case "png":
- type = "IMAGE";
- break;
+});
+define('ripple/platform/tizen/2.0/Message', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- case "avi":
- case "mpeg":
- case "mpg":
- case "wmv":
- case "mp4":
- type = "VIDEO";
- break;
+var msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
+ MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');
- case "wav":
- case "mp3":
- type = "AUDIO";
- break;
+module.exports = function (type, messageInit) {
+ var _id = null, _serviceId = null, _conversationId = null,
+ _folderId = null, _type = type, _timestamp = null,
+ _from = null, _hasAttachment = false, _messageStatus = null,
+ msg = {};
- default:
- type = "OTHER";
- break;
+ if (messageInit !== undefined && messageInit !== null) {
+ if (msg_utils.setMsg(messageInit, msg) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
}
-
- return type;
+ if (messageInit.priv !== undefined) {
+ /* secret constructor for PrivateMessage */
+ _id = messageInit.priv.id;
+ _serviceId = messageInit.priv.serviceId;
+ _conversationId = messageInit.priv.conversationId;
+ _folderId = messageInit.priv.folderId;
+ _type = messageInit.priv.type;
+ _timestamp = new Date(messageInit.priv.timestamp);
+ _from = messageInit.priv.from;
+ _hasAttachment = messageInit.priv.hasAttachment;
+ _messageStatus = messageInit.priv.messageStatus;
+ }
+ msg.body = new MessageBody(_id, msg.body.loaded, msg.body.plainBody, msg.body.htmlBody, []);
}
- function getMimeType(file) {
- var mimeTypeTab = {
- IMAGE: "image/x-msimage",
- VIDEO: "video/x-msvideo",
- AUDIO: "audio/x-msaudio",
- OTHER: "other/unknown"
- };
+ msg.__defineGetter__("id", function () {
+ return _id;
+ });
+ msg.__defineGetter__("conversationId", function () {
+ return _conversationId;
+ });
+ msg.__defineGetter__("folderId", function () {
+ return _folderId;
+ });
+ msg.__defineGetter__("type", function () {
+ return _type;
+ });
+ msg.__defineGetter__("timestamp", function () {
+ return _timestamp;
+ });
+ msg.__defineGetter__("from", function () {
+ return _from;
+ });
+ msg.__defineGetter__("hasAttachment", function () {
+ return _hasAttachment;
+ });
+ msg.__defineGetter__("messageStatus", function () {
+ return _messageStatus;
+ });
+ return msg;
+};
- return mimeTypeTab[getType(file)];
- }
+});
+define('ripple/platform/tizen/2.0/NDEFRecordMedia', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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 getTitle(file) {
- var title;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
+ NDEFRecordMedia;
- title = file.substr(0, file.lastIndexOf("."));
- title = title.charAt(0).toUpperCase() + title.substr(1).toLowerCase();
+NDEFRecordMedia = function (mimeType, data) {
+ var i, type = [], payload;
- return title;
- }
+ t.NDEFRecordMedia(arguments, this);
- function getDirectoryURI(contentURI) {
- return contentURI.slice(0, contentURI.lastIndexOf("/") + 1)
- .replace(/file:\/\//, "");
+ for (i = 0; i < mimeType.length; i++) {
+ type[i] = mimeType.charCodeAt(i);
}
+ payload = t.byte(data, "[]");
- function extractProperties(entry) {
- var contentInitDict = {};
+ // Normally, we can use prototype to inherit a class, for example:
+ // NDEFRecordMedia.prototype = new NDEFRecord(2, [...], [...], [...]);
+ // But the test case thinks that all the inherited property should be
+ // the object's own property. So, we can only change the "this" point
+ // of NDEFRecord constructor here.
+ NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_MIME_MEDIA, type,
+ payload, []);
- contentInitDict.editableAttributes = ["name", "title", "description",
- "rating"];
- contentInitDict.name = entry.name;
- contentInitDict.type = getType(entry.name);
- contentInitDict.mimeType = getMimeType(entry.name);
- contentInitDict.title = getTitle(entry.name);
- contentInitDict.contentURI = entry.fullPath ?
- "file://" + entry.fullPath : entry.fullPath;
- contentInitDict.thumbnailURIs = [entry.fullPath];
- contentInitDict.releaseDate = entry.lastModifiedDate;
- contentInitDict.modifiedDate = entry.lastModifiedDate;
- contentInitDict.size = 1048576;
+ this.__defineGetter__("mimeType", function () {
+ return mimeType;
+ });
+};
- return contentInitDict;
- }
+module.exports = NDEFRecordMedia;
- function updateContents(contents, successCallback, errorCallback) {
- var i, isFound = false, dir, matched = [];
+});
+define('ripple/platform/tizen/2.0/WebAPIException', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- for (i in contents) {
- dir = getDirectoryURI(contents[i].contentURI);
+var errorcode = require('ripple/platform/tizen/2.0/errorcode');
- isFound = ((dir in _data.content) && (contents[i].contentURI in
- _data.content[dir].contents));
+var msg = {
+ 0: "Generic Error",
+ 1: "Index or size is negative, or greater than the allowed value.",
+ 2: "Specified range of text does not fit into a DOMString.",
+ 3: "Node is inserted somewhere it doesn't belong.",
+ 4: "Node is used in a different document than the one that created it (that doesn't support it).",
+ 5: "An invalid or illegal character is specified.",
+ 6: "Data is specified for a Node which does not support data.",
+ 7: "An attempt is made to modify an object where modifications are not allowed.",
+ 8: "An attempt is made to reference a Node in a context where it does not exist.",
+ 9: "The implementation does not support the requested type of object or operation.",
+ 10: "An attempt is made to add an attribute that is already in use elsewhere.",
+ 11: "An attempt is made to use an object that is not, or is no longer, usable.",
+ 12: "An invalid or illegal string is specified.",
+ 13: "An attempt is made to modify the type of the underlying object.",
+ 14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
+ 15: "A parameter or an operation is not supported by the underlying object.",
+ 16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
+ 17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
+ 18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
+ 19: "A network error occurs in synchronous requests.",
+ 20: "The abort error occurs in asynchronous requests by user prompt.",
+ 21: "The operation could not be completed because the URL does not match.",
+ 22: "The quota has been exceeded.",
+ 23: "The operation timed out.",
+ 24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
+ 25: "The object can not be cloned.",
+ 99: "The content of an object does not include valid values.",
+ 100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
+ 111: "Requested service is not available."
+},
+ errType = {
+ 0: "UnknownError",
+ 1: "IndexSizeError",
+ 2: "DOMStringSizeError",
+ 3: "HierarchyRequestError",
+ 4: "WrongDocumentError",
+ 5: "InvalidCharacterError",
+ 6: "NoDataAllowedError",
+ 7: "NoModificationAllowedError",
+ 8: "NotFoundError",
+ 9: "NotSupportedError",
+ 10: "InuseAttributeError",
+ 11: "InvalidStateError",
+ 12: "SyntaxError",
+ 13: "InvalidModificationError",
+ 14: "NamespaceError",
+ 15: "InvalidAccessError",
+ 16: "ValidationError",
+ 17: "TypeMismatchError",
+ 18: "SecurityError",
+ 19: "NetworkError",
+ 20: "AbortError",
+ 21: "URLMismatchError",
+ 22: "QuotaExceededError",
+ 23: "TimeoutError",
+ 24: "InvalidNodeTypeError",
+ 25: "DataCloneError",
+ 99: "InvalidValuesError",
+ 100: "IOError",
+ 111: "ServiceNotAvailableError"
+};
- if (!isFound)
- break;
+/*
+ support 3 types of error:
+ - WebAPIError()
+ code = errorcode.UNKNOWN_ERR
+ message = errorcode.message[UNKNOWN_ERR]
+ - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
+ code = 17
+ message = errorcode.message[17]
+ - WebAPIError(my_own_error_code, "This is my error message.")
+ code = my_own_error_code(number)
+ message = "This is my error message."
+*/
- matched.push(dir);
- }
+module.exports = function (code, message, name) {
+ var g, c, _code, _message, _name;
- if (!isFound) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
+ for (c in errorcode) {
+ g = errorcode.__lookupGetter__(c);
+ if (g) {
+ this.__defineGetter__(c, g);
}
+ }
- for (i in matched) {
- _data.content[matched[i]].contents[contents[i].contentURI] =
- new ContentFactory(contents[i], true);
+ if (typeof code !== 'number') {
+ _code = errorcode.UNKNOWN_ERR;
+ _message = msg[_code];
+ _name = errType[_code];
+ } else {
+ _code = code;
+ if (typeof message === 'string') {
+ _message = message;
+ } else {
+ _message = msg[_code];
+ }
+ if (typeof name === 'string') {
+ _name = name;
+ } else {
+ _name = errType[_code];
}
+ }
- _save();
+ this.__defineGetter__("code", function () {
+ return _code;
+ });
+ this.__defineGetter__("message", function () {
+ return _message;
+ });
+ this.__defineGetter__("name", function () {
+ return _name;
+ });
+};
- if (successCallback) {
- successCallback();
- }
+});
+define('ripple/platform/tizen/2.0/ApplicationControlData', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if (_data.listener !== null) {
- for (i in matched) {
- _data.listener.oncontentupdated(new ContentFactory(_data
- .content[matched[i]].contents[contents[i].contentURI],
- false));
- }
- }
- }
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ApplicationControlData;
- // public
- function update(content) {
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ApplicationControlData = function (key, value) {
+ var applicationControlData = {};
- t.ContentManager("update", arguments);
+ t.ApplicationControlData(arguments, this);
- updateContents([content]);
- }
+ applicationControlData.key = key;
+ applicationControlData.value = value;
- function updateBatch(contents, successCallback, errorCallback) {
- if (!_security.updateBatch) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("key", function () {
+ return applicationControlData.key;
+ });
+ this.__defineSetter__("key", function (val) {
+ try {
+ applicationControlData.key = t.DOMString(val);
+ } catch (e) {
}
+ });
- t.ContentManager("updateBatch", arguments);
+ this.__defineGetter__("value", function () {
+ return applicationControlData.value;
+ });
+ this.__defineSetter__("value", function (val) {
+ try {
+ applicationControlData.value = t.DOMString(val, '[]');
+ } catch (e) {
+ }
+ });
+};
- window.setTimeout(function () {
- updateContents(contents, successCallback, errorCallback);
- }, 1);
- }
+module.exports = ApplicationControlData;
- function getDirectories(successCallback, errorCallback) {
- t.ContentManager("getDirectories", arguments);
+});
+define('ripple/platform/tizen/2.0/MessagingService', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- window.setTimeout(function () {
- var i, directories = [];
+var event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ deviceSettings = require('ripple/deviceSettings'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
+ MessageStorage = require('ripple/platform/tizen/2.0/MessageStorage'),
+ msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
+ t = require('ripple/platform/tizen/2.0/typedef'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ _self,
+ TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
+ "messaging.mms": "13572468",
+ "messaging.email": "tizen.simulator@tizen.org"},
+ INCOMING_TYPE = {"messaging.sms": "sms",
+ "messaging.mms": "mms",
+ "messaging.email": "email"};
- for (i in _data.content) {
- directories.push(new ContentDirectory(_data.content[i]));
- }
+_self = function (id, type, security_check) {
+ var msg_service = {},
+ pendingOperations = {},
+ _msgSending = {},
+ _receivedEmails = [],
+ _id = id,
+ _type = type,
+ _security_check = security_check,
+ _from = TIZEN_DEFAULT_MSG_FROM[_type],
+ _incomingType = INCOMING_TYPE[_type],
+ _messages = msg_utils.loadMsg(_type, _id),
+ _messageStorage = new MessageStorage(_messages, _security_check);
- if (directories.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ event.on("MessageSent", function (rst) {
+ var i, rsp_ok = [], rsp_fail = [];
+ // rst.msg is the real msg in module
+ if (rst.msg.priv.type !== _type ||
+ rst.msg.priv.serviceId !== _id) {
+ // not my msg
+ return;
+ }
+ if (_msgSending[rst.id] !== undefined) {
+ for (i in rst) {
+ if ((i !== "id") && (i !== "msg")) {
+ if (rst[i] === true) {
+ rsp_ok.push(i);
+ } else {
+ rsp_fail.push(i);
+ }
}
- return;
}
+ rst.msg.priv.folderId = "SENTBOX";
+ if (rsp_fail.length === 0) {
+ rst.msg.priv.messageStatus = "SENT";
+ _msgSending[rst.id].onsuccess(rsp_ok);
+ } else {
+ rst.msg.priv.messageStatus = "FAILED";
+ _msgSending[rst.id].onerror(rsp_fail);
+ }
+ msg_utils.saveMsg(rst.msg); // sync to remote
+ event.trigger("MsgSentRst", [rst.msg]);
+ delete _msgSending[rst.id];
+ }
+ });
- successCallback(directories);
- }, 1);
- }
+ event.on("MessageReceived", function (rst) {
+ var m, opt = {}, msgInit = {}, msg = {};
- function find(successCallback, errorCallback, directoryId, filter, sortMode,
- count, offset) {
- if (!_security.find) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (rst.type !== _incomingType) {
+ // not my msg
+ return;
}
+ msgInit.plainBody = rst.body;
+ msgInit.to = [_from];
+ // TODO: handle attachment
+ if (msg_utils.setMsg(msgInit, msg) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR, "received message error"));
+ }
+ opt.id = Math.uuid(8, 16);
+ opt.serviceId = _id;
+ opt.conversationId = opt.id;
+ opt.folderId = "INBOX";
+ opt.type = _type;
+ opt.timestamp = new Date();
+ opt.from = rst.from;
+ if (msg.attachments.length === 0) {
+ opt.hasAttachment = false;
+ } else {
+ opt.hasAttachment = true;
+ }
+ opt.messageStatus = "RECEIVED";
+ m = new PrivMessage(msg, opt);
+ msg_utils.saveMsg(m); // save in server
+ if (_type !== "messaging.email") {
+ _messages.msg[m.priv.id] = m; // sync to local
+ event.trigger("MsgRecv", [m]);
+ } else {
+ _receivedEmails.push(m); // don't sync to local yet
+ }
+ });
- t.ContentManager("find", arguments);
-
- window.setTimeout(function () {
- var i, dir, contents = [], results = [], matchedDir;
+ msg_service = {
+ sendMessage: function (_msg, onSuccess, onError) {
+ var m, msg = {}, opt = {}, shortMsg = {}, rst = {};
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (_msg === null || _msg === undefined || _msg.id === undefined) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
- if (!directoryId) {
- for (dir in _data.content) {
- for (i in _data.content[dir].contents) {
- contents.push(_data.content[dir].contents[i]);
- }
+ if (msg_utils.setMsg(_msg, msg) === false) {
+ throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
+ (_incomingType === 'sms' || _incomingType === 'mms')) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
}
- } else {
- for (dir in _data.content) {
- if (_data.content[dir].id === directoryId) {
- matchedDir = dir;
- break;
- }
+ return;
+ }
+ if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
+ _incomingType === 'email') {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
}
-
- if (!matchedDir) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ return;
+ }
+ if (typeof _msg.id === 'string') {
+ if (_messages.msg[_msg.id] === undefined) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
}
return;
}
-
- for (i in _data.content[matchedDir].contents) {
- contents.push(_data.content[matchedDir].contents[i]);
+ if (_messages.msg[_msg.id].priv.messageStatus === "DRAFT") {
+ msg_utils.delMsg(_messages.msg[_msg.id]);
+ delete _messages.msg[_msg.id];
+ } else {
+ // if msg found in storage, it can only be a draft.
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }, 1);
+ }
+ return;
}
}
-
- if (contents.length === 0) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
+ opt.id = Math.uuid(8, 16);
+ opt.serviceId = _id;
+ if ((msg.inResponseTo !== null) &&
+ (_messages.msg[msg.inResponseTo] !== undefined) &&
+ (_messages.msg[msg.inResponseTo].priv.messageStatus !== "DRAFT")) {
+ opt.conversationId = _messages.msg[msg.inResponseTo].priv.conversationId;
+ } else {
+ opt.conversationId = opt.id;
}
-
- contents = tizen1_utils.query(contents, filter, sortMode, count,
- offset);
-
- contents.forEach(function (content) {
- results.push(new ContentFactory(content, false));
- });
-
- successCallback(results);
- }, 1);
- }
-
- function scanFile(contentURI, successCallback, errorCallback) {
- var dir, isFound;
-
- function onStatSuccess(entry) {
- var contentInitDict, content;
-
- if (isFound) {
- content = new ContentFactory(_data.content[dir]
- .contents[contentURI], true);
+ opt.folderId = "OUTBOX";
+ opt.type = _type;
+ opt.timestamp = new Date();
+ opt.from = _from;
+ if (msg.attachments.length === 0) {
+ opt.hasAttachment = false;
} else {
- contentInitDict = extractProperties(entry);
- content = new ContentFactory(contentInitDict, true);
- _data.content[dir].contents[contentURI] = content;
+ opt.hasAttachment = true;
}
+ opt.messageStatus = "SENDING";
- _save();
+ m = new PrivMessage(msg, opt);
+ _messages.msg[m.priv.id] = m;
+ msg_utils.saveMsg(m); // sync to remote
+ shortMsg.msg = m; // pass by ref
+ shortMsg.id = m.priv.id;
+ shortMsg.body = m.body.plainBody;
+ shortMsg.to = m.to.slice(0);
+ shortMsg.cc = m.cc.slice(0);
+ shortMsg.bcc = m.bcc.slice(0);
+ event.trigger("OutsideMessageReceived", [shortMsg]);
+ rst.onsuccess = onSuccess;
+ rst.onerror = onError;
+ _msgSending[m.priv.id] = rst;
+ },
- if (successCallback) {
- successCallback(contentURI);
+ loadMessageBody: function (msg, onSuccess, onError) {
+ var pendingID;
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (_messages.msg[msg.id] === undefined) {
+ throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageBodySuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
}
+ pendingID = setTimeout(function () {
+ if (pendingOperations.hasOwnProperty(pendingID) === false) {
+ // has been cancelled/expired
+ return;
+ }
+ delete pendingOperations[pendingID];
+ onSuccess(_messages.msg[msg.id].body);
+ }, 1);
+ pendingOperations[pendingID] = onError;
+ return pendingID;
+ },
+ loadMessageAttachment: function (msg, onSuccess, onError) {
+ var pendingID;
- if (_data.listener !== null) {
- if (isFound) {
- _data.listener.oncontentupdated(
- new ContentFactory(content, false));
- } else {
- _data.listener.oncontentadded(
- new ContentFactory(content, false));
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (_messages.msg[msg.id] === undefined) {
+ throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageAttachmentSuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ pendingID = setTimeout(function () {
+ if (pendingOperations.hasOwnProperty(pendingID) === false) {
+ // has been cancelled/expired
+ return;
}
+ delete pendingOperations[pendingID];
+ onSuccess(_messages.msg[msg.id].attachments);
+ }, 1);
+ pendingOperations[pendingID] = onError;
+ return pendingID;
+ },
+ sync: function (successCallback, errorCallback, limit) {
+ var i, m, pendingID;
+
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
}
- }
+ if ((arguments.length > 0) && successCallback !== null && !(new TypeCoerce(t.SuccessCallback)).match(successCallback)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 1) && errorCallback !== null && !(new TypeCoerce(t.ErrorCallback)).match(errorCallback)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 2) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ pendingID = setTimeout(function () {
+ if (pendingOperations.hasOwnProperty(pendingID) === false) {
+ // has been cancelled/expired
+ return;
+ }
+ delete pendingOperations[pendingID];
+ for (i = 0; i < _receivedEmails.length; i++) {
+ m = _receivedEmails[i];
+ _messages.msg[m.priv.id] = m; // sync to local
+ event.trigger("MsgRecv", [m]);
+ }
+ _receivedEmails = [];
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ pendingOperations[pendingID] = errorCallback;
+ return pendingID;
+ },
- function onStatError() {
- if (isFound) {
- delete _data.content[dir].contents[contentURI];
- _save();
+ syncFolder: function (folder, onSuccess, onError, limit) {
+ var i, m, pendingID;
- if (successCallback) {
- successCallback(contentURI);
+ if (_security_check.write === false) {
+ throw (new WebAPIException(errorcode.SECURITY_ERR));
+ }
+ if (!(new TypeCoerce(t.MessageFolder)).match(folder)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if ((arguments.length > 3) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ pendingID = setTimeout(function () {
+ if (pendingOperations.hasOwnProperty(pendingID) === false) {
+ // has been cancelled/expired
+ return;
}
-
- if (_data.listener !== null) {
- _data.listener.oncontentremoved(_data.content[dir]
- .contents[contentURI].id);
+ delete pendingOperations[pendingID];
+ if (folder.id === "INBOX") {
+ for (i = 0; i < _receivedEmails.length; i++) {
+ m = _receivedEmails[i];
+ _messages.msg[m.priv.id] = m; // sync to local
+ event.trigger("MsgRecv", [m]);
+ }
+ _receivedEmails = [];
}
- } else if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ onSuccess();
+ }, 1);
+ pendingOperations[pendingID] = onError;
+ return pendingID;
+ },
+
+ stopSync: function (pendingID) {
+ if (!(new TypeCoerce(t.long)).match(pendingID)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (pendingOperations[pendingID] !== undefined) {
+ clearTimeout(pendingID);
+ pendingOperations[pendingID](new WebAPIError(errorcode.ABORT_ERR));
}
+ delete pendingOperations[pendingID];
}
+ };
+ msg_service.__defineGetter__("type", function () {
+ return _type;
+ });
+ msg_service.__defineGetter__("messageStorage", function () {
+ return _messageStorage;
+ });
+ return msg_service;
+};
- if (!_security.scanFile) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+module.exports = _self;
- t.ContentManager("scanFile", arguments);
+});
+define('ripple/platform/tizen/2.0/vibration', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- window.setTimeout(function () {
- dir = getDirectoryURI(contentURI);
+var event = require('ripple/event'),
+ deviceSettings = require('ripple/deviceSettings'),
+ constants = require('ripple/constants'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ emulatorBridge = require('ripple/emulatorBridge'),
+ curPost,
+ _self;
- isFound = ((dir in _data.content) &&
- (contentURI in _data.content[dir].contents));
+function isVibratorOn() {
+ return deviceSettings.retrieve("Config.vibratingMode");
+}
- dbfs.stat(contentURI.replace(/file:\/\//, ""), onStatSuccess,
- onStatError);
- }, 1);
- }
+var vibrator = (function () {
+ var vibratorPattern,
+ isVibrating = false,
+ runTime = 0,
+ vibrateTimeout = null,
+ MILLILSECONDS_OF_ONE_VIBRATION = 100,
+ node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
+ movementIndex = 0,
+ movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
+ {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];
- function setChangeListener(changeCallback) {
- if (!_security.setChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ function _clearTimeout() {
+ if (vibrateTimeout) {
+ clearInterval(vibrateTimeout);
+ vibrateTimeout = null;
}
+ }
- t.ContentManager("setChangeListener", arguments);
+ function stopVibrate() {
+ isVibrating = false;
+ _clearTimeout();
+ node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
+ }
- _data.listener = changeCallback;
+ function vibrate() {
+ node.css(movement[movementIndex]);
+ movementIndex = (movementIndex + 1) % 8;
}
- function unsetChangeListener() {
- if (!_security.unsetChangeListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ function changePulse() {
+ if (emulatorBridge.document().hidden) {
+ return;
}
- _data.listener = null;
+ //run time
+ runTime = runTime + MILLILSECONDS_OF_ONE_VIBRATION;
+ if (curPost >= vibratorPattern.length) {
+ setTimeout(stopVibrate, 1);
+ }
+ if (runTime > vibratorPattern[curPost]) {
+ curPost = curPost + 1;
+ runTime = 0;
+ } else {
+ if ((curPost % 2) === 0) {
+ vibrate();
+ }
+ }
}
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ function startVibrate(_pattern) {
+ if (!isVibratorOn())
+ return;
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
+ vibratorPattern = _pattern;
+ _clearTimeout();
+ movementIndex = 0;
+ if (_pattern) {
+ runTime = 0;
+ vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
}
+ isVibrating = true;
}
- content = {
- update: update,
- updateBatch: updateBatch,
- getDirectories: getDirectories,
- find: find,
- scanFile: scanFile,
- setChangeListener: setChangeListener,
- unsetChangeListener: unsetChangeListener,
- handleSubFeatures: handleSubFeatures
+ return {
+ isVibrating: isVibrating,
+ startVibrate: startVibrate,
+ stopVibrate: stopVibrate
};
+}());
- return content;
-};
+_self = {
+ vibrate: function () {
+ var pattern = arguments[0],
+ i;
-ContentDirectoryInternal = function (contentDirectoryInitDict) {
- this.id = contentDirectoryInitDict.id || null;
- this.directoryURI = contentDirectoryInitDict.directoryURI || null;
- this.title = contentDirectoryInitDict.title || "";
- this.storageType = contentDirectoryInitDict.storageType || "INTERNAL";
- this.modifiedDate = contentDirectoryInitDict.modifiedDate ?
- new Date(contentDirectoryInitDict.modifiedDate) : null;
-};
+ // If vibrator is off, stop the vibration
+ event.on("VibratingModeChanged", function (value) {
+ if (value === false) {
+ vibrator.stopVibrate();
+ }
+ });
-ContentDirectory = function (contentDirectoryInitDict) {
- var contentDirectory = {};
+ //1. If the hidden attribute [PAGE-VISIBILITY] is set to true, abort these steps.
+ if (emulatorBridge.document().hidden) {
+ return;
+ }
- contentDirectory.id = contentDirectoryInitDict.id || null;
- contentDirectory.directoryURI = contentDirectoryInitDict.directoryURI || null;
- contentDirectory.title = contentDirectoryInitDict.title || "";
- contentDirectory.storageType = contentDirectoryInitDict.storageType || "INTERNAL";
- contentDirectory.modifiedDate = contentDirectoryInitDict.modifiedDate ?
- new Date(contentDirectoryInitDict.modifiedDate) : null;
+ //2. Let pattern be the value of the first argument.
+ if (!tizen1_utils.isValidArray(pattern)) {
+ pattern |= 0;
+ } else {
+ for (i = 0; i < pattern.length; i++) {
+ pattern[i] |= 0;
+ }
+ }
- this.__defineGetter__("id", function () {
- return contentDirectory.id;
- });
+ //3. If pattern is 0, or an empty list, cancel the pre-existing instance of the processing vibration patterns algorithm, if any, and abort these steps.
+ if (pattern === 0 || (tizen1_utils.isValidArray(pattern) && pattern.length === 0)) {
+ vibrator.stopVibrate();
+ return;
+ }
- this.__defineGetter__("directoryURI", function () {
- return contentDirectory.directoryURI;
- });
+ //4. If pattern is a list, proceed to the next step. Otherwise run the following substeps:
+ //a. Let list be an initially empty list, and add pattern to list.
+ //b. Let pattern be list.
+ if (!tizen1_utils.isValidArray(pattern)) {
+ pattern = [pattern];
+ }
- this.__defineGetter__("title", function () {
- return contentDirectory.title;
- });
+ //5. If any entry of pattern exceeds an implementation-dependent limit, then the user agent may throw a NotSupportedError exception and abort these steps.
- this.__defineGetter__("storageType", function () {
- return contentDirectory.storageType;
- });
+ //6. If the length of pattern is even, then remove the last entry in pattern.
+ if (pattern.length % 2 === 0) {
+ pattern.pop();
+ }
- this.__defineGetter__("modifiedDate", function () {
- return contentDirectory.modifiedDate;
- });
-};
+ //7. Cancel the pre-existing instance of the processing vibration patterns algorithm, if any.
+ if (vibrator.isVibrating) {
+ vibrator.stopVibrate();
+ }
-ContentInternal = function (contentInitDict) {
- this.editableAttributes = contentInitDict.editableAttributes || [];
- this.id = contentInitDict.id || Math.uuid(null, 16);
- this.type = contentInitDict.type || "IMAGE";
- this.mimeType = contentInitDict.mimeType || "";
- this.title = contentInitDict.title || "";
- this.contentURI = contentInitDict.contentURI || "";
- this.thumbnailURIs = contentInitDict.thumbnailURIs || null;
- this.releaseDate = contentInitDict.releaseDate ?
- new Date(contentInitDict.releaseDate) : null;
- this.modifiedDate = contentInitDict.modifiedDate ?
- new Date(contentInitDict.modifiedDate) : null;
- this.size = contentInitDict.size || 0;
- this.name = contentInitDict.name || "";
- this.description = contentInitDict.description || null;
- this.rating = contentInitDict.rating || 0;
+ curPost = 0;
+ vibrator.startVibrate(pattern);
+ }
};
-Content = function (contentInitDict) {
- var content = {};
-
- content.editableAttributes = contentInitDict.editableAttributes || [];
- content.id = contentInitDict.id || Math.uuid(null, 16);
- content.name = contentInitDict.name || "";
- content.type = contentInitDict.type || "IMAGE";
- content.mimeType = contentInitDict.mimeType || "";
- content.title = contentInitDict.title || "";
- content.contentURI = contentInitDict.contentURI || "";
- content.thumbnailURIs = contentInitDict.thumbnailURIs || null;
- content.releaseDate = contentInitDict.releaseDate ?
- new Date(contentInitDict.releaseDate) : null;
- content.modifiedDate = contentInitDict.modifiedDate ?
- new Date(contentInitDict.modifiedDate) : null;
- content.size = contentInitDict.size || 0;
- content.description = contentInitDict.description || null;
- content.rating = contentInitDict.rating || 0;
+module.exports = _self;
- this.__defineGetter__("editableAttributes", function () {
- return content.editableAttributes;
- });
+});
+define('ripple/platform/tizen/2.0/poiBackend_openmapquest', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- this.__defineGetter__("id", function () {
- return content.id;
- });
+var lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
+ SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ _security;
- this.__defineGetter__("name", function () {
- return content.name;
- });
- this.__defineSetter__("name", function (val) {
- try {
- content.name = t.DOMString(val);
- } catch (e) {
+function POIPublic(prop) {
+ /* This is created for public use */
+ var _self, i, copy, attr, _id = null, _providerName = null;
+ if (prop.id) {
+ _id = prop.id;
+ }
+ if (prop.providerName) {
+ _providerName = prop.providerName;
+ }
+ _self = {
+ name : null,
+ categories : [],
+ address : null,
+ phoneNumbers : [],
+ geometry : null,
+ urls : [],
+ rating : null,
+ tags : null,
+ toGeoJSON : function () {
+ throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
}
- });
-
- this.__defineGetter__("type", function () {
- return content.type;
- });
-
- this.__defineGetter__("mimeType", function () {
- return content.mimeType;
- });
-
- this.__defineGetter__("title", function () {
- return content.title;
- });
-
- this.__defineGetter__("contentURI", function () {
- return content.contentURI;
- });
-
- this.__defineGetter__("thumbnailURIs", function () {
- return content.thumbnailURIs;
- });
-
- this.__defineGetter__("releaseDate", function () {
- return content.releaseDate;
- });
+ };
- this.__defineGetter__("modifiedDate", function () {
- return content.modifiedDate;
+ _self.__defineGetter__("id", function () {
+ return _id;
});
- this.__defineGetter__("size", function () {
- return content.size;
+ _self.__defineGetter__("providerName", function () {
+ return _providerName;
});
- this.__defineGetter__("description", function () {
- return content.description;
- });
- this.__defineSetter__("description", function (val) {
- try {
- content.description = t.DOMString(val, "?");
- } catch (e) {
+ if (prop) {
+ if (prop.name) {
+ _self.name = String(prop.name);
}
- });
-
- this.__defineGetter__("rating", function () {
- return content.rating;
- });
- this.__defineSetter__("rating", function (val) {
- try {
- val = t.unsigned_long(val);
- if ((val < 0) || (val > 10))
- return;
- content.rating = val;
- } catch (e) {
+ if (tizen1_utils.isValidArray(prop.categories)) {
+ _self.categories = [];
+ for (i in prop.categories) {
+ _self.categories.push(String(prop.categories[i]));
+ }
+ }
+ if (prop.address) {
+ if (typeof prop.address === "string") {
+ _self.address = String(prop.address);
+ } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
+ copy = prop.address.constructor();
+ for (attr in prop.address) {
+ if (prop.address.hasOwnProperty(attr)) {
+ copy[attr] = prop.address[attr];
+ }
+ }
+ _self.address = copy;
+ }
+ }
+ if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
+ _self.phoneNumbers = [];
+ for (i in prop.phoneNumbers) {
+ _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
+ }
+ }
+ if (prop.geometry) {
+ _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
+ }
+ if (tizen1_utils.isValidArray(prop.urls)) {
+ _self.urls = [];
+ for (i in prop.urls) {
+ _self.urls.push(String(prop.urls[i]));
+ }
+ }
+ if (typeof prop.rating === "number") {
+ _self.rating = prop.rating;
+ }
+ if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
+ copy = prop.tags.constructor();
+ for (attr in prop.tags) {
+ if (prop.tags.hasOwnProperty(attr)) {
+ copy[attr] = prop.tags[attr];
+ }
+ }
+ _self.tags = copy;
}
- });
-};
-
-VideoContentInternal = function (videoContentInitDict) {
- ContentInternal.call(this, videoContentInitDict);
-
- this.album = videoContentInitDict.album || null;
- this.artists = videoContentInitDict.artists || null;
- this.duration = videoContentInitDict.duration || 0;
- this.width = videoContentInitDict.width || 0;
- this.height = videoContentInitDict.height || 0;
- this.geolocation = null;
-
- if (videoContentInitDict.geolocation) {
- this.geolocation = new SimpleCoordinates(
- videoContentInitDict.geolocation.latitude || null,
- videoContentInitDict.geolocation.longitude || null);
}
-};
-VideoContent = function (videoContentInitDict) {
- var videoContent = {};
+ return _self;
+}
- Content.call(this, videoContentInitDict);
+module.exports = function (prop) {
- videoContent.album = videoContentInitDict.album || null;
- videoContent.artists = videoContentInitDict.artists || null;
- videoContent.duration = videoContentInitDict.duration || 0;
- videoContent.width = videoContentInitDict.width || 0;
- videoContent.height = videoContentInitDict.height || 0;
- videoContent.geolocation = null;
+ var _self = new lbs.LocationServiceProvider(prop);
- if (videoContentInitDict.geolocation) {
- videoContent.geolocation = new SimpleCoordinates(
- videoContentInitDict.geolocation.latitude,
- videoContentInitDict.geolocation.longitude);
+ if (prop.metaData) {
+ _security = prop.metaData;
}
- this.__defineGetter__("geolocation", function () {
- return videoContent.geolocation;
- });
- this.__defineSetter__("geolocation", function (val) {
- try {
- videoContent.geolocation = t.SimpleCoordinates(val, "?");
- } catch (e) {
- }
+ _self.__defineGetter__("supportedFilterTypes", function () {
+ return [];
});
- this.__defineGetter__("album", function () {
- return videoContent.album;
+ _self.__defineGetter__("supportedPOIFilterAttributes", function () {
+ return [];
});
- this.__defineGetter__("artists", function () {
- return videoContent.artists;
+ _self.__defineGetter__("supportedCategories", function () {
+ /* reference: http://wiki.openstreetmap.org/wiki/Map_Features#Amenity */
+ return ["bar", "bbq", "biergarten", "cafe", "drinking_water", "fast_food", "food_court", "ice_cream",
+ "pub", "restaurant", "college", "kindergarten", "library", "school", "university",
+ "bicycle_parking", "bicycle_rental", "bus_station", "car_rental", "car_sharing", "car_wash",
+ "ev_charging", "ferry_terminal", "fuel", "grit_bin", "parking", "parking_entrance",
+ "parking_space", "taxi", "atm", "bank", "bureau_de_change", "baby_hatch", "clinic",
+ "dentist", "doctors", "hospital", "nursing_home", "pharmacy", "social_facility", "veterinary",
+ "arts_centre", "cinema", "community_centre", "fountain", "nightclub", "social_centre",
+ "stripclub", "studio", "swingerclub", "theatre", "bench", "brothel", "clock", "courthouse",
+ "crematorium", "embassy", "fire_station", "grave_yard", "hunting_stand", "marketplace",
+ "place_of_worship", "police", "post_box", "post_office", "prison", "public_building",
+ "recycling", "sauna", "shelter", "shower", "telephone", "toilets", "townhall", "vending_machine",
+ "waste_basket", "waste_disposal", "watering_place"];
});
- this.__defineGetter__("duration", function () {
- return videoContent.duration;
+ _self.__defineGetter__("capabilities", function () {
+ /* The set is empty, indicating that this provider supports only 'find' operations */
+ return [];
});
- this.__defineGetter__("width", function () {
- return videoContent.width;
- });
+ _self.find = function (point, successCallback, errorCallback, options) {
+ /* This provider only supports searching by "GeoRectBounds" due to MapQuest XAPI limitation */
- this.__defineGetter__("height", function () {
- return videoContent.height;
- });
-};
+ function _find() {
+ var searchStr, pois = [], isTypeOK = false,
+ id, providerName, name, categories = [], geometry;
-AudioContentInternal = function (audioContentInitDict) {
- ContentInternal.call(this, audioContentInitDict);
+ if (Object.prototype.toString.call(point) === "[object Object]") {
+ if (point.southWest && point.northEast) {
+ if (typeof point.southWest.latitude === "number" &&
+ typeof point.southWest.longitude === "number" &&
+ typeof point.northEast.latitude === "number" &&
+ typeof point.northEast.longitude === "number") {
+ isTypeOK = true;
+ }
+ }
+ }
- this.album = audioContentInitDict.album || null;
- this.genres = audioContentInitDict.genres || null;
- this.artists = audioContentInitDict.artists || null;
- this.composers = audioContentInitDict.composers || null;
- this.lyrics = audioContentInitDict.lyrics ?
- new AudioContentLyrics(audioContentInitDict.lyrics) : null;
- this.copyright = audioContentInitDict.copyright || null;
- this.bitrate = audioContentInitDict.bitrate || 0;
- this.trackNumber = audioContentInitDict.trackNumber || null;
- this.duration = audioContentInitDict.duration || 0;
-};
+ if (!isTypeOK) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
-AudioContentLyrics = function (lyrics) {
- var audioContentLyrics = {};
+ searchStr = "http://open.mapquestapi.com/xapi/api/0.6/node";
+ if (options && tizen1_utils.isValidArray(options.categories) &&
+ options.categories.length > 0 && typeof options.categories[0] === "string") {
+ /* xapi support single amenity only */
+ searchStr += "[amenity=" + options.categories[0] + "]";
+ }
+ searchStr += "[bbox=" + point.southWest.longitude + "," + point.southWest.latitude + "," +
+ point.northEast.longitude + "," + point.northEast.latitude + "]";
- audioContentLyrics.type = lyrics.type;
- audioContentLyrics.texts = lyrics.texts;
- audioContentLyrics.timestamps = (lyrics.type === "SYNCHRONIZED") ?
- lyrics.timestamps : undefined;
+ /* use Open MapQuest online xapi service. (http://open.mapquestapi.com/xapi/) */
+ $.ajax({
+ type: "GET",
+ url: searchStr,
+ dataType: "xml",
+ timeout: 15000, /* 15 secs timeout */
+ success: function (xml) {
+ providerName = $(xml).find("osm").attr("generator");
+ $(xml).find("node").each(function () {
+ var $item = $(this);
+ categories = [];
+ id = $item.attr("id");
+ geometry = new POIGeometry(new SimpleCoordinates($item.attr("lat"), $item.attr("lon")));
+ $item.find("tag").each(function () {
+ if ($(this).attr("k") === "name") {
+ name = $(this).attr("v");
+ } else if ($(this).attr("k") === "amenity") {
+ categories.push($(this).attr("v"));
+ }
+ });
+ pois.push(new POIPublic({id: id, providerName: providerName, name: name,
+ categories: categories, geometry: geometry}));
+ });
+ successCallback(pois);
+ },
+ error: function (obj, msg) {
+ if (errorCallback) {
+ if (msg === "timeout") {
+ setTimeout(function () {
+ errorCallback(new WebAPIError(errorcode.TIMEOUT_ERR));
+ }, 1);
+ } else {
+ setTimeout(function () {
+ errorCallback(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
+ }
+ }
+ }
+ });
+ }
- this.__defineGetter__("type", function () {
- return audioContentLyrics.type;
- });
+ if (!_security.all && !_security.find) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("texts", function () {
- return audioContentLyrics.texts;
- });
+ tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
+ };
- this.__defineGetter__("timestamps", function () {
- return audioContentLyrics.timestamps;
- });
-};
+ _self.update = function (poi, successCallback, errorCallback) {
+ if (!_security.all && !_security.update) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
-AudioContent = function (audioContentInitDict) {
- var audioContent = {};
+ throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
+ };
- Content.call(this, audioContentInitDict);
+ _self.add = function (poi, successCallback, errorCallback) {
+ if (!_security.all && !_security.add) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
- audioContent.album = audioContentInitDict.album || null;
- audioContent.genres = audioContentInitDict.genres || null;
- audioContent.artists = audioContentInitDict.artists || null;
- audioContent.composers = audioContentInitDict.composers || null;
- audioContent.lyrics = audioContentInitDict.lyrics ?
- new AudioContentLyrics(audioContentInitDict.lyrics) : null;
- audioContent.copyright = audioContentInitDict.copyright || null;
- audioContent.bitrate = audioContentInitDict.bitrate || 0;
- audioContent.trackNumber = audioContentInitDict.trackNumber || null;
- audioContent.duration = audioContentInitDict.duration || 0;
+ throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
+ };
- this.__defineGetter__("album", function () {
- return audioContent.album;
- });
+ _self.remove = function (poi, successCallback, errorCallback) {
+ if (!_security.all && !_security.remove) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
- this.__defineGetter__("genres", function () {
- return audioContent.genres;
- });
+ throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
+ };
- this.__defineGetter__("artists", function () {
- return audioContent.artists;
- });
+ return _self;
+};
- this.__defineGetter__("composers", function () {
- return audioContent.composers;
- });
+});
+define('ripple/platform/tizen/2.0/BluetoothClassDeviceService', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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.
+ */
- this.__defineGetter__("lyrics", function () {
- return audioContent.lyrics;
+var BluetoothClassDeviceService = function () {
+ this.__defineGetter__("LIMITED_DISCOVERABILITY", function () {
+ return 0x0001;
});
- this.__defineGetter__("copyright", function () {
- return audioContent.copyright;
+ this.__defineGetter__("POSITIONING", function () {
+ return 0x0008;
});
- this.__defineGetter__("bitrate", function () {
- return audioContent.bitrate;
+ this.__defineGetter__("NETWORKING", function () {
+ return 0x0010;
});
- this.__defineGetter__("trackNumber", function () {
- return audioContent.trackNumber;
+ this.__defineGetter__("RENDERING", function () {
+ return 0x0020;
});
- this.__defineGetter__("duration", function () {
- return audioContent.duration;
+ this.__defineGetter__("CAPTURING", function () {
+ return 0x0040;
});
-};
-
-ImageContentInternal = function (imageContentInitDict) {
- ContentInternal.call(this, imageContentInitDict);
-
- this.geolocation = null;
- this.width = imageContentInitDict.width || 0;
- this.height = imageContentInitDict.height || 0;
- this.orientation = imageContentInitDict.orientation || "NORMAL";
-
- if (imageContentInitDict.geolocation) {
- this.geolocation = new SimpleCoordinates(
- imageContentInitDict.geolocation.latitude,
- imageContentInitDict.geolocation.longitude);
- }
-};
-
-ImageContent = function (imageContentInitDict) {
- var imageContent = {};
-
- Content.call(this, imageContentInitDict);
-
- imageContent.width = imageContentInitDict.width || 0;
- imageContent.height = imageContentInitDict.height || 0;
- imageContent.geolocation = null;
- imageContent.orientation = imageContentInitDict.orientation || "NORMAL";
-
- if (imageContentInitDict.geolocation) {
- imageContent.geolocation = new SimpleCoordinates(
- imageContentInitDict.geolocation.latitude,
- imageContentInitDict.geolocation.longitude);
- }
- this.__defineGetter__("geolocation", function () {
- return imageContent.geolocation;
- });
- this.__defineSetter__("geolocation", function (val) {
- try {
- imageContent.geolocation = t.SimpleCoordinates(val, "?");
- } catch (e) {
- }
+ this.__defineGetter__("OBJECT_TRANSFER", function () {
+ return 0x0080;
});
- this.__defineGetter__("width", function () {
- return imageContent.width;
+ this.__defineGetter__("AUDIO", function () {
+ return 0x0100;
});
- this.__defineGetter__("height", function () {
- return imageContent.height;
+ this.__defineGetter__("TELEPHONY", function () {
+ return 0x0200;
});
- this.__defineGetter__("orientation", function () {
- return imageContent.orientation;
- });
- this.__defineSetter__("orientation", function (val) {
- try {
- imageContent.orientation = t.ImageContentOrientation(val);
- } catch (e) {
- }
+ this.__defineGetter__("INFORMATION", function () {
+ return 0x0400;
});
};
-ContentFactory = function (contentInitDict, isInternal) {
- var ContentType;
-
- switch (contentInitDict.type) {
- case "IMAGE":
- ContentType = isInternal ? ImageContentInternal : ImageContent;
- break;
-
- case "VIDEO":
- ContentType = isInternal ? VideoContentInternal : VideoContent;
- break;
-
- case "AUDIO":
- ContentType = isInternal ? AudioContentInternal : AudioContent;
- break;
-
- default:
- ContentType = isInternal ? ContentInternal : Content;
- break;
- }
-
- return new ContentType(contentInitDict);
-};
-
-ContentStorage = function (content) {
- var i;
-
- ContentDirectoryInternal.call(this, content);
- this.contents = {};
-
- for (i in content.contents) {
- this.contents[i] = new ContentFactory(content.contents[i], true);
- }
-};
-
-_initialize();
-
-module.exports = _self;
+module.exports = BluetoothClassDeviceService;
});
-define('ripple/platform/tizen/2.0/datacontrol', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/download', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
var db = require('ripple/db'),
- utils = require('ripple/utils'),
+ event = require('ripple/event'),
t = require('ripple/platform/tizen/2.0/typecast'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ filesystem = require('ripple/platform/tizen/2.0/filesystem'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- DataControlConsumerFactory,
- DataControlConsumerObject,
- SQLDataControlConsumer,
- MappedDataControlConsumer,
- SQLData,
- MappedData,
- _data = {
- DB_DATACONTROL_KEY: "tizen1-db-datacontrol",
- IDS_PROVIDER: ["http://tizen.org/datacontrol/provider/DictionaryDataControlProvider"],
- IDS_DATA: ["Dictionary"],
- PERSIST_DELAY: 1000,
- SQL: null,
- MAP: null,
- dbStorage: null
+ DownloadRequest = require('ripple/platform/tizen/2.0/DownloadRequest'),
+ DownloadState = {
+ QUEUED: "QUEUED",
+ DOWNLOADING: "DOWNLOADING",
+ PAUSED: "PAUSED",
+ CANCELED: "CANCELED",
+ COMPLETED: "COMPLETED",
+ FAILED: "FAILED"
},
_security = {
- "http://tizen.org/privilege/datacontrol.consumer":
- ["getDataControlConsumer", "insert", "update", "remove", "select",
- "addValue", "removeValue", "getValue", "updateValue"]
+ "http://tizen.org/privilege/download": ["start"]
},
- _self;
+ DB_DOWNLOAD_KEY = "tizen1-db-download",
+ DownloadItem, _isInitialized = false, INTERVAL = 1000,
+ _downloads = [], _resources = [], _self;
-function _get() {
- _data.dbStorage = db.retrieveObject(_data.DB_DATACONTROL_KEY) || {};
+function _initDownloadItem(download) {
+ var url, index, isExist = false;
+ url = download.url;
+ if (download.destination === null) {
+ download.destination = "downloads";
+ }
+ if (download.fileName === null) {
+ index = url.lastIndexOf('\/') + 1;
+ download.fileName = url.substring(index);
+ }
+ if (!_isInitialized) {
+ initializeResource();
+ }
+ _resources.some(function (value) {
+ if (value.url === url) {
+ download.size = Number(value.size);
+ download.speed = Number(value.speed);
+ download.estimatedTime = Math.round(value.estimatedTime * 100) / 100;
+ download.MIMEType = value.MIMEType;
+ isExist = true;
+ return;
+ }
+ });
+ if (!isExist) {
+ download.state = DownloadState.FAILED;
+ _exec(download.callback, 'onfailed', download.id, new WebAPIError(errorcode.NOT_FOUND_ERR));
+ return;
+ }
+ return download;
+}
+
+function _exec(callback, name, downloadId, arg1, arg2) {
+ if (callback === null) {
+ return;
+ }
+
+ window.setTimeout(function () {
+ switch (name) {
+ case "onprogress":
+ callback[name](downloadId, arg1, arg2);
+ break;
+
+ case "onpaused":
+ callback[name](downloadId);
+ break;
+
+ case "oncanceled":
+ callback[name](downloadId);
+ break;
+
+ case "oncompleted":
+ callback[name](downloadId, arg1);
+ break;
+
+ case "onfailed":
+ callback[name](downloadId, arg1);
+ break;
+
+ default:
+ break;
+ }
+ }, 1);
+}
+
+function _getDownloadObjById(id) {
+ var isFound = false, backObj;
+ id = Number(id);
+ _downloads.some(function (obj) {
+ if (obj.id === id) {
+ backObj = obj;
+ isFound = true;
+ return;
+ }
+ });
+ if (!isFound) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ return backObj;
+}
+
+function initializeResource() {
+ _resources = db.retrieveObject(DB_DOWNLOAD_KEY);
+ _isInitialized = true;
+}
+
+function _saveFile(downloadObj, callback) {
+ var name, path, content;
+
+ name = downloadObj.fileName;
+ path = downloadObj.destination;
+ content = 'size|' + downloadObj.size + ',speed|' + downloadObj.speed + ',url|' + downloadObj.url + ',estimatedTime|' + downloadObj.estimatedTime;
+ function onsuccess(fs) {
+ fs.write(content);
+ fs.close();
+ }
+ function onerror(e) {
+ _exec(downloadObj.callback, 'onfailed', downloadObj.id, e);
+ }
+ function rename(name) { //index.html==>index_1.html
+ var index, c;
+ index = name.lastIndexOf('.');
+ if (index < 0) {
+ index = name.length;
+ }
+ c = name.substr(index - 2, 1);
+ if (c === '_') {
+ name = name.substr(0, index - 1) + (Number(name.substr(index - 1, 1)) + 1) + name.substring(index);
+ } else {
+ name = name.substr(0, index) + "_1" + name.substring(index);
+ }
+ return name;
+ }
+
+ filesystem.resolve(path, function (dir) {
+ var file, isExist = true;
+ while (isExist) {
+ try {
+ file = dir.resolve(name);
+ name = rename(name);
+ } catch (e) {
+ isExist = false;
+ }
+ }
+ file = dir.createFile(name);
+ file.openStream('w', onsuccess, onerror, 'UTF-8');
+ callback(name);
+ }, onerror, "rw");
}
-function _save() {
- db.saveObject(_data.DB_DATACONTROL_KEY, _data.dbStorage);
-}
+DownloadItem = function (download, callback) {
+ var _self;
+ _self = {
+ id : Number(Math.uuid(8, 10)),
+ url : download.url,
+ state : DownloadState.QUEUED,
+ fileName : download.fileName || null,
+ destination : download.destination || null,
+ callback : callback || null
+ };
+ return _self;
+};
+
+_self = function () {
+ function start(downloadRequest, downloadCallback) {
+ var downloadObj, fileSize, increment, receivedSize = 0, intervalId;
+
+ if (!_security.start) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.DownloadManager("start", arguments);
+
+ downloadObj = new DownloadItem(downloadRequest, downloadCallback);
+ _downloads.push(downloadObj);
+ downloadObj = _initDownloadItem(downloadObj);
+ if (downloadObj === null || downloadObj === undefined) {
+ return;
+ }
+ downloadObj.state = DownloadState.DOWNLOADING;
+
+ fileSize = downloadObj.size;
+ increment = downloadObj.speed;
+ intervalId = setInterval(function () {
+ if (receivedSize >= fileSize) {//Finish downloading
+ receivedSize = fileSize;
+ downloadObj.state = DownloadState.COMPLETED;
+ _saveFile(downloadObj, function (fileName) {
+ _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
+ });
+ clearInterval(intervalId);
+ } else { // Continue downloading
+ receivedSize += increment;
+ downloadObj.receivedSize = receivedSize;
+ _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
+ }
+ }, INTERVAL);
+ downloadObj.intervalId = intervalId;
+ return downloadObj.id;
+ }
+
+ function cancel(downloadId) {
+ var downloadObj;
+
+ t.DownloadManager("cancel", arguments);
+
+ downloadObj = _getDownloadObjById(downloadId);
+ clearInterval(downloadObj.intervalId);
+ if (downloadObj.state !== DownloadState.DOWNLOADING &&
+ downloadObj.state !== DownloadState.PAUSED) {
+ _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ return;
+ }
+ downloadObj.state = DownloadState.CANCELED;
+ _exec(downloadObj.callback, 'oncanceled', downloadObj.id);
+ }
+
+ function pause(downloadId) {
+ var downloadObj;
-function _load(type) {
- if (!_data.dbStorage[type])
- return;
+ t.DownloadManager("pause", arguments);
- _data[type] = {};
+ downloadObj = _getDownloadObjById(downloadId);
+ clearInterval(downloadObj.intervalId);
+ if (downloadObj.state !== DownloadState.DOWNLOADING) {
+ _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ return;
+ }
+ downloadObj.state = DownloadState.PAUSED;
+ _exec(downloadObj.callback, 'onpaused', downloadObj.id);
+ }
- utils.forEach(_data.dbStorage[type], function (provider, id) {
- var dataId;
+ function resume(downloadId) {
+ var downloadObj, fileSize, receivedSize, increment, intervalId;
- _data[type][id] = {};
+ t.DownloadManager("resume", arguments);
- for (dataId in provider) {
- _data[type][id][dataId] = new DataControlConsumerFactory(type,
- id, dataId, provider[dataId]);
+ downloadObj = _getDownloadObjById(downloadId);
+ fileSize = downloadObj.size;
+ receivedSize = downloadObj.receivedSize;
+ increment = downloadObj.speed;
+
+ if (downloadObj.state !== DownloadState.PAUSED) {
+ _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ return;
}
- });
-}
+ downloadObj.state = DownloadState.DOWNLOADING;
+ intervalId = setInterval(function () {
+ if (receivedSize >= fileSize) {//Finish downloading
+ receivedSize = fileSize;
+ downloadObj.state = DownloadState.COMPLETED;
+ _saveFile(downloadObj, function (fileName) {
+ _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
+ });
+ clearInterval(intervalId);
+ } else {// Continue downloading
+ receivedSize += increment;
+ downloadObj.receivedSize = receivedSize;
+ _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
+ }
+ }, INTERVAL);
+ downloadObj.intervalId = intervalId;
+ }
-function _initialize() {
- _get();
+ function getState(downloadId) {
+ var downloadObj;
- _load("SQL");
- _load("MAP");
-}
+ t.DownloadManager("getState", arguments);
-_self = function () {
- var datacontrol;
+ downloadObj = _getDownloadObjById(downloadId);
+ return downloadObj.state;
+ }
- // private
- function initConsumer(type) {
- var providers;
+ function getDownloadRequest(downloadId) {
+ var req, downloadObj;
- _data.dbStorage[type] = {};
- providers = _data.dbStorage[type];
+ t.DownloadManager("getDownloadRequest", arguments);
- _data.IDS_PROVIDER.forEach(function (id) {
- providers[id] = {};
+ downloadObj = _getDownloadObjById(downloadId);
+ req = new DownloadRequest(downloadObj.url, downloadObj.destination, downloadObj.fileName);
+ return req;
+ }
- _data.IDS_DATA.forEach(function (dataId) {
- providers[id][dataId] = {};
- });
- });
+ function getMIMEType(downloadId) {
+ var downloadObj;
- _load(type);
+ t.DownloadManager("getMIMEType", arguments);
+
+ downloadObj = _getDownloadObjById(downloadId);
+ return downloadObj.MIMEType;
}
- // public
- function getDataControlConsumer(providerId, dataId, type) {
- if (!_security.getDataControlConsumer) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ function setListener(downloadId, downloadCallback) {
+ var downloadObj;
- t.DataControlManager("getDataControlConsumer", arguments);
+ t.DownloadManager("setListener", arguments);
- if (_data[type] === null) {
- initConsumer(type);
- }
- if (!_data[type][providerId] || !_data[type][providerId][dataId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ downloadObj = _getDownloadObjById(downloadId);
+ if (downloadObj) {
+ downloadObj.callback = downloadCallback;
}
-
- return _data[type][providerId][dataId];
}
function handleSubFeatures(subFeatures) {
}
}
- datacontrol = {
- getDataControlConsumer: getDataControlConsumer,
- handleSubFeatures: handleSubFeatures
+ var download = {
+ start: start,
+ cancel: cancel,
+ pause: pause,
+ resume: resume,
+ getState: getState,
+ getDownloadRequest: getDownloadRequest,
+ getMIMEType: getMIMEType,
+ setListener: setListener,
+ handleSubFeatures: handleSubFeatures
};
- return datacontrol;
+ return download;
};
-DataControlConsumerObject = function (type, providerId, dataId) {
- this.__defineGetter__("type", function () {
- return type;
- });
+event.on('downloadResourceChanged', function () {
+ _isInitialized = false;
+});
- this.__defineGetter__("providerId", function () {
- return providerId;
- });
+module.exports = _self;
- this.__defineGetter__("dataId", function () {
- return dataId;
- });
-};
+});
+define('ripple/platform/tizen/2.0/CalendarAttendee', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
-SQLDataControlConsumer = function (providerId, dataId, dc) {
- var self, privateData = new SQLData(dc);
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ CalendarAttendee;
- // public
- function insert(reqId, insertionData, successCallback, errorCallback) {
- if (!_security.insert) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+CalendarAttendee = function (uri, attendeeInitDict) {
+ var calendarAttendee = {}, attr;
- t.SQLDataControlConsumer("insert", arguments, true);
+ t.CalendarAttendee(arguments, this);
- privateData.insert(insertionData, function (rowId) {
- if (successCallback) {
- successCallback(reqId, rowId);
- }
- }, function (error) {
- if (errorCallback) {
- errorCallback(reqId, error);
- }
- });
- }
+ calendarAttendee.uri = uri;
+ calendarAttendee.name = undefined;
+ calendarAttendee.role = "REQ_PARTICIPANT";
+ calendarAttendee.status = "PENDING";
+ calendarAttendee.RSVP = false;
+ calendarAttendee.type = "INDIVIDUAL";
+ calendarAttendee.group = undefined;
+ calendarAttendee.delegatorURI = undefined;
+ calendarAttendee.delegateURI = undefined;
+ calendarAttendee.contactRef = null;
- function update(reqId, updateData, where, successCallback, errorCallback) {
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (attendeeInitDict) {
+ for (attr in attendeeInitDict) {
+ calendarAttendee[attr] = attendeeInitDict[attr];
}
-
- t.SQLDataControlConsumer("update", arguments, true);
-
- privateData.update(updateData, where, function () {
- if (successCallback) {
- successCallback(reqId);
- }
- }, function (error) {
- if (errorCallback) {
- errorCallback(reqId, error);
- }
- });
}
- function remove(reqId, where, successCallback, errorCallback) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("uri", function () {
+ return calendarAttendee.uri;
+ });
+ this.__defineSetter__("uri", function (val) {
+ try {
+ calendarAttendee.uri = t.DOMString(val);
+ } catch (e) {
}
+ });
- t.SQLDataControlConsumer("remove", arguments, true);
-
- privateData.remove(where, function () {
- if (successCallback) {
- successCallback(reqId);
- }
- }, function (error) {
- if (errorCallback) {
- errorCallback(reqId, error);
- }
- });
- }
-
- function select(reqId, columns, where, successCallback, errorCallback, page,
- maxNumberPerPage) {
- if (!_security.select) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("name", function () {
+ return calendarAttendee.name;
+ });
+ this.__defineSetter__("name", function (val) {
+ try {
+ calendarAttendee.name = t.DOMString(val, "?");
+ } catch (e) {
}
+ });
- t.SQLDataControlConsumer("select", arguments, true);
-
- privateData.select(columns, where, function (rows) {
- successCallback(rows, reqId);
- }, function (error) {
- if (errorCallback) {
- errorCallback(reqId, error);
- }
- }, page, maxNumberPerPage);
- }
-
- self = new DataControlConsumerObject("SQL", providerId, dataId);
-
- self.insert = insert;
- self.update = update;
- self.remove = remove;
- self.select = select;
-
- return self;
-};
-
-MappedDataControlConsumer = function (providerId, dataId, dc) {
- var self, privateData = new MappedData(dc);
-
- function addValue(reqId, key, value, successCallback, errorCallback) {
- if (!_security.addValue) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("role", function () {
+ return calendarAttendee.role;
+ });
+ this.__defineSetter__("role", function (val) {
+ try {
+ calendarAttendee.role = t.AttendeeRole(val);
+ } catch (e) {
}
+ });
- t.MappedDataControlConsumer("addValue", arguments);
-
- window.setTimeout(function () {
- if (privateData.insert(key, value)) {
- if (successCallback) {
- successCallback(reqId);
- }
- } else if (errorCallback) {
- errorCallback(reqId, new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- }, 1);
- }
-
- function removeValue(reqId, key, value, successCallback, errorCallback) {
- if (!_security.removeValue) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("status", function () {
+ return calendarAttendee.status;
+ });
+ this.__defineSetter__("status", function (val) {
+ try {
+ calendarAttendee.status = t.AttendeeStatus(val);
+ } catch (e) {
}
+ });
- t.MappedDataControlConsumer("removeValue", arguments);
-
- window.setTimeout(function () {
- if (privateData.remove(key, value)) {
- successCallback(reqId);
- } else if (errorCallback) {
- errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- }, 1);
- }
-
- function getValue(reqId, key, successCallback, errorCallback) {
- if (!_security.getValue) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("RSVP", function () {
+ return calendarAttendee.RSVP;
+ });
+ this.__defineSetter__("RSVP", function (val) {
+ try {
+ calendarAttendee.RSVP = t.boolean(val);
+ } catch (e) {
}
+ });
- t.MappedDataControlConsumer("getValue", arguments);
-
- window.setTimeout(function () {
- var values;
-
- values = privateData.search(key);
-
- if (values !== null) {
- successCallback(values, reqId);
- } else if (errorCallback) {
- errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- }, 1);
- }
-
- function updateValue(reqId, key, oldValue, newValue, successCallback,
- errorCallback) {
- if (!_security.updateValue) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineGetter__("type", function () {
+ return calendarAttendee.type;
+ });
+ this.__defineSetter__("type", function (val) {
+ try {
+ calendarAttendee.type = t.AttendeeType(val);
+ } catch (e) {
}
+ });
- t.MappedDataControlConsumer("updateValue", arguments);
-
- window.setTimeout(function () {
- if (privateData.update(key, oldValue, newValue)) {
- successCallback(reqId);
- } else if (errorCallback) {
- errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- }, 1);
- }
+ this.__defineGetter__("group", function () {
+ return calendarAttendee.group;
+ });
+ this.__defineSetter__("group", function (val) {
+ try {
+ calendarAttendee.group = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- self = new DataControlConsumerObject("MAP", providerId, dataId);
+ this.__defineGetter__("delegatorURI", function () {
+ return calendarAttendee.delegatorURI;
+ });
+ this.__defineSetter__("delegatorURI", function (val) {
+ try {
+ calendarAttendee.delegatorURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- self.addValue = addValue;
- self.removeValue = removeValue;
- self.getValue = getValue;
- self.updateValue = updateValue;
+ this.__defineGetter__("delegateURI", function () {
+ return calendarAttendee.delegateURI;
+ });
+ this.__defineSetter__("delegateURI", function (val) {
+ try {
+ calendarAttendee.delegateURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- return self;
+ this.__defineGetter__("contactRef", function () {
+ return calendarAttendee.contactRef;
+ });
+ this.__defineSetter__("contactRef", function (val) {
+ try {
+ calendarAttendee.contactRef = t.ContactRef(val, "?");
+ } catch (e) {
+ }
+ });
};
-DataControlConsumerFactory = function (type, providerId, dataId, dc) {
- var self;
-
- switch (type) {
- case "SQL":
- self = new SQLDataControlConsumer(providerId, dataId, dc);
- break;
+module.exports = CalendarAttendee;
- case "MAP":
- self = new MappedDataControlConsumer(providerId, dataId, dc);
- break;
- }
+});
+define('ripple/platform/tizen/2.0/decorator', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- return self;
-};
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactDecorator,
+ _self;
-SQLData = function (dc) {
- var self, data, columnNames, SQLErr2WebAPIErr;
+ContactDecorator = function (contact, overlap) {
+ var raw = {};
// private
- function getDBTableName() {
- return "DC_" + Math.uuid(8, 16);
- }
-
- function getColumnNames(tx, results) {
- columnNames = results.rows.item(0).sql
- .replace(/^[^\(]+\(([^\)]+)\)/g, "$1")
- .replace(/(^|(,) )([^ ,]+)([^,]*|$)/g, "$2$3")
- .split(",");
- }
+ function clone(obj) {
+ return function () {
+ var Contact = require('ripple/platform/tizen/2.0/ContactBase'),
+ duplicate;
- function queryColumns(columns) {
- return columns.join("=?,") + "=?";
- }
+ duplicate = new Contact(obj);
- function queryValues(n) {
- return (new Array(n)).join("?,") + "?";
- }
+ duplicate.__defineGetter__("id", function () {
+ return null;
+ });
- function shedQuotes(values) {
- return values.every(function (value, i, arr) {
- arr[i] = value.replace(/^('|")(.*)\1$/g, "$2");
+ duplicate.__defineGetter__("addressBookId", function () {
+ return null;
+ });
- return (arr[i] !== value);
- });
+ return duplicate;
+ };
}
- function isNull(p) {
- return ((p === undefined) || (p === null));
+ // public
+ function convertToString(format) {
+ t.Contact("convertToString", arguments);
+
+ // TODO: Convert contact according to VCard protocal
+ return "";
}
- function initialize() {
- SQLErr2WebAPIErr = [
- 0, // 0: UNKNOWN_ERR 0: UNKNOWN_ERR
- 100, // 1: DATABASE_ERR 100: IO_ERR
- 100, // 2: VERSION_ERR 100: IO_ERR
- 100, // 3: TOO_LARGE_ERR 100: IO_ERR
- 22, // 4: QUOTA_ERR 22: QUOTA_EXCEEDED_ERR
- 12, // 5: SYNTAX_ERR 12: SYNTAX_ERR
- 100, // 6: CONSTRAINT_ERR 100: IO_ERR
- 23 // 7: TIMEOUT_ERR 23: TIMEOUT_ERR
- ];
+ raw.id = overlap ? overlap.id : null;
+ raw.personId = overlap ? overlap.personId : null;
+ raw.addressBookId = overlap ? overlap.addressBookId : null;
+ raw.lastUpdated = overlap ? overlap.lastUpdated : null;
+ raw.isFavorite = overlap ? overlap.isFavorite : false;
+ raw.name = contact.name;
+ raw.addresses = contact.addresses;
+ raw.photoURI = contact.photoURI;
+ raw.phoneNumbers = contact.phoneNumbers;
+ raw.emails = contact.emails;
+ raw.birthday = contact.birthday;
+ raw.anniversaries = contact.anniversaries;
+ raw.organizations = contact.organizations;
+ raw.notes = contact.notes;
+ raw.urls = contact.urls;
+ raw.ringtoneURI = contact.ringtoneURI;
+ raw.groupIds = contact.groupIds;
- if (!("table" in dc)) {
- dc.table = getDBTableName();
- columnNames = ["id"];
- _save();
- }
+ contact.__defineGetter__("id", function () {
+ return raw.id;
+ });
- data = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence',
- 2 * 1024 * 1024);
+ contact.__defineGetter__("personId", function () {
+ return raw.personId;
+ });
- data.transaction(function (tx) {
- tx.executeSql('CREATE TABLE IF NOT EXISTS ' + dc.table +
- ' (id unique)');
- tx.executeSql('SELECT sql FROM sqlite_master WHERE type="table" AND name=?',
- [dc.table], getColumnNames);
- });
- }
+ contact.__defineGetter__("addressBookId", function () {
+ return raw.addressBookId;
+ });
- // public
- function insert(rowData, onSuccess, onError) {
- if (rowData.columns.length > rowData.values.length) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- if (!shedQuotes(rowData.values)) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
+ contact.__defineGetter__("lastUpdated", function () {
+ return raw.lastUpdated;
+ });
- data.transaction(function (tx) {
- rowData.columns.forEach(function (column) {
- if (columnNames.indexOf(column) !== -1)
- return;
+ contact.__defineGetter__("isFavorite", function () {
+ return raw.isFavorite;
+ });
- tx.executeSql('ALTER TABLE ' + dc.table + ' ADD ' + column +
- ' TEXT', [], function () {
- columnNames.push(column);
- }, function (tx, error) {
- onError(new WebAPIError(
- SQLErr2WebAPIErr[error.code],
- error.message));
- });
- });
+ contact.__defineGetter__("name", function () {
+ return raw.name;
+ });
+ contact.__defineSetter__("name", function (val) {
+ try {
+ raw.name = t.ContactName(val, "?");
+ } catch (e) {
+ }
+ });
- tx.executeSql('INSERT INTO ' + dc.table + ' (' +
- rowData.columns.join() + ') VALUES (' +
- queryValues(rowData.values.length) + ')', rowData.values,
- function (tx, results) {
- onSuccess(results.insertId);
- }, function (tx, error) {
- onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
- error.message));
- });
- });
- }
+ contact.__defineGetter__("addresses", function () {
+ return raw.addresses;
+ });
+ contact.__defineSetter__("addresses", function (val) {
+ try {
+ raw.addresses = t.ContactAddress(val, "[]");
+ } catch (e) {
+ }
+ });
- function update(rowData, where, onSuccess, onError) {
- if (rowData.columns.length > rowData.values.length) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ contact.__defineGetter__("photoURI", function () {
+ return raw.photoURI;
+ });
+ contact.__defineSetter__("photoURI", function (val) {
+ try {
+ raw.photoURI = t.DOMString(val, "?");
+ } catch (e) {
}
- if (!shedQuotes(rowData.values)) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ });
+
+ contact.__defineGetter__("phoneNumbers", function () {
+ return raw.phoneNumbers;
+ });
+ contact.__defineSetter__("phoneNumbers", function (val) {
+ try {
+ raw.phoneNumbers = t.ContactPhoneNumber(val, "[]");
+ } catch (e) {
}
+ });
- data.transaction(function (tx) {
- tx.executeSql('UPDATE ' + dc.table + ' SET ' +
- queryColumns(rowData.columns) + ' WHERE ' + where,
- rowData.values, onSuccess, function (tx, error) {
- onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
- error.message));
- });
- });
- }
+ contact.__defineGetter__("emails", function () {
+ return raw.emails;
+ });
+ contact.__defineSetter__("emails", function (val) {
+ try {
+ raw.emails = t.ContactEmailAddress(val, "[]");
+ } catch (e) {
+ }
+ });
- function remove(where, onSuccess, onError) {
- data.transaction(function (tx) {
- tx.executeSql('DELETE FROM ' + dc.table + ' WHERE ' + where, [],
- onSuccess, function (tx, error) {
- onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
- error.message));
- });
- });
- }
+ contact.__defineGetter__("birthday", function () {
+ return raw.birthday;
+ });
+ contact.__defineSetter__("birthday", function (val) {
+ try {
+ raw.birthday = t.Date(val, "?");
+ } catch (e) {
+ }
+ });
- function select(columns, where, onSuccess, onError, page, maxNumberPerPage) {
- if (isNull(page)) {
- page = 1;
- } else {
- if (page <= 0) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- page = parseInt(page, 10);
+ contact.__defineGetter__("anniversaries", function () {
+ return raw.anniversaries;
+ });
+ contact.__defineSetter__("anniversaries", function (val) {
+ try {
+ raw.anniversaries = t.ContactAnniversary(val, "[]");
+ } catch (e) {
}
+ });
- if (isNull(maxNumberPerPage)) {
- if (page > 1) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- } else {
- if (maxNumberPerPage <= 0) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- maxNumberPerPage = parseInt(maxNumberPerPage, 10);
+ contact.__defineGetter__("organizations", function () {
+ return raw.organizations;
+ });
+ contact.__defineSetter__("organizations", function (val) {
+ try {
+ raw.organizations = t.ContactOrganization(val, "[]");
+ } catch (e) {
}
+ });
- data.transaction(function (tx) {
- tx.executeSql('SELECT ' + columns.join() + ' FROM ' + dc.table +
- ' WHERE ' + where, [], function (tx, results) {
- var rows = [], rowStart, rowData, r, c;
+ contact.__defineGetter__("notes", function () {
+ return raw.notes;
+ });
+ contact.__defineSetter__("notes", function (val) {
+ try {
+ raw.notes = t.DOMString(val, "[]");
+ } catch (e) {
+ }
+ });
- rowStart = maxNumberPerPage ?
- (page - 1) * maxNumberPerPage : 0;
+ contact.__defineGetter__("urls", function () {
+ return raw.urls;
+ });
+ contact.__defineSetter__("urls", function (val) {
+ try {
+ raw.urls = t.ContactWebSite(val, "[]");
+ } catch (e) {
+ }
+ });
- for (r = rowStart; r < results.rows.length; ++r) {
- rowData = {
- columns: columns,
- values: []
- };
- for (c in columns) {
- rowData.values.push(results.rows
- .item(r)[columns[c]]);
- }
- rows.push(rowData);
+ contact.__defineGetter__("ringtoneURI", function () {
+ return raw.ringtoneURI;
+ });
+ contact.__defineSetter__("ringtoneURI", function (val) {
+ try {
+ raw.ringtoneURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- if (maxNumberPerPage && (--maxNumberPerPage === 0))
- break;
- }
+ contact.__defineGetter__("groupIds", function () {
+ return raw.groupIds;
+ });
+ contact.__defineSetter__("groupIds", function (val) {
+ try {
+ raw.groupIds = t.ContactGroupId(val, "[]");
+ } catch (e) {
+ }
+ });
- onSuccess(rows);
- }, function (tx, error) {
- onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
- error.message));
- });
+ if (contact.name) {
+ contact.name.__defineGetter__("displayName", function () {
+ return ((overlap && overlap.name) ? overlap.name.displayName :
+ null);
});
}
- initialize();
-
- self = {
- insert: insert,
- update: update,
- remove: remove,
- select: select
- };
+ contact.convertToString = convertToString;
+ contact.clone = clone(contact);
+};
- return self;
+_self = {
+ Contact: ContactDecorator
};
-MappedData = function (dc) {
- var self, data = {}, ioStamp = 0;
+module.exports = _self;
- // private
- function addNode(tree, arr, i) {
- var key, value;
+});
+define('ripple/platform/tizen/2.0/BookmarkItem', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if (typeof arr[i] === "string") {
- key = arr[i];
- value = 1;
- } else {
- key = arr[i][0];
- value = arr[i][1];
- }
- tree.insert(key, value);
- }
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ BookmarkItem;
- function bisearch(tree, arr, queue) {
- var start, end, mid;
+BookmarkItem = function (title, url) {
+ t.BookmarkItem(arguments, this);
- if (queue.length === 0)
- return;
+ this.__defineGetter__("parent", function () {
+ return undefined;
+ });
+ this.__defineGetter__("title", function () {
+ return title;
+ });
+ this.__defineGetter__("url", function () {
+ return url;
+ });
+};
- start = queue.shift();
- end = queue.shift();
+module.exports = BookmarkItem;
- if (start > end)
- return;
+});
+define('ripple/platform/tizen/2.0/ContactAddress', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- mid = start + parseInt((end - start) / 2, 10);
- addNode(tree, arr, mid);
- queue.push(start, mid - 1);
- queue.push(mid + 1, end);
- }
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactAddress;
- function build(arr) {
- var tree, mid, lTree = [], rTree = [];
+ContactAddress = function (addressInitDict) {
+ var contactAddress = {}, attr, arr, i;
- tree = redblack.tree();
- mid = parseInt(arr.length / 2, 10);
- addNode(tree, arr, mid);
+ t.ContactAddress(arguments, this);
- lTree.push(0, mid - 1);
- rTree.push(mid + 1, arr.length - 1);
+ contactAddress.country = null;
+ contactAddress.region = null;
+ contactAddress.city = null;
+ contactAddress.streetAddress = null;
+ contactAddress.additionalInformation = null;
+ contactAddress.postalCode = null;
+ contactAddress.isDefault = false;
+ contactAddress.types = ["HOME"];
- while ((lTree.length > 0) || (rTree.length > 0)) {
- bisearch(tree, arr, lTree);
- bisearch(tree, arr, rTree);
+ this.__defineGetter__("country", function () {
+ return contactAddress.country;
+ });
+ this.__defineSetter__("country", function (val) {
+ try {
+ contactAddress.country = t.DOMString(val, "?");
+ } catch (e) {
}
+ });
- return tree;
- }
-
- function initialize() {
- for (var key in dc) {
- data[key] = build(dc[key]);
+ this.__defineGetter__("region", function () {
+ return contactAddress.region;
+ });
+ this.__defineSetter__("region", function (val) {
+ try {
+ contactAddress.region = t.DOMString(val, "?");
+ } catch (e) {
}
- }
-
- function traverse(tree, key) {
- dc[key] = [];
- tree.forEach(function (count, value) {
- dc[key].push((count === 1) ? value : [value, count]);
- });
- }
+ });
- function persist() {
- if (ioStamp !== 0) {
- window.clearTimeout(ioStamp);
+ this.__defineGetter__("city", function () {
+ return contactAddress.city;
+ });
+ this.__defineSetter__("city", function (val) {
+ try {
+ contactAddress.city = t.DOMString(val, "?");
+ } catch (e) {
}
- ioStamp = window.setTimeout(function () {
- var key;
-
- for (key in data) {
- traverse(data[key], key);
- }
-
- _save();
-
- ioStamp = 0;
- }, _data.PERSIST_DELAY);
- }
-
- // public
- function insert(key, value) {
- var tree, count;
+ });
- if (!(key in data)) {
- data[key] = redblack.tree();
+ this.__defineGetter__("streetAddress", function () {
+ return contactAddress.streetAddress;
+ });
+ this.__defineSetter__("streetAddress", function (val) {
+ try {
+ contactAddress.streetAddress = t.DOMString(val, "?");
+ } catch (e) {
}
+ });
- tree = data[key];
-
- if (!tree)
- return false;
-
- count = tree.get(value);
- tree.insert(value, count ? (count + 1) : 1);
- persist();
-
- return true;
- }
+ this.__defineGetter__("additionalInformation", function () {
+ return contactAddress.additionalInformation;
+ });
+ this.__defineSetter__("additionalInformation", function (val) {
+ try {
+ contactAddress.additionalInformation = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- function remove(key, value) {
- var tree, count;
+ this.__defineGetter__("postalCode", function () {
+ return contactAddress.postalCode;
+ });
+ this.__defineSetter__("postalCode", function (val) {
+ try {
+ contactAddress.postalCode = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- if (!(key in data))
- return false;
+ this.__defineGetter__("isDefault", function () {
+ return contactAddress.isDefault;
+ });
+ this.__defineSetter__("isDefault", function (val) {
+ try {
+ contactAddress.isDefault = t.boolean(val);
+ } catch (e) {
+ }
+ });
- tree = data[key];
- count = tree.get(value);
- if (count === null)
- return false;
+ this.__defineGetter__("types", function () {
+ return contactAddress.types;
+ });
+ this.__defineSetter__("types", function (val) {
+ try {
+ contactAddress.types = t.DOMString(val, "[]");
+ } catch (e) {
+ }
+ });
- tree.delete(value);
+ if (addressInitDict) {
+ for (attr in addressInitDict) {
+ switch (attr) {
+ case "types":
+ arr = addressInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ contactAddress[attr][i] = arr[i];
+ }
+ }
+ break;
- if (tree.root === null) {
- delete data[key];
- if (key in dc) {
- delete dc[key];
+ default:
+ contactAddress[attr] = addressInitDict[attr];
+ break;
}
}
-
- persist();
-
- return true;
}
+};
- function search(key) {
- var values = [], tree;
-
- if (!(key in data))
- return null;
-
- tree = data[key];
- tree.forEach(function (count, value) {
- while (count--) {
- values.push(value);
- }
- });
-
- return values;
- }
+module.exports = ContactAddress;
- function update(key, oldValue, newValue) {
- var tree, count, countNew;
+});
+define('ripple/platform/tizen/2.0/ContactEmailAddress', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if (!(key in data))
- return false;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactEmailAddress;
- tree = data[key];
- count = tree.get(oldValue);
- if (count === null)
- return false;
+ContactEmailAddress = function (email, types, isDefault) {
+ var contactEmailAddress = {};
- countNew = tree.get(newValue);
- count += (countNew === null) ? 0 : countNew;
- tree.delete(oldValue);
- tree.insert(newValue, count);
- persist();
+ t.ContactEmailAddress(arguments, this);
- return true;
- }
+ contactEmailAddress.email = email;
+ contactEmailAddress.isDefault = isDefault || false;
+ contactEmailAddress.types = (types && types[0]) ? types : ["WORK"];
- initialize();
+ this.__defineGetter__("email", function () {
+ return contactEmailAddress.email;
+ });
+ this.__defineSetter__("email", function (val) {
+ try {
+ contactEmailAddress.email = t.DOMString(val);
+ } catch (e) {
+ }
+ });
- self = {
- insert: insert,
- remove: remove,
- search: search,
- update: update
- };
+ this.__defineGetter__("isDefault", function () {
+ return contactEmailAddress.isDefault;
+ });
+ this.__defineSetter__("isDefault", function (val) {
+ try {
+ contactEmailAddress.isDefault = t.boolean(val);
+ } catch (e) {
+ }
+ });
- return self;
+ this.__defineGetter__("types", function () {
+ return contactEmailAddress.types;
+ });
+ this.__defineSetter__("types", function (val) {
+ try {
+ contactEmailAddress.types = t.DOMString(val, "[]");
+ } catch (e) {
+ }
+ });
};
-_initialize();
-
-module.exports = _self;
+module.exports = ContactEmailAddress;
});
-define('ripple/platform/tizen/2.0/datasync', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/account', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
var db = require('ripple/db'),
utils = require('ripple/utils'),
- ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
- t = require('ripple/platform/tizen/2.0/typecast'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- SyncInfoMod = require('ripple/platform/tizen/2.0/SyncInfo'),
- SyncServiceInfoMod = require('ripple/platform/tizen/2.0/SyncServiceInfo'),
- SyncProfileInfoMod = require('ripple/platform/tizen/2.0/SyncProfileInfo'),
- SyncStatistics = require('ripple/platform/tizen/2.0/SyncStatistics'),
_data = {
- DB_DATASYNC_ITEMS: "tizen1-db-datasync-items",
- DB_DATASYNC_COUNTER: "tizen1-db-datasync-counter",
- MAX_PROFILE_NUMBER: 5,
- profile_num: 0,
- profiles: {},
- sync_accounts: {},
- service_accounts: {},
- item_counter: 1000,
- type_table: {
- "TWO_WAY": 1,
- "SLOW": 2,
- "ONE_WAY_FROM_CLIENT": 3,
- "REFRESH_FROM_CLIENT": 4,
- "ONE_WAY_FROM_SERVER": 5,
- "REFRESH_FROM_SERVER": 6
- },
- mode_table: {
- "TWO_WAY": 200,
- "SLOW": 201,
- "ONE_WAY_FROM_CLIENT": 202,
- "REFRESH_FROM_CLIENT": 203,
- "ONE_WAY_FROM_SERVER": 204,
- "REFRESH_FROM_SERVER": 205
- },
- items: {}
- },
- _security = {
- "http://tizen.org/privilege/datasync":
- ["add", "update", "remove", "getMaxProfilesNum", "getProfilesNum",
- "get", "getAll", "startSync", "stopSync", "getLastSyncStatistics"]
- },
- _self,
- syncml = {
- adapter: require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
- agent: require('ripple/platform/tizen/2.0/syncml-js-lib/agent'),
- base64: require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
- codec: require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
- common: require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant: require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- context: require('ripple/platform/tizen/2.0/syncml-js-lib/context'),
- ctype: require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
- devinfo: require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
- item: require('ripple/platform/tizen/2.0/syncml-js-lib/item'),
- localadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
- matcher: require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
- protocol: require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
- remoteadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
- router: require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
- state: require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
- storage: require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
- store: require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
- synchronizer: require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
- useragent: require('ripple/platform/tizen/2.0/syncml-js-lib/useragent')
+ DB_ACCOUNT_KEY : "tizen1-db-accounts",
+ accounts : {}
},
- TizenAgent;
+ _self;
-function _get() {
- _data.item_counter = db.retrieveObject(_data.DB_DATASYNC_COUNTER) || 1000;
- _data.items = db.retrieveObject(_data.DB_DATASYNC_ITEMS) || {};
-}
+function _checkAccount(account) {
+ if (typeof account !== "object" ||
+ typeof account.id !== "string" ||
+ typeof account.appid !== "string" ||
+ typeof account.userName !== "string" ||
+ typeof account.displayName !== "string" ||
+ typeof account.service !== "object") {
+ return false;
+ }
-function _save() {
- db.saveObject(_data.DB_DATASYNC_COUNTER, _data.item_counter);
- db.saveObject(_data.DB_DATASYNC_ITEMS, _data.items);
+ return true;
}
-TizenAgent = syncml.agent.Agent.extend({
- constructor: function() {
- },
- getContentTypes: function() {
- return [
- new syncml.ctype.ContentTypeInfo('text/x-vcard', '2.1',{preferred: true})
- ];
- },
- dumpsItem: function(item, contentType, version, cb) {
- var cdata = new ET.CdataElement(item.item);
- cb(null, cdata);
- },
- loadsItem: function(data, contentType, version, cb) {
- return cb(null, {item: data._node.textContent});
- },
- getAllItems: function(cb) {
- var items = [];
- utils.forEach(_data.items, function(contact) {
- items.push(contact);
- });
- return cb(null, items);
- },
- addItem: function(item, cb) {
- _data.item_counter++;
- item.id = _data.item_counter.toString();
- _data.items[item.id] = item;
- _save();
- return cb(null, item);
- },
- getItem: function(itemID, cb) {
- return cb(null, _data.items[itemID]);
- },
- replaceItem: function(item, reportChanges, cb) {
- _data.items[item.id] = item;
- _save();
- return cb(null, null);
- },
- deleteItem: function(itemID, cb) {
- delete _data.items[itemID];
- _save();
- return cb(null);
+function _checkCallback(successCallback, errorCallback) {
+ tizen1_utils.validateArgumentType(successCallback, "function",
+ new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ if (errorCallback) {
+ tizen1_utils.validateArgumentType(errorCallback, "function",
+ new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
-});
-
-function _initialize() {
- _data.agent = new TizenAgent();
- _get();
}
-_self = function () {
- var datasync;
-
- // private
- function createInternalProfile(profile) {
- var _profile, sync_account, service_accounts;
+_self = {
+ getAccounts : function () {
+ var results = [];
+ utils.forEach(_data.accounts, function (account) {
+ results.push(utils.copy(account));
+ });
- sync_account = db.retrieveObject("save-syncinfo")[profile.syncInfo.__syncInfoID__];
+ return results;
+ },
- _profile = {
- profileName: profile.profileName,
- syncInfo: {
- url: profile.syncInfo.url,
- id: sync_account.id,
- password: sync_account.password,
- mode: profile.syncInfo.mode
- },
- serviceInfo: []
- };
+ getAccountById : function (id) {
+ var acccount = null;
- switch (_profile.syncInfo.mode) {
- case "MANUAL":
- _profile.syncInfo.type = profile.syncInfo.type || "TWO_WAY";
- break;
- case "PERIODIC":
- //TODO: set 1_HOUR as default value
- _profile.interval = profile.syncInfo.interval || "1_HOUR";
- _profile.syncInfo.type = "TWO_WAY";
- break;
- case "PUSH":
- _profile.syncInfo.type = "TWO_WAY";
- break;
+ if (typeof id !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- if (profile.serviceInfo) {
- service_accounts = db.retrieveObject("save-syncserviceinfo");
- utils.forEach(profile.serviceInfo, function (service) {
- _profile.serviceInfo.push({
- enable: service.enable,
- serviceType: service.serviceType,
- serverDatabaseUri: service.serverDatabaseUri,
- id: service_accounts[service.__syncServiceInfoID__].id,
- password: service_accounts[service.__syncServiceInfoID__].password
- });
- });
+ if (_data.accounts[id]) {
+ account = utils.copy(_data.accounts[id]);
}
- return _profile;
- }
-
- function createExternalProfile(profileId) {
- var profile, i, _syncinfo, _serviceinfo, p;
+ return account;
+ },
- p = _data.profiles[profileId];
+ getAccountByUserName : function (userName) {
+ var result = null;
- switch (p.syncInfo.mode) {
- case "MANUAL":
- _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "MANUAL", p.syncInfo.type);
- _syncinfo.interval = null;
- break;
- case "PERIODIC":
- _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PERIODIC", p.syncInfo.interval);
- break;
- case "PUSH":
- _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PUSH");
- break;
+ if (typeof userName !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- if (p.serviceInfo) {
- _serviceinfo = [];
- for (i in p.serviceInfo) {
- var info;
- info = new SyncServiceInfoMod(p.serviceInfo[i].enable,
- p.serviceInfo[i].serviceType, p.serviceInfo[i].serverDatabaseUri,
- p.serviceInfo[i].id || null, p.serviceInfo[i].password || null);
- _serviceinfo.push(info);
+ utils.forEach(_data.accounts, function (account) {
+ if (userName === account.userName) {
+ result = utils.copy(account);
}
- }
-
- profile = new SyncProfileInfoMod(p.profileName, _syncinfo, _serviceinfo);
- Object.defineProperty(profile, "profileId", {value: p.profileId, writable: false});
+ });
- return profile;
- }
+ return result;
+ },
- // public
- function add(profile) {
- var _profile;
+ getAccountByappId : function (appId) {
+ var result = null;
- if (!_security.add) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (typeof appId !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- t.DataSynchronizationManager("add", arguments);
+ utils.forEach(_data.accounts, function (account) {
+ if (appId === account.appId) {
+ result = utils.copy(account);
+ }
+ });
- _profile = createInternalProfile(profile);
+ return result;
+ },
- if (_data.profile_num > _data.MAX_PROFILE_NUMBER) {
- throw new WebAPIException(errorcode.QUOTA_EXCEEDED_ERR);
+ getAccountByServiceId : function (serviceId) {
+ var result = null;
+
+ if (typeof serviceId !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- _profile.profileId = Math.uuid(null, 16);
- _data.profiles[_profile.profileId] = _profile;
- _data.profile_num++;
+ utils.forEach(_data.accounts, function (account) {
+ if (serviceId === account.service.id) {
+ result = utils.copy(account);
+ }
+ });
- Object.defineProperty(profile, "profileId", {value: _profile.profileId, writable: false});
- }
+ return result;
+ },
- function update(profile) {
- var _profile;
+ getAccountByTag : function (tag) {
+ var results = [], i;
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (typeof tag !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- t.DataSynchronizationManager("update", arguments);
-
- _profile = createInternalProfile(profile);
-
- if (!profile.profileId || !_data.profiles[profile.profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+ utils.forEach(_data.accounts, function (account) {
+ for (i in account.service.tag) {
+ if (tag === account.service.tag[i]) {
+ results.push(utils.copy(account));
+ break;
+ }
+ }
+ });
- _profile.profileId = profile.profileId;
- _data.profiles[_profile.profileId] = _profile;
- }
+ return results;
+ },
- function remove(profileId) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ add : function (account, successCallback, errorCallback) {
+ if (!_checkAccount(account)) {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- t.DataSynchronizationManager("remove", arguments);
+ _checkCallback(successCallback, errorCallback);
- if (!_data.profiles[profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ if (!_data.accounts[account.id]) {
+ _data.accounts[account.id] = utils.copy(account);
}
- delete _data.profiles[profileId];
- _data.profile_num--;
- }
+ successCallback();
+ },
- function getMaxProfilesNum() {
- if (!_security.getMaxProfilesNum) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ update : function (account, successCallback, errorCallback) {
+ if (!_checkAccount(account)) {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- return _data.MAX_PROFILE_NUMBER;
- }
+ _checkCallback(successCallback, errorCallback);
- function getProfilesNum() {
- if (!_security.getProfilesNum) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if (!_data.accounts[account.id]) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ return;
}
- return _data.profile_num;
- }
-
- function get(profileId) {
- var profile;
+ _data.accounts[account.id] = utils.copy(account);
+ successCallback();
+ },
- if (!_security.get) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ remove : function (id, successCallback, errorCallback) {
+ if (typeof id !== "string") {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
}
- t.DataSynchronizationManager("get", arguments);
+ _checkCallback(successCallback, errorCallback);
- if (!_data.profiles[profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ if (!_data.accounts[id]) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ return;
}
- profile = createExternalProfile(profileId);
+ delete _data.accounts[id];
+ successCallback();
+ },
- return profile;
+ getAccountApplications : function () {
+ var results = [];
+ /* FIXME: wait for API update */
+ return results;
}
+};
- function getAll() {
- var profiles = [], i;
+function _initialize() {
+ _data.accounts = db.retrieveObject(_data.DB_ACCOUNT_KEY) || {};
+}
- if (!_security.getAll) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_initialize();
- for (i in _data.profiles) {
- profiles.push(createExternalProfile(_data.profiles[i].profileId));
- }
+module.exports = _self;
- return profiles;
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/agent', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.agent
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/10/22
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- function startSync(profileId, progressCallback) {
- var _profile, _stores, _routes, sync_peer;
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');
- if (!_security.startSync) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+var _self = (function () {
- t.DataSynchronizationManager("startSync", arguments);
+ var exports = {};
- if (!_data.profiles[profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- _data.profiles[profileId].stop_flag = false;
+ //---------------------------------------------------------------------------
+ exports.Agent = common.Base.extend({
- sync_peer = function(adapter, store, peer, type) {
- adapter.sync(peer, type, function(err, stats) {
- var p, name, hereTotal, peerTotal;
- p = _data.profiles[profileId];
- if (p.stop_flag === true) {
- p.syncStatistics =[{
- syncStatus: "STOP",
- serviceType: p.serviceInfo[0].serviceType,
- lastSyncTime: new Date(),
- serverToClientTotal: 0,
- serverToClientAdded: 0,
- serverToClientUpdated: 0,
- serverToClientRemoved: 0,
- clientToServerTotal: 0,
- clientToServerAdded: 0,
- clientToServerUpdated: 0,
- clientToServerRemoved: 0
- }];
- p.stop_flag = false;
- return;
- }
- if (err) {
- if (progressCallback) {
- if (progressCallback.onfailed) {
- progressCallback.onfailed(profileId, new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- }
- p.syncStatistics =[{
- syncStatus: "FAIL",
- serviceType: p.serviceInfo[0].serviceType,
- lastSyncTime: new Date(),
- serverToClientTotal: 0,
- serverToClientAdded: 0,
- serverToClientUpdated: 0,
- serverToClientRemoved: 0,
- clientToServerTotal: 0,
- clientToServerAdded: 0,
- clientToServerUpdated: 0,
- clientToServerRemoved: 0
- }];
- p.stop_flag = false;
- return;
- }
- name = p.profileName + "-" + p.serviceInfo[0].serviceType;
- hereTotal = stats[name].hereAdd + stats[name].hereDel + stats[name].hereMod;
- peerTotal = stats[name].peerAdd + stats[name].peerDel + stats[name].peerMod;
- p.syncStatistics =[{
- syncStatus: "SUCCESS",
- serviceType: p.serviceInfo[0].serviceType,
- lastSyncTime: new Date(),
- serverToClientTotal: hereTotal,
- serverToClientAdded: stats[name].hereAdd,
- serverToClientUpdated: stats[name].hereMod,
- serverToClientRemoved: stats[name].hereDel,
- clientToServerTotal: peerTotal,
- clientToServerAdded: stats[name].peerAdd,
- clientToServerUpdated: stats[name].peerMod,
- clientToServerRemoved: stats[name].peerDel
- }];
- p.stop_flag = false;
+ //-------------------------------------------------------------------------
+ constructor: function(options) {
+ options = _.defaults(options, {
+ hierarchicalSync: false
+ });
+ this.hierarchicalSync = options.hierarchicalSync;
+ },
- if (progressCallback) {
- if (progressCallback.oncompleted) {
- progressCallback.oncompleted(profileId);
+ //-------------------------------------------------------------------------
+ dumpItem: function(item, stream, contentType, version, cb) {
+ return this.dumpsItem(
+ item, contentType, version,
+ function(err, data, new_contentType, new_version) {
+ if ( err ) {
+ return cb(err);
}
+ stream.write(data, function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ cb(null, new_contentType, new_version);
+ });
+ });
+ },
+
+ //-------------------------------------------------------------------------
+ loadItem: function(stream, contentType, version, cb) {
+ var self = this;
+ stream.read(function(err, data) {
+ if ( err ) {
+ cb(err);
}
+ self.loadsItem(data, contentType, version, cb);
});
- };
- _profile = _data.profiles[profileId];
- _profile.context = new syncml.context.Context({prefix: "tizen-"});
- _stores = [];
- _routes = [];
- utils.forEach(_profile.serviceInfo, function(service) {
- var name = _profile.profileName + "-" + service.serviceType;
- _stores.push({
- uri: name,
- displayName: name,
- maxGuidSize: 64,
- maxObjSize: 4000000,
- agent: _data.agent
- });
- _routes.push([name, service.serverDatabaseUri]);
- });
- _profile.context.getEasyClientAdapter({
- displayName: "Tizen syncML adapter",
- devInfo: {
- devID: "tizen-syncml-03",
- devType: syncml.constant.DEVTYPE_WORKSTATION,
- manufacturerName: "Tizen",
- modelName: "tizen.syncml.client",
- hierarchicalSync: false
- },
- stores: _stores,
- peer: {
- url: _profile.syncInfo.url,
- username: _profile.syncInfo.id,
- password: _profile.syncInfo.password
- },
- routes: _routes
- }, function(err, adapter, stores, peer) {
- if (err) {
- console.log("[datasync.syncml] getEasyClientAdapter fail:", err);
- return;
- }
- utils.forEach(stores, function(store) {
- var args = {
- data: _data.mode_table[_profile.syncInfo.type],
- source: store.uri,
- target: _profile.serviceInfo[0].serverDatabaseUri,
- nextAnchor: syncml.common.ts()
- };
- if (args.data === _data.mode_table["SLOW"]) {
- args.lastAnchor = null;
- } else if (peer.getStore(args.target)) {
- args.lastAnchor = peer.getStore(args.target)._getBinding().localAnchor;
- }
+ },
- db.saveObject("syncml-alert-args", args);
- db.saveObject("syncml-first-flag", false);
- sync_peer(adapter, store, peer, _data.type_table[_profile.syncInfo.type]);
+ //-------------------------------------------------------------------------
+ deleteAllItems: function(cb) {
+ var self = this;
+ self.getAllItems(function(err, items) {
+ if ( err ) {
+ return cb(err);
+ }
+ common.cascade(items, function(e, cb) {
+ self.deleteItem(e, cb);
+ }, cb);
});
- });
+ },
- }
+ // TODO: add documentation about all expected methods...
- function stopSync(profileId) {
- if (!_security.stopSync) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ getAllItems: function(cb) {
+ // cb(null, LIST)
+ return cb(new common.NotImplementedError());
+ },
- t.DataSynchronizationManager("stopSync", arguments);
+ dumpsItem: function(item, contentType, version, cb) {
+ // cb(null, DATA [, NEW-CONTENTTYPE [, NEW-VERSION]])
+ return cb(new common.NotImplementedError());
+ },
- if (!_data.profiles[profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
+ loadsItem: function(data, contentType, version, cb) {
+ // cb(null, ITEM)
+ return cb(new common.NotImplementedError());
+ },
- _data.profiles[profileId].stop_flag = true;
- }
+ addItem: function(item, cb) {
+ // cb(null, ITEM)
+ return cb(new common.NotImplementedError());
+ },
- function getLastSyncStatistics(profileId) {
- var s, statistics = [], i;
+ getItem: function(itemID, cb) {
+ // cb(null, ITEM)
+ return cb(new common.NotImplementedError());
+ },
- if (!_security.getLastSyncStatistics) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ replaceItem: function(item, reportChanges, cb) {
+ // cb(null [, CSPEC])
+ return cb(new common.NotImplementedError());
+ },
- t.DataSynchronizationManager("getLastSyncStatistics", arguments);
+ deleteItem: function(itemID, cb) {
+ // cb(null)
+ return cb(new common.NotImplementedError());
+ },
- if (!_data.profiles[profileId]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ getContentTypes: function() {
+ throw new common.NotImplementedError();
+ },
+
+ matchItem: function(item, cb) {
+ this.getAllItems(function(err, list) {
+ if ( err ) {
+ return cb(err);
+ }
+ var match = _.find(list, function(cur) {
+ return cur.compare && cur.compare(item) == 0;
+ });
+ return cb(null, match);
+ });
}
- s = _data.profiles[profileId].syncStatistics;
+ // TODO: mergeItems()
- for (i in s) {
- statistics.push(
- new SyncStatistics(s[i].syncStatus, s[i].serviceType, s[i].lastSyncTime,
- s[i].serverToClientTotal, s[i].serverToClientAdded,
- s[i].serverToClientUpdated, s[i].serverToClientRemoved,
- s[i].clientToServerTotal, s[i].clientToServerAdded,
- s[i].clientToServerUpdated, s[i].clientToServerRemoved)
- );
+ });
+
+ return exports;
+
+})();
+
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/item', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.item
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/30
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
+
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');
+
+var _self = (function () {
+ var exports = {};
+
+ //---------------------------------------------------------------------------
+ exports.Item = common.Base.extend({
+
+ //: the unique identifier (within the context of a SyncML datastore)
+ //: of the current SyncML item.
+ id: null,
+
+ compare: function(other) {
+ return ( other === this ? 0 : 1 );
}
- return statistics;
+ });
+
+ return exports;
+
+})();
+
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/storage', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.storage
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/10/31
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
+
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant');
+
+var _self = (function () {
+
+ var exports = {};
+
+ //---------------------------------------------------------------------------
+ _.extend(exports, {
+
+ //-------------------------------------------------------------------------
+ errstr: function(target) {
+ if ( target.error && typeof(target.error.toString) == 'function' )
+ return target.error.toString();
+ var ret = '';
+ var count = 0;
+ for ( var key in target.error )
+ count += 1;
+ if ( count == 1 && target.error.name )
+ ret = '' + target.error.name;
+ else
+ {
+ ret = '{';
+ for ( var key in target.error )
+ {
+ ret += key + ': ' + target.error[key];
+ count -= 1;
+ if ( count > 0 )
+ ret += ', ';
+ }
+ }
+ if ( target.errorCode )
+ {
+ if ( ret.length <= 0 || ret == '{}' )
+ ret = '' + target.errorCode;
+ else
+ ret = '[' + target.errorCode + '] ' + ret;
}
+ if ( ret.length <= 0 || ret == '{}' )
+ // last ditch effort...
+ ret = common.prettyJson(target);
+ return ret;
+ },
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ //-------------------------------------------------------------------------
+ openDatabase: function(context, cb) {
+ var dbreq = context.storage.indexedDB.open(context.dbname, 1);
+ dbreq.onblocked = function(event) {
+ cb({code: 'syncml-js.storage.OD.10',
+ message: 'database blocked by other process/tab/window'});
+ };
+ dbreq.onerror = function(event) {
+ var errmsg = exports.errstr(event.target);
+ cb({code: 'syncml-js.storage.OD.20',
+ message: 'failed to open syncml-js database: ' + errmsg});
+ };
+ dbreq.onupgradeneeded = function(event) {
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
+
+ var db = event.target.result;
+
+ var adapterTable = db.createObjectStore('adapter', {keyPath: 'id'});
+ adapterTable.createIndex('isLocal', 'isLocal', {unique: false});
+ adapterTable.createIndex('devID', 'devID', {unique: true});
+
+ var mappingTable = db.createObjectStore(
+ 'mapping',
+ {keyPath: ['store_id', 'guid']});
+ mappingTable.createIndex('store_id', 'store_id', {unique: false});
+ // mappingTable.createIndex('guid', 'guid', {unique: false});
+ // mappingTable.createIndex('luid', 'luid', {unique: false});
+
+ var changeTable = db.createObjectStore(
+ 'change',
+ {keyPath: ['store_id', 'item_id']});
+ changeTable.createIndex('store_id', 'store_id', {unique: false});
+ // changeTable.createIndex('item_id', 'item_id', {unique: false});
+
+ };
+ dbreq.onsuccess = function(event) {
+ cb(null, event.target.result);
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ getTransaction: function(db, tables, mode) {
+ // NOTE: the spec says passing in null should be valid... but
+ // mozilla's indexedDB seems to barf with:
+ // [Exception... "The operation failed because the
+ // requested database object could not be found. For
+ // example, an object store did not exist but was
+ // being opened." code: "8" nsresult: "0x80660003
+ // (NotFoundError)"
+ if ( ! tables )
+ tables = ['adapter','mapping','change'];
+ if ( ! mode )
+ mode = 'readwrite';
+ return db.transaction(tables, mode);
+ },
+
+ //-------------------------------------------------------------------------
+ dumpDatabase: function(context, cb) {
+
+ var ret = {};
+ var txn = context._txn();
+
+ var steps = [
+ function(cb) {
+ exports.getAll(context, txn.objectStore('adapter'), {}, function(err, adapters) {
+ ret.adapter = adapters;
+ return cb(err);
+ });
+ },
+ function(cb) {
+ exports.getAll(context, txn.objectStore('mapping'), {}, function(err, mappings) {
+ ret.mapping = mappings;
+ return cb(err);
+ });
+ },
+ function(cb) {
+ exports.getAll(context, txn.objectStore('change'), {}, function(err, changes) {
+ ret.change = changes;
+ return cb(err);
+ });
+ }
+ ];
+
+ common.cascade(steps, function(step, cb) {
+ return step(cb);
+ }, function(err) {
+ return cb(err, ret);
+ });
+ },
+
+ //-------------------------------------------------------------------------
+ clearDatabase: function(context, cb) {
+ var dbreq = context.storage.indexedDB.open(context.dbname, 1);
+ dbreq.onblocked = function(event) {
+ cb({code: 'syncml-js.storage.CD.10',
+ message: 'database blocked by other process/tab/window'});
+ };
+ dbreq.onerror = function(event) {
+ var errmsg = exports.errstr(event.target);
+ cb({code: 'syncml-js.storage.CD.20',
+ message: 'failed to open syncml-js database: ' + errmsg});
+ };
+ dbreq.onsuccess = function(event) {
+ var db = event.target.result;
+ db.onerror = dbreq.onerror;
+ async.map(['adapter', 'mapping', 'change'], function(name, cb) {
+ cb();
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ db.close();
+ });
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ getAll: function(context, source, options, cb) {
+ // supported options:
+ // - range
+ // - only
+ options = options || {};
+ var range = options.range;
+ if ( ! range && options.only )
+ range = context.storage.IDBKeyRange.only(options.only);
+ var req = source.openCursor(range);
+ var ret = [];
+ req.onsuccess = function(event) {
+ var cursor = event.target.result;
+ if ( cursor )
+ {
+ ret.push(cursor.value);
+ // ret.push({key: cursor.key, value: cursor.value});
+ return cursor.continue();
+ }
+ cb(null, ret);
+ };
+ req.onerror = function(event) {
+ cb(exports.errstr(event.target));
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ put: function(store, object, cb) {
+ var req = store.put(object);
+ req.onsuccess = function(event) { cb(); };
+ req.onerror = function(event) {
+ cb(exports.errstr(event.target));
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ delete: function(store, objectID, cb) {
+ var req = store.delete(objectID);
+ req.onsuccess = function(event) { cb(); };
+ req.onerror = function(event) {
+ cb(exports.errstr(event.target));
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ deleteAll: function(source, matches, cb) {
+ var req = source.openCursor();
+ req.onsuccess = function(event) {
+ var cursor = event.target.result;
+ if ( cursor )
+ {
+ for (key in matches)
+ if ( matches[key] != cursor.value[key] )
+ return cursor.continue();
+ exports.delete(source, cursor.key, function(err) {
+ if ( err )
+ return cb(err);
+ return cursor.continue();
+ });
+ return;
+ }
+ cb(null);
+ };
+ req.onerror = function(event) {
+ cb(exports.errstr(event.target));
+ };
+ },
+
+ //-------------------------------------------------------------------------
+ iterateCursor: function(openCursor, iterator, cb) {
+ openCursor.onsuccess = function(event) {
+ var cursor = event.target.result;
+ if ( ! cursor )
+ return cb();
+ iterator(cursor.value.value, cursor.value.id, function(err) {
+ if ( err )
+ return cb(err);
+ return cursor.continue();
+ });
+ };
+ openCursor.onerror = function(event) {
+ cb(exports.errstr(event.target));
+ };
}
- }
- }
- datasync = {
- add: add,
- update: update,
- remove: remove,
- getMaxProfilesNum: getMaxProfilesNum,
- getProfilesNum: getProfilesNum,
- get: get,
- getAll: getAll,
- startSync: startSync,
- stopSync: stopSync,
- getLastSyncStatistics: getLastSyncStatistics,
- handleSubFeatures: handleSubFeatures
- };
+ });
- return datasync;
-};
+ return exports;
-_initialize();
+})();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/dbfs', function (require, exports, module) {
-/*
- * Copyright 2011 Research In Motion Limited.
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+define('ripple/platform/tizen/2.0/syncml-js-lib/devinfo', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.devinfo
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/06
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- _console = require('ripple/console'),
- _cache = {},
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
+ ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
_self;
-function _get(path) {
- return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
- return token === "" ? obj : ((obj && obj.children) ? obj.children[token] || null : null);
- }, _cache);
-}
-
-function _getInfo(path) {
- var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
- name = parent.splice(parent.length - 1, 1).join("");
-
- return {
- name: name,
- parent: parent.join("/") || "/"
- };
-}
-
-function _set(path, obj) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
-
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
-
- parent.children = parent.children || {};
- parent.children[child] = obj;
-}
+_self = (function () {
-function _delete(path) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ var exports = {};
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ var strAttributeMap = [
+ ['manufacturerName', 'Man'],
+ ['modelName', 'Mod'],
+ ['oem', 'OEM'],
+ ['firmwareVersion', 'FwV'],
+ ['softwareVersion', 'SwV'],
+ ['hardwareVersion', 'HwV'],
+ ['devID', 'DevID'],
+ ['devType', 'DevTyp']
+ ];
- delete parent.children[child];
-}
+var boolAttributeMap = [
+ ['utc', 'UTC'],
+ ['largeObjects', 'SupportLargeObjs'],
+ ['hierarchicalSync', 'SupportHierarchicalSync'],
+ ['numberOfChanges', 'SupportNumberOfChanges']
+ ];
-function _save() {
- db.saveObject("tizen1-db-filesystem", _cache);
-}
+//---------------------------------------------------------------------------
+exports.DevInfo = common.Base.extend({
-function _walk(path, parent) {
- _self.ls(path, function (entries) {
- parent.children = parent.children || {};
+ //-------------------------------------------------------------------------
+ constructor: function(adapter, options) {
+ var self = this;
+ var options = _.defaults({}, options, {
+ devType : constant.DEVTYPE_WORKSTATION,
+ manufacturerName : '-',
+ modelName : '-',
+ oem : '-',
+ hardwareVersion : '-',
+ firmwareVersion : '-',
+ softwareVersion : '-',
+ utc : true,
+ largeObjects : true,
+ hierarchicalSync : true,
+ numberOfChanges : true,
+ extensions : {}
+ });
- entries.forEach(function (entry) {
- parent.children[entry.name] = entry;
+ // todo: is there anyway to mark attributes as read-only?...
- if (entry.isDirectory) {
- _walk(entry.fullPath, entry);
- } else {
- /* after getting Date out of DB, Date will become
- a string, so need to recast it back to Date */
- if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
- entry.lastModifiedDate = new Date(entry.lastModifiedDate);
- if (entry.createdDate !== null && entry.createdDate !== undefined)
- entry.createdDate = new Date(entry.createdDate);
+ //: [read-only] these are all read-only attributes
+ this.devID = options.devID || common.makeID();
+ this.devType = options.devType;
+ this.manufacturerName = options.manufacturerName;
+ this.modelName = options.modelName;
+ this.oem = options.oem;
+ this.hardwareVersion = options.hardwareVersion;
+ this.firmwareVersion = options.firmwareVersion;
+ this.softwareVersion = options.softwareVersion;
+ this.utc = options.utc;
+ this.largeObjects = options.largeObjects;
+ this.hierarchicalSync = options.hierarchicalSync;
+ this.numberOfChanges = options.numberOfChanges;
+ this.extensions = {};
- _self.read(entry.fullPath, function (data) {
- parent.children[entry.name].data = data;
- }, function (e) {
- _console.error(e);
- });
- }
+ _.each(options.extensions, function(values, name) {
+ self.setExtension(name, values);
});
- }, function (e) {
- _console.error(e);
- });
-}
-function _createPath(path) {
- var parts = path.replace(/^\//, '').split("/"),
- workflow = jWorkflow.order();
+ // --- private attributes
+ this._a = adapter;
+ },
- parts.forEach(function (part, index) {
- var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+ //-------------------------------------------------------------------------
+ setExtension: function(name, values) {
+ this.extensions[name] = _.isArray(values) ? values : [values];
+ },
- workflow.andThen(function (prev, baton) {
- baton.take();
- _self.mkdir(dir, baton.pass, baton.pass);
- });
- });
+ //-------------------------------------------------------------------------
+ getExtensionKeys: function() {
+ return _.keys(this.extensions);
+ },
- workflow.start();
-}
+ //-------------------------------------------------------------------------
+ getExtension: function(name) {
+ return this.extensions[name];
+ },
-_self = {
- // The order is consistent with _virtualRoots in filesystem.js
- roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
- initialize: function () {
- // TODO: Initialize at bootstrap and emulatorBridge.link
- _cache = db.retrieveObject("tizen1-db-filesystem") || {};
- // create real root paths if empty
- _self.roots.every(function (root) {
- _createPath(root);
- return true;
- });
- // build the file system cache so that we could access information synchronously
- _walk("/", _cache);
- },
- ls: function (path, success, error) {
- try {
- var dir = _get(path),
- items = [];
+ //-------------------------------------------------------------------------
+ _load: function(cb) {
+ cb();
+ },
- if (dir) {
- utils.forEach(dir.children, function (item) {
- items.push(item);
- });
+ //-------------------------------------------------------------------------
+ _updateModel: function(cb) {
+ if ( ! this._a._model )
+ return cb('devinfo created on un-initialized adapter');
+ this._a._model.devInfo = {
+ devID : this.devID,
+ devType : this.devType,
+ manufacturerName : this.manufacturerName,
+ modelName : this.modelName,
+ oem : this.oem,
+ hardwareVersion : this.hardwareVersion,
+ firmwareVersion : this.firmwareVersion,
+ softwareVersion : this.softwareVersion,
+ utc : this.utc,
+ largeObjects : this.largeObjects,
+ hierarchicalSync : this.hierarchicalSync,
+ numberOfChanges : this.numberOfChanges,
+ extensions : this.extensions
+ };
+ cb();
+ },
+
+ //-------------------------------------------------------------------------
+ toSyncML: function(dtdVersion, stores) {
+ dtdVersion = dtdVersion || constant.SYNCML_DTD_VERSION_1_2;
+ if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
+ throw new Error('unsupported DTD version "' + dtdVersion + '"')
+ var xret = ET.Element('DevInf', {'xmlns': constant.NAMESPACE_DEVINF})
+ ET.SubElement(xret, 'VerDTD').text = dtdVersion;
+ for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
+ {
+ var map = strAttributeMap[idx];
+ // todo: should i enforce the fact that these are all *required*?...
+ if ( this[map[0]] != undefined )
+ ET.SubElement(xret, map[1]).text = this[map[0]];
}
- else {
- items = {};
+ for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
+ {
+ var map = boolAttributeMap[idx];
+ if ( this[map[0]] )
+ ET.SubElement(xret, map[1])
}
+ if ( stores && stores.length > 0 )
+ for ( var idx=0 ; idx<stores.length ; idx++ )
+ xret.append(stores[idx].toSyncML());
+ var xext = null;
+ for ( var name in this.extensions )
+ {
+ if ( ! xext )
+ xext = ET.SubElement(xret, 'Ext');
+ ET.SubElement(xext, 'XNam').text = name;
+ var values = this.extensions[name];
+ for ( var idx=0 ; idx<values.length ; idx++ )
+ ET.SubElement(xext, 'XVal').text = '' + values[idx];
+ };
+ return xret;
+ },
- success(items);
+}, {
+
+ //-------------------------------------------------------------------------
+ fromSyncML: function(xnode) {
+ var options = {};
+ var stores = []
+ var dtdVersion = xnode.findtext('VerDTD')
+ if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
+ throw new common.ProtocolError('unsupported DTD version "' + dtdVersion + '"');
+ for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
+ {
+ var map = strAttributeMap[idx];
+ // todo: should i enforce the fact that these are all *required*?...
+ options[map[0]] = xnode.findtext(map[1]);
}
- catch (e) {
- e.code = 1;
- error(e);
+ for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
+ {
+ var map = boolAttributeMap[idx];
+ options[map[0]] = xnode.find(map[1]) != undefined;
}
- },
- rm: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
- rmdir: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
- mkdir: function (path, success, error) {
- var entry = _get(path),
- info = _getInfo(path);
-
- if (!entry) {
- _set(path, {
- lastModifiedDate: new Date(),
- createdDate: new Date(),
- name: info.name,
- isDirectory: true,
- fullPath: path
- });
- entry = _get(path);
- _save();
+ _.each(xnode.getchildren(), function(child) {
+ if ( child.tag == 'DataStore' )
+ return stores.push(storemod.Store.fromSyncML(child));
+ if ( child.tag == 'Ext' )
+ {
+ options.extensions = {};
+ var elist = child.getchildren();
+ var ecur = null;
+ for ( var idx=0 ; idx<elist.length ; idx++ )
+ {
+ var eitem = elist[idx];
+ if ( eitem.tag == 'XNam' )
+ {
+ ecur = eitem.text;
+ continue;
}
-
- if (entry) {
- success(entry);
+ if ( ! ecur )
+ // paranoia...
+ continue;
+ if ( ! options.extensions[ecur] )
+ options.extensions[ecur] = [];
+ options.extensions[ecur].push(eitem.text);
}
- else {
- error({code: 1});
+ return;
}
- },
- mv: function (from, to, success, error) {
- try {
- var fromEntry = _get(from),
- toInfo = _getInfo(to);
+ });
+ return [new exports.DevInfo(null, options), stores];
+ }
- fromEntry.fullPath = to;
- fromEntry.name = toInfo.name;
+});
- _set(to, fromEntry);
- _delete(from);
- _save();
- success();
- }
- catch (e) {
- e.code = 1;
- error(e);
- }
- },
- touch: function (path, success, error) {
- var entry = _get(path),
- info = _getInfo(path);
+return exports;
- if (!entry) {
- _set(path, {
- lastModifiedDate: new Date(),
- createdDate: new Date(),
- name: info.name,
- isDirectory: false,
- fullPath: path,
- data: ""
- });
- entry = _get(path);
- }
- _save();
- success(entry);
- },
- cp: function (from, to, success, error) {
- try {
- var fromEntry = _get(from),
- copied = utils.copy(fromEntry);
+})();
- copied.name = _getInfo(to).name;
- copied.fullPath = to;
- _set(to, copied);
- _save();
- success();
- }
- catch (e) {
- e.code = 1;
- error(e);
- }
- },
- stat: function (path, success, error) {
- var entry = _get(path);
+module.exports = _self;
- if (entry) {
- success(entry);
- } else {
- error({code: 1});
- }
- },
- write: function (path, contents, success, error, options) {
- var entry = _get(path);
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/ctype', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// auth: metagriffin <metagriffin@uberdev.org>
+// date: 2012/10/13
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
+ _self;
- if (entry) {
- entry.lastModifiedDate = new Date();
- entry.data = contents;
- _save();
- success();
- } else {
- error({code: 1});
- }
+_self = (function () {
- },
- read: function (path, success, error) {
- var entry = _get(path);
+ var exports = {};
- if (entry) {
- success(utils.copy(entry.data));
- }
- else {
- error({code: 1});
- }
- }
-};
+ //---------------------------------------------------------------------------
+ exports.ContentTypeInfo = common.Base.extend({
-module.exports = _self;
+ //-------------------------------------------------------------------------
+ constructor: function(ctype, versions, options) {
+ this.ctype = ctype;
+ this.versions = _.isArray(versions) ? versions : [versions];
+ _.defaults(this, options || {}, {
+ preferred: false,
+ transmit: true,
+ receive: true,
+ });
+ },
-});
-define('ripple/platform/tizen/2.0/dbinit', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ //-------------------------------------------------------------------------
+ merge: function(other) {
+ if ( this.ctype != other.ctype
+ || ! _.isEqual(this.versions, other.versions)
+ || this.preferred != other.preferred )
+ return false;
+ this.transmit = this.transmit || other.transmit;
+ this.receive = this.receive || other.receive;
+ return true
+ },
-var utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- dbfs = require('ripple/platform/tizen/2.0/dbfs'),
- filesystem = require('ripple/platform/tizen/2.0/filesystem'),
- DBBuilder,
- Content,
- FileSystem,
- _data = {
- dbBuilder: null
- },
- _self = {};
+ //-------------------------------------------------------------------------
+ toStruct: function() {
+ return {
+ ctype: this.ctype,
+ versions: this.versions,
+ preferred: this.preferred,
+ transmit: this.transmit,
+ receive: this.receive
+ };
+ },
-function _initialize() {
- _data.dbBuilder = new DBBuilder();
+ //-------------------------------------------------------------------------
+ toSyncML: function(nodeName, uniqueVerCt) {
+ if ( _.isFunction(nodeName) )
+ {
+ cb = nodeName;
+ nodeName = null;
+ }
+ else if ( _.isFunction(uniqueVerCt) )
+ {
+ cb = uniqueVerCt;
+ uniqueVerCt = null;
+ }
+ if ( ! nodeName )
+ {
+ nodeName = this.transmit ? 'Tx' : 'Rx';
+ if ( this.preferred )
+ nodeName += '-Pref';
+ }
+ if ( this.preferred )
+ nodeName += '-Pref';
- _data.dbBuilder.register("FileSystem", "", FileSystem);
- _data.dbBuilder.register("Content", "dbcontent.xml", Content);
- _data.dbBuilder.register("Package", "dbpackage.xml");
- _data.dbBuilder.register("Application", "dbapplication.xml");
- _data.dbBuilder.register("Bluetooth", "dbbluetooth.xml");
+ if ( uniqueVerCt )
+ {
+ var ret = _.map(this.versions, function(v) {
+ var tmp = ET.Element(nodeName);
+ ET.SubElement(tmp, 'CTType').text = this.ctype;
+ ET.SubElement(tmp, 'VerCT').text = v;
+ return tmp;
+ }, this);
+ return ret;
+ }
+ var ret = ET.Element(nodeName);
+ ET.SubElement(ret, 'CTType').text = this.ctype;
+ _.each(this.versions, function(v) {
+ ET.SubElement(ret, 'VerCT').text = v;
+ });
+ return ret;
+ },
- _data.FileSystem.initdb();
-}
+ describe: function(stream, cb) {
+ stream.write(this.ctype);
+ stream.write(this.versions.length == 1 ? ' version ' : ' versions ');
+ stream.write(this.versions.join(', '));
+ var flags = [];
+ if ( this.preferred )
+ flags.push('preferred');
+ if ( this.transmit )
+ flags.push('tx');
+ if ( this.receive )
+ flags.push('rx');
+ if ( flags.length > 0 )
+ {
+ stream.write(' (');
+ stream.write(flags.join(', '));
+ stream.write(')');
+ }
+ stream.write('\n');
+ }
-DBBuilder = function () {
- var self;
+ }, {
- // private
- function formatString(str) {
- return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, " ");
- }
+ //-------------------------------------------------------------------------
+ fromStruct: function(struct) {
+ return new exports.ContentTypeInfo(struct.ctype, struct.versions, struct);
+ },
- function getType(node) {
- var type, reNum, reDate, reHexNum;
+ //-------------------------------------------------------------------------
+ fromSyncML: function(xnode) {
+ return new exports.ContentTypeInfo(
+ xnode.findtext('CTType'),
+ _.map(xnode.findall('VerCT'), function(e) { return e.text; }),
+ {
+ preferred: xnode.tag.match('-Pref$') != undefined,
+ transmit: xnode.tag.indexOf('Tx') >= 0,
+ receive: xnode.tag.indexOf('Rx') >= 0
+ }
+ );
+ }
- if (node.childNodes) {
- return (node.childNodes[0].nodeName === "i") ? "Array" : "Object";
- }
+ });
- // Special case
- if (node.nodeName === "version") {
- return "DOMString";
- }
+ return exports;
- reNum = /^(-?\d+)(\.\d+)?$/;
- reHexNum = /^0[xX][0-9a-fA-F]+$/;
- reDate = /^(\d{4})\-(\d{2})\-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/;
+})();
- if (reNum.test(node.textContent)) {
- type = "Number";
- } else if (reHexNum.test(node.textContent)) {
- type = "Number";
- } else if (reDate.test(node.textContent)) {
- type = "Date";
- } else if (node.textContent === "true" || node.textContent === "false") {
- type = "Boolean";
- } else {
- type = "DOMString";
- }
+module.exports = _self;
- return type;
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.remoteadapter
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/04
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- function build(node) {
- var i, value;
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
+ adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
+ storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
+ _self;
- switch (getType(node)) {
- case "Boolean":
- value = (formatString(node.textContent) === "true");
- break;
+_self = (function () {
+ var exports = {};
- case "Date":
- value = new Date(formatString(node.textContent));
- break;
+ //---------------------------------------------------------------------------
+ exports.RemoteAdapter = adapter.Adapter.extend({
- case "Number":
- value = Number(formatString(node.textContent));
- break;
+ //-------------------------------------------------------------------------
+ constructor: function(adapter, options) {
- case "Object":
- value = {};
- for (i in node.childNodes) {
- value[node.childNodes[i].nodeName] = build(node.childNodes[i]);
- }
- break;
+ //: [read-only] the URL of the remote syncml peer, acting as a server,
+ //: to connect to.
+ this.url = options.url || null;
- case "Array":
- value = [];
- for (i in node.childNodes) {
- value.push(build(node.childNodes[i]));
- }
- break;
+ //: [read-only] specifies whether this Adapter represents a local
+ //: or remote peer.
+ this.isLocal = false;
- default: // "DOMString"
- value = formatString(node.textContent);
- break;
- }
+ //: [read-only] the DevID of the remote syncml peer (which usually
+ //: defaults to the URL).
+ this.devID = options.devID || options.url || null;
- return value;
- }
+ //: [read-only] the authentication method to use to identify the local
+ //: peer to the remote peer.
+ ///TODO: this.auth = options.auth || null;
+ this.auth = 'syncml:auth-basic';
- function parse(obj) {
- var i, res = {};
+ //: [read-only] the human-friendly display name of the remote peer.
+ this.displayName = options.displayName || null;
- res.nodeName = ("name" in obj.attributes) ?
- obj.attributes["name"].value : obj.nodeName;
+ //: [read-only] the username to use during credential-based authentication.
+ this.username = options.username || null;
- if (obj.childElementCount === 0) {
- res.textContent = obj.textContent;
- } else {
- res.childNodes = [];
+ //: [read-only] the password to use during credential-based authentication.
+ this.password = options.password || null;
- for (i in obj.childNodes) {
- if (obj.childNodes[i].attributes) {
- res.childNodes.push(parse(obj.childNodes[i]));
- }
- }
- }
+ //: [read-only] the peer-wide default value of the maximum
+ //: message size.
+ this.maxMsgSize = options.maxMsgSize || null;
- return res;
- }
+ //: [read-only] the peer-wide default value of the maximum
+ //: object size.
+ this.maxObjSize = options.maxObjSize || null;
- // public
- function register(type, dbXml, Extension) {
- _data[type] = Extension ? new Extension() : {};
+ //: [read-only] the DevInfo object for this remote peer.
+ this.devInfo = null;
- if (!dbXml)
- return;
+ this.lastSessionID = options.lastSessionID || null;
- _self.__defineGetter__(type, function () {
- var fnInit;
+ // --- private attributes
+ this.id = options.id || common.makeID();
+ this._a = adapter;
+ this._c = adapter._c;
+ this._stores = {};
+ this._proxy = null;
- if (!_data[type].db) {
- fnInit = _data[type].initdb || initdb;
- _data[type].db = fnInit(dbXml);
- }
+ // TODO: filter these options for db-valid only properties...
+ this._options = options;
+ },
- return _data[type].db;
- });
- }
+ //-------------------------------------------------------------------------
+ _load: function(cb) {
- function initdb(dbXml) {
- var db = {}, xmlHttp, res;
+ var self = this;
+ var model = this._getModel();
- try {
- xmlHttp = new XMLHttpRequest();
- xmlHttp.open("GET", "dbsamples/" + dbXml, false);
- xmlHttp.send();
- } catch (e) {
- exception.handle(e);
- }
+ // todo: should this be loading these?...
+ // self.displayName = model.displayName;
+ // self.devID = model.devID;
- if (!xmlHttp.responseXML) {
- return null;
- }
+ var loadDevInfo = function(cb) {
+ var di = new devinfomod.DevInfo(self, model.devInfo);
+ di._load(function(err) {
+ if ( err )
+ return cb(err);
+ self.devInfo = di;
+ cb();
+ });
+ };
- res = parse(xmlHttp.responseXML.documentElement);
- res.childNodes.forEach(function (node) {
- db[node.nodeName] = build(node);
- });
+ var loadStores = function(cb) {
+ common.cascade(model.stores, function(e, cb) {
+ var store = new storemod.Store(self, e);
+ store._load(function(err) {
+ if ( err )
+ return cb(err);
+ self._stores[store.uri] = store;
+ return cb();
+ });
+ }, cb);
+ };
- return db;
- }
+ loadDevInfo(function(err) {
+ if ( err )
+ return cb(err);
+ loadStores(cb);
+ });
+ },
- self = {
- register: register,
- initdb: initdb
- };
+ //-------------------------------------------------------------------------
+ _updateModel: function(cb) {
+ var self = this;
+ if ( ! this._a._model || ! this._a._model.peers )
+ return cb(new common.InternalError('peer created on un-initialized adapter'));
+ var model = self._getModel();
+ // todo: should this be in this._getModel()?...
+ if ( ! model )
+ {
+ model = {
+ id: self.id,
+ devInfo: null,
+ stores: [],
+ routes: []
+ };
+ self._a._model.peers.push(model);
+ }
- return self;
-};
+ model.isLocal = 0;
+ model.url = self.url;
+ model.devID = self.devID;
+ model.displayName = self.displayName;
+ model.auth = self.auth;
+ model.username = self.username;
+ model.password = self.password;
+ model.lastSessionID = self.lastSessionID
+ model.maxMsgSize = self.maxMsgSize;
+ model.maxObjSize = self.maxObjSize;
-/*
- * FileSystem
- */
+ common.cascade([
-FileSystem = function () {
- var self;
+ // update the devInfo model
+ function(cb) {
+ if ( ! self.devInfo )
+ return cb();
+ return self.devInfo._updateModel(cb);
+ },
- // private
- function createPath(path) {
- var parts = path.replace(/^\//, "").split("/"),
- workflow = jWorkflow.order();
+ // update the stores model
+ function(cb) {
+ // TODO: this should really be the responsibility of the Store class...
+ // NOTE: since bindings are not stored in Store, they need to be saved
+ // and re-applied.
+ // TODO: or, perhaps better, i should purge all unwanted stores
+ // instead of doing this brute-force method...
+ var bindings = _.object(_.map(model.stores, function(store) {
+ return [store.uri, store.binding];
+ }));
+ model.stores = [];
+ common.cascade(_.values(self._stores), function(store, cb) {
+ store._updateModel(cb);
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ _.each(bindings, function(binding, uri) {
+ var store = _.find(model.stores, function(s) { return s.uri == uri; });
+ if ( ! store )
+ return;
+ store.binding = binding;
+ });
+ return cb();
+ });
+ },
- parts.forEach(function (part, index) {
- var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+ ], cb);
- workflow.andThen(function (prev, baton) {
- baton.take();
- dbfs.mkdir(dir, baton.pass, baton.pass);
- });
- });
+ },
- workflow.start();
- }
+ //-------------------------------------------------------------------------
+ _getModel: function() {
+ return _.find(this._a._model.peers,
+ function(e) { return e.id == this.id; }, this);
+ },
- // public
- function initdb() {
- filesystem.resolve("images", function () {});
- filesystem.resolve("videos", function () {});
- filesystem.resolve("music", function () {});
- }
+ //-------------------------------------------------------------------------
+ _setRemoteInfo: function(devInfo, stores, cb) {
+ var self = this;
+ self._model = self._getModel();
+ devInfo._a = self;
+ self.devInfo = devInfo;
+ self.devInfo._updateModel(function(err) {
+ if ( err )
+ return cb(err);
+ // merge the new datastore info with any pre-existing store bindings
+ // step 1: prepare the new stores (clean up the URIs)
+ var lut = _.object(_.map(stores, function(store) {
+ store.uri = self.normUri(store.uri);
+ return [store.uri, store];
+ }));
+ // step 2: remove all stores that are no longer mentioned
+ self._stores = _.object(
+ _.map(
+ _.filter(_.keys(self._stores), function(oldUri) {
+ return _.indexOf(_.keys(lut), oldUri) >= 0;
+ }), function(uri) {
+ return [uri, self._stores[uri]];
+ }
+ )
+ );
+ // step 3: merge the datastore info for existing stores
+ var merge_stores = function(cb) {
+ common.cascade(_.values(self._stores), function(store, cb) {
+ store.merge(lut[store.uri], function(err) {
+ if ( err )
+ return cb(err);
+ delete lut[store.uri];
+ return cb();
+ });
+ }, cb);
+ };
+ // step 4: add new datastores
+ var add_stores = function(cb) {
+ common.cascade(_.values(lut), function(store, cb) {
+ self.addStore(store, cb);
+ }, cb);
+ };
+ merge_stores(function(err) {
+ if ( err )
+ return cb(err);
+ add_stores(cb);
+ });
+ });
+ },
- function createFile(uri) {
- var directoryURI;
+ //-------------------------------------------------------------------------
+ setRoute: function(localUri, remoteUri, autoMapped, cb) {
+ if ( _.isFunction(autoMapped) )
+ // defaulting 'autoMapped' to false
+ return this.setRoute(localUri, remoteUri, false, autoMapped);
+ var pmodel = this._getModel();
+ if ( ! pmodel )
+ return cb(new common.InternalError('could not locate this peer in local adapter'));
+ pmodel.routes = _.filter(pmodel.routes, function(r) {
+ return r.localUri != localUri && r.remoteUri != remoteUri;
+ });
+ pmodel.routes.push({localUri : localUri,
+ remoteUri : remoteUri,
+ autoMapped : autoMapped
+ });
+ // now search through previous bindings, breaking incorrect ones...
+ // NOTE: this requires that a router.recalculate() is called at
+ // some point later since other valid bindings may now be
+ // possible...
+ _.each(pmodel.stores, function(store) {
+ if ( store.uri != remoteUri
+ && ( ! store.binding || store.binding.uri != localUri ) )
+ {
+ return;
+ }
+ if ( ! store.binding )
+ {
+ store.binding = {
+ uri : localUri,
+ autoMapped : autoMapped,
+ localAnchor : null,
+ remoteAnchor : null
+ };
+ return;
+ }
+ if ( store.uri == remoteUri && store.binding.uri == localUri )
+ {
+ store.binding.autoMapped = store.binding.autoMapped && autoMapped;
+ return;
+ }
+ store.binding = null;
+ return;
+ });
+ // TODO: this additional route may impact "smart routing" - recalculate?...
+ // TODO: saving adapter from peer --- SHOULD IT BE DOING THIS?...
+ // TODO: get transaction from a session!...
+ this._a._save(this._c._txn(), cb);
+ },
- directoryURI = uri.slice(0, uri.lastIndexOf("/") + 1)
- .replace(/file:\/\//, "");
+ //-------------------------------------------------------------------------
+ sendRequest: function(session, contentType, data, cb) {
+ var xmlhttp;
- dbfs.stat(directoryURI, function () {}, function () {
- createPath(directoryURI);
- });
+ // TODO: shouldn't proxies just overwrite .sendRequest() ?...
+ if ( this._proxy )
+ return this._proxy.sendRequest(session, contentType, data, cb);
- uri = uri.replace(/file:\/\//, "");
- dbfs.touch(uri, function () {});
- }
+ var req = {
+ url : session.info.respUri || this.url,
+ method : 'POST',
+ headers : {'Content-Type': contentType},
+ body : data
+ };
- self = {
- initdb: initdb,
- createFile: createFile
- };
+ xmlhttp = new XMLHttpRequest();
+ xmlhttp.open(req.method, req.url, false);
- return self;
-};
+ xmlhttp.setRequestHeader("Content-Type", contentType);
+ xmlhttp.send(req.body);
-/*
- * Content
- */
+ var response = {
+ headers: {
+ "Content-Type": xmlhttp.getResponseHeader("content-type")
+ },
+ body: xmlhttp.responseXML
+ };
+ return cb(null, response);
+ }
-Content = function () {
- var self, ContentStorage;
+ });
- ContentStorage = function (contents, directories) {
- var i, parentURI;
+ return exports;
- for (i in directories) {
- directories[i].contents = {};
- this[directories[i].directoryURI] = directories[i];
- }
+})();
- for (i in contents) {
- parentURI = contents[i].contentURI.slice(0,
- contents[i].contentURI.lastIndexOf("/") + 1)
- .replace(/file:\/\//, "");
+module.exports = _self;
- if (parentURI in this) {
- this[parentURI].contents[contents[i].contentURI] = contents[i];
- }
- }
- };
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/base64', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+//-----------------------------------------------------------------------------
- // public
- function initdb(dbXml) {
- var i, db;
+var _self = (function() {
- db = _data.dbBuilder.initdb(dbXml);
+ // shamelessly scrubbed from:
+ // http://www.webtoolkit.info/javascript-base64.html
- if (!db)
- return null;
+ /**
+ *
+ * Base64 encode / decode
+ * http://www.webtoolkit.info/
+ *
+ **/
- for (i in db.contents) {
- _data.FileSystem.createFile(db.contents[i].contentURI);
- }
+ var Base64 = {
- return new ContentStorage(db.contents, db.directories);
- }
+ // private property
+ _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
- self = {
- initdb: initdb
- };
+ // public method for encoding
+ encode : function (input) {
+ var output = "";
+ var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+ var i = 0;
- return self;
-};
+ input = Base64._utf8_encode(input);
-_initialize();
+ while (i < input.length) {
-module.exports = _self;
+ chr1 = input.charCodeAt(i++);
+ chr2 = input.charCodeAt(i++);
+ chr3 = input.charCodeAt(i++);
-});
-define('ripple/platform/tizen/2.0/decorator', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
-var t = require('ripple/platform/tizen/2.0/typecast'),
- ContactDecorator,
- _self;
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ } else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
-ContactDecorator = function (contact, overlap) {
- var raw = {};
+ output = output +
+ this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+ this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
- // private
- function clone(obj) {
- return function () {
- var Contact = require('ripple/platform/tizen/2.0/ContactBase'),
- duplicate;
+ }
- duplicate = new Contact(obj);
+ return output;
+ },
- duplicate.__defineGetter__("id", function () {
- return null;
- });
+ // public method for decoding
+ decode : function (input) {
+ var output = "";
+ var chr1, chr2, chr3;
+ var enc1, enc2, enc3, enc4;
+ var i = 0;
- duplicate.__defineGetter__("addressBookId", function () {
- return null;
- });
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- return duplicate;
- };
- }
+ while (i < input.length) {
- // public
- function convertToString(format) {
- t.Contact("convertToString", arguments);
+ enc1 = this._keyStr.indexOf(input.charAt(i++));
+ enc2 = this._keyStr.indexOf(input.charAt(i++));
+ enc3 = this._keyStr.indexOf(input.charAt(i++));
+ enc4 = this._keyStr.indexOf(input.charAt(i++));
- // TODO: Convert contact according to VCard protocal
- return "";
- }
+ chr1 = (enc1 << 2) | (enc2 >> 4);
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+ chr3 = ((enc3 & 3) << 6) | enc4;
- raw.id = overlap ? overlap.id : null;
- raw.personId = overlap ? overlap.personId : null;
- raw.addressBookId = overlap ? overlap.addressBookId : null;
- raw.lastUpdated = overlap ? overlap.lastUpdated : null;
- raw.isFavorite = overlap ? overlap.isFavorite : false;
- raw.name = contact.name;
- raw.addresses = contact.addresses;
- raw.photoURI = contact.photoURI;
- raw.phoneNumbers = contact.phoneNumbers;
- raw.emails = contact.emails;
- raw.birthday = contact.birthday;
- raw.anniversaries = contact.anniversaries;
- raw.organizations = contact.organizations;
- raw.notes = contact.notes;
- raw.urls = contact.urls;
- raw.ringtoneURI = contact.ringtoneURI;
- raw.groupIds = contact.groupIds;
+ output = output + String.fromCharCode(chr1);
- contact.__defineGetter__("id", function () {
- return raw.id;
- });
+ if (enc3 != 64) {
+ output = output + String.fromCharCode(chr2);
+ }
+ if (enc4 != 64) {
+ output = output + String.fromCharCode(chr3);
+ }
- contact.__defineGetter__("personId", function () {
- return raw.personId;
- });
+ }
- contact.__defineGetter__("addressBookId", function () {
- return raw.addressBookId;
- });
+ output = Base64._utf8_decode(output);
- contact.__defineGetter__("lastUpdated", function () {
- return raw.lastUpdated;
- });
+ return output;
- contact.__defineGetter__("isFavorite", function () {
- return raw.isFavorite;
- });
+ },
- contact.__defineGetter__("name", function () {
- return raw.name;
- });
- contact.__defineSetter__("name", function (val) {
- try {
- raw.name = t.ContactName(val, "?");
- } catch (e) {
- }
- });
+ // private method for UTF-8 encoding
+ _utf8_encode : function (string) {
+ string = string.replace(/\r\n/g,"\n");
+ var utftext = "";
- contact.__defineGetter__("addresses", function () {
- return raw.addresses;
- });
- contact.__defineSetter__("addresses", function (val) {
- try {
- raw.addresses = t.ContactAddress(val, "[]");
- } catch (e) {
- }
- });
+ for (var n = 0; n < string.length; n++) {
- contact.__defineGetter__("photoURI", function () {
- return raw.photoURI;
- });
- contact.__defineSetter__("photoURI", function (val) {
- try {
- raw.photoURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ var c = string.charCodeAt(n);
- contact.__defineGetter__("phoneNumbers", function () {
- return raw.phoneNumbers;
- });
- contact.__defineSetter__("phoneNumbers", function (val) {
- try {
- raw.phoneNumbers = t.ContactPhoneNumber(val, "[]");
- } catch (e) {
- }
- });
+ if (c < 128) {
+ utftext += String.fromCharCode(c);
+ }
+ else if((c > 127) && (c < 2048)) {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
- contact.__defineGetter__("emails", function () {
- return raw.emails;
- });
- contact.__defineSetter__("emails", function (val) {
- try {
- raw.emails = t.ContactEmailAddress(val, "[]");
- } catch (e) {
- }
- });
+ }
- contact.__defineGetter__("birthday", function () {
- return raw.birthday;
- });
- contact.__defineSetter__("birthday", function (val) {
- try {
- raw.birthday = t.Date(val, "?");
- } catch (e) {
- }
- });
+ return utftext;
+ },
- contact.__defineGetter__("anniversaries", function () {
- return raw.anniversaries;
- });
- contact.__defineSetter__("anniversaries", function (val) {
- try {
- raw.anniversaries = t.ContactAnniversary(val, "[]");
- } catch (e) {
- }
- });
+ // private method for UTF-8 decoding
+ _utf8_decode : function (utftext) {
+ var string = "";
+ var i = 0;
+ var c = c1 = c2 = 0;
- contact.__defineGetter__("organizations", function () {
- return raw.organizations;
- });
- contact.__defineSetter__("organizations", function (val) {
- try {
- raw.organizations = t.ContactOrganization(val, "[]");
- } catch (e) {
- }
- });
+ while ( i < utftext.length ) {
- contact.__defineGetter__("notes", function () {
- return raw.notes;
- });
- contact.__defineSetter__("notes", function (val) {
- try {
- raw.notes = t.DOMString(val, "[]");
- } catch (e) {
- }
- });
+ c = utftext.charCodeAt(i);
- contact.__defineGetter__("urls", function () {
- return raw.urls;
- });
- contact.__defineSetter__("urls", function (val) {
- try {
- raw.urls = t.ContactWebSite(val, "[]");
- } catch (e) {
- }
- });
+ if (c < 128) {
+ string += String.fromCharCode(c);
+ i++;
+ }
+ else if((c > 191) && (c < 224)) {
+ c2 = utftext.charCodeAt(i+1);
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+ i += 2;
+ }
+ else {
+ c2 = utftext.charCodeAt(i+1);
+ c3 = utftext.charCodeAt(i+2);
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+ i += 3;
+ }
- contact.__defineGetter__("ringtoneURI", function () {
- return raw.ringtoneURI;
- });
- contact.__defineSetter__("ringtoneURI", function (val) {
- try {
- raw.ringtoneURI = t.DOMString(val, "?");
- } catch (e) {
- }
- });
+ }
- contact.__defineGetter__("groupIds", function () {
- return raw.groupIds;
- });
- contact.__defineSetter__("groupIds", function (val) {
- try {
- raw.groupIds = t.ContactGroupId(val, "[]");
- } catch (e) {
- }
- });
+ return string;
+ }
- if (contact.name) {
- contact.name.__defineGetter__("displayName", function () {
- return ((overlap && overlap.name) ? overlap.name.displayName :
- null);
- });
- }
+ };
- contact.convertToString = convertToString;
- contact.clone = clone(contact);
-};
+ return Base64;
-_self = {
- Contact: ContactDecorator
-};
+})();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/download', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+define('ripple/platform/tizen/2.0/syncml-js-lib/constant', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// desc: SyncML constants
+// auth: metagriffin <metagriffin@uberdev.org>
+// date: 2012/10/13
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
-var db = require('ripple/db'),
- event = require('ripple/event'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- filesystem = require('ripple/platform/tizen/2.0/filesystem'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- DownloadRequest = require('ripple/platform/tizen/2.0/DownloadRequest'),
- DownloadState = {
- QUEUED: "QUEUED",
- DOWNLOADING: "DOWNLOADING",
- PAUSED: "PAUSED",
- CANCELED: "CANCELED",
- COMPLETED: "COMPLETED",
- FAILED: "FAILED"
- },
- _security = {
- "http://tizen.org/privilege/download": ["start"]
- },
- DB_DOWNLOAD_KEY = "tizen1-db-download",
- DownloadItem, _isInitialized = false, INTERVAL = 1000,
- _downloads = [], _resources = [], _self;
+var _self = {
+ // SyncML versions
+ SYNCML_VERSION_1_0 : 'SyncML/1.0',
+ SYNCML_VERSION_1_1 : 'SyncML/1.1',
+ SYNCML_VERSION_1_2 : 'SyncML/1.2',
+ SYNCML_DTD_VERSION_1_0 : '1.0',
+ SYNCML_DTD_VERSION_1_1 : '1.1',
+ SYNCML_DTD_VERSION_1_2 : '1.2',
-function _initDownloadItem(download) {
- var url, index, isExist = false;
- url = download.url;
- if (download.destination === null) {
- download.destination = "downloads";
- }
- if (download.fileName === null) {
- index = url.lastIndexOf('\/') + 1;
- download.fileName = url.substring(index);
- }
- if (!_isInitialized) {
- initializeResource();
- }
- _resources.some(function (value) {
- if (value.url === url) {
- download.size = Number(value.size);
- download.speed = Number(value.speed);
- download.estimatedTime = Math.round(value.estimatedTime * 100) / 100;
- download.MIMEType = value.MIMEType;
- isExist = true;
- return;
- }
- });
- if (!isExist) {
- download.state = DownloadState.FAILED;
- _exec(download.callback, 'onfailed', download.id, new WebAPIError(errorcode.NOT_FOUND_ERR));
- return;
- }
- return download;
-}
+ // SyncML alert/sync codes
+ ALERT_DISPLAY : 100,
+ ALERT_TWO_WAY : 200,
+ ALERT_SLOW_SYNC : 201,
+ ALERT_ONE_WAY_FROM_CLIENT : 202,
+ ALERT_REFRESH_FROM_CLIENT : 203,
+ ALERT_ONE_WAY_FROM_SERVER : 204,
+ ALERT_REFRESH_FROM_SERVER : 205,
+ ALERT_TWO_WAY_BY_SERVER : 206,
+ ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER : 207,
+ ALERT_REFRESH_FROM_CLIENT_BY_SERVER : 208,
+ ALERT_ONE_WAY_FROM_SERVER_BY_SERVER : 209,
+ ALERT_REFRESH_FROM_SERVER_BY_SERVER : 210,
+ // alert codes 211-220 are reserved for future use
-function _exec(callback, name, downloadId, arg1, arg2) {
- if (callback === null) {
- return;
- }
+ // SyncML SyncCap SyncTypes
+ SYNCTYPE_AUTO : null,
+ SYNCTYPE_TWO_WAY : 1,
+ SYNCTYPE_SLOW_SYNC : 2,
+ SYNCTYPE_ONE_WAY_FROM_CLIENT : 3,
+ SYNCTYPE_REFRESH_FROM_CLIENT : 4,
+ SYNCTYPE_ONE_WAY_FROM_SERVER : 5,
+ SYNCTYPE_REFRESH_FROM_SERVER : 6,
+ SYNCTYPE_SERVER_ALERTED : 7,
- window.setTimeout(function () {
- switch (name) {
- case "onprogress":
- callback[name](downloadId, arg1, arg2);
- break;
+ // Special syncml-js SyncTypes
+ SYNCTYPE_DISCOVER : 'discover',
- case "onpaused":
- callback[name](downloadId);
- break;
+ // SyncML synctype-to-alertcode mapping
+ // taking advantage of the fact that 1..7 maps to 200..206
+ // (more or less... "7" is a bit "nebulous"...)
+ SyncTypeToAlert: _.object(_.map(_.range(7), function(i) {
+ return [ i + 1, i + 200 ];
+ })),
- case "oncanceled":
- callback[name](downloadId);
- break;
+ // Conflict handling policies
+ POLICY_ERROR : 1,
+ POLICY_CLIENT_WINS : 2,
+ POLICY_SERVER_WINS : 3,
- case "oncompleted":
- callback[name](downloadId, arg1);
- break;
+ // SyncML XML namespaces
+ NAMESPACE_SYNCML_1_0 : 'syncml:syncml1.0',
+ NAMESPACE_SYNCML_1_1 : 'syncml:syncml1.1',
+ NAMESPACE_SYNCML_1_2 : 'syncml:syncml1.2',
+ NAMESPACE_METINF : 'syncml:metinf',
+ NAMESPACE_DEVINF : 'syncml:devinf',
+ NAMESPACE_AUTH_BASIC : 'syncml:auth-basic',
+ NAMESPACE_AUTH_MD5 : 'syncml:auth-md5',
+ NAMESPACE_FILTER_CGI : 'syncml:filtertype-cgi',
- case "onfailed":
- callback[name](downloadId, arg1);
- break;
+ // Commonly used content-types
+ TYPE_TEXT_PLAIN : 'text/plain',
+ TYPE_VCARD_V21 : 'text/x-vcard',
+ TYPE_VCARD_V30 : 'text/vcard',
+ TYPE_VCALENDAR : 'text/x-vcalendar',
+ TYPE_ICALENDAR : 'text/calendar',
+ TYPE_MESSAGE : 'text/message',
+ TYPE_SYNCML : 'application/vnd.syncml',
+ TYPE_SYNCML_DEVICE_INFO : 'application/vnd.syncml-devinf',
+ TYPE_SYNCML_ICALENDAR : 'application/vnd.syncml-xcal',
+ TYPE_SYNCML_EMAIL : 'application/vnd.syncml-xmsg',
+ TYPE_SYNCML_BOOKMARK : 'application/vnd.syncml-xbookmark',
+ TYPE_SYNCML_RELATIONAL_OBJECT : 'application/vnd.syncml-xrelational',
+ TYPE_OMADS_FOLDER : 'application/vnd.omads-folder',
+ TYPE_OMADS_FILE : 'application/vnd.omads-file',
+ TYPE_OMADS_EMAIL : 'application/vnd.omads-email',
+ TYPE_SQL : 'application/sql',
+ TYPE_LDAP : 'text/directory',
+ TYPE_EMAIL : 'message/rfc2822',
+ TYPE_EMAIL_822 : 'message/rfc822',
+ TYPE_SIF_CONTACT : 'text/x-s4j-sifc',
+ TYPE_SIF_NOTE : 'text/x-s4j-sifn',
+ TYPE_SIF_TASK : 'text/x-s4j-sift',
+ TYPE_SIF_EVENT : 'text/x-s4j-sife',
- default:
- break;
- }
- }, 1);
-}
+ // non-agent URI paths
+ URI_DEVINFO_1_0 : 'devinf10',
+ URI_DEVINFO_1_1 : 'devinf11',
+ URI_DEVINFO_1_2 : 'devinf12',
-function _getDownloadObjById(id) {
- var isFound = false, backObj;
- id = Number(id);
- _downloads.some(function (obj) {
- if (obj.id === id) {
- backObj = obj;
- isFound = true;
- return;
- }
- });
- if (!isFound) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- return backObj;
-}
+ // Response codes - Generic
+ STATUS_INVALID_CODE : 0,
+ // Response codes - Informational 1xx
+ STATUS_IN_PROGRESS : 101,
+ // Response codes - Successful 2xx
+ STATUS_OK : 200,
+ STATUS_ITEM_ADDED : 201,
+ STATUS_ACCEPTED_FOR_PROCESSING : 202,
+ STATUS_NONAUTHORIATATIVE_RESPONSE : 203,
+ STATUS_NO_CONTENT : 204,
+ STATUS_RESET_CONTENT : 205,
+ STATUS_PARTIAL_CONTENT : 206,
+ STATUS_CONFLICT_RESOLVED_MERGE : 207,
+ STATUS_CONFLICT_RESOLVED_CLIENT_DATA : 208,
+ STATUS_CONFLICT_RESOLVED_DUPLICATE : 209,
+ STATUS_DELETE_WITHOUT_ARCHIVE : 210,
+ STATUS_ITEM_NOT_DELETED : 211,
+ STATUS_AUTHENTICATION_ACCEPTED : 212,
+ STATUS_CHUNKED_ITEM_ACCEPTED : 213,
+ STATUS_OPERATION_CANCELLED_OK : 214,
+ STATUS_NOT_EXECUTED : 215,
+ STATUS_ATOMIC_ROLLBACK_OK : 216,
+ STATUS_RESULT_ALERT : 221,
+ STATUS_NEXT_MESSAGE : 222,
+ STATUS_NO_END_OF_DATA : 223,
+ STATUS_SUSPEND : 224,
+ STATUS_RESUME : 225,
+ STATUS_DATA_MANAGEMENT : 226,
+ // status codes 227-250 are reserved for future use,
+ // Response codes - Redirection 3xx
+ STATUS_MULTIPLE_CHOICES : 300,
+ STATUS_MOVED_PERMANENTLY : 301,
+ STATUS_FOUND : 302,
+ STATUS_SEE_ANOTHER_URI : 303,
+ STATUS_NOT_MODIFIED : 304,
+ STATUS_USE_PROXY : 305,
+ // Response codes - Originator Exceptions 4xx
+ STATUS_BAD_REQUEST : 400,
+ STATUS_INVALID_CREDENTIALS : 401,
+ STATUS_PAYMENT_REQUIRED : 402,
+ STATUS_FORBIDDEN : 403,
+ STATUS_NOT_FOUND : 404,
+ STATUS_COMMAND_NOT_ALLOWED : 405,
+ STATUS_OPTIONAL_FEATURE_NOT_SUPPORTED : 406,
+ STATUS_MISSING_CREDENTIALS : 407,
+ STATUS_REQUEST_TIMEOUT : 408,
+ STATUS_UPDATE_CONFLICT : 409,
+ STATUS_GONE : 410,
+ STATUS_SIZE_REQUIRED : 411,
+ STATUS_INCOMPLETE_COMMAND : 412,
+ STATUS_REQUESTED_ENTITY_TOO_LARGE : 413,
+ STATUS_URI_TOO_LONG : 414,
+ STATUS_UNSUPPORTED_MEDIA_TYPE : 415,
+ STATUS_REQUESTED_SIZE_TOO_BIG : 416,
+ STATUS_RETRY_LATER : 417,
+ STATUS_ALREADY_EXISTS : 418,
+ STATUS_CONFLICT_RESOLVED_SERVER_DATA : 419,
+ STATUS_DEVICE_FULL : 420,
+ STATUS_UNKNOWN_SEARCH_GRAMMAR : 421,
+ STATUS_BAD_CGI_SCRIPT : 422,
+ STATUS_SOFT_DELETE_CONFLICT : 423,
+ STATUS_OBJECT_SIZE_MISMATCH : 424,
+ STATUS_PERMISSION_DENIED : 425,
+ // Response codes - Recipient Exceptions 5xx
+ STATUS_COMMAND_FAILED : 500,
+ STATUS_NOT_IMPLEMENTED : 501,
+ STATUS_BAD_GATEWAY : 502,
+ STATUS_SERVICE_UNAVAILABLE : 503,
+ STATUS_GATEWAY_TIMEOUT : 504,
+ STATUS_VERSION_NOT_SUPPORTED : 505,
+ STATUS_PROCESSING_ERROR : 506,
+ STATUS_ATOMIC_FAILED : 507,
+ STATUS_REFRESH_REQUIRED : 508,
+ STATUS_RECIPIENT_EXCEPTION_RESERVED1 : 509,
+ STATUS_DATASTORE_FAILURE : 510,
+ STATUS_SERVER_FAILURE : 511,
+ STATUS_SYNCHRONIZATION_FAILED : 512,
+ STATUS_PROTOCOL_VERSION_NOT_SUPPORTED : 513,
+ STATUS_OPERATION_CANCELLED : 514,
+ STATUS_ATOMIC_ROLLBACK_FAILED : 516,
+ STATUS_ATOMIC_RESPONSE_TOO_LARGE_TO_FIT : 517,
-function initializeResource() {
- _resources = db.retrieveObject(DB_DOWNLOAD_KEY);
- _isInitialized = true;
-}
+ // SyncML codecs
+ CODEC_XML : 'xml',
+ CODEC_WBXML : 'wbxml',
+ FORMAT_B64 : 'b64',
+ FORMAT_AUTO : 'auto',
-function _saveFile(downloadObj, callback) {
- var name, path, content;
+ // SyncML nodes
+ NODE_SYNCML : 'SyncML',
+ NODE_SYNCBODY : 'SyncBody',
- name = downloadObj.fileName;
- path = downloadObj.destination;
- content = 'size|' + downloadObj.size + ',speed|' + downloadObj.speed + ',url|' + downloadObj.url + ',estimatedTime|' + downloadObj.estimatedTime;
- function onsuccess(fs) {
- fs.write(content);
- fs.close();
- }
- function onerror(e) {
- _exec(downloadObj.callback, 'onfailed', downloadObj.id, e);
- }
- function rename(name) { //index.html==>index_1.html
- var index, c;
- index = name.lastIndexOf('.');
- if (index < 0) {
- index = name.length;
- }
- c = name.substr(index - 2, 1);
- if (c === '_') {
- name = name.substr(0, index - 1) + (Number(name.substr(index - 1, 1)) + 1) + name.substring(index);
- } else {
- name = name.substr(0, index) + "_1" + name.substring(index);
- }
- return name;
- }
+ // SyncML commands
+ CMD_SYNCHDR : 'SyncHdr',
+ CMD_SYNC : 'Sync',
+ CMD_ALERT : 'Alert',
+ CMD_STATUS : 'Status',
+ CMD_GET : 'Get',
+ CMD_PUT : 'Put',
+ CMD_ADD : 'Add',
+ CMD_REPLACE : 'Replace',
+ CMD_DELETE : 'Delete',
+ CMD_RESULTS : 'Results',
+ CMD_ATOMIC : 'Atomic',
+ CMD_COPY : 'Copy',
+ CMD_EXEC : 'Exec',
+ CMD_MAP : 'Map',
+ CMD_MAPITEM : 'MapItem',
+ CMD_SEARCH : 'Search',
+ CMD_SEQUENCE : 'Sequence',
+ CMD_FINAL : 'Final',
- filesystem.resolve(path, function (dir) {
- var file, isExist = true;
- while (isExist) {
- try {
- file = dir.resolve(name);
- name = rename(name);
- } catch (e) {
- isExist = false;
- }
- }
- file = dir.createFile(name);
- file.openStream('w', onsuccess, onerror, 'UTF-8');
- callback(name);
- }, onerror, "rw");
-}
+ // SyncML standard device types
+ DEVTYPE_HANDHELD : 'handheld',
+ DEVTYPE_PAGER : 'pager',
+ DEVTYPE_PDA : 'pda',
+ DEVTYPE_PHONE : 'phone',
+ DEVTYPE_SERVER : 'server',
+ DEVTYPE_SMARTPHONE : 'smartphone',
+ DEVTYPE_WORKSTATION : 'workstation',
-DownloadItem = function (download, callback) {
- var _self;
- _self = {
- id : Number(Math.uuid(8, 10)),
- url : download.url,
- state : DownloadState.QUEUED,
- fileName : download.fileName || null,
- destination : download.destination || null,
- callback : callback || null
- };
- return _self;
+ // Item status codes
+ ITEM_OK : 0,
+ ITEM_ADDED : 1,
+ ITEM_MODIFIED : 2,
+ ITEM_DELETED : 3,
+ ITEM_SOFTDELETED : 4,
};
-_self = function () {
- function start(downloadRequest, downloadCallback) {
- var downloadObj, fileSize, increment, receivedSize = 0, intervalId;
+module.exports = _self;
- if (!_security.start) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/context', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.context
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/10/22
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- t.DownloadManager("start", arguments);
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
+ router = require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
+ synchronizer = require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
+ protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
+ localadapter = require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
+ idxdb = {},
+ _self;
- downloadObj = new DownloadItem(downloadRequest, downloadCallback);
- _downloads.push(downloadObj);
- downloadObj = _initDownloadItem(downloadObj);
- if (downloadObj === null || downloadObj === undefined) {
- return;
- }
- downloadObj.state = DownloadState.DOWNLOADING;
+// todo: is this the right place to put this?...
+// the reason that i did not put it in the `define` call is
+// because it needs access to `this.indexedDB`...
+var idxdb = {};
+if ( typeof(window) != 'undefined' && window.indexedDB )
+{
+ idxdb.indexedDB = window.indexedDB;
+ idxdb.IDBKeyRange = window.IDBKeyRange;
+}
+else
+{
+ idxdb.indexedDB = this.indexedDB;
+ idxdb.IDBKeyRange = this.IDBKeyRange;
+}
- fileSize = downloadObj.size;
- increment = downloadObj.speed;
- intervalId = setInterval(function () {
- if (receivedSize >= fileSize) {//Finish downloading
- receivedSize = fileSize;
- downloadObj.state = DownloadState.COMPLETED;
- _saveFile(downloadObj, function (fileName) {
- _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
- });
- clearInterval(intervalId);
- } else { // Continue downloading
- receivedSize += increment;
- downloadObj.receivedSize = receivedSize;
- _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
- }
- }, INTERVAL);
- downloadObj.intervalId = intervalId;
- return downloadObj.id;
- }
+_self = (function () {
+ var exports = {};
- function cancel(downloadId) {
- var downloadObj;
+ //---------------------------------------------------------------------------
+ exports.Context = common.Base.extend({
- t.DownloadManager("cancel", arguments);
+ //-------------------------------------------------------------------------
+ constructor: function(options) {
+ // options.storage expects the following properties:
+ // - indexedDB
+ // - IDBKeyRange
+ options = options || {};
+ this.storage = options.storage || idxdb;
+ this.dbname = ( options.prefix || '' ) + 'syncml-js';
+ this.autoCommit = options.autoCommit == undefined ? true : options.autoCommit;
+ this.router = options.router || new router.SmartRouter();
+ this.synchronizer = options.synchronizer || new synchronizer.Synchronizer();
+ this.protocol = options.protocol || new protocol.Protocol();
+ this.codec = options.codec || constant.CODEC_XML;
+ this.listener = options.listener;
+ this.ua = options.ua;
+ this.config = _.defaults({}, options.config, {
+ trustDevInfo : false,
+ exposeErrorTrace : false
+ });
+ this._db = null;
+ this._dbtxn = null;
+ },
- downloadObj = _getDownloadObjById(downloadId);
- clearInterval(downloadObj.intervalId);
- if (downloadObj.state !== DownloadState.DOWNLOADING &&
- downloadObj.state !== DownloadState.PAUSED) {
- _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
- return;
- }
- downloadObj.state = DownloadState.CANCELED;
- _exec(downloadObj.callback, 'oncanceled', downloadObj.id);
- }
+ //-------------------------------------------------------------------------
+ getAdapter: function(options, devInfo, cb) {
+ options = options || {};
+ var self = this;
+ if ( this._db == undefined )
+ {
+ storage.openDatabase(this, function(err, db) {
+ if ( err ) {
+ return cb(err);
+ }
+ self._db = db;
+ self._db.onerror = function(event) {
+ // todo: remove this?...
+ };
+ self._dbtxn = storage.getTransaction(self._db, null, 'readwrite');
+ self.getAdapter(options, devInfo, cb);
+ });
+ }
+ else
+ {
+ var ret = new localadapter.LocalAdapter(this, options, devInfo);
+ return ret._load(cb);
+ }
+ },
- function pause(downloadId) {
- var downloadObj;
+ //-------------------------------------------------------------------------
+ _txn: function() {
+ try {
+ // this is a work-around for XPC-based syncml... try to open
+ // a store, if it fails, we need a new transaction.
+ var store = this._dbtxn.objectStore('mapping');
+ return this._dbtxn;
+ } catch ( exc ) {
+ this._dbtxn = storage.getTransaction(this._db, null, 'readwrite');
+ return this._dbtxn;
+ }
+ },
- t.DownloadManager("pause", arguments);
+ //-------------------------------------------------------------------------
+ getEasyClientAdapter: function(options, cb) {
+ try{
+ this._getEasyClientAdapter(options, cb);
+ }catch(e){
+ cb(e);
+ }
+ },
- downloadObj = _getDownloadObjById(downloadId);
- clearInterval(downloadObj.intervalId);
- if (downloadObj.state !== DownloadState.DOWNLOADING) {
- _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
- return;
- }
- downloadObj.state = DownloadState.PAUSED;
- _exec(downloadObj.callback, 'onpaused', downloadObj.id);
- }
+ //-------------------------------------------------------------------------
+ _getEasyClientAdapter: function(options, cb) {
+ // options should be:= {
+ // // devID,
+ // // displayName,
+ // devInfo: {},
+ // stores: [],
+ // peer: {},
+ // routes: [
+ // [ source, target ],
+ // ]
+ // }
+ // response: cb(err, adapter, stores, peer);
- function resume(downloadId) {
- var downloadObj, fileSize, receivedSize, increment, intervalId;
+ var self = this;
- t.DownloadManager("resume", arguments);
+ var ret = {
+ adapter: null,
+ stores: [],
+ peer: null
+ };
- downloadObj = _getDownloadObjById(downloadId);
- fileSize = downloadObj.size;
- receivedSize = downloadObj.receivedSize;
- increment = downloadObj.speed;
+ var setupAdapter = function(cb) {
+ var adapterOptions = _.omit(options, 'devInfo', 'stores', 'peers', 'routes');
+ self.getAdapter(adapterOptions, options.devInfo, function(err, adapter) {
+ if ( err ) {
+ return cb(err);
+ }
+ ret.adapter = adapter;
+ if ( adapter.devInfo ) {
+ return cb();
+ }
+ adapter.setDevInfo(options.devInfo, cb);
+ });
+ };
- if (downloadObj.state !== DownloadState.PAUSED) {
- _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
- return;
- }
- downloadObj.state = DownloadState.DOWNLOADING;
- intervalId = setInterval(function () {
- if (receivedSize >= fileSize) {//Finish downloading
- receivedSize = fileSize;
- downloadObj.state = DownloadState.COMPLETED;
- _saveFile(downloadObj, function (fileName) {
- _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
+ var setupStores = function(cb) {
+ common.cascade(options.stores, function(storeInfo, cb) {
+ var store = ret.adapter.getStore(storeInfo.uri);
+ if ( store != undefined )
+ {
+ if ( storeInfo.agent ) {
+ store.agent = storeInfo.agent;
+ }
+ ret.stores.push(store);
+ return cb();
+ }
+ ret.adapter.addStore(storeInfo, function(err, store) {
+ if ( err ) {
+ return cb(err);
+ }
+ ret.stores.push(store);
+ return cb();
+ });
+ }, cb);
+ };
+
+ var setupPeer = function(cb) {
+ var peer = _.find(ret.adapter.getPeers(), function(p) {
+ return p.url == options.peer.url;
+ });
+ if ( peer )
+ {
+ ret.peer = peer;
+ return cb();
+ }
+ ret.adapter.addPeer(options.peer, function(err, peer) {
+ if ( err ) {
+ return cb(err);
+ }
+ ret.peer = peer;
+ common.cascade(options.routes, function(route, cb) {
+ ret.peer.setRoute(route[0], route[1], cb);
+ }, cb);
+ });
+ };
+ setupAdapter(function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ setupStores(function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ setupPeer(function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ cb(null, ret.adapter, ret.stores, ret.peer);
+ });
+ });
});
- clearInterval(intervalId);
- } else {// Continue downloading
- receivedSize += increment;
- downloadObj.receivedSize = receivedSize;
- _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
+ },
+
+ //-------------------------------------------------------------------------
+ close: function(cb) {
+ if ( this._db )
+ this._db.close();
+ this._db = null;
+ cb(null);
}
- }, INTERVAL);
- downloadObj.intervalId = intervalId;
- }
- function getState(downloadId) {
- var downloadObj;
+ });
- t.DownloadManager("getState", arguments);
+ return exports;
+
+})();
+
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/state', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// auth: metagriffin <metagriffin@uberdev.org>
+// date: 2012/10/27
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- downloadObj = _getDownloadObjById(downloadId);
- return downloadObj.state;
- }
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ _self;
- function getDownloadRequest(downloadId) {
- var req, downloadObj;
+_self = (function () {
+ var exports = {};
- t.DownloadManager("getDownloadRequest", arguments);
+ //---------------------------------------------------------------------------
+ exports.makeCommand = function(options) {
+ return _.defaults({}, options, {
+ // ?
+ });
+ };
- downloadObj = _getDownloadObjById(downloadId);
- req = new DownloadRequest(downloadObj.url, downloadObj.destination, downloadObj.fileName);
- return req;
- }
+ //---------------------------------------------------------------------------
+ exports.makeStats = function(options) {
+ return _.defaults({}, options, {
+ mode : null,
+ hereAdd : 0,
+ hereMod : 0,
+ hereDel : 0,
+ hereErr : 0,
+ peerAdd : 0,
+ peerMod : 0,
+ peerDel : 0,
+ peerErr : 0,
+ conflicts : 0,
+ merged : 0,
+ });
+ };
- function getMIMEType(downloadId) {
- var downloadObj;
+ //---------------------------------------------------------------------------
+ exports.makeSessionInfo = function(options) {
+ return _.defaults({}, options, {
+ id : null,
+ msgID : null,
+ cmdID : 0,
+ dsstates : {},
+ lastCommands : [],
+ stats : exports.makeStats()
+ });
+ };
- t.DownloadManager("getMIMEType", arguments);
+ //---------------------------------------------------------------------------
+ exports.makeStoreSyncState = function(options) {
+ return _.defaults({}, options, {
+ uri : null,
+ peerUri : null,
+ lastAnchor : null,
+ nextAnchor : '' + common.ts(),
+ mode : constant.ALERT_TWO_WAY,
+ action : null,
+ stats : exports.makeStats()
+ });
+ };
- downloadObj = _getDownloadObjById(downloadId);
- return downloadObj.MIMEType;
- }
+ //---------------------------------------------------------------------------
+ exports.makeSession = function(options) {
+ return new (function() {
+ this.context = options.context || null;
+ this.ua = options.ua || null;
+ this.txn = options.txn || options.context.txn;
+ this.adapter = options.adapter || null;
+ this.peer = options.peer || null;
+ this.info = options.info || null;
+ this.discover = options.discover ? true : false;
+ this.isServer = options.isServer ? true : false;
+ this.nextCmdID = function() {
+ this.info.cmdID += 1;
+ return this.info.cmdID;
+ };
+ })();
- function setListener(downloadId, downloadCallback) {
- var downloadObj;
+ // return _.defaults({}, options, {
+ // context : null,
+ // adapter : null,
+ // peer : null,
+ // info : null
+ // });
+ };
- t.DownloadManager("setListener", arguments);
+ var smult = function(s, count) {
+ var ret = '';
+ for ( var idx=0 ; idx<count ; idx++ )
+ ret += s;
+ return ret;
+ };
- downloadObj = _getDownloadObjById(downloadId);
- if (downloadObj) {
- downloadObj.callback = downloadCallback;
+ var num2str = function(num) {
+ // TODO: i18n...
+ // TODO: this is *UGLY*
+ // TODO: OMG, i'm *so* embarrassed
+ // TODO: but it works... sort of.
+ if ( num == 0 )
+ return '-';
+ var ret = '';
+ num = '' + num;
+ for ( var idx=num.length ; idx>0 ; idx-=3 )
+ {
+ if ( ret.length > 0 )
+ ret = ',' + ret;
+ ret = num.charAt(idx - 1) + ret;
+ if ( idx - 1 > 0 )
+ ret = num.charAt(idx - 2) + ret;
+ if ( idx - 2 > 0 )
+ ret = num.charAt(idx - 3) + ret;
}
- }
-
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ return ret;
+ };
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+ var center = function(s, wid, pad) {
+ // todo: is there no way to get sprintf to do this for me???...
+ pad = pad || ' ';
+ if ( wid <= s.length )
+ return s;
+ var diff = wid - s.length;
+ return smult(pad, Math.floor(diff / 2)) + s + smult(pad, Math.ceil(diff / 2));
+ };
- var download = {
- start: start,
- cancel: cancel,
- pause: pause,
- resume: resume,
- getState: getState,
- getDownloadRequest: getDownloadRequest,
- getMIMEType: getMIMEType,
- setListener: setListener,
- handleSubFeatures: handleSubFeatures
+ var right = function(s, wid, pad) {
+ // todo: is there no way to get sprintf to do this for me???...
+ pad = pad || ' ';
+ if ( wid <= s.length )
+ return s;
+ return smult(pad, wid - s.length) + s;
};
- return download;
-};
+ //---------------------------------------------------------------------------
+ // TODO: this should probably be put into another package...
+ exports.describeStats = function(stats, stream, options) {
-event.on('downloadResourceChanged', function () {
- _isInitialized = false;
-});
+ // ASCII OBJECTIVE:
+ // +----------------------------------------------------------------------------------+
+ // | TITLE |
+ // +----------+------+-------------------------+--------------------------+-----------+
+ // | | | Local | Remote | Conflicts |
+ // | Source | Mode | Add | Mod | Del | Err | Add | Mod | Del | Err | Col | Mrg |
+ // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
+ // | contacts | <= | - | - | - | - | 10,387 | - | - | - | - | - |
+ // | note | SS | 1,308 | - | 2 | - | - | - | - | - | - | - |
+ // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
+ // | 1,310 local changes and 10,387 remote changes. |
+ // +----------------------------------------------------------------------------------+
-module.exports = _self;
+ // UNICODE OBJECTIVE:
+ // ┌──────────────────────────────────────────────────────────────────────────────────┐
+ // │ TITLE │
+ // ├──────────┬──────┬─────────────────────────┬──────────────────────────┬───────────┤
+ // │ │ │ Local │ Remote │ Conflicts │
+ // │ Source │ Mode │ Add Mod Del Err │ Add Mod Del Err │ Col Mrg │
+ // ├──────────┼──────┼───────┼─────┼─────┼─────┼────────┼─────┼─────┼─────┼─────┼─────┤
+ // │ contacts │ <= │ │ │ │ │ 10,387 │ │ │ │ │ │
+ // │ note │ SS │ 1,308 │ │ 2 │ │ │ │ │ │ │ │
+ // ├──────────┴──────┴───────┴─────┴─────┴─────┴────────┴─────┴─────┴─────┴─────┴─────┤
+ // │ 1,310 local changes and 10,387 remote changes. │
+ // └──────────────────────────────────────────────────────────────────────────────────┘
-});
-define('ripple/platform/tizen/2.0/errorcode', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+ // todo: perhaps the fancy version should have color-coding as well?...
-var _self = {};
+ options = _.defaults({}, options, {
+ title : null,
+ details : true,
+ totals : true,
+ ascii : false,
+ gettext : function(text) { return text; }
+ });
-_self.__defineGetter__("UNKNOWN_ERR", function () {
- return 0;
-});
+ var modeStringLut = _.object([
+ [constant.SYNCTYPE_TWO_WAY , '<>'],
+ [constant.SYNCTYPE_SLOW_SYNC , 'SS'],
+ [constant.SYNCTYPE_ONE_WAY_FROM_CLIENT , '->'],
+ [constant.SYNCTYPE_REFRESH_FROM_CLIENT , '=>'],
+ [constant.SYNCTYPE_ONE_WAY_FROM_SERVER , '<-'],
+ [constant.SYNCTYPE_REFRESH_FROM_SERVER , '<=']
+ ]);
-_self.__defineGetter__("INDEX_SIZE_ERR", function () {
- return 1;
-});
+ if ( options.ascii )
+ {
-_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
- return 2;
-});
+ // unicode graphing characters: ('\xe2\x94\x80' - '\xe2\x94\xc0')
+ // mapping table unicode ==> ascii
-_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
- return 3;
-});
+ glyphs = {
+ '─': '-',
+ '━': '-',
+ '│': '|',
+ '┃': '|',
+ '┄': '-',
+ '┅': '-',
+ '┆': '|',
+ '┇': '|',
+ '┈': '-',
+ '┉': '-',
+ '┊': '|',
+ '┋': '|',
+ '┌': '+',
+ '┍': '+',
+ '┎': '+',
+ '┏': '+',
+ '┐': '+',
+ '┑': '+',
+ '┒': '+',
+ '┓': '+',
+ '└': '+',
+ '┕': '+',
+ '┖': '+',
+ '┗': '+',
+ '┘': '+',
+ '┙': '+',
+ '┚': '+',
+ '┛': '+',
+ '├': '+',
+ '┝': '+',
+ '┞': '+',
+ '┟': '+',
+ '┠': '+',
+ '┡': '+',
+ '┢': '+',
+ '┣': '+',
+ '┤': '+',
+ '┥': '+',
+ '┦': '+',
+ '┧': '+',
+ '┨': '+',
+ '┩': '+',
+ '┪': '+',
+ '┫': '+',
+ '┬': '+',
+ '┭': '+',
+ '┮': '+',
+ '┯': '+',
+ '┰': '+',
+ '┱': '+',
+ '┲': '+',
+ '┳': '+',
+ '┴': '+',
+ '┵': '+',
+ '┶': '+',
+ '┷': '+',
+ '┸': '+',
+ '┹': '+',
+ '┺': '+',
+ '┻': '+',
+ '┼': '+',
+ '┽': '+',
+ '┾': '+',
+ '┿': '+',
+ };
-_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
- return 4;
-});
+ var UnicodeToAsciiStream = common.Stream.extend({
+ constructor: function(stream) {
+ this.stream = stream;
+ },
+ write: function(data) {
+ if ( data == undefined )
+ return;
+ var ascii = '';
+ for ( var idx=0 ; idx<data.length ; idx++ )
+ {
+ var el = data[idx];
+ if ( glyphs[el] != undefined )
+ ascii += glyphs[el];
+ else
+ ascii += el;
+ }
+ this.stream.write(ascii);
+ }
+ });
-_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
- return 5;
-});
+ stream = new UnicodeToAsciiStream(stream);
-_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
- return 6;
-});
+ }
-_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
- return 7;
-});
+ // todo: this does not handle the case where the title is wider than the table.
-_self.__defineGetter__("NOT_FOUND_ERR", function () {
- return 8;
-});
+ var wSrc = options.gettext('Source').length;
+ var wMode = options.gettext('Mode').length;
+ var wCon = options.gettext('Conflicts').length;
+ var wCol = options.gettext('Col').length;
+ var wMrg = options.gettext('Mrg').length;
+ var wHereAdd = wPeerAdd = options.gettext('Add').length;
+ var wHereMod = wPeerMod = options.gettext('Mod').length;
+ var wHereDel = wPeerDel = options.gettext('Del').length;
+ var wHereErr = wPeerErr = options.gettext('Err').length
-_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
- return 9;
-});
+ var totLoc = 0;
+ var totRem = 0;
+ var totErr = 0;
+ var totCol = 0;
+ var totMrg = 0;
-_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
- return 10;
-});
+ _.each(stats, function(value, key) {
+ wSrc = Math.max(wSrc, key.length);
+ wMode = Math.max(wMode, modeStringLut[value.mode].length);
+ wCol = Math.max(wCol, num2str(value.conflicts).length);
+ wMrg = Math.max(wMrg, num2str(value.merged).length);
+ wHereAdd = Math.max(wHereAdd, num2str(value.hereAdd).length);
+ wPeerAdd = Math.max(wPeerAdd, num2str(value.peerAdd).length);
+ wHereMod = Math.max(wHereMod, num2str(value.hereMod).length);
+ wPeerMod = Math.max(wPeerMod, num2str(value.peerMod).length);
+ wHereDel = Math.max(wHereDel, num2str(value.hereDel).length);
+ wPeerDel = Math.max(wPeerDel, num2str(value.peerDel).length);
+ wHereErr = Math.max(wHereErr, num2str(value.hereErr).length);
+ wPeerErr = Math.max(wPeerErr, num2str(value.peerErr).length);
+ totLoc += value.hereAdd + value.hereMod + value.hereDel;
+ totRem += value.peerAdd + value.peerMod + value.peerDel;
+ totErr += value.hereErr + value.peerErr;
+ totCol += value.conflicts;
+ totMrg += value.merged;
+ });
-_self.__defineGetter__("INVALID_STATE_ERR", function () {
- return 11;
-});
+ // TODO: i'm 100% sure there is a python library that can do this for me...
-_self.__defineGetter__("SYNTAX_ERR", function () {
- return 12;
-});
+ if ( wCon > wCol + 3 + wMrg )
+ {
+ diff = wCon - ( wCol + 3 + wMrg );
+ wCol += diff / 2;
+ wMrg = wCon - 3 - wCol;
+ }
+ else
+ wCon = wCol + 3 + wMrg;
-_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
- return 13;
-});
+ if ( options.details )
+ tWid = ( wSrc + 3 + wMode + 3
+ + wHereAdd + wHereMod + wHereDel + wHereErr + 9 + 3
+ + wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 + 3
+ + wCon );
+ else
+ tWid = options.title ? options.title.length : 0;
-_self.__defineGetter__("NAMESPACE_ERR", function () {
- return 14;
-});
+ if ( options.totals )
+ {
+ // TODO: oh dear. from an i18n POV, this is *horrible*!...
+ sumlist = [];
+ // for val, singular, plural in [
+ _.each([
+ [totLoc, options.gettext('local change'), options.gettext('local changes')],
+ [totRem, options.gettext('remote change'), options.gettext('remote changes')],
+ [totErr, options.gettext('error'), options.gettext('errors')]
+ ], function(set) {
+ if ( set[0] <= 0 )
+ return;
+ sumlist.push(num2str(set[0]) + ' ' + ( set[0] == 1 ? set[1] : set[2] ));
+ });
+ if ( sumlist.length <= 0 )
+ sumlist = options.gettext('No changes');
+ else if ( sumlist.length == 1 )
+ sumlist = sumlist[0];
+ else
+ sumlist = ( sumlist.slice(0, -1).join(', ') + ' '
+ + options.gettext('and') + ' ' + sumlist[sumlist.length - 1] );
+ if ( totMrg > 0 || totCol > 0 )
+ {
+ sumlist += ': ';
+ if ( totMrg == 1 )
+ sumlist += num2str(totMrg) + ' ' + options.gettext('merge');
+ else if ( totMrg > 1 )
+ sumlist += num2str(totMrg) + ' ' + options.gettext('merges');
+ if ( totMrg > 0 && totCol > 0 )
+ sumlist += ' ' + options.gettext('and') + ' ';
+ if ( totCol == 1 )
+ sumlist += num2str(totCol) + ' ' + options.gettext('conflict');
+ else if ( totCol > 1 )
+ sumlist += num2str(totCol) + ' ' + options.gettext('conflicts');
+ }
+ sumlist += '.';
+ if ( sumlist.length > tWid )
+ {
+ wSrc += sumlist.length - tWid;
+ tWid = sumlist.length;
+ }
+ }
-_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
- return 15;
-});
+ if ( options.title )
+ {
+ stream.write('┏━' + smult('━', tWid) + '━┓\n');
+ stream.write('┃ ' + center(options.title, tWid) + ' ┃\n');
+ }
-_self.__defineGetter__("VALIDATION_ERR", function () {
- return 16;
-});
+ if ( options.details )
+ {
+ if ( options.title )
+ stream.write('┡━'
+ + smult('━', wSrc)
+ + '━┯━'
+ + smult('━', wMode)
+ + '━┯━'
+ + smult('━', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
+ + '━┯━'
+ + smult('━', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
+ + '━┯━'
+ + smult('━', wCon)
+ + '━┩\n'
+ );
+ else
+ stream.write('┌─'
+ + smult('─', wSrc)
+ + '─┬─'
+ + smult('─', wMode)
+ + '─┬─'
+ + smult('─', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
+ + '─┬─'
+ + smult('─', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
+ + '─┬─'
+ + smult('─', wCon)
+ + '─┐\n'
+ );
-_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
- return 17;
-});
+ stream.write('│ ' + smult(' ', wSrc));
+ stream.write(' │ ' + smult(' ', wMode));
+ stream.write(' │ ' + center(options.gettext('Local'), wHereAdd + wHereMod + wHereDel + wHereErr + 9 ));
+ stream.write(' │ ' + center(options.gettext('Remote'), wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ));
+ stream.write(' │ ' + center(options.gettext('Conflicts'), wCon));
+ stream.write(' │\n');
-_self.__defineGetter__("SECURITY_ERR", function () {
- return 18;
-});
+ stream.write('│ ' + right(options.gettext('Source'), wSrc));
+ stream.write(' │ ' + center(options.gettext('Mode'), wMode));
+ stream.write(' │ ' + center(options.gettext('Add'), wHereAdd));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mod'), wHereMod));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Del'), wHereDel));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Err'), wHereErr));
+ stream.write(' │ ' + center(options.gettext('Add'), wPeerAdd));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mod'), wPeerMod));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Del'), wPeerDel));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Err'), wPeerErr));
+ stream.write(' │ ' + center(options.gettext('Col'), wCol));
+ stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mrg'), wMrg));
+ stream.write(' │\n');
-_self.__defineGetter__("NETWORK_ERR", function () {
- return 19;
-});
+ stream.write('├─' + smult('─', wSrc)
+ + '─┼─' + smult('─', wMode)
+ + '─┼─' + smult('─', wHereAdd)
+ + '─┼─' + smult('─', wHereMod)
+ + '─┼─' + smult('─', wHereDel)
+ + '─┼─' + smult('─', wHereErr)
+ + '─┼─' + smult('─', wPeerAdd)
+ + '─┼─' + smult('─', wPeerMod)
+ + '─┼─' + smult('─', wPeerDel)
+ + '─┼─' + smult('─', wPeerErr)
+ + '─┼─' + smult('─', wCol)
+ + '─┼─' + smult('─', wMrg)
+ + '─┤\n'
+ );
-_self.__defineGetter__("ABORT_ERR", function () {
- return 20;
-});
+ var numcol = function(val, wid) {
+ if ( val == 0 )
+ return ' │ ' + center(options.ascii ? '-' : ' ', wid);
+ return ' │ ' + right(num2str(val), wid);
+ };
-_self.__defineGetter__("URL_MISMATCH_ERR", function () {
- return 21;
-});
+ var keys = _.keys(stats);
+ // todo: sort case insensitively...
+ keys.sort();
+ _.each(keys, function(key) {
+ var stat = stats[key];
+ stream.write('│ ' + right(key, wSrc));
+ stream.write(' │ ' + center(modeStringLut[stat.mode], wMode));
+ stream.write(numcol(stat.hereAdd, wHereAdd));
+ stream.write(numcol(stat.hereMod, wHereMod));
+ stream.write(numcol(stat.hereDel, wHereDel));
+ stream.write(numcol(stat.hereErr, wHereErr));
+ stream.write(numcol(stat.peerAdd, wPeerAdd));
+ stream.write(numcol(stat.peerMod, wPeerMod));
+ stream.write(numcol(stat.peerDel, wPeerDel));
+ stream.write(numcol(stat.peerErr, wPeerErr));
+ stream.write(numcol(stat.conflicts, wCol));
+ stream.write(numcol(stat.merged, wMrg));
+ stream.write(' │\n');
+ });
-_self.__defineGetter__("QUOTA_EXCEEDED_ERR", function () {
- return 22;
-});
+ if ( options.totals )
+ stream.write('├─');
+ else
+ stream.write('└─');
-_self.__defineGetter__("TIMEOUT_ERR", function () {
- return 23;
-});
+ stream.write(smult('─', wSrc)
+ + '─┴─' + smult('─', wMode)
+ + '─┴─' + smult('─', wHereAdd)
+ + '─┴─' + smult('─', wHereMod)
+ + '─┴─' + smult('─', wHereDel)
+ + '─┴─' + smult('─', wHereErr)
+ + '─┴─' + smult('─', wPeerAdd)
+ + '─┴─' + smult('─', wPeerMod)
+ + '─┴─' + smult('─', wPeerDel)
+ + '─┴─' + smult('─', wPeerErr)
+ + '─┴─' + smult('─', wCol)
+ + '─┴─' + smult('─', wMrg)
+ );
-_self.__defineGetter__("INVALID_NODE_TYPE_ERR", function () {
- return 24;
-});
+ if ( options.totals )
+ stream.write('─┤\n');
+ else
+ stream.write('─┘\n');
+ }
-_self.__defineGetter__("DATA_CLONE_ERR", function () {
- return 25;
-});
+ // ─━│┃┄┅┆┇┈┉┊┋┼┽┾┿
+ // ┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛
+ // ├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫
+ // ┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻
-_self.__defineGetter__("INVALID_VALUES_ERR", function () {
- return 99;
-});
+ if ( options.totals )
+ {
+ if ( !! options.title && ! options.details )
+ stream.write('┌─' + smult('─', tWid) + '─┐\n');
+ stream.write('│ ' + center(sumlist, tWid));
+ stream.write(' │\n');
+ stream.write('└─' + smult('─', tWid) + '─┘\n');
+ }
-_self.__defineGetter__("IO_ERR", function () {
- return 100;
-});
+ return;
-_self.__defineGetter__("SERVICE_NOT_AVAILABLE_ERR", function () {
- return 111;
-});
+ };
-module.exports = _self;
+ return exports;
+})();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/filesystem', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/syncml-js-lib/elementtree', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- utils = require('ripple/utils'),
- dbfs = require('ripple/platform/tizen/2.0/dbfs'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- _maxPathLength = 256,
- _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
- _security = {
- "http://tizen.org/privilege/filesystem": [],
- "http://tizen.org/privilege/filesystem.read": ["copyTo", "moveTo", "createDirectory", "createFile", "deleteDirectory", "deleteFile", "openStreamR"],
- "http://tizen.org/privilege/filesystem.write": ["readAsText", "openStreamW"],
- all: true
- },
- _realRoots = dbfs.roots,
- _r2vmap = {},
- _v2rmap = {},
- _initialized = false,
- _readOnly = false,
- _writeOnly = false,
- _defaultMode = "rw",
- _storages = [], // filesystem storages
- _observers = [],
- File,
- FileStream,
- FileFilter,
- FileSystemStorage;
-
-function _isValidChar(c) {
- return (c >= '0' && c <= '9') ||
- (c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z') ||
- (c === ' ') ||
- (c === '_') ||
- (c === '-') ||
- (c === '.');
-}
-
-function _isValidFileName(name) {
- var _valid = true,
- _c;
-
- if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
- _valid = false;
- } else {
- for (_c = 0; _c < name.length; _c++) {
- if (!_isValidChar(name[_c])) {
- _valid = false;
- break;
- }
- }
- }
-
- return _valid;
-}
-
-function _initialize() {
- var _i;
-
- _storages.push(FileSystemStorage("InternalFlash", "INTERNAL", "MOUNTED" ));
- _storages.push(FileSystemStorage("MMC", "EXTERNAL", "REMOVED"));
- dbfs.initialize();
-
- // set up the map between real path and virtual path
- for (_i = 0; _i < _virtualRoots.length; _i++) {
- _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
- }
-
- utils.forEach(_r2vmap, function (value, key) {
- _v2rmap[value] = key;
- });
-}
-
-function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
- var _parts = srcLocation.replace(/\/$/, '').split("/"),
- _header, _fullPath,
- _i;
-
- // TODO: Initialize at bootstrap and emulatorBridge.link
- if (!_initialized) {
- _initialize();
- _initialized = true;
- }
-
- for (_i = 0; _i < _parts.length; _i++) {
- if (!_isValidFileName(_parts[_i])) {
- if (onError) {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- }
-
- _header = _v2rmap[_parts[0]];
- if (_header === undefined) {
- if (onError) {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
-
- if (_parts.length === 1) {
- _fullPath = _header;
- } else {
- _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
- }
-
- dbfs.stat(_fullPath,
- function (entry) {
- onSuccess(new File(entry, accessMode));
- },
- function () {
- if (onError) {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- });
-}
-
-function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
- _resolveSync(srcLocation,
- function (file) {
- setTimeout(function () {
- onSuccess(file);
- }, 1);
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- accessMode);
-}
-
-File = function (entry, mode) {
- var _entry = entry,
- _mode = mode,
- _parent,
- _self;
-
- function _r2v(rpath) {
- var i, v, r, regExp;
+var utils = require('ripple/utils'),
+ _parser,
+ _serializer,
+ _self;
- for (i = 0; i < _virtualRoots.length; i++) {
- v = _virtualRoots[i];
- r = _v2rmap[v];
- if (rpath.match("^" + r)) {
- regExp = new RegExp("^" + r);
- return rpath.replace(regExp, v);
- }
- }
+function _find(query, element, type) {
+ var querylist = query.split("/"),
+ e = element._node,
+ tag, i, ret;
- return "";
+ if (querylist.length === 0) {
+ return undefined;
}
- function _v2r(vpath) {
- var i, v, r, regExp;
-
- for (i = 0; i < _virtualRoots.length; i++) {
- v = _virtualRoots[i];
- r = _v2rmap[v];
- if (vpath.match("^" + v)) {
- regExp = new RegExp("^" + v);
- return vpath.replace(regExp, r);
- }
+ for(i = 0; i < querylist.length; i++) {
+ tag = querylist[i];
+ try {
+ e = e.getElementsByTagName(tag)[0];
+ } catch (error) {
+ e = undefined;
+ break;
}
-
- return "";
}
- function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
- var _srcName = String(src),
- _dstName = String(dst),
- _src = null,
- _dst = null,
- _error = false,
- _dstParent = null,
- _dstParts = _dstName.split("/"),
- _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");
-
- if (!_entry.isDirectory) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- return undefined;
- }
-
- _resolveSync(_srcName,
- function (file) {
- _src = file;
+ if (e) {
+ if (type === "TEXT") {
+ return e.textContent;
+ } else if (type === "NODE") {
+ ret = {
+ _doc: element,
+ _node: e,
+ find: function (query) {
+ return _find(query, this, "NODE");
},
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
},
- _mode);
-
- if (_src) {
- if (_src.parent.fullPath === _self.fullPath) {
- if (!_readOnly && _mode !== "r") {
- _resolveSync(_dstParentName,
- function (file) {
- _dstParent = file;
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- _mode);
-
- if (_dstParent === null) {
- return undefined;
- }
-
- _resolveSync(_dstName,
- function (file) {
- _dst = file;
- },
- function (e) {
- if (e.code !== errorcode.NOT_FOUND_ERR) {
- setTimeout(function () {
- onError(e);
- }, 1);
- _error = true;
- }
- },
- _mode);
-
- if (_error) {
- return undefined;
- }
-
- if (_src.isFile) {
- if (_dst === null) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
- } else {
- if (_dst === null) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
-
- return undefined;
- }
-
- _self = {
- toURI: function () {
- return "file://" + _entry.fullPath;
- },
- listFiles: function (onSuccess, onError, filter) {
- var _filter, _filterName, _startCreated, _endCreated, _startModified, _endModified;
-
- if (filter !== null && filter !== undefined) {
-
- if (typeof filter === 'number' || typeof filter === 'string') {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- _filter = filter;
- _filterName = _filter.name;
- _startModified = _filter.startModified;
- _endModified = _filter.endModified;
- _startCreated = _filter.startCreated;
- _endCreated = _filter.endCreated;
-
- }
- if ((_filterName !== undefined && typeof _filterName !== 'string') ||
- (_startModified !== undefined && !tizen1_utils.isValidDate(_startModified)) ||
- (_endModified !== undefined && !tizen1_utils.isValidDate(_endModified)) ||
- (_endCreated !== undefined && !tizen1_utils.isValidDate(_endCreated)) ||
- (_startCreated !== undefined && !tizen1_utils.isValidDate(_startCreated))) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
-
- function _matchName(fileName) {
- var _matched = true,
- _name1 = String(_filterName).toLowerCase(),
- _name2 = fileName.toLowerCase(),
- _pattern;
-
- if (_filterName !== undefined && _filterName !== null) {
- if (!_name1.match("\\\\%")) {
- if (_name1.match("%")) {
- _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
- _matched = _name2.match(_pattern) ? true : false;
- } else {
- _matched = (_name1 === _name2);
- }
- } else {
- // % is not allowed as a part of file name
- _matched = false;
- }
- }
-
- return _matched;
- }
-
- function _matchDate(date) {
- var _matched = true;
-
- if (date === undefined) return true;
-
- if (_startModified !== undefined && _startModified !== null) {
- _matched = (date.getTime() >= _startModified.getTime());
- }
-
- if (_matched && (_endModified !== undefined && _endModified !== null)) {
- _matched = (date.getTime() <= _endModified.getTime());
- }
-
- return _matched;
- }
-
- function _matchFilter(entry) {
- return _matchName(entry.name) && _matchDate(entry.lastModifiedDate) && _matchDate(entry.createdDate);
- }
-
- function _listFiles() {
- var _files = [];
-
- if (!_entry.isDirectory) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- return undefined;
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
}
+ };
+ ret.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
+ ret.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
+ ret.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
+ return ret;
+ }
+ } else {
+ return undefined;
+ }
+}
- utils.forEach(_entry.children, function (child) {
- if (_matchFilter(child)) {
- _files.push(new File(child, _mode));
- }
- });
+function _findall(query, element) {
+ var querylist = query.split("/"),
+ e = element._node,
+ tag,
+ array,
+ tmp,
+ ret = [],
+ i;
- setTimeout(function () {
- onSuccess(_files);
- }, 1);
+ for(i = 0; i < querylist.length - 1; i++) {
+ tag = querylist[i];
+ try {
+ e = e.getElementsByTagName(tag)[0];
+ } catch (error) {
+ return ret;
+ }
+ }
- return null;
+ tag = querylist[querylist.length - 1];
+ array = e.getElementsByTagName(tag);
+ ///return ret;
+ for(i = 0; i < array.length; i++) {
+ tmp = {
+ _doc: element,
+ _node: array[i],
+ find: function (query) {
+ return _find(query, this, "NODE");
+ },
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
+ },
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
}
+ };
+ tmp.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
+ tmp.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
+ tmp.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
+ ret.push(tmp);
+ }
+ return ret;
+}
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
- },
- openStream: function (mode, onSuccess, onError, encoding) {
- function _openStream() {
- var _openMode = String(mode),
- _encoding = encoding ? String(encoding) : "UTF-8";
+function _tag(element) {
+ var array;
+ array = element._node.tagName.split(":");
+ return array[array.length - 1];
+}
- if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+function _getchildren(element) {
+ var ret = [], e, i;
+ for (i = 0; i < element._node.childNodes.length; i++) {
+ e = {
+ _doc: element,
+ _node: element._node.childNodes[i],
+ find: function (query) {
+ return _find(query, this, "NODE");
+ },
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
+ },
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
+ }
+ };
+ e.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
+ e.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
+ e.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
+ ret.push(e);
+ }
- if (!_security.all && ((!_security.openStreamR && _openMode === "r") || (!_security.openStreamW && _openMode === "w"))) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ return ret;
+}
- if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
- (_writeOnly && _openMode === "r")) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+_self = (function () {
+ ET = {};
- setTimeout(function () {
- onSuccess(new FileStream(_entry, _openMode, _encoding));
- }, 1);
+ ET.Element = function(name, attributes) {
+ var element = {},
+ doc,
+ node;
- return null;
- }
+ doc = _parser.parseFromString("<" + name + "></" + name + ">", "text/xml");
+ node = doc.childNodes[0];
+ if (attributes) {
+ utils.forEach(attributes, function (value, key) {
+ node.setAttribute(key, value);
+ });
+ }
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
- },
- readAsText: function (onSuccess, onError, encoding) {
- if (!_security.all && !_security.readAsText) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ element = {
+ _doc: doc,
+ _node: node,
+ find: function (query) {
+ return _find(query, this, "NODE");
+ },
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
+ },
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
}
+ };
- function _readAsText() {
- var _encoding = encoding ? String(encoding) : "UTF-8";
- if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+ element.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
- if (_writeOnly) {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+ element.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
- if (_self.isFile) {
- dbfs.read(_entry.fullPath,
- function (data) {
- setTimeout(function () {
- onSuccess(data);
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
+ element.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
- return undefined;
- }
+ return element;
+ };
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
- },
- copyTo: function (src, dst, overwrite, onSuccess, onError) {
- if (!_security.all && !_security.copyTo) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ ET.SubElement = function(element, name, attributes) {
+ var subElement = {},
+ node;
+ node = element._doc.createElement(name);
+ if (attributes) {
+ utils.forEach(attributes, function (value, key) {
+ node.setAttribute(key, value);
+ });
+ }
+ element._node.appendChild(node);
+ subElement = {
+ _doc: element._doc,
+ _node: node,
+ find: function (query) {
+ return _find(query, this, "NODE");
+ },
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
+ },
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
}
+ };
+ subElement.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
+ subElement.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
+ subElement.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
- function _copyTo() {
- return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
- }
+ return subElement;
+ };
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
- },
- moveTo: function (src, dst, overwrite, onSuccess, onError) {
- if (!_security.all && !_security.moveTo) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ ET.tostring = function(element) {
+ return _serializer.serializeToString(element._node);
+ };
+ ET.parse = function(doc) {
+ var element = {};
- function _moveTo() {
- return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
+ element = {
+ _doc: doc,
+ _node: doc.childNodes[0],
+ find: function (query) {
+ return _find(query, this, "NODE");
+ },
+ findtext: function (query) {
+ return _find(query, this, "TEXT");
+ },
+ findall: function (query) {
+ return _findall(query, this);
+ },
+ getchildren: function () {
+ return _getchildren(this);
+ },
+ append: function (node) {
+ this._node.appendChild(node._node);
+ },
+ getroot: function () {
+ return this;
}
+ };
+ element.__defineSetter__("text", function (text) {
+ this._node.textContent = text;
+ });
+ element.__defineGetter__("text", function () {
+ return this._node.textContent;
+ });
+ element.__defineGetter__("tag", function () {
+ return _tag(this);
+ });
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
- },
- createDirectory: function (dirPath) {
- var _path = String(dirPath),
- _parts = _path.replace(/\/$/, "").split("/"),
- _dir = null,
- _exist = null,
- _current = _entry.fullPath,
- _i;
+ return element;
+ };
- if (!_security.all && !_security.createDirectory) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ ET.CdataElement = function(str) {
+ var doc, cdata;
+ doc = _parser.parseFromString("<data></data>", "text/xml");
+ cdata = doc.createCDATASection(str);
+ return cdata;
+ };
- function onSuccess(entry) {
- _dir = entry;
- }
+ return ET;
+})();
- for (_i = 0; _i < _parts.length; _i++) {
- if (!_isValidFileName(_parts[_i])) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- }
+_parser = new DOMParser();
+_serializer = new XMLSerializer();
- if (!entry.isDirectory) {
- throw new WebAPIException(errorcode.IO_ERR);
- }
+module.exports = _self;
- _exist = _parts.reduce(function (obj, token) {
- return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
- }, _entry);
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/localadapter', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.localadapter
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/10/22
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- if (_exist) {
- throw new WebAPIException(errorcode.IO_ERR);
- }
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ codec = require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
+ storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
+ remote = require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
+ storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
+ devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
+ adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
+ state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
+ useragent = require('ripple/platform/tizen/2.0/syncml-js-lib/useragent'),
+ _self;
- if (_readOnly || _mode === "r") {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+_self = (function () {
+ var exports = {};
- for (_i = 0; _i < _parts.length; _i++) {
- _current = _current + "/" + _parts[_i];
- dbfs.mkdir(_current, onSuccess);
- }
+ //---------------------------------------------------------------------------
+ exports.LocalAdapter = adapter.Adapter.extend({
- return new File(_dir, _mode);
- },
- createFile: function (filePath) {
- var _name = String(filePath),
- _file = null;
+ //-------------------------------------------------------------------------
+ constructor: function(context, options, devInfo) {
- if (!_security.all && !_security.createFile) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // todo: is there anyway to mark attributes as read-only?...
- if (!_isValidFileName(_name)) {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
+ //: [read-only] devInfo describes this adapter's device info and
+ //: capabilities.
+ this.devInfo = null;
- if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
- throw new WebAPIException(errorcode.IO_ERR);
- }
+ //: [read-only] the device ID of this adapter.
+ this.devID = options.devID || null;
- if (_readOnly || _mode === "r") {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //: [read-only] specifies whether this Adapter represents a local
+ //: or remote peer.
+ this.isLocal = true;
- dbfs.touch(_entry.fullPath + "/" + _name,
- function (entry) {
- _file = new File(entry, _mode);
- },
- function () {});
+ //: [read-only] human-facing name of this adapter
+ this.displayName = options.displayName || null;
- return _file;
- },
- resolve: function (filePath) {
- var _fullPath = _self.fullPath + "/" + String(filePath),
- _file = null;
+ //: [read-only] the adapter-wide default value of the maximum
+ //: message size.
+ this.maxMsgSize = options.maxMsgSize || null;
- if (!_entry.isDirectory) {
- throw new WebAPIException(errorcode.IO_ERR);
- }
+ //: [read-only] the adapter-wide default value of the maximum
+ //: object size.
+ this.maxObjSize = options.maxObjSize || null;
- _resolveSync(_fullPath,
- function (file) {
- _file = file;
- },
- function (e) {
- throw (e);
- },
- _mode);
+ //: [read-only] specifies default conflict resolution policy for
+ //: this adapter. if undefined, defaults to constant.POLICY_ERROR.
+ this.conflictPolicy = options.conflictPolicy || constant.POLICY_ERROR;
- return _file;
+ // --- private attributes
+ this.id = options.id || common.makeID();
+ this._c = context;
+ // TODO: use _.pick() for these options...
+ this._options = options;
+ this._devInfo = devInfo;
+ this._model = null;
+ this._stores = {};
+ this._peers = [];
},
- deleteDirectory: function (directory, recursive, onSuccess, onError) {
- if (!_security.all && !_security.deleteDirectory) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- function _deleteDirectory() {
- var _dir = null,
- _dirName = String(directory);
- _resolveSync(_dirName,
- function (file) {
- _dir = file;
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- _mode);
-
- if (_dir) {
- if (_dir.isDirectory &&
- _dir.parent.fullPath === _self.fullPath &&
- (!recursive && _dir.length === 0)) {
- if (!_readOnly && _mode !== "r") {
- dbfs.rmdir(_v2r(_dirName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
-
- return undefined;
- }
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
- },
- deleteFile: function (fileName, onSuccess, onError) {
- if (!_security.all && !_security.deleteFile) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ _getModel: function() {
+ return this._model;
+ },
- function _deleteFile() {
- var _file = null;
- _resolveSync(String(fileName),
- function (file) {
- _file = file;
- },
- function (e) {
- if (onError) {
- setTimeout(function () {
- onError(e);
- }, 1);
- }
- },
- _mode);
+ //-------------------------------------------------------------------------
+ setDevInfo: function(devInfo, cb) {
+ if ( this._model == undefined )
+ this._model = {
+ id : this.id,
+ displayName : this.displayName,
+ maxMsgSize : this.maxMsgSize,
+ maxObjSize : this.maxObjSize,
+ conflictPolicy : this.conflictPolicy,
+ devInfo : null,
+ stores : [],
+ peers : [],
+ isLocal : 1
+ };
- if (_file) {
- if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
- if (!_readOnly && _mode !== "r") {
- dbfs.rm(_v2r(fileName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
+ var di = new devinfomod.DevInfo(this, devInfo);
+ di._updateModel(_.bind(function(err) {
+ if ( err )
+ return cb(err);
- return undefined;
- }
+ this._model.devID = this._model.devInfo.devID;
+ this.devID = this._model.devInfo.devID;
+ this.devInfo = di;
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
- }
- };
+ // since the local devinfo has changed, we need to ensure that
+ // we rebroadcast it (in case there are any affects...), thus
+ // resetting all anchors.
+ // TODO: this seems a little heavy-handed, since this will force
+ // a slow-sync for each datastore. is that really the best
+ // thing?...
+ this._resetAllAnchors();
- _self.__defineGetter__("parent", function () {
- var _parts = _self.fullPath.split("/");
+ this._save(this._c._txn(), cb);
- if (_parent === undefined) {
- if (_parts.length === 1) {
- // virtual root's parent is null
- _parent = null;
- } else {
- _resolveSync(_parts.splice(0, _parts.length - 1).join("/"),
- function (file) {
- _parent = file;
- },
- function () {},
- _mode);
- }
- return _parent;
- } else {
- return _parent;
- }
- });
+ }, this));
+ },
- _self.__defineGetter__("readOnly", function () {
- return false;
- });
+ //-------------------------------------------------------------------------
+ _resetAllAnchors: function() {
+ _.each(this._model.peers, function(peer) {
+ _.each(peer.stores, function(store) {
+ if ( ! store.binding )
+ return;
+ store.binding.localAnchor = null;
+ store.binding.remoteAnchor = null;
+ });
+ });
+ },
- _self.__defineGetter__("isFile", function () {
- return !_entry.isDirectory;
- });
+ //-------------------------------------------------------------------------
+ getPeers: function() {
+ return this._peers;
+ },
- _self.__defineGetter__("isDirectory", function () {
- return _entry.isDirectory;
- });
+ //-------------------------------------------------------------------------
+ addPeer: function(peerInfo, cb) {
+ var self = this;
- _self.__defineGetter__("created", function () {
- return _entry.createdDate;
- });
+ // TODO: if there is already a peer for the specified URL, then
+ // we may have a problem!...
- _self.__defineGetter__("modified", function () {
- return _entry.lastModifiedDate;
- });
+ // todo: if we are adding a peer to an adapter that already has
+ // non-client peers, then we may have a problem!...
+ // (this is only true while syncml-js is not capable of truly
+ // operating in peer-to-peer mode)
- _self.__defineGetter__("path", function () {
- var _parts = _self.fullPath.split("/");
+ var peer = new remote.RemoteAdapter(this, peerInfo);
+ peer._updateModel(function(err) {
+ if ( err )
+ return cb(err);
+ self._peers.push(peer);
+ cb(null, peer);
+ });
+ },
- if (_parts.length === 1) {
- // virtual root
- return _parts.join("");
- } else {
- return _parts.splice(0, _parts.length - 1).join("/") + "/";
- }
- });
+ //-------------------------------------------------------------------------
+ save: function(cb) {
+ this._save(this._c._txn(), cb);
+ },
- _self.__defineGetter__("name", function () {
- return _entry.name;
- });
+ //-------------------------------------------------------------------------
+ _save: function(dbtxn, cb) {
+ var self = this;
+ self._updateModel(function(err) {
+ if ( err )
+ return cb(err);
+ storage.put(dbtxn.objectStore('adapter'), self._model, cb);
+ });
+ },
- _self.__defineGetter__("fullPath", function () {
- return _r2v(_entry.fullPath);
- });
+ //-------------------------------------------------------------------------
+ _updateModel: function(cb) {
+ var self = this;
+ var model = self._model;
+ model.displayName = self.displayName;
+ model.devID = self.devID;
+ model.maxMsgSize = self.maxMsgSize;
+ model.maxObjSize = self.maxObjSize;
+ model.conflictPolicy = self.conflictPolicy;
+ model.isLocal = 1;
+ common.cascade([
+ // update the devInfo model
+ function(cb) {
+ if ( ! self.devInfo )
+ return cb();
+ return self.devInfo._updateModel(cb);
+ },
+ // update the stores model
+ function(cb) {
+ model.stores = [];
+ common.cascade(_.values(self._stores), function(store, cb) {
+ store._updateModel(cb);
+ }, cb);
+ },
- _self.__defineGetter__("fileSize", function () {
- if (_entry.isDirectory) {
- return undefined;
- } else {
- return _entry.data.length;
- }
- });
+ // update the peers model
+ function(cb) {
+ // NOTE: unlike stores, which can completely regenerate the
+ // model based on the class, the peers store binding
+ // and routing info is only in the model, so cannot be
+ // completely deleted...
+ common.cascade(self._peers, function(peer, cb) {
+ peer._updateModel(cb);
+ }, cb);
+ }
- _self.__defineGetter__("length", function () {
- var _l = 0;
- if (_entry.isDirectory) {
- utils.forEach(_entry.children, function () {
- _l++;
- });
- return _l;
- } else {
- return undefined;
- }
- });
+ ], cb);
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ _load: function(cb) {
+ var self = this;
-FileStream = function (entry, mode, encoding) {
- var _entry = entry,
- _data = entry.data,
- _mode = mode,
- _position = (_mode === "a" ? _data.length : 0),
- _self;
+ // TODO: if options specifies a devID/name/etc, use that...
- _self = {
- close: function () {
- var _element;
- if (mode === "a" || mode === "w") {
- dbfs.write(_entry.fullPath, _data, function () {}, function () {});
- }
- for (_element in _self) {
- delete _self[_element];
- }
- },
- read: function (charCount) {
- var _count = charCount | 0,
- _substr = _data.substring(_position, _position + _count);
+ storage.getAll(
+ this._c,
+ this._c._txn().objectStore('adapter').index('isLocal'),
+ {only: 1},
+ function(err, adapters) {
+ if ( err ) {
+ return cb(err);
+ }
+ if ( adapters.length > 1 )
+ return cb('multiple local adapters defined - specify which devID to load');
+ if ( adapters.length <= 0 )
+ return cb(null, self);
+ self._loadModel(adapters[0], function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, self);
+ });
+ }
+ );
+ },
- if (_position + _count > _data.length) {
- _position = _data.length;
- } else {
- _position += _count;
- }
+ //-------------------------------------------------------------------------
+ _loadModel: function(model, cb) {
+ var self = this;
+ self._model = model;
+ self.displayName = model.displayName;
+ self.devID = model.devID;
+ self.maxMsgSize = model.maxMsgSize;
+ self.maxObjSize = model.maxObjSize;
+ self.conflictPolicy = model.conflictPolicy;
+ common.cascade([
+ // load device info
+ function(cb) {
+ var di = new devinfomod.DevInfo(self, self._model.devInfo);
+ di._load(function(err) {
+ if ( err )
+ return cb(err);
+ self.devInfo = di;
+ cb();
+ });
+ },
+ // load stores
+ function(cb) {
+ common.cascade(model.stores, function(e, cb) {
+ var store = new storemod.Store(self, e);
+ store._load(function(err) {
+ if ( err )
+ return cb(err);
+ self._stores[store.uri] = store;
+ return cb();
+ });
+ }, cb);
+ },
+ // load peers
+ function(cb) {
+ var remotes = _.filter(model.peers, function(e) {
+ return ! e.isLocal;
+ });
+ self._peers = [];
+ common.cascade(remotes, function(e, cb) {
+ var peer = new remote.RemoteAdapter(self, e);
+ peer._load(function(err) {
+ if ( err )
+ return cb(err);
+ self._peers.push(peer);
+ return cb();
+ });
+ }, cb);
+ }
+ ], cb);
+ },
- return _substr;
- },
- readBytes: function (byteCount) {
- var _substr = _self.read(byteCount),
- _bytes = [],
- _i;
+ //-------------------------------------------------------------------------
+ sync: function(peer, mode, options, cb) {
+ // `options` is optional and can have the following properties:
+ // * `ua`
- for (_i = 0; _i < _substr.length; _i++) {
- _bytes.push(_substr.charCodeAt(_i));
- }
+ // TODO: initialize a new context transaction?...
+ // todo: or perhaps add a new session.txn?...
- return _bytes;
- },
- readBase64: function (byteCount) {
- var _substr = _self.read(byteCount);
+ if ( cb == undefined && _.isFunction(options) )
+ {
+ cb = options;
+ options = {};
+ }
+ options = options || {};
- return window.atob(_substr);
- },
- write: function (stringData) {
- var _stringData = String(stringData),
- _substr = _data.substring(0, _position);
+ var self = this;
+ var discover = ( mode == constant.SYNCTYPE_DISCOVER );
+ if ( discover )
+ mode = constant.SYNCTYPE_SLOW_SYNC;
- _data = _substr.concat(_stringData);
- _position = _data.length;
- },
- writeBytes: function (byteData) {
- _self.write(String.fromCharCode.apply(String, byteData));
- },
- writeBase64: function (base64Data) {
- _self.write(window.btoa(String(base64Data)));
- }
- };
+ if ( ! _.find(self._peers, function(p) { return p === peer; }) )
+ return cb(new common.InvalidAdapter('invalid peer for adapter'));
+ if ( mode != constant.SYNCTYPE_AUTO )
+ {
+ mode = common.synctype2alert(mode);
+ if ( ! mode )
+ return cb(new common.TypeError('invalid synctype'));
+ }
+ if ( ! self.devInfo )
+ return cb(new common.InvalidAdapter('cannot synchronize adapter as client: invalid devInfo'));
- _self.__defineGetter__("eof", function () {
- return _position === _data.length;
- });
+ var session = state.makeSession({
+ context : self._c,
+ ua : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
+ txn : _.bind(self._c._txn, self._c),
+ adapter : self,
+ peer : peer,
+ isServer : false,
+ discover : discover,
+ info : state.makeSessionInfo({
+ id : ( peer.lastSessionID || 0 ) + 1,
+ msgID : 1,
+ codec : self._c.codec,
+ mode : mode
+ })
+ });
- _self.__defineGetter__("position", function () {
- return _position;
- });
+ session.send = function(contentType, data, cb) {
+ session.peer.sendRequest(session, contentType, data, function(err, response) {
+ if ( err )
+ return cb(err);
+ // todo: allow the client to force the server to authorize itself as well...
+ self._receive(session, response, null, cb);
+ });
+ };
- _self.__defineSetter__("position", function (value) {
- var _value = value | 0;
+ // TODO: should i do a router.calculate() at this point?
+ // the reason is that if there was a sync, then a
+ // .setRoute(), then things may have changed...
+ // corner-case, yes... but still valid.
- if (_value >= 0 && _value <= _data.length) {
- _position = _value;
- } else {
- throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
- }
- });
+ var failed = 0;
- _self.__defineGetter__("bytesAvailable", function () {
- return (_data.length - _position) || -1;
- });
+ var startSession = function() {
+ session.context.protocol.initialize(session, null, function(err, commands) {
+ if ( err )
+ return cb(err);
+ self._transmit(session, commands, function(err) {
+ if ( err )
+ {
+ if ( ! ( err instanceof common.InvalidCredentials )
+ && ! ( err instanceof common.CredentialsRequired ) )
+ return cb(err);
+ if ( err instanceof common.InvalidCredentials )
+ failed += 1;
+ if ( failed > 100 )
+ {
+ return cb(err);
+ }
+ var credErr = err;
+ var uaEvent = {
+ session : session,
+ auth : err.auth,
+ count : failed
+ };
+ return session.ua.fetchCredentials(uaEvent, function(err, auth) {
+ if ( err )
+ return cb(err);
+ if ( ! auth )
+ return cb(credErr);
+ if ( auth.persist )
+ {
+ session.peer.auth = auth.type;
+ session.peer.username = auth.username;
+ session.peer.password = auth.password;
+ }
+ else
+ session.auth = auth;
+ // todo: should i just create a new session?...
+ session.info.id += 1;
+ session.info.msgID = 1;
+ return startSession();
+ });
+ }
+ self._save(session.txn(), function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, self._session2stats(session));
+ });
+ });
+ });
+ };
- return _self;
-};
+ session.context.synchronizer.initStoreSync(session, function(err) {
+ if ( err )
+ return cb(err);
+ startSession();
+ });
-FileFilter = function (name, startModified, endModified, startCreated, endCreated) {
- var _self = {
- name: name,
- startModified: utils.copy(startModified),
- endModified: utils.copy(endModified),
- endCreated: utils.copy(endCreated)
- };
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ _session2stats: function(session) {
+ var ret = {};
+ _.each(_.values(session.info.dsstates), function(ds) {
+ var stats = _.clone(ds.stats);
+ stats.mode = common.alert2synctype(ds.mode);
+ if ( ds.action == 'error' && ds.error )
+ stats.error = ds.error;
+ ret[ds.uri] = stats;
+ });
+ return ret;
+ },
-FileSystemStorage = function (label, type, state) {
- var _self = {
- label: label,
- type: type,
- state: state
- };
+ //-------------------------------------------------------------------------
+ _transmit: function(session, commands, cb) {
+ var self = this;
+ if ( session.info.msgID > 20 )
+ return cb('too many client/server messages');
+ session.context.protocol.negotiate(session, commands, function(err, commands) {
+ if ( err )
+ return cb(err);
+ if ( session.context.protocol.isComplete(session, commands) )
+ {
+ // we're done! store all the anchors and session IDs and exit...
+ var pmodel = session.peer._getModel();
+ if ( ! pmodel )
+ return cb('unexpected error: could not locate this peer in local adapter');
+ _.each(session.info.dsstates, function(ds, uri) {
+ var pstore = _.find(pmodel.stores, function(s) { return s.uri == ds.peerUri; });
+ if ( ! pstore )
+ return cb('unexpected error: could not locate bound peer store in local adapter');
+ pstore.binding.localAnchor = ds.nextAnchor;
+ pstore.binding.remoteAnchor = ds.peerNextAnchor;
+ });
+ session.peer.lastSessionID = session.info.id;
+ pmodel.lastSessionID = session.info.id;
+ return cb();
+ }
+ session.context.protocol.produce(session, commands, function(err, tree) {
+ if ( err )
+ return cb(err);
+ codec.Codec.autoEncode(tree, session.info.codec, function(err, contentType, data) {
+ if ( err )
+ return cb(err);
+ // update the session with the last request commands so
+ // that when we receive the response package, it can be
+ // compared against that.
+ // TODO: should that only be done on successful transmit?...
+ session.info.lastCommands = commands;
+ session.send(contentType, data, function(err) {
+ if ( err )
+ return cb(err);
+ cb();
+ });
+ })
+ });
+ });
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ authorize: function(request, sessionInfo, authorize, cb) {
+ var self = this;
+ var ct = request.headers['Content-Type'];
+ codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
+ if ( err )
+ return cb(err);
+ self._c.protocol.authorize(xtree, null, authorize, cb);
+ });
+ },
-module.exports = {
- maxPathLength: _maxPathLength,
- resolve: function (srcLocation, onSuccess, onError, accessMode) {
- function _resolve() {
- var _mode = accessMode ? String(accessMode) : _defaultMode;
+ //-------------------------------------------------------------------------
+ getTargetID: function(request, sessionInfo, cb) {
+ var self = this;
+ var ct = request.headers['Content-Type'];
+ codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
+ if ( err )
+ return cb(err);
+ return cb(null, self._c.protocol.getTargetID(xtree));
+ });
+ },
- if (_mode === "r" || _mode === "rw") {
- _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- }
- return undefined;
- }
+ //-------------------------------------------------------------------------
+ handleRequest: function(request, sessionInfo, authorize, response, options, cb) {
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
- },
+ // TODO: initialize a new context transaction?...
+ // todo: or perhaps add a new session.txn?...
- getStorage: function (label, onSuccess, onError) {
- var storage = null, _label = String(label);
+ if ( cb == undefined && _.isFunction(options) )
+ {
+ cb = options;
+ options = {};
+ }
+ options = options || {};
- _storages.some(function (value) {
- if (value.label === _label) {
- storage = utils.copy(value);
- setTimeout(function () {
- onSuccess(storage);
- }, 1);
- return true;
- }
- });
+ var self = this;
+ var session = state.makeSession({
+ context : self._c,
+ ua : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
+ txn : _.bind(self._c._txn, self._c),
+ adapter : self,
+ peer : null,
+ isServer : true,
+ info : sessionInfo
+ });
+ session.send = response;
+ this._receive(session, request, authorize, function(err, stats) {
+ if ( err )
+ return cb(err);
+ self._save(session.txn(), function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, self._session2stats(session));
+ });
+ });
+ },
- if (!storage) {
- if(onError) {
- setTimeout(function () {
- onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }, 1);
+ //-------------------------------------------------------------------------
+ _receive: function(session, request, authorize, cb) {
+ var self = this;
+ if ( ! session.isServer )
+ {
+ session.info.lastMsgID = session.info.msgID;
+ session.info.msgID += 1;
+ }
+ var ct = request.headers['Content-Type'];
+ codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
+ if ( err )
+ return cb(err);
+ session.info.codec = codecName;
+ var do_authorize = ( ! authorize ) ? common.noop : function(cb) {
+ session.context.protocol.authorize(xtree, null, authorize, function(err) {
+ return cb(err);
+ });
+ };
+ do_authorize(function(err) {
+ if ( err )
+ return cb(err);
+ session.context.protocol.consume(
+ session, session.info.lastCommands, xtree,
+ function(err, commands) {
+ if ( err ) {
+ return cb(err);
+ }
+ if ( session.discover && session.peer.devInfo )
+ return cb(null, self._session2stats(session));
+ self._transmit(session, commands, function(err) {
+ if ( err )
+ return cb(err);
+ if ( ! session.isServer )
+ return cb();
+ self._save(session.txn(), function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, self._session2stats(session));
+ });
+ });
+ }
+ );
+ });
+ })
+ },
- } else {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- }
- },
+ });
- listStorages: function (onSuccess, onError) {
- function _listStorages() {
- setTimeout(function () {
- onSuccess(utils.copy(_storages));
- }, 1);
- }
+ return exports;
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listStorages", _listStorages);
- },
+})();
- addStorageStateChangeListener: function(onSuccess, onError) {
- function _addStorageStateChangeListener() {
- var watchId = (new Date()).getTime() || 0;
- _observers[watchId] = function(storage) {//storage is which state is changed
- onSuccess(storage);
- };
+module.exports = _self;
- // This event should be triggered from outside
- event.on("StateChange", _observers[watchId]);
- return Number(watchId);
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/protocol', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.protocol
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/04
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- return tizen1_utils.validateTypeMismatch(onSuccess, onError, "addStorageStateChangeListener", _addStorageStateChangeListener);
- },
+var db = require('ripple/db'),
+ common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ devinfo = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
+ state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
+ base64 = require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
+ ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
+ _firstflag = false,
+ changednum, _counts;
- removeStorageStateChangeListener: function (watchId) {
- if (!_observers[watchId])
- return;
+var _self = (function () {
- event.deleteEventHandler("StateChange", _observers[watchId]);
- delete _observers[watchId];
- },
+ var exports = {};
- handleSubFeatures: function (subFeatures) {
- function setSecurity(_security) {
- return function (method) {
- _security[method] = true;
- };
+ //---------------------------------------------------------------------------
+ var getError = function(xnode) {
+ var ret = {
+ message: xnode.findtext('Item/Data')
+ };
+ try{
+ var xerr = xnode.find('Error');
+ }catch(e){
+ var xerr = null;
}
+ if ( ! xerr )
+{
+ try{
+ var xerr = xnode.find('Item/Error');
+ }catch(e){
+ var xerr = null;
+ }
+}
+if ( ! xerr )
+{
+ if ( ! ret.message )
+ return null;
+ return ret;
+}
+ret.code = xerr.findtext('Code');
+ret.message = xerr.findtext('Message');
+ret.trace = xerr.findtext('Trace');
+return ret;
+}
- for (var subFeature in subFeatures) {
- if (_security[subFeature].length === 0) {
- _security.all = true;
- return;
- }
- _security.all = false;
- utils.forEach(_security[subFeature], setSecurity);
- }
+//---------------------------------------------------------------------------
+var badStatus = function(xnode, kls, attrs) {
+ if ( ! kls )
+ kls = common.ProtocolError;
+ var code = xnode.findtext('Data');
+ var cname = xnode.findtext('Cmd');
+ var msg = null;
+ if ( kls == common.ProtocolError )
+ msg = 'unexpected status code ' + code + ' for command "' + cname + '"';
+ else
+ msg = 'received status code ' + code + ' for command "' + cname + '"';
+ var error = getError(xnode);
+ if ( error )
+ {
+ if ( error.code )
+ msg += ': [' + error.code + '] ' + error.message;
+ else
+ msg += ': ' + error.message;
}
+ return new kls(msg, undefined, attrs)
};
+//---------------------------------------------------------------------------
+exports.getError = getError;
+exports.badStatus = badStatus;
-});
-define('ripple/platform/tizen/2.0/geoBackend_local', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+//---------------------------------------------------------------------------
+exports.Protocol = common.Base.extend({
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- PendingObject = require('ripple/platform/tizen/2.0/pendingObject'),
- PendingOperation = require('ripple/platform/tizen/2.0/pendingoperation'),
- GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult'),
- _GEO_OBJECTS = "tizen1.0-geocode-objects",
- _get, _save, _geoList_init, GeoEntry,
- _checkAddressType, _transAddressStr,
- _geocodeByString, _findCoordsByString, _geocodeByAddress,
- _reverseGeocodeBySimple, _reverseGeocodeByGeo, _checkCoordsType,
- _geoList = [],
- _PENDING_TIME = 10;
+ //-------------------------------------------------------------------------
+ constructor: function(options) {
+ },
-function _get() {
- var geoList = [],
- data = db.retrieveObject(_GEO_OBJECTS);
+ //-------------------------------------------------------------------------
+ authorize: function(xtree, uri, authorize, cb) {
- utils.forEach(data, function (geo) {
- geoList.push(geo);
- });
- return geoList;
-}
+ // TODO: if this session has been authorized before, don't call authorize
+ // ie.:
+ // if ( session.info.authAccepted )
+ // return cb();
+ // BUT this requires the session object... oops.
-function _save() {
- db.saveObject(_GEO_OBJECTS, _geoList);
+ if ( ! authorize )
+ authorize = function(uri, data, cb) { return cb(null, data); };
+if ( xtree.tag != 'SyncML' )
+ throw new common.ProtocolError('root element was not "SyncML"');
+var xcred = xtree.find('SyncHdr/Cred');
+if ( ! xcred )
+ return authorize(uri, null, cb);
+var data = xcred.findtext('Data');
+var authtype = xcred.findtext('Meta/Type');
+var format = xcred.findtext('Meta/Format');
+if ( format == constant.FORMAT_B64 )
+ data = base64.decode(data);
+else if ( format )
+ throw new common.UnknownFormatType(format);
+switch ( authtype )
+{
+ case constant.NAMESPACE_AUTH_BASIC:
+ {
+ data = common.splitn(data, ':', 1);
+ return authorize(uri, {
+ auth: constant.NAMESPACE_AUTH_BASIC,
+ username: data[0],
+ password: data[1]
+ }, cb);
+ }
+ case constant.NAMESPACE_AUTH_MD5:
+ {
+ return authorize(uri, {
+ auth: constant.NAMESPACE_AUTH_BASIC,
+ digest: data
+ }, cb);
+ }
+ default:
+ {
+ return cb(new common.UnknownAuthType(
+ 'unknown/unimplemented auth type "' + authtype + '"'));
+ }
}
+},
-function _geoList_init() {
- var entry;
- _geoList = _get();
-
- /* Put some default data if database is empty */
- if (_geoList.length === 0) {
- entry = new GeoEntry(new lbs.StructuredAddress({
- country : "UK",
- region : "London",
- county : "Lambeth",
- city : "London",
- street : "Westminster Bridge Road",
- streetNumber : "1",
- premises : "Riverside Building",
- additionalInformation : "London Eye",
- postalCode : "SE1 7PB"
- }),
- new lbs.GeoCoordinates({
- latitude : 51.510452,
- longitude : -0.119820,
- altitude : 0,
- accuracy : 0,
- altitudeAccuracy : 0,
- heading : 0,
- speed : 0
- }));
- _geoList.push(entry);
- entry = new GeoEntry(new lbs.StructuredAddress({
- country : "UK",
- city : "London",
- street : "Baker Street",
- streetNumber : "221B",
- postalCode : "NW1 6XE"
- }),
- new lbs.GeoCoordinates({
- latitude : 51.524552,
- longitude : -0.158615,
- altitude : 0,
- accuracy : 0,
- altitudeAccuracy : 0,
- heading : 0,
- speed : 0
- }));
- _geoList.push(entry);
- entry = new GeoEntry(new lbs.StructuredAddress({
- country : "US",
- region : "OR",
- city : "Portland",
- street : "SE Water Ave",
- streetNumber : "1945",
- additionalInformation : "OMSI",
- }),
- new lbs.GeoCoordinates({
- latitude : 45.508490,
- longitude : -122.665953,
- altitude : 0,
- accuracy : 0,
- altitudeAccuracy : 0,
- heading : 0,
- speed : 0
- }));
- _geoList.push(entry);
- entry = new GeoEntry(new lbs.StructuredAddress({
- country : "US",
- region : "OR",
- city : "Portland",
- street : "NW Pittock Drive",
- streetNumber : "3229",
- additionalInformation : "Pittock Mansion",
- }),
- new lbs.GeoCoordinates({
- latitude : 45.531365,
- longitude : -122.716255,
- altitude : 0,
- accuracy : 0,
- altitudeAccuracy : 0,
- heading : 0,
- speed : 0
- }));
- _geoList.push(entry);
- entry = new GeoEntry(new lbs.StructuredAddress({
- region : "OR",
- city : "Hillsboro",
- street : "NE 25th St",
- streetNumber : "2111",
- postalCode : "97124"
- }),
- new lbs.GeoCoordinates({
- latitude : 45.543479,
- longitude : -122.9621601,
- altitude : 0,
- accuracy : 0,
- altitudeAccuracy : 0,
- heading : 0,
- speed : 0
- }));
- _geoList.push(entry);
- _save();
- }
-}
+ //-------------------------------------------------------------------------
+ getTargetID: function(xtree) {
+ if ( xtree.tag != 'SyncML' )
+ throw new common.ProtocolError('root element was not "SyncML"');
+ // todo: do more validity checks?...
+ return xtree.findtext('SyncHdr/Target/LocURI');
+ },
-function _pendingOperate(operate) {
- var pendingObj, pendingOperation, i, argumentVector = [];
+ //-------------------------------------------------------------------------
+ isComplete: function(session, commands) {
+ return (! session.isServer
+ && commands.length == 3
+ && commands[0].name == constant.CMD_SYNCHDR
+ && commands[1].name == constant.CMD_STATUS
+ && commands[1].statusOf == constant.CMD_SYNCHDR
+ && commands[1].statusCode == constant.STATUS_OK
+ && commands[2].name == constant.CMD_FINAL
+ );
+ },
- for (i = 0; i < arguments.length - 1; i++)
- argumentVector[i] = arguments[i + 1];
+ //----------------------<---------------------------------------------------
+ initialize: function(session, xtree, cb) {
+ var cmd = state.makeCommand({
+ name : constant.CMD_SYNCHDR,
+ cmdID : 0,
+ version : constant.SYNCML_VERSION_1_2,
+ source : session.info.effectiveID || session.adapter.devID,
+ sourceName : session.adapter.displayName,
+ respUri : session.isServer ? session.info.returnUrl : null
+ });
- pendingObj = new PendingObject();
+ var checkPeer = ( ! session.isServer ) ? function(cb) {
+ if ( ! xtree )
+ return cb();
+ var xhdr = xtree.find('SyncHdr');
+ // todo: check peer id...
+ if ( session.info.id != common.int(xhdr.findtext('SessionID')) )
+ {
+ return cb(new common.ProtocolError('session ID mismatch "'
+ + xhdr.findtext('SessionID')
+ + '" (expected: ' + session.info.id + ')'));
+ }
+ // todo: check message id...
+ cb();
+ } : function(cb) {
+ var xhdr = xtree.find('SyncHdr');
+ var peerID = xhdr.findtext('Source/LocURI');
+ if ( session.info.peerID && session.info.peerID != peerID )
+ {
+ return cb(new common.ProtocolError('unexpected peer ID "' + peerID + '"'));
+ }
+ if ( session.peer && session.peer.devID != peerID )
+ {
+ return cb(new common.ProtocolError('unacceptable peer ID "' + peerID + '"'));
+ }
+ session.info.peerID = peerID;
+ // check that no session swapping occurred
+ if ( session.info.id != undefined
+ && session.info.id != common.int(xhdr.findtext('SessionID')) )
+ {
+ return cb(new common.ProtocolError('session ID mismatch "'
+ + xhdr.findtext('SessionID')
+ + '" (expected: ' + session.info.id + ')'));
+ }
+ session.info.id = common.int(xhdr.findtext('SessionID'));
+ session.info.msgID = common.int(xhdr.findtext('MsgID'));
+ if ( session.peer && session.peer.devID == peerID )
+ return cb();
+ // TODO: i should delete unused peers here... ie. anything that
+ // hasn't been used in some configurable number of seconds,
+ // which should probably default to something like a month...
+ session.peer = _.find(session.adapter.getPeers(), function(peer) {
+ return ( peer.devID == peerID );
+ });
+ if ( session.peer )
+ {
+ return cb();
+ }
+ var peerInfo = {
+ devID: peerID,
+ displayName: xhdr.findtext('Source/LocName'),
+ maxMsgSize: common.int(xhdr.findtext('Meta/MaxMsgSize')),
+ maxObjSize: common.int(xhdr.findtext('Meta/MaxObjSize'))
+ };
+ session.adapter.addPeer(peerInfo, function(err, peer) {
+ if ( err )
+ return cb(err);
+ session.peer = peer;
+ return cb();
+ });
+ };
- pendingObj.pendingID = window.setTimeout(function () {
- pendingObj.setCancelFlag(false);
- operate.apply(this, argumentVector);
- }, _PENDING_TIME);
+ checkPeer(function(err) {
- pendingOperation = new PendingOperation(pendingObj);
+ session.info.cmdID = 0;
+ session.info.pendingMsgID = ( session.isServer
+ ? session.info.msgID
+ : session.info.lastMsgID );
+ cmd.sessionID = session.info.id;
+ cmd.msgID = session.info.msgID;
+ cmd.target = session.peer ? session.peer.devID || null : null;
+ cmd.targetName = session.peer ? session.peer.displayName || null : null;
+ cmd.auth = session.auth
+ ? session.auth.type
+ : session.peer
+ ? session.peer.auth
+ : null;
- return pendingOperation;
-}
+ if ( err )
+ return cb(err, [cmd]);
-function GeoEntry(addr, coord) {
- var _self;
- _self = {
- address : addr || null,
- coordinate : coord || null
- };
- return _self;
-}
+ if ( cmd.msgID == 1 )
+ {
+ // NOTE: normally, the "server" would not send this info. however, in
+ // the syncml-js world where it is much more peer-oriented
+ // instead of client/server, i send this as well... the
+ // idea being, if two "client" peers are communicating in
+ // the event of server unavailability, then they may need
+ // to know each-others limitations...
+ cmd.maxMsgSize = common.getMaxMemorySize(session.context);
+ cmd.maxObjSize = common.getMaxMemorySize(session.context);
+ ///cmd.maxMsgSize = 150000;
+ ///cmd.maxObjSize = 4000000;
+ }
+ cb(null, [cmd]);
+ });
+ },
-function SortMode() {
- var _self;
- _self = {
- attributeName : "",
- order : "ASC"
- };
- return _self;
-}
+ //-------------------------------------------------------------------------
+ negotiate: function(session, commands, cb) {
+ // // todo: determine why i decided to clone the commands...
+ // commands = _.clone(commands);
-function _transAddressStr(addr) {
- var str = "";
- if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
- str = str + addr.additionalInformation + ", ";
- if (addr.premises !== null && addr.premises !== undefined)
- str = str + addr.premises + ", ";
- if (addr.streetNumber !== null && addr.streetNumber !== undefined)
- str = str + addr.streetNumber + " ";
- if (addr.street !== null && addr.street !== undefined)
- str = str + addr.street + ", ";
- if (addr.city !== null && addr.city !== undefined)
- str = str + addr.city + ", ";
- if (addr.county !== null && addr.county !== undefined)
- str = str + addr.county + ", ";
- if (addr.region !== null && addr.region !== undefined)
- str = str + addr.region + ", ";
- if (addr.country !== null && addr.country !== undefined)
- str = str + addr.country + ", ";
- if (addr.postalCode !== null && addr.postalCode !== undefined)
- str = str + addr.postalCode;
+ if ( commands.length > 0 && _.last(commands).name == constant.CMD_FINAL )
+ return cb(null, commands);
- if (str.lastIndexOf(", ") === str.length - 2)
- str = str.slice(0, -2);
- return str;
-}
+ if ( commands.length > 0
+ && _.last(commands).name == constant.CMD_ALERT
+ && _.last(commands).data == constant.STATUS_NEXT_MESSAGE )
+ // todo: should i add a "final" here?...
+ // commands.push(state.makeCommand({name: constant.CMD_FINAL}));
+ return cb(null, commands);
-function _concatAddress(addr) {
- var str = "";
- if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
- str = str + addr.additionalInformation + " ";
- if (addr.premises !== null && addr.premises !== undefined)
- str = str + addr.premises + " ";
- if (addr.streetNumber !== null && addr.streetNumber !== undefined)
- str = str + addr.streetNumber + " ";
- if (addr.street !== null && addr.street !== undefined)
- str = str + addr.street + " ";
- if (addr.city !== null && addr.city !== undefined)
- str = str + addr.city + " ";
- if (addr.county !== null && addr.county !== undefined)
- str = str + addr.county + " ";
- if (addr.region !== null && addr.region !== undefined)
- str = str + addr.region + " ";
- if (addr.country !== null && addr.country !== undefined)
- str = str + addr.country + " ";
- if (addr.postalCode !== null && addr.postalCode !== undefined)
- str = str + addr.postalCode;
+ var createDevInfoCommands = function(commands, cb) {
+ // todo: this flag is crap. instead, the local devInfo should have
+ // a record of which sessionID lead to the recording, and
+ // base it on that. maybe timestamp too... (but it must be
+ // in the minutes, just in case...)
+ session.info.gotinfo = true;
+ if ( ! session.discover )
+ {
+ commands.push(state.makeCommand({
+ name : constant.CMD_PUT,
+ cmdID : session.nextCmdID(),
+ type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
+ source : './' + constant.URI_DEVINFO_1_2,
+ data : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
+ _.values(session.adapter._stores))
+ }));
+ }
+ commands.push(state.makeCommand({
+ name : constant.CMD_GET,
+ cmdID : session.nextCmdID(),
+ type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
+ target : './' + constant.URI_DEVINFO_1_2
+ }));
+ return cb(null, commands);
+ };
- return str;
-}
+ var createCommands = function(commands, cb) {
+ // request the remote device info if not currently available or
+ // in discover mode or explicitly re-exchanging it (paranoid mode)
+ var putget = false;
+ if ( !! session.discover )
+ {
+ return createDevInfoCommands(commands, cb);
+ }
+ if ( ! session.peer.devInfo )
+ {
+ var uaEvent = {session: session};
+ return session.ua.acceptDevInfoSwap(uaEvent, function(err) {
+ if ( err )
+ {
+ return cb(err);
+ }
+ return createDevInfoCommands(commands, cb);
+ });
+ }
+ if ( ! session.context.config.trustDevInfo && ! session.info.gotinfo )
+ {
+ return createDevInfoCommands(commands, cb);
+ }
+ // NOTE: in the current handling of "trustDevInfo", i am doing a
+ // potentially unnecessary extra request/response phase to
+ // confirm that the devInfo has not changed... i *could*
+ // issue the put/get as well as the alert, *assuming* that
+ // no devInfo is going to change...
+ return session.context.synchronizer.actions(session, commands, cb);
+ };
-function _findCoordsByString(address) {
- var array = [], reg, str, searchAddr, pieces, i;
- if (address.length === 0)
- return array;
+ return createCommands(commands, function(err, commands) {
+ if ( err )
+ return cb(err);
+ //Hack: Memotoo service need to send alert command at the beging
+ var args, tmp;
+ args = db.retrieveObject("syncml-alert-args");
+ tmp = {
+ name : constant.CMD_ALERT,
+ cmdID : session.nextCmdID(),
+ data : args.data,
+ source : args.source,
+ target : args.target,
+ maxObjSize : "4000000"
+ };
+ if (args.lastAnchor) {
+ tmp.lastAnchor = args.lastAnchor;
+ }
- pieces = address.split(",");
- searchAddr = "";
- for (i = 0; i < pieces.length; i++) {
- searchAddr = searchAddr + pieces[i];
- }
- reg = new RegExp(searchAddr, "i");
+ if (args.nextAnchor) {
+ tmp.nextAnchor = args.nextAnchor;
+ }
+ _firstflag = db.retrieveObject("syncml-first-flag");
+ if( !_firstflag) {
+ commands.push(state.makeCommand(tmp));
+ db.saveObject("syncml-first-flag", true);
+ }
+ commands.push(state.makeCommand({name: constant.CMD_FINAL}));
+ cb(null, commands);
+ });
+ },
- utils.forEach(_geoList, function (item) {
- str = _concatAddress(item.address);
- if (str.search(reg) !== -1)
- array.push(new GeocodeResult(item.coordinate.latitude, item.coordinate.longitude));
- });
+ //-------------------------------------------------------------------------
+ // NOTE: `produce` is equivalent to the `pysyncml.protocol.commands2tree`...
+ // Consumes state.Command commands and converts them to an ET protocol tree
+ produce: function(session, commands, cb) {
- return array;
-}
+ if ( commands.length <= 0 )
+ return cb('protocol.produce received empty commands');
-function _geocodeByString(address, successCB, errorCB, options) {
- var array;
- array = _findCoordsByString(address);
- successCB(array);
-}
+ var hdrcmd = commands[0];
+ commands = _.rest(commands, 1);
-function _findCoordsByAddress(addr) {
- var array = [], select = false, i;
- for (i = 0; i < _geoList.length; i++) {
- select = false;
- if (addr.country !== null && addr.country !== undefined) {
- if (addr.country === _geoList[i].address.country)
- select = true;
- else
- continue;
- }
+ if ( hdrcmd.name != constant.CMD_SYNCHDR )
+ return cb('unexpected first command "' + hdrcmd.name + '"');
- if (addr.region !== null && addr.region !== undefined) {
- if (addr.region === _geoList[i].address.region)
- select = true;
- else
- continue;
- }
+ if ( hdrcmd.version != constant.SYNCML_VERSION_1_2 )
+ return cb('unsupported SyncML version "' + hdrcmd.version + '"');
- if (addr.county !== null && addr.county !== undefined) {
- if (addr.county === _geoList[i].address.county)
- select = true;
- else
- continue;
+ var xsync = ET.Element(constant.NODE_SYNCML);
+ var xhdr = ET.SubElement(xsync, hdrcmd.name);
+ if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
+ {
+ ET.SubElement(xhdr, 'VerDTD').text = constant.SYNCML_DTD_VERSION_1_2;
+ ET.SubElement(xhdr, 'VerProto').text = hdrcmd.version;
}
- if (addr.city !== null && addr.city !== undefined) {
- if (addr.city === _geoList[i].address.city)
- select = true;
- else
- continue;
- }
+ ET.SubElement(xhdr, 'SessionID').text = hdrcmd.sessionID;
+ ET.SubElement(xhdr, 'MsgID').text = hdrcmd.msgID;
+ var xsrc = ET.SubElement(xhdr, 'Source');
+ ET.SubElement(xsrc, 'LocURI').text = hdrcmd.source;
+ if ( hdrcmd.sourceName )
+ ET.SubElement(xsrc, 'LocName').text = hdrcmd.sourceName;
+ var xtgt = ET.SubElement(xhdr, 'Target');
+ ET.SubElement(xtgt, 'LocURI').text = hdrcmd.target;
+ if ( hdrcmd.targetName )
+ ET.SubElement(xtgt, 'LocName').text = hdrcmd.targetName;
+ if ( hdrcmd.respUri )
+ ET.SubElement(xhdr, 'RespURI').text = hdrcmd.respUri;
- if (addr.street !== null && addr.street !== undefined) {
- if (addr.street === _geoList[i].address.street)
- select = true;
- else
- continue;
- }
+ if ( hdrcmd.auth && ! session.info.authAccepted )
+ {
+ // TODO: implement other auth schemes...
+ if ( hdrcmd.auth != constant.NAMESPACE_AUTH_BASIC )
+ return cb('auth method "' + hdrcmd.auth + '" not implemented');
- if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
- if (addr.streetNumber === _geoList[i].address.streetNumber)
- select = true;
- else
- continue;
- }
+ if ( hdrcmd.auth == constant.NAMESPACE_AUTH_BASIC )
+ {
+ var xcred = ET.SubElement(xhdr, 'Cred');
+ var xmeta = ET.SubElement(xcred, 'Meta');
+ ET.SubElement(xmeta, 'Format', {'xmlns': constant.NAMESPACE_METINF}).text = 'b64';
+ ET.SubElement(xmeta, 'Type', {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.auth;
+ ET.SubElement(xcred, 'Data').text = base64.encode(
+ ( session.auth ? session.auth.username : session.peer.username )
+ + ':' + ( session.auth ? session.auth.password : session.peer.password ) );
+ }
- if (addr.premises !== null && addr.premises !== undefined) {
- if (addr.premises === _geoList[i].address.premises)
- select = true;
- else
- continue;
}
-
- if (addr.additionalInformation !== null &&
- addr.additionalInformation !== undefined) {
- if (addr.additionalInformation === _geoList[i].address.additionalInformation)
- select = true;
- else
- continue;
+ if ( hdrcmd.maxMsgSize || hdrcmd.maxObjSize )
+ {
+ var xmeta = ET.SubElement(xhdr, 'Meta');
+ if ( hdrcmd.maxMsgSize )
+ ET.SubElement(xmeta, 'MaxMsgSize',
+ {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxMsgSize;
+ if ( hdrcmd.maxObjSize )
+ ET.SubElement(xmeta, 'MaxObjSize',
+ {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxObjSize;
}
- if (addr.postalCode !== null && addr.postalCode !== undefined) {
- if (addr.postalCode === _geoList[i].address.postalCode)
- select = true;
- else
- continue;
- }
+ var xbody = ET.SubElement(xsync, constant.NODE_SYNCBODY);
- if (select === true) {
- array.push(new GeocodeResult(_geoList[i].coordinate.latitude, _geoList[i].coordinate.longitude));
+ for ( var idx=0 ; idx<commands.length ; idx++ )
+ {
+ var cmd = commands[idx];
+ var xcmd = ET.SubElement(xbody, cmd.name);
+ if ( cmd.cmdID != undefined )
+ ET.SubElement(xcmd, 'CmdID').text = cmd.cmdID;
+ var func = this['_produce_cmd_' + cmd.name.toLowerCase()];
+ if ( ! func )
+ return cb(new common.InternalError('unexpected command "' + cmd.name + '"'));
+ try{
+ func.call(this, session, cmd, xcmd);
+ }catch(e){
+ return cb(new common.InternalError(
+ 'failed invoking protocol sub-production of "' + cmd.name + '": ' + e, e));
+ }
+ if ( cmd.name == constant.CMD_FINAL && idx + 1 != commands.length )
+ return cb('command "' + cmd.name + '" not at end of commands');
}
- }
-
- return array;
-}
-
-function _geocodeByAddress(address, successCB, errorCB, options) {
- var array;
- array = _findCoordsByAddress(address);
- successCB(array);
-}
-function _checkAddressType(address) {
- var str;
- if (typeof address === "string") {
- str = "string";
- } else if (typeof address === "object") {
- str = "StructuredAddress";
- } else {
- str = "typeMismatch";
- }
- return str;
-}
+ cb(null, xsync);
+ },
-function _checkCoordsType(coord) {
- var str;
- /* SimpleCoordinates is a subset of GeoCoordinates.
- SimpleCoordinates includes latitude, longitude as mandatory fields only.
- GeoCoordinates not only includes latitude, longitude as mandatory fields
- but also at least includes one more other optional fields */
- if (typeof coord !== "object") {
- str = "typeMismatch";
- } else if (typeof coord.latitude === "number" &&
- typeof coord.longitude === "number") {
- str = "simpleCoordinates";
- if (typeof coord.altitude === "number" ||
- typeof coord.accuracy === "number" ||
- typeof coord.altitudeAccuracy === "number" ||
- typeof coord.heading === "number" ||
- typeof coord.speed === "number") {
- str = "geoCoordinates";
+ //-------------------------------------------------------------------------
+ _produce_cmd_alert: function(session, cmd, xcmd) {
+ ET.SubElement(xcmd, 'Data').text = cmd.data;
+ var xitem = ET.SubElement(xcmd, 'Item');
+ ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.source;
+ ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.target;
+ if ( cmd.lastAnchor || cmd.nextAnchor || cmd.maxObjSize )
+ {
+ var xmeta = ET.SubElement(xitem, 'Meta');
+ var xanch = ET.SubElement(xmeta, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
+ if ( cmd.lastAnchor )
+ ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
+ if ( cmd.nextAnchor )
+ ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
+ if ( cmd.maxObjSize )
+ ET.SubElement(xmeta, 'MaxObjSize',
+ {'xmlns': constant.NAMESPACE_METINF}).text = cmd.maxObjSize;
}
- } else {
- str = "typeMismatch";
- }
-
- return str;
-}
+ },
-function _findReverseGeocode(coords, options) {
- var array = [], _isStructured = false, i;
- if (options !== null && options !== undefined) {
- if (options.resultType === "STRUCTURED") {
- _isStructured = true;
+ //-------------------------------------------------------------------------
+ _produce_cmd_status: function(session, cmd, xcmd) {
+ ET.SubElement(xcmd, 'MsgRef').text = '' + cmd.msgRef;
+ ET.SubElement(xcmd, 'CmdRef').text = '' + cmd.cmdRef;
+ ET.SubElement(xcmd, 'Cmd').text = cmd.statusOf;
+ if ( cmd.sourceRef )
+ ET.SubElement(xcmd, 'SourceRef').text = cmd.sourceRef;
+ if ( cmd.targetRef )
+ ET.SubElement(xcmd, 'TargetRef').text = cmd.targetRef;
+ ET.SubElement(xcmd, 'Data').text = cmd.statusCode;
+ var xitem = null;
+ var xdata = null;
+ if ( cmd.nextAnchor || cmd.lastAnchor )
+ {
+ xitem = ET.SubElement(xcmd, 'Item');
+ xdata = ET.SubElement(xitem, 'Data');
+ var xanch = ET.SubElement(xdata, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
+ if ( cmd.lastAnchor )
+ ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
+ if ( cmd.nextAnchor )
+ ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
}
- }
- for (i = 0; i < _geoList.length; i++) {
- if (_geoList[i].coordinate.latitude === coords.latitude &&
- _geoList[i].coordinate.longitude === coords.longitude) {
- if (coords.altitude) {
- if (_geoList[i].coordinate.altitude !== coords.altitude)
- continue;
- }
- if (coords.accuracy) {
- if (_geoList[i].coordinate.accuracy !== coords.accuracy)
- continue;
- }
- if (coords.altitudeAccuracy) {
- if (_geoList[i].coordinate.altitudeAccuracy !== coords.altitudeAccuracy)
- continue;
- }
- if (coords.heading) {
- if (_geoList[i].coordinate.heading !== coords.heading)
- continue;
+ // NOTE: this is NOT standard SyncML...
+ if ( cmd.errorCode || cmd.errorMsg )
+ {
+ xitem = xitem || ET.SubElement(xcmd, 'Item');
+ xdata = xdata || ET.SubElement(xitem, 'Data');
+ var xerr = ET.SubElement(xitem, 'Error');
+ xdata.text = cmd.errorMsg;
+ if ( cmd.errorCode )
+ ET.SubElement(xerr, 'Code').text = cmd.errorCode;
+ if ( cmd.errorMsg )
+ ET.SubElement(xerr, 'Message').text = cmd.errorMsg;
+ if ( session.context.config.exposeErrorTrace && cmd.errorTrace )
+ ET.SubElement(xerr, 'Trace').text = cmd.errorTrace;
+ }
+ },
+
+ //-------------------------------------------------------------------------
+ _produce_cmd_get: function(session, cmd, xcmd) {
+ ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
+ {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
+ if ( cmd.source || cmd.target || cmd.data )
+ {
+ var xitem = ET.SubElement(xcmd, 'Item');
+ if ( cmd.source )
+ {
+ var xsrc = ET.SubElement(xitem, 'Source');
+ ET.SubElement(xsrc, 'LocURI').text = cmd.source;
+ ET.SubElement(xsrc, 'LocName').text = cmd.source;
}
- if (coords.speed) {
- if (_geoList[i].coordinate.speed !== coords.speed)
- continue;
+ if ( cmd.target )
+ {
+ var xtgt = ET.SubElement(xitem, 'Target');
+ ET.SubElement(xtgt, 'LocURI').text = cmd.target;
+ ET.SubElement(xtgt, 'LocName').text = cmd.target;
}
-
- if (_isStructured === true) {
- array.push(new lbs.StructuredAddress(_geoList[i].address));
- } else {
- array.push(_transAddressStr(_geoList[i].address));
+ if ( cmd.data )
+ {
+ if ( _.isString(cmd.data) )
+ ET.SubElement(xitem, 'Data').text = cmd.data;
+ else
+ // assuming here that it is an ElementTree object...
+ ET.SubElement(xitem, 'Data').append(cmd.data);
}
}
- }
- return array;
-}
-
-function _reverseGeocodeByGeo(coordinates, successCB, errorCB, options) {
- var array, coord;
- coord = new lbs.GeoCoordinates(coordinates);
- array = _findReverseGeocode(coord, options);
- return successCB(array);
-}
+ },
-function _reverseGeocodeBySimple(coordinates, successCB, errorCB, options) {
- var array, coord;
- coord = new lbs.GeoCoordinates({
- latitude : coordinates.latitude,
- longitude : coordinates.longitude
- });
- array = _findReverseGeocode(coord, options);
- return successCB(array);
-}
+ //-------------------------------------------------------------------------
+ _produce_cmd_put: function(session, cmd, xcmd) {
+ return this._produce_cmd_get(session, cmd, xcmd);
+ },
-module.exports = function (prop) {
- var _self = new lbs.LocationServiceProvider(prop);
- _geoList_init();
+ //-------------------------------------------------------------------------
+ _produce_cmd_results: function(session, cmd, xcmd) {
+ ET.SubElement(xcmd, 'MsgRef').text = cmd.msgRef;
+ ET.SubElement(xcmd, 'CmdRef').text = cmd.cmdRef;
+ ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
+ {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
+ var xitem = ET.SubElement(xcmd, 'Item');
+ var xsrc = ET.SubElement(xitem, 'Source');
+ ET.SubElement(xsrc, 'LocURI').text = cmd.source;
+ ET.SubElement(xsrc, 'LocName').text = cmd.source;
+ if ( cmd.data )
+ {
+ if ( _.isString(cmd.data) )
+ ET.SubElement(xitem, 'Data').text = cmd.data;
+ else
+ // assuming here that it is an ElementTree object...
+ ET.SubElement(xitem, 'Data').append(cmd.data);
+ }
+ },
- _self.geocode = function (address, successCB, errorCB, options) {
- function _geocode() {
- var ret;
+ //-------------------------------------------------------------------------
+ _produce_cmd_sync: function(session, cmd, xcmd) {
+ ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
+ ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
+ if ( cmd.noc != undefined )
+ ET.SubElement(xcmd, 'NumberOfChanges').text = '' + cmd.noc;
+ if ( ! cmd.data )
+ return;
+ for ( var idx=0 ; idx<cmd.data.length ; idx++ )
+ {
+ var scmd = cmd.data[idx];
+ var xscmd = ET.SubElement(xcmd, scmd.name);
+ if ( scmd.cmdID )
+ ET.SubElement(xscmd, 'CmdID').text = scmd.cmdID;
+ if ( scmd.type
+ || ( scmd.format && scmd.format != constant.FORMAT_AUTO ) )
+ {
+ var xsmeta = ET.SubElement(xscmd, 'Meta')
+ // todo: implement auto encoding determination...
+ // (the current implementation just lets XML encoding
+ // do it, which is for most things good enough, but
+ // not so good for sequences that need a large amount
+ // of escaping such as binary data...)
+ if ( scmd.format && scmd.format != constant.FORMAT_AUTO )
+ ET.SubElement(xsmeta, 'Format',
+ {'xmlns': constant.NAMESPACE_METINF}).text = scmd.format;
+ if ( scmd.type )
+ ET.SubElement(xsmeta, 'Type',
+ {'xmlns': constant.NAMESPACE_METINF}).text = scmd.type;
+ }
+ var xsitem = ET.SubElement(xscmd, 'Item');
+ if ( scmd.source )
+ ET.SubElement(ET.SubElement(xsitem, 'Source'),
+ 'LocURI').text = scmd.source;
+ if ( scmd.sourceParent )
+ ET.SubElement(ET.SubElement(xsitem, 'SourceParent'),
+ 'LocURI').text = scmd.sourceParent;
+ if ( scmd.target )
+ ET.SubElement(ET.SubElement(xsitem, 'Target'),
+ 'LocURI').text = scmd.target;
+ if ( scmd.targetParent )
+ ET.SubElement(ET.SubElement(xsitem, 'TargetParent'),
+ 'LocURI').text = scmd.targetParent;
+ if ( scmd.data )
+ {
+ if ( _.isString(scmd.data) )
+ ET.SubElement(xsitem, 'Data').text = scmd.data;
+ else
+ // assuming here that it is an ElementTree object...
+ ET.SubElement(xsitem, 'Data')._node.appendChild(scmd.data);
+ }
+ }
+ },
- ret = _pendingOperate(function () {
- /* address: its type is AbstractAddress.
- It could be StructuredAddress or String */
- if (_checkAddressType(address) === "string") {
- _geocodeByString(address, successCB, errorCB, options);
- } else if (_checkAddressType(address) === "StructuredAddress") {
- _geocodeByAddress(address, successCB, errorCB, options);
- } else {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- });
+ //-------------------------------------------------------------------------
+ _produce_cmd_map: function(session, cmd, xcmd) {
+ ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
+ ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
+ if ( cmd.sourceItem || cmd.targetItem )
+ {
+ var xitem = ET.SubElement(xcmd, constant.CMD_MAPITEM);
+ if ( cmd.sourceItem )
+ ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.sourceItem;
+ if ( cmd.targetItem )
+ ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.targetItem;
}
+ },
- tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
- };
+ //-------------------------------------------------------------------------
+ _produce_cmd_final: function(session, cmd, xcmd) {
+ return;
+ },
- _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
- function _reverseGeocode() {
- var ret;
+ //-------------------------------------------------------------------------
+ // NOTE: `consume` is equivalent to the `pysyncml.protocol.tree2commands`...
+ // consume: function...
+ consume: function(session, lastcmds, xsync, cb) {
- ret = _pendingOperate(function () {
- /* coordinates: Its type is AbstractCoordinates.
- It could be SimpleCoordinates or GeoCoordinates */
- if (_checkCoordsType(coordinates) === "simpleCoordinates") {
- _reverseGeocodeBySimple(coordinates, successCB, errorCB, options);
- } else if (_checkCoordsType(coordinates) === "geoCoordinates") {
- _reverseGeocodeByGeo(coordinates, successCB, errorCB, options);
- } else {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- });
+ // do some preliminary sanity checks...
+ // todo: do i really want to be returning an error instead of
+ // generating an error response?...
+
+ if ( xsync.tag != constant.NODE_SYNCML
+ || xsync.getchildren().length != 2
+ || xsync.getchildren()[0].tag != constant.CMD_SYNCHDR
+ || xsync.getchildren()[1].tag != constant.NODE_SYNCBODY
+ )
+ {
+ return cb('unexpected SyncML document structure');
}
- tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
- };
+ var version = xsync.getchildren()[0].findtext('VerProto');
+ if ( version != constant.SYNCML_VERSION_1_2 )
+ return cb('unsupported SyncML version "' + version + '"');
- return _self;
-};
+ var verdtd = xsync.getchildren()[0].findtext('VerDTD');
+ if ( verdtd != constant.SYNCML_DTD_VERSION_1_2 )
+ return cb('unsupported SyncML DTD version "' + verdtd + '"');
+ var self = this;
-});
-define('ripple/platform/tizen/2.0/geoBackend_nominatim', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ self.initialize(session, xsync, function(err, cmds) {
+ var hdrcmd = ( cmds && cmds.length > 0 ) ? cmds[0] : null;
+ var makeErrorCommands = function(err, cb) {
-var lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult');
+ if ( err.exception )
-function _concatAddrString(addr) {
- var ret = "", i, pieces;
- if (typeof addr === "string") {
- pieces = addr.split(" ");
- for (i = 0; i < pieces.length; i++) {
- ret = ret + pieces[i] + "+";
- }
- } else if (typeof addr === "object") {
- if (addr.premises !== null && addr.premises !== undefined) {
- ret = ret + addr.premises + "+";
- }
- if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
- ret = ret + addr.streetNumber + "+";
- }
- if (addr.street !== null && addr.street !== undefined) {
- ret = ret + addr.street + "+";
- }
- if (addr.city !== null && addr.city !== undefined) {
- ret = ret + addr.city + "+";
- }
- if (addr.county !== null && addr.county !== undefined) {
- ret = ret + addr.county + "+";
- }
- if (addr.region !== null && addr.region !== undefined) {
- ret = ret + addr.region + "+";
- }
- if (addr.postalCode !== null && addr.postalCode !== undefined) {
- ret = ret + addr.postalCode + "+";
- }
- if (addr.country !== null && addr.country !== undefined) {
- ret = ret + addr.country + "+";
- }
- } else {
- return undefined;
- }
- ret = ret.slice(0, -1);
- return ret;
-}
+ if ( ! session.isServer )
+ return cb(err);
-module.exports = function (prop) {
- var _self = new lbs.LocationServiceProvider(prop);
+ var errcmd = state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : '1',
+ msgRef : session.info.pendingMsgID,
+ cmdRef : 0,
+ sourceRef : xsync.getchildren()[0].findtext('Source/LocURI'),
+ targetRef : xsync.getchildren()[0].findtext('Target/LocURI'),
+ statusOf : constant.CMD_SYNCHDR,
+ statusCode : constant.STATUS_COMMAND_FAILED,
+ errorMsg : 'an error occurred during processing'
+ });
- _self.geocode = function (address, successCB, errorCB, options) {
- function _geocode() {
- var i, searchStr, coordinates = [], result;
+ // TODO: make this configurable as to whether or not any error
+ // is sent back to the peer as a SyncML "standardized" error
+ // status...
- searchStr = _concatAddrString(address);
- if (searchStr === undefined) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- searchStr = "http://nominatim.openstreetmap.org/search?q=" + searchStr + "&format=json&polygon=1&addressdetails=1";
+ // TODO: make sure this is doing what is expected/intended...
+ if ( err.code || err.name )
+ errcmd.errorCode = 'syncml-js.' + ( err.code || err.name );
+ errcmd.errorMsg = err.message || common.j(err) || '' + err;
- /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
- $.getJSON(searchStr, function (data) {
- for (i = 0; i < data.length; i++) {
- result = new GeocodeResult(parseFloat(data[i].lat), parseFloat(data[i].lon));
- coordinates.push(result);
- }
- successCB(coordinates);
- }).error(function () {
- if (errorCB) {
- setTimeout(function () {
- errorCB(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- });
- }
+ return cb(null, [hdrcmd, errcmd,
+ state.makeCommand({name: constant.CMD_FINAL})]);
+ };
- tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
- };
+ if ( err )
+ return makeErrorCommands(err, cb);
- _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
- function _reverseGeocode() {
- var searchStr = "";
- if (typeof coordinates !== "object" ||
- typeof coordinates.latitude !== "number" ||
- typeof coordinates.longitude !== "number") {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ try {
+ self._consume(session, lastcmds, xsync, cmds, function(err, commands) {
+ if ( err )
+ return makeErrorCommands(err, cb);
+ return cb(null, commands);
+ });
+ } catch ( exc ) {
+ return makeErrorCommands(exc, cb);
}
- searchStr = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" +
- coordinates.latitude + "&lon=" + coordinates.longitude + "&zoom=18&addressdetails=1";
- /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
- $.getJSON(searchStr, function (data) {
- var addr;
+ });
+ },
- if (options && options.resultType === "STRUCTURED") {
- addr = new lbs.StructuredAddress({
- country : data.address.country,
- region : data.address.state,
- county : data.address.county,
- city : data.address.city,
- street : data.address.road,
- streetNumber : data.address.streetNumber,
- postalCode : data.address.postcode
- });
- } else {
- addr = data.display_name;
- }
- successCB([addr]);
- }).error(function () {
- if (errorCB) {
- setTimeout(function () {
- errorCB(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- });
- }
+ //-------------------------------------------------------------------------
+ _consume: function(session, lastcmds, xsync, commands, cb) {
- tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
- };
+ var self = this;
+ var hdrcmd = commands[0];
+ var statusCode = constant.STATUS_OK;
- return _self;
-};
+ // analyze the SyncHdr
+ var children = xsync.getchildren()[0].getchildren();
+ for ( var idx=0 ; idx<children.length ; idx++ )
+ {
+ var child = children[idx];
-});
-define('ripple/platform/tizen/2.0/geocoder', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ if ( child.tag == 'VerDTD' )
+ {
+ if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
+ {
+ if ( child.text != constant.SYNCML_DTD_VERSION_1_2 )
+ return cb(new common.ProtocolError('bad VerDTD "' + child.text + '"'));
+ }
+ else
+ return cb(new common.FeatureNotSupported(
+ 'unsupported internal SyncML version "' + hdrcmd.version + '"'));
+ continue;
+ }
-var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- ProviderLocal = require('ripple/platform/tizen/2.0/geoBackend_local'),
- ProviderNominatim = require('ripple/platform/tizen/2.0/geoBackend_nominatim'), // Nominatim geocode service
- _getProviders,
- _providers,
- _self;
+ if ( child.tag == 'VerProto' )
+ // this was checked earlier...
+ continue;
-function _initialize() {
- _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})
- /* ,new ProviderLocal({name : "Tizen Database", connectivity : "OFFLINE"}) */];
-}
+ if ( child.tag == 'SessionID' )
+ {
+ if ( child.text != hdrcmd.sessionID )
+ return cb(new common.ProtocolError(
+ 'session ID mismatch: "' + child.text + '" != "' + hdrcmd.sessionID + '"'));
+ continue;
+ }
-_initialize();
+ if ( child.tag == 'MsgID' )
+ {
+ var chkmsg = ( session.isServer ? hdrcmd.msgID : lastcmds[0].msgID );
+ if ( child.text != chkmsg )
+ return cb(new common.ProtocolError(
+ 'message ID mismatch: "' + child.text + '" != "' + chkmsg + '"'));
+ continue;
+ }
-_self = {
- getDefaultProvider : function () {
- return _providers[0];
- },
- getProviders : function () {
- return _providers;
- }
-};
+ if ( child.tag == 'Target' )
+ {
+ var uri = child.findtext('LocURI');
-module.exports = _self;
+ // TODO... server-side...
-});
-define('ripple/platform/tizen/2.0/lbs_utils', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ if ( uri != hdrcmd.source )
+ return cb(new common.ProtocolError(
+ 'incoming target mismatch: "' + uri + '" != "' + hdrcmd.source + '"'));
+ continue;
+ }
-var tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- _self;
+ if ( child.tag == 'Source' )
+ {
+ var uri = child.findtext('LocURI');
+ if ( uri != hdrcmd.target && uri != lastcmds[0].target )
+ return cb(new common.ProtocolError(
+ 'incoming source mismatch: "' + uri + '" != "' + hdrcmd.target + '"'));
+ continue;
+ }
-function CoordinateProperties(prop) {
- var _self;
- _self = {
- latitude : prop.latitude || 0,
- longitude : prop.longitude || 0,
- altitude : prop.altitude || 0,
- accuracy : prop.accuracy || 0,
- altitudeAccuracy : prop.altitudeAccuracy || 0,
- heading : prop.heading || 0,
- speed : prop.speed || 0
- };
- return _self;
-}
+ if ( child.tag == 'RespURI' )
+ {
+ // hdrcmd.target = child.text
+ // session.info.respUri = child.text
+ if ( ! session.isServer )
+ session.info.respUri = child.text;
+ continue;
+ }
-function _checkAddressProperties(p, dst) {
- if (p.country !== null && p.country !== undefined)
- dst.country = String(p.country);
- if (p.region !== null && p.region !== undefined)
- dst.region = String(p.region);
- if (p.county !== null && p.county !== undefined)
- dst.county = String(p.county);
- if (p.city !== null && p.city !== undefined)
- dst.city = String(p.city);
- if (p.street !== null && p.street !== undefined)
- dst.street = String(p.street);
- if (p.streetNumber !== null && p.streetNumber !== undefined)
- dst.streetNumber = String(p.streetNumber);
- if (p.premises !== null && p.premises !== undefined)
- dst.premises = String(p.premises);
- if (p.additionalInformation !== null &&
- p.additionalInformation !== undefined)
- dst.additionalInformation = String(p.additionalInformation);
- if (p.postalCode !== null && p.postalCode !== undefined)
- dst.postalCode = String(p.postalCode);
-}
+ if ( child.tag == 'Cred' )
+ {
+ // the responsibility is on the calling framework to ensure this is
+ // checked long before we get here... ie. Adapter.authorize(...)
+ // or via the Adapter.handleRequest() `authorize` parameter...
+ statusCode = constant.STATUS_AUTHENTICATION_ACCEPTED;
+ continue;
+ }
-function AddressProperties(prop) {
- var _self;
- _self = {
- country : null,
- region : null,
- county : null,
- city : null,
- street : null,
- streetNumber : null,
- premises : null,
- additionalInformation : null,
- postalCode : null
- };
- if (prop) {
- if (_checkAddressProperties(prop, _self) === false)
- return undefined;
- }
- return _self;
-}
+ if ( child.tag == 'Meta' )
+ {
+ // this should already have been consumed during the protocol.initialize() call
+ continue;
+ }
-_self = {
- LocationServiceProvider : function (prop) {
- var _self;
- _self = {
- name : "",
- metaData : Object,
- attribution : "",
- supportedOptions : [],
- setOptions : function (options, successCB, errorCB) {},
- connectivity : "" // "ONLINE" "OFFLINE" "HYBRID"
+ return cb(new common.ProtocolError('unexpected header node "' + child.tag + '"'));
};
- if (prop.name !== null && prop.name !== undefined)
- _self.name = String(prop.name);
- if (prop.metaData !== null && prop.metaData !== undefined)
- _self.metaData = prop.metaData;
+ commands.push(state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : session.info.pendingMsgID,
+ cmdRef : 0,
+ sourceRef : xsync.getchildren()[0].findtext('Source/LocURI'),
+ targetRef : xsync.getchildren()[0].findtext('Target/LocURI'),
+ statusOf : constant.CMD_SYNCHDR,
+ statusCode : statusCode
+ }));
- if (prop.attribution !== null && prop.attribution !== undefined)
- _self.attribution = String(prop.attribution);
+ // and now evaluate the SyncBody
- if (prop.supportedOptions !== null && prop.supportedOptions !== undefined)
- _self.supportedOptions = [prop.supportedOptions];
+ var chkcmds = _.filter(lastcmds, function(e) {
+ return e.name != constant.CMD_STATUS && e.name != constant.CMD_FINAL;
+ });
- if (prop.setOptions !== null && prop.setOptions !== undefined)
- _self.setOptions = prop.setOptions;
+ // for each "sync" command, search for sub-commands
+ // todo: should this be generalized to search for any sub-commands?...
+ _.each(chkcmds, function(e) {
+ if ( e.name != constant.CMD_SYNC || ! e.data || e.data.length <= 0 )
+ return;
+ _.each(e.data, function(sub) { chkcmds.push(sub); });
+ });
- if (prop.connectivity !== null && prop.connectivity !== undefined)
- _self.connectivity = String(prop.connectivity);
+ var children = xsync.getchildren()[1].getchildren();
- return _self;
- },
+ // first, check all the 'Status' commands
- GeoCoordinates : function (prop) {
- var _self = new CoordinateProperties(prop);
- if (tizen1_utils.isEmptyObject(_self)) {
- return undefined;
- }
+ var consumeStatus = function(cb) {
- return _self;
- },
+ common.cascade(children, function(child, cb) {
- StructuredAddress : function (prop) {
- var _self;
- _self = new AddressProperties(prop);
- if (tizen1_utils.isEmptyObject(_self)) {
- return undefined;
- }
+ if ( child.tag != constant.CMD_STATUS )
+ return cb();
- return _self;
- }
-};
+ cname = child.findtext('Cmd');
-module.exports = _self;
+ var blen = chkcmds.length;
+ var chkcmd = null;
+ var chkerr = null;
-});
-define('ripple/platform/tizen/2.0/map', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation
- *
- * 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.
- */
+ chkcmds = _.filter(chkcmds, function(cmd) {
+ if ( chkerr )
+ return;
+ if ( cmd.cmdID != child.findtext('CmdRef')
+ || cmd.name != cname
+ || lastcmds[0].msgID != child.findtext('MsgRef') )
+ return true;
+ if ( chkcmd )
+ chkerr = new Error('unexpected error: multiple check commands match status command');
+ chkcmd = cmd;
+ return false;
+ });
-var lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
- mapProviders = [],
- MapStyle,
- MapProvider,
- _self;
+ if ( chkerr )
+ return cb(chkerr);
-function _initialize() {
- // EPSG:3857 is a Spherical Mercator projection coordinate system popularized by web services such as Google and later OpenStreetMap
- // mapStyles are from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
- var projection = "EPSG:3857",
- mapStyle1 = new MapStyle("Mapnik", "http://b.tile.openstreetmap.org/${z}/${x}/${y}.png"),
- mapStyle2 = new MapStyle("Cycle", "http://b.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png");
+ if ( chkcmds.length >= blen )
+ return cb(new common.ProtocolError(
+ 'unexpected status node "s' + session.info.id + '.m' + child.findtext('MsgRef')
+ + '.c' + child.findtext('CmdRef') + ' cmd=' + cname + '"'));
- mapProviders = [new MapProvider({name: "OpenStreetMap", connectivity: "ONLINE"}, projection, [mapStyle1, mapStyle2])];
-}
+ // TODO: check for unknown elements (and complain?)...
-_self = {
- getDefaultProvider: function () {
- return mapProviders[0];
- },
- getProviders: function () {
- return mapProviders;
- }
-};
+ var code = common.int(child.findtext('Data'));
-MapStyle = function (name, url) {
- return {
- name: name,
- url: url
- };
-};
+ if ( code == constant.STATUS_MISSING_CREDENTIALS )
+ {
+ var authtype = child.findtext('Chal/Meta/Type');
+ var attrs = {auth: {type: authtype}};
+ return cb(badStatus(child, common.CredentialsRequired, attrs));
+ }
-MapProvider = function (prop, projection, mapStyles) {
- var mapProvider = new lbs.LocationServiceProvider(prop);
+ if ( code == constant.STATUS_INVALID_CREDENTIALS )
+ {
+ // TODO: get the auth type... from where??...
+ var authtype = child.findtext('Chal/Meta/Type');
+ var attrs = {auth: {type: authtype}};
+ return cb(badStatus(child, common.InvalidCredentials, attrs));
+ }
- mapProvider.__defineGetter__("projection", function () {
- return projection;
- });
+ var targetRef = child.findtext('TargetRef');
+ if ( targetRef )
+ {
+ // note: doing a normUri on chkcmd.target because it could be "./devinf12"...
+ if ( session.peer.normUri(targetRef) != session.peer.normUri(chkcmd.target) )
+ return cb(new common.ProtocolError('unexpected target-ref "'
+ + targetRef + '" != "' + chkcmd.target
+ + '" for command "' + cname + '"'));
+ }
- mapProvider.__defineGetter__("mapStyles", function () {
- return mapStyles;
- });
+ var sourceRef = child.findtext('SourceRef');
+ if ( sourceRef )
+ {
+ // note: doing a normUri on chkcmd.source because it could be "./devinf12"...
+ if ( cname == constant.CMD_SYNCHDR )
+ {
+ // this is a little odd, but syncevolution strips the sessionid path
+ // parameter off for some reason, so compensating here...
+ if ( _.indexOf([session.adapter.normUri(chkcmd.source),
+ session.info.effectiveID,
+ session.info.returnUrl],
+ session.adapter.normUri(sourceRef)) < 0
+ && session.adapter.normUri(chkcmd.source).indexOf(session.adapter.normUri(sourceRef)) != 0 )
+ return cb(new common.ProtocolError('unexpected source-ref "'
+ + sourceRef + '" != "' + chkcmd.source
+ + '" for command "' + cname + '"'));
+ }
+ else
+ {
+ if ( session.adapter.normUri(sourceRef) != session.adapter.normUri(chkcmd.source) )
+ return cb(new common.ProtocolError('unexpected source-ref "'
+ + sourceRef + '" != "' + chkcmd.source
+ + '" for command "' + cname + '"'));
+ }
+ }
- return mapProvider;
-};
+ // todo: any other common elements?...
-_initialize();
+ switch ( cname )
+ {
-module.exports = _self;
+ case constant.CMD_SYNCHDR:
+ {
+ if ( code != constant.STATUS_OK && code != constant.STATUS_AUTHENTICATION_ACCEPTED )
+ return cb(badStatus(child));
+ if ( code == constant.STATUS_AUTHENTICATION_ACCEPTED )
+ {
+ // TODO: there is currently nothing that can "reset" the
+ // authAccepted flag... there should be a trap such
+ // that if an auth fails, then authAccepted gets set
+ // to false.
+ session.info.authAccepted = true;
+ }
+ return cb();
+ }
-});
-define('ripple/platform/tizen/2.0/messaging', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ case constant.CMD_ALERT:
+ {
+ if ( code == constant.STATUS_OK )
+ // TODO: do something with the Item/Data/Anchor/Next?...
+ return cb();
+ if ( code == constant.STATUS_REFRESH_REQUIRED && ! session.isServer )
+ {
+ // TODO: support the ability for the UA to control which kind of
+ // refresh to do (slow-sync, client-refresh, server-refresh)
+ return cb();
+ }
+ return cb(badStatus(child));
+ }
-var _self,
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- MessagingService = require('ripple/platform/tizen/2.0/MessagingService'),
- t = require('ripple/platform/tizen/2.0/typedef'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- TIZEN_MESSAGING_SMS = "messaging.sms",
- TIZEN_MESSAGING_MMS = "messaging.mms",
- TIZEN_MESSAGING_EMAIL = "messaging.email",
- _security_check = {read: false, write: false},
- _sms_service = null,
- _mms_service = null,
- _email_service = null;
+ case constant.CMD_GET:
+ {
+ if ( code != constant.STATUS_OK )
+ return cb(badStatus(child));
+ return cb();
+ }
-_self = function () {
- this.getMessageServices = function (messageServiceType, onSuccess, onError) {
- var service;
+ case constant.CMD_PUT:
+ {
+ if ( code != constant.STATUS_OK )
+ return cb(badStatus(child));
+ return cb();
+ }
- if (!(new TypeCoerce(t.MessageServiceTag)).match(messageServiceType)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (!(new TypeCoerce(t.MessageServiceArraySuccessCallback)).match(onSuccess)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ case constant.CMD_RESULTS:
+ {
+ if ( code != constant.STATUS_OK )
+ return cb(badStatus(child));
+ return cb();
+ }
- switch (messageServiceType) {
- case "messaging.sms":
- if (_sms_service === null) {
- _sms_service = [new MessagingService("Tizen SMS Service 1", TIZEN_MESSAGING_SMS, _security_check), new MessagingService("Tizen SMS Service 2", TIZEN_MESSAGING_SMS, _security_check)];
- }
- service = _sms_service;
- break;
- case "messaging.mms":
- if (_mms_service === null) {
- _mms_service = [new MessagingService("Tizen MMS Service", TIZEN_MESSAGING_MMS, _security_check)];
- }
- service = _mms_service;
- break;
- case "messaging.email":
- if (_email_service === null) {
- _email_service = [new MessagingService("Tizen Email Service", TIZEN_MESSAGING_EMAIL, _security_check)];
- }
- service = _email_service;
- break;
- default:
- throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
- }
- setTimeout(function () {
- onSuccess(service);
- }, 1);
- };
- this.handleSubFeatures = function (subFeatures) {
- if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.read')) {
- _security_check.read = true;
- }
- if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.write')) {
- _security_check.write = true;
- }
- };
-};
+ case constant.CMD_SYNC:
+ {
+ // todo: should this be moved into the synchronizer as a "settle" event?...
+ var ds = session.info.dsstates[session.adapter.normUri(chkcmd.source)]
+ if ( code != constant.STATUS_OK )
+ {
+ // check for server-side errors...
+ if ( code >= 500 && code < 600 && child.findtext('Item/Data') )
+ {
+ ds.action = 'error';
+ ds.error = getError(child);
+ ds.stats.peerErr += 1;
+ return cb();
+ }
+ return cb(badStatus(child));
+ }
+ if ( ds.action == 'send' )
+ {
+ if ( session.isServer )
+ {
+ ds.action = 'save';
+ return cb();
+ }
+ ds.action = common.oneWayOut(session, ds.mode) ? 'done' : 'recv';
+ return cb();
+ }
+ return cb(new common.ProtocolError('unexpected sync state for action=' + ds.action));
+ }
-module.exports = _self;
+ case constant.CMD_ADD:
+ case constant.CMD_REPLACE:
+ case constant.CMD_DELETE:
+ {
+ var scmd = state.makeCommand({
+ name : cname,
+ msgID : hdrcmd.msgID,
+ cmdID : child.findtext('CmdID'),
+ sourceRef : sourceRef,
+ targetRef : targetRef,
+ data : code
+ });
-});
-define('ripple/platform/tizen/2.0/msg_utils', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ session.context.synchronizer.settle(
+ session, scmd, chkcmd, child,
+ function(err, cmds) {
+ if ( err )
+ return cb(err);
+ _.each(cmds, function(cmd) { commands.push(cmd); });
+ return cb();
+ });
+ return;
+ }
+
+ case constant.CMD_MAP:
+ {
+ if ( session.isServer )
+ return cb(new common.ProtocolError(
+ 'unexpected server-side status for command "' + cname + '"'));
+ if ( code != constant.STATUS_OK )
+ return cb(badStatus(child));
+ return cb();
+ }
+ default:
+ {
+ return cb(new common.ProtocolError('unexpected status for command "' + cname + '"'));
+ }
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
- _TIZEN_MESSAGE_DB_KEY = "tizen_db_messages",
- MessageElement = function (_type, _id) {
- return {
- type: _type,
- id: _id,
- msg: {},
- conv: {}
- };
- },
+ }
- _conversationCount = function (msg, cid, rst) {
- var old_time = new Date(0), t;
+ }, cb);
- utils.forEach(msg.msg, function (o) {
- if (o.priv.conversationId === cid &&
- o.priv.messageStatus !== "DRAFT") {
- rst.cnt += 1;
- t = new Date(o.priv.timestamp);
- if (t > old_time) {
- rst.lastid = o.priv.id;
- old_time = t;
- }
- if (o.isRead === false) {
- rst.unread++;
- }
- }
- });
- },
+ };
- _updateConversation = function (msg, cid) {
- var privConv = {}, lastm, rst = {};
+ // second, check all the non-'Status' commands
- rst.cnt = 0;
- rst.unread = 0;
- rst.lastid = "";
- _conversationCount(msg, cid, rst);
- if (rst.cnt === 0) {
- if (msg.conv[cid] !== undefined) {
- delete msg.conv[cid];
- }
- return;
- }
- lastm = msg.msg[rst.lastid];
+ var consumeCommands = function(cb) {
- privConv.id = cid;
- privConv.type = msg.type;
- privConv.timestamp = new Date(lastm.priv.timestamp);
- privConv.messageCount = rst.cnt;
- privConv.unreadMessages = rst.unread;
- privConv.preview = lastm.body.plainBody;
- privConv.subject = lastm.subject;
- privConv.isRead = lastm.isRead;
- privConv.from = lastm.priv.from;
- privConv.to = lastm.to.slice(0);
- privConv.cc = lastm.cc.slice(0);
- privConv.bcc = lastm.bcc.slice(0);
- privConv.lastMessageId = rst.lastid;
- msg.conv[cid] = privConv;
- };
+ var gotFinal = false;
-module.exports = {
- conversationCount: _conversationCount,
- setMsg: function (m, newm) {
- if ((m.to === null) || (m.to === undefined)) {
- newm.to = [];
- } else {
- if (tizen1_utils.isValidArray(m.to)) {
- newm.to = m.to.slice(0);
- } else {
- return false;
- }
- }
+ common.cascade(children, function(child, cb) {
- if ((m.cc === null) || (m.cc === undefined)) {
- newm.cc = [];
- } else {
- if (tizen1_utils.isValidArray(m.cc)) {
- newm.cc = m.cc.slice(0);
- } else {
- return false;
- }
- }
- if ((m.bcc === null) || (m.bcc === undefined)) {
- newm.bcc = [];
- } else {
- if (tizen1_utils.isValidArray(m.bcc)) {
- newm.bcc = m.bcc.slice(0);
- } else {
- return false;
- }
- }
+ if ( child.tag == constant.CMD_STATUS )
+ return cb();
- if ((m.body === null) || (m.body === undefined)) {
- if (m.htmlBody === null || m.htmlBody === undefined) {
- m.htmlBody = "";
- }
- if (m.plainBody === null || m.plainBody === undefined) {
- m.plainBody = "";
- }
- if (typeof m.plainBody !== 'string' || typeof m.htmlBody !== 'string') {
- return false;
- }
- m.body = new MessageBody(null, true, m.plainBody, m.htmlBody, []);
- } else {
- if (typeof m.body.plainBody !== 'string' || typeof m.body.htmlBody !== 'string') {
- return false;
+ if ( child.tag == constant.CMD_FINAL )
+ {
+ gotFinal = true;
+ return cb();
}
- m.body = new MessageBody(null, true, m.body.plainBody, m.body.htmlBody, []);
- }
- newm.body = utils.copy(m.body);
- if (typeof m.isRead === 'boolean') {
- newm.isRead = m.isRead;
- } else {
- newm.isRead = false;
- }
- if (typeof m.isHighPriority === 'boolean') {
- newm.isHighPriority = m.isHighPriority;
- } else {
- newm.isHighPriority = false;
- }
+ // todo: restrict this to the following commands?...
+ // CMD_ALERT, CMD_GET, CMD_PUT,
+ // CMD_SYNC, CMD_RESULTS, CMD_MAP
- if ((m.subject === null) || (m.subject === undefined)) {
- newm.subject = "";
- } else {
- newm.subject = String(m.subject);
- }
+ var func = self['_consume_node_' + child.tag.toLowerCase()];
- if ((m.inResponseTo === null) || (m.inResponseTo === undefined)) {
- newm.inResponseTo = null;
- } else {
- newm.inResponseTo = String(m.inResponseTo);
- }
+ if ( ! func )
+ return cb(new common.ProtocolError('unexpected command node "' + child.tag + '"'));
- if ((m.attachments === null) || (m.attachments === undefined)) {
- newm.attachments = [];
- } else {
- newm.attachments = utils.copy(m.attachments);
- }
- return true;
- },
+ try{
- loadMsg: function (type, id) {
- var i, ret, msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || null;
- if (msg === null) {
- ret = new MessageElement(type, id);
- } else {
- for (i = 0; i < msg.length; i++) {
- if (msg[i].type === type && msg[i].id === id) {
- ret = msg[i];
- break;
- }
- }
- if (ret === undefined) {
- ret = new MessageElement(type, id);
- } else {
- /* after getting Date out of DB, Date will become
- a string, so need to recast it back to Date */
- for (i in ret.msg) {
- ret.msg[i].priv.timestamp = new Date(ret.msg[i].priv.timestamp);
- }
- }
- }
- return ret;
- },
+ func.call(self, session, lastcmds, xsync, child, function(err, cmds) {
+ if ( err )
+ return cb(err);
+ _.each(cmds, function(cmd) { commands.push(cmd); });
+ return cb();
+ });
- delMsg: function (m) { // m is a PrivMessage
- var i, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
- if (_msg.length === 0) {
- return;
- } else {
- for (i = 0; i < _msg.length; i++) {
- if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
- delete _msg[i].msg[m.priv.id];
- if (m.priv.messageStatus !== "DRAFT") {
- _updateConversation(_msg[i], m.priv.conversationId);
- }
- db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
- return;
- }
+ }catch(e){
+ // log.error('failed invoking protocol sub-consumption of "%s": %s', child.tag, e);
+ // log.error(' ' + stacktrace({e: e}).join('\n '));
+ return cb(new common.InternalError(
+ 'failed invoking protocol sub-consumption of "' + child.tag + '": ' + e, e));
}
- }
- },
- saveMsg: function (m) { // m is a PrivMessage
- var i, new_msg, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
- if (_msg.length === 0) {
- _msg = new MessageElement(m.priv.type, m.priv.serviceId);
- _msg.msg[m.priv.id] = m;
- if (m.priv.messageStatus !== "DRAFT") {
- _updateConversation(_msg, m.priv.conversationId);
- }
- db.saveObject(_TIZEN_MESSAGE_DB_KEY, [_msg]);
- } else {
- for (i = 0; i < _msg.length; i++) {
- if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
- _msg[i].msg[m.priv.id] = m;
- if (m.priv.messageStatus !== "DRAFT") {
- _updateConversation(_msg[i], m.priv.conversationId);
- }
- db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
- break;
- }
- }
- if (i === _msg.length) {
- new_msg = new MessageElement(m.priv.type, m.priv.serviceId);
- new_msg.msg[m.priv.id] = m;
- if (m.priv.messageStatus !== "DRAFT") {
- _updateConversation(new_msg, m.priv.conversationId);
- }
- _msg.push(new_msg);
- db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
- }
- }
- },
+ }, function(err) {
- loadConv: function (type, id) {
- var i, ret;
- ret = this.loadMsg(type, id).conv;
- for (i in ret) {
- ret[i].timestamp = new Date(ret[i].timestamp);
- }
- return ret;
- }
-};
+ if ( err )
+ return cb(err);
-});
-define('ripple/platform/tizen/2.0/navigator', function (require, exports, module) {
-/*
- * Copyright 2011 Research In Motion Limited.
- * Copyright 2012 Intel Corporation.
- *
- * 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 _original = window.navigator,
- utils = require('ripple/utils'),
- devices = require('ripple/devices'),
- constants = require('ripple/constants'),
- vibration = require('ripple/platform/tizen/2.0/vibration'),
- _self = {};
+ if ( ! gotFinal )
+ {
+ commands.push(state.makeCommand({
+ name : constant.CMD_ALERT,
+ cmdID : session.nextCmdID(),
+ data : constant.STATUS_NEXT_MESSAGE,
+ source : session.adapter.devID,
+ target : session.peer.devID,
+ }));
+ }
-(function () {
- var key,
- nav = window.navigator;
+ return cb();
+
+ });
- function _handle(obj, key) {
- return typeof obj[key] !== "function" ? obj[key] : function () {
- return obj[key].apply(obj, Array.prototype.slice.call(arguments));
};
- }
- for (key in nav) {
- _self[key] = _handle(nav, key);
- }
-}());
+ // do it!
-_self.__defineGetter__('userAgent', function () {
- var currentUserAgent = devices.getCurrentDevice().userAgent;
+ consumeStatus(function(err) {
- return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
- _original.userAgent : currentUserAgent;
-});
+ if ( err )
+ return cb(err);
-_self.__defineGetter__('vibrate', function () {
- return vibration.vibrate;
-});
+ // TODO: is this right?... or should i be getting pissed off and
+ // raising hell that all my commands were not addressed?...
-module.exports = _self;
+ _.each(chkcmds, function(chkcmd) {
+ commands.push(chkcmd);
+ });
-});
-define('ripple/platform/tizen/2.0/networkbearerselection', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ return consumeCommands(function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, commands);
+ });
+
+ });
-var event = require('ripple/event'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- _security = {
- "http://tizen.org/privilege/networkbearerselection":
- ["requestRouteToHost", "releaseRouteToHost"]
},
- _self;
-_self = function () {
- var networkBearerSelection;
+ //-------------------------------------------------------------------------
+ _consume_node_get: function(session, lastcmds, xsync, xnode, cb) {
+ var cttype = xnode.findtext('Meta/Type');
+ var target = xnode.findtext('Item/Target/LocURI');
+ if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
+ && session.adapter.normUri(target) == constant.URI_DEVINFO_1_2 )
+ return this._consume_node_get_devinf12(session, lastcmds, xsync, xnode, cb);
+ // todo: make error status node...
+ cb(new common.ProtocolError(
+ 'unexpected "' + constant.CMD_GET + '" command for local "' + target + '"'));
+ },
- function requestRouteToHost(networkType, domainName, successCallback, errorCallback) {
- var evNetworkOpened = "NO_" + networkType + "_" + domainName,
- evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
+ //-------------------------------------------------------------------------
+ _consume_node_get_devinf12: function(session, lastcmds, xsync, xnode, cb) {
+ var ret = [];
+ ret.push(state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : session.info.pendingMsgID,
+ cmdRef : xnode.findtext('CmdID'),
+ statusOf : xnode.tag,
+ statusCode : constant.STATUS_OK,
+ targetRef : xnode.findtext('Item/Target/LocURI')
+ }));
+ ret.push(state.makeCommand({
+ name : constant.CMD_RESULTS,
+ cmdID : session.nextCmdID(),
+ msgRef : session.info.pendingMsgID,
+ cmdRef : xnode.findtext('CmdID'),
+ type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
+ source : './' + constant.URI_DEVINFO_1_2,
+ data : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
+ _.values(session.adapter._stores))
- if (!_security.requestRouteToHost) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ }));
+ cb(null, ret);
+ },
- t.NetworkBearerSelection("requestRouteToHost", arguments);
-
- if (!domainName) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+ //-------------------------------------------------------------------------
+ _consume_node_put: function(session, lastcmds, xsync, xnode, cb) {
+ var cttype = xnode.findtext('Meta/Type');
+ var source = xnode.findtext('Item/Source/LocURI');
+ if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
+ && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
+ return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
+ // todo: make error status node...
+ cb(new common.ProtocolError(
+ 'unexpected "' + constant.CMD_PUT + '" command for remote "' + source + '"'));
+ },
- event.once(evNetworkOpened, function (isOpened) {
- if (!isOpened)
- return;
+ //-------------------------------------------------------------------------
+ _consume_node_put_devinf12: function(session, lastcmds, xsync, xnode, cb) {
+ var xdev = xnode.find('Item/Data/DevInf');
+ var res = devinfo.DevInfo.fromSyncML(xdev);
+ session.peer._setRemoteInfo(res[0], res[1], function(err) {
+ if ( err )
+ return cb(err);
- successCallback.onsuccess();
+ var okcmd = state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : xsync.findtext('SyncHdr/MsgID'),
+ cmdRef : xnode.findtext('CmdID'),
+ sourceRef : xnode.findtext('Item/Source/LocURI'),
+ statusOf : xnode.tag,
+ statusCode : constant.STATUS_OK
});
- event.once(evNetworkDisconnected, successCallback.ondisconnected);
- event.trigger("NetworkRequest", [networkType, domainName]);
- }
-
- function releaseRouteToHost(networkType, domainName, successCallback, errorCallback) {
- var evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
-
- if (!_security.releaseRouteToHost) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- t.NetworkBearerSelection("releaseRouteToHost", arguments);
-
- if (!domainName) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
- event.once(evNetworkDisconnected, successCallback);
- event.trigger("NetworkRelease", [networkType, domainName]);
- }
+ if ( session.isServer )
+ return cb(null, [okcmd]);
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ // TODO: this should only cause a `recalculate` if any
+ // meta-information actually changed...
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+ session.context.router.recalculate(session.adapter, session.peer, function(err) {
+ if ( err )
+ return cb(err);
+ session.context.synchronizer.initStoreSync(session, function(err) {
+ if ( err )
+ return cb(err);
- networkBearerSelection = {
- requestRouteToHost: requestRouteToHost,
- releaseRouteToHost: releaseRouteToHost,
- handleSubFeatures: handleSubFeatures
- };
+ // TODO: the call to _setRemoteInfo makes the peer
+ // "dirty" without saving changes to the model...
+ // make sure the `save` executed in Adapter.sync()
+ // or Adapter.handleRequest() appropriately causes
+ // objects to save themselves to the model...
- return networkBearerSelection;
-};
+ // session.adapter._save(session.txn(), function(err) {
+ // if ( err )
+ // return cb(err);
-module.exports = _self;
+ return cb(null, [okcmd]);
-});
-define('ripple/platform/tizen/2.0/nfc', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation
- *
- * 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 db = require('ripple/db'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
- NDEFMessage = require('ripple/platform/tizen/2.0/NDEFMessage'),
- NFCAdapter,
- NFCAdapterPrototype,
- NFCTag,
- NFCPeer,
- _data = {
- DB_NFC_TAG: "tizen1.0-nfc-tag",
- DB_NFC_PEER: "tizen1.0-nfc-peer",
- DB_NFC_OUTPUT_MESSAGE: "tizen1.0-nfc-output-message",
- INTERVAL: 1000,
- listener: {
- onCardEmulationChanged: null,
- onTagDetected: null,
- onPeerDetected: null,
- onNDEFReceived: null
- },
- pairedNFC: null,
- nfcAdapter: {},
- nfcCardEmulation: {},
- nfcTags: [],
- nfcTag: {},
- nfcPeer: null,
- isNear: false, // Identify the device is whether near
- isDetectTag: false, // Identify NFC tag is detected
- isPeerConnected: false,
- connectedState: false
- },
- _security = {
- "http://tizen.org/privilege/nfc.admin": ["setPowered"],
- "http://tizen.org/privilege/nfc.common": ["getDefaultAdapter",
- "setExclusiveMode", "getCachedMessage"],
- "http://tizen.org/privilege/nfc.p2p": ["setPeerListener",
- "unsetPeerListener", "setReceiveNDEFListener",
- "unsetReceiveNDEFListener", "sendNDEF"],
- "http://tizen.org/privilege/nfc.tag": ["setTagListener",
- "unsetTagListener", "readNDEF", "writeNDEF", "transceive"]
+ });
+ });
+ });
},
- _self;
-
-_self = function () {
- var nfc, _exclusiveMode = false;
- function getDefaultAdapter() {
- if (!_security.getDefaultAdapter) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ _consume_node_results: function(session, lastcmds, xsync, xnode, cb) {
+ var cttype = xnode.findtext('Meta/Type');
+ var source = xnode.findtext('Item/Source/LocURI');
+ if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
+ && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
+ return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
+ // todo: make error status node...
+ return cb(new common.ProtocolError('unexpected "' + constant.CMD_RESULTS
+ + '" command for remote "' + source + '"'))
+ },
- t.NFCManager("getDefaultAdapter", arguments);
+ //-------------------------------------------------------------------------
+ _consume_node_alert: function(session, lastcmds, xsync, xnode, cb) {
+ var code = common.int(xnode.findtext('Data'));
+ var statusCode = constant.STATUS_OK
+ switch ( code )
+ {
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_SLOW_SYNC:
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ // todo: these should only be received out-of-band: right?...
+ // case constant.ALERT_TWO_WAY_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
+ {
+ break;
+ }
+ default:
+ {
+ if ( session.isServer && code == constant.STATUS_RESUME )
+ {
+ code = constant.ALERT_SLOW_SYNC;
+ }
+ else
+ {
+ return cb(new common.FeatureNotSupported(
+ 'unimplemented sync mode '
+ + code + ' ("' + common.mode2string(code) + '")'));
+ }
+ }
+ }
- if (!_data.nfcAdapter) {
- throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ if ( session.isServer )
+ {
+ // TODO: if this is the server, we need to validate that the requested
+ // sync mode is actually feasible... i.e. check:
+ // - do the anchors match?
+ // - have we bound the datastores together?
+ // - is there a pending sync?
}
- return _data.nfcAdapter;
- }
+ var uri = session.adapter.normUri(xnode.findtext('Item/Target/LocURI'));
+ var ruri = session.peer.normUri(xnode.findtext('Item/Source/LocURI'));
- /* API Description:
- * If it gets priority and it is in foreground, system doesn't
- * send app controls that are usually sent when detecting NFC Tag
- * or receiving NDEF Message from the connected NFC peer-to-peer target
- *
- * Implementation detail:
- * due to simulator only support single running instance and doesn't have
- * other app controls which be called by design. we just put some system
- * exclusive mode info on the 'System Summary' panel
- */
- function setExclusiveMode(mode) {
- if (!_security.setExclusiveMode) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // TODO: this should really be done by the synchronizer... as it can
+ // then also do a lot of checks - potentially responding with
+ // an error...
- t.NFCManager("setExclusiveMode", arguments);
+ var getDS = function(cb) {
+ if ( session.isServer )
+ {
+ var ds = session.info.dsstates[uri];
+ if ( ds )
+ {
+ ds.action = 'alert';
+ return cb(null, ds);
+ }
- _exclusiveMode = mode;
- jQuery("#NFCExclusiveModeValue").text(_exclusiveMode);
- }
+ var peerStore = session.peer.getStore(ruri);
+ if ( ! peerStore )
+ return cb(new common.ProtocolError(
+ 'request to synchronize unknown remote client URI "' + ruri
+ + '" (to local server URI "' + uri + '")'));
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ // todo: if already correctly bound, then we don't need to re-bind
+ // if ( peerStore._getBinding() )
+ // {
+ // log.critical('(currently bound)');
+ // }
+ // else
+ // log.critical('(currently unbound)');
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
+ session.peer.setRoute(uri, ruri, true, function(err) {
+ if ( err )
+ return cb(err);
+ var peerStore = session.peer.getStore(ruri);
+ var ds = state.makeStoreSyncState({
+ uri : uri,
+ peerUri : ruri,
+ lastAnchor : peerStore._getBinding().localAnchor,
+ mode : null,
+ action : 'alert'
+ });
+ session.info.dsstates[uri] = ds;
+ return cb(null, ds);
+ });
+ return;
}
- }
- }
-
- nfc = {
- getDefaultAdapter: getDefaultAdapter,
- setExclusiveMode: setExclusiveMode,
- handleSubFeatures: handleSubFeatures
- };
-
- nfc.__defineGetter__("NFC_RECORD_TNF_EMPTY", function () {
- return 0;
- });
-
- nfc.__defineGetter__("NFC_RECORD_TNF_WELL_KNOWN", function () {
- return 1;
- });
+ else
+ {
+ var ds = session.info.dsstates[uri];
+ if ( ! ds )
+ return cb(new common.ProtocolError('request for unreflected local datastore "'
+ + uri + '"'));
+ ds.action = 'send';
+ if ( code == ds.mode )
+ return cb(null, ds);
- nfc.__defineGetter__("NFC_RECORD_TNF_MIME_MEDIA", function () {
- return 2;
- });
+ var uaEvent = {
+ session : session,
+ uri : uri,
+ peerUri : ruri,
+ modeReq : ds.mode,
+ modeRes : code
+ };
+ session.ua.acceptSyncModeSwitch(uaEvent, function(err) {
+ if ( err )
+ {
+ return cb(err);
+ }
+ if ( session.context.listener )
+ session.context.listener(uaEvent);
+ return cb(null, ds);
+ });
+ }
+ };
- nfc.__defineGetter__("NFC_RECORD_TNF_URI", function () {
- return 3;
- });
- nfc.__defineGetter__("NFC_RECORD_TNF_EXTERNAL_RTD", function () {
- return 4;
- });
+ getDS(function(err, ds) {
- nfc.__defineGetter__("NFC_RECORD_TNF_UNKNOWN", function () {
- return 5;
- });
+ if ( err )
+ return cb(err);
- nfc.__defineGetter__("NFC_RECORD_TNF_UNCHANGED", function () {
- return 6;
- });
+ ds.mode = code;
+ ds.peerLastAnchor = xnode.findtext('Item/Meta/Anchor/Last', null);
+ ds.peerNextAnchor = xnode.findtext('Item/Meta/Anchor/Next', null);
- return nfc;
-};
+ if ( ds.peerLastAnchor != session.peer.getStore(ruri)._getBinding().remoteAnchor )
+ {
+ ds.peerLastAnchor = null;
+ switch ( ds.mode )
+ {
+ case constant.ALERT_SLOW_SYNC:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ {
+ break;
+ }
+ default:
+ {
+ if ( session.isServer )
+ {
+ ds.mode = constant.ALERT_SLOW_SYNC;
+ statusCode = constant.STATUS_REFRESH_REQUIRED;
+ }
+ else
+ {
+ // todo: should i assume that the server knows something
+ // that i don't and just go along with it?...
+ return cb(new common.ProtocolError(
+ 'server-side requested inappropriate ' + common.mode2string(ds.mode)
+ + ' sync mode on unbound datastore "' + uri + '"'));
+ }
+ }
+ }
+ }
-NFCAdapterPrototype = function () {
- var nfcAdapterPrototype,
- interval,
- powered = false, // Identify the device on or off
- polling = false; // Identify the device is polled
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : xsync.findtext('SyncHdr/MsgID'),
+ cmdRef : xnode.findtext('CmdID'),
+ targetRef : xnode.findtext('Item/Target/LocURI'),
+ sourceRef : xnode.findtext('Item/Source/LocURI'),
+ statusOf : xnode.tag,
+ statusCode : statusCode,
+ // todo: syncevolution does not echo the remote last anchor... why not?
+ lastAnchor : ds.peerLastAnchor,
+ nextAnchor : ds.peerNextAnchor
+ })]);
- event.trigger("nfc-power-changed", [powered]);
- event.on("nfc-power-setting", function (status) {
- updatePowerStatus(status);
- });
- event.on("nfc-attach-setting", function (type, isAttached) {
- var isDetectTag;
+ });
- isDetectTag = (type === "Tag");
- updateIsNear(isDetectTag, isAttached);
- });
- event.on("nfc-tag-send", function (status) {
- var tag;
+ },
- if (status) {
- tag = db.retrieveObject(_data.DB_NFC_TAG);
- if (tag.isSupportedNDEF) {
- _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
- tag.ndefSize, null, true, tag.ndefs);
- } else {
- _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
- tag.ndefSize, null, true, tag.rawData);
- }
- if (_data.listener.onTagDetected) {
- _data.listener.onTagDetected.onattach(_data.nfcTag);
- }
- } else {
- tag = {};
- if (_data.listener.onTagDetected) {
- _data.listener.onTagDetected.ondetach();
- }
+ //-------------------------------------------------------------------------
+ _consume_node_sync: function(session, lastcmds, xsync, xnode, cb) {
+ var self = this;
+ var uri = xnode.findtext('Target/LocURI');
+ var store = session.adapter.getStore(session.adapter.normUri(uri));
+ var ds = session.info.dsstates[session.adapter.normUri(uri)];
+ var commands = [state.makeCommand({
+ name : constant.CMD_SYNC,
+ msgID : xsync.findtext('SyncHdr/MsgID'),
+ cmdID : xnode.findtext('CmdID'),
+ source : xnode.findtext('Source/LocURI'),
+ target : uri,
+ data : [],
+ })];
+ var noc = common.int(xnode.findtext('NumberOfChanges'));
+ if (noc !== undefined) {
+ changednum = noc;
+ _counts = 0;
}
- });
- event.on("nfc-peer-send", function (status) {
- if (status) {
- if (!_data.nfcPeer) {
- _data.nfcPeer = new NFCPeer(true);
- }
- _data.isPeerConnected = true;
- if (_data.listener.onPeerDetected) {
- _data.listener.onPeerDetected.onattach(_data.nfcPeer);
- }
- } else {
- _data.isPeerConnected = false;
- if (_data.listener.onPeerDetected) {
- _data.listener.onPeerDetected.ondetach();
- }
+ common.cascade(xnode.getchildren(), function(child, cb) {
+ switch ( child.tag )
+ {
+ case 'CmdID':
+ case 'Target':
+ case 'Source':
+ case 'NumberOfChanges':
+ {
+ return cb();
+ }
+ case constant.CMD_ADD:
+ case constant.CMD_REPLACE:
+ case constant.CMD_DELETE:
+ {
+ var func = self['_consume_sync_' + child.tag.toLowerCase()];
+ func.call(self, session, lastcmds, store, xsync, child, function(err, cmds) {
+ if ( err )
+ return cb(err);
+ _.each(cmds, function(cmd) { commands[0].data.push(cmd); });
+ return cb();
+ });
+ return;
+ }
+ default:
+ {
+ return cb(new common.ProtocolError('unexpected sync command "' + child.tag + '"'));
+ }
}
- });
- event.on("nfc-peer-sending-ndef", function () {
- var peer, _records = [], rec, _ndef, i;
-
- if (_data.isPeerConnected) {
- peer = db.retrieveObject(_data.DB_NFC_PEER);
- for (i in peer.ndef.records) {
- rec = peer.ndef.records[i];
- _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
- rec.id));
- }
- _ndef = new NDEFMessage(_records);
- if (_data.listener.onNDEFReceived) {
- _data.listener.onNDEFReceived(_ndef);
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ // confirm that i received the right number of changes...
+ /*
+ if ( noc != undefined && noc != commands[0].data.length )
+ return cb(new common.ProtocolError('number-of-changes mismatch (received '
+ + commands[0].data.length + ', expected '
+ + noc + ')'));
+ */
+ _counts = _counts + commands[0].data.length;
+ if ( ds.action != 'error' )
+ {
+ if ( ! session.isServer )
+ {
+ if ( ds.action != 'recv' )
+ return cb(new common.ProtocolError('unexpected sync state for URI "'
+ + uri + '": action=' + ds.action));
+ if (changednum != undefined && changednum <= _counts) {
+ ds.action = 'done';
+ changednum = undefined;
+ _counts = 0;
+ }
+ }
+ else
+ {
+ if ( ds.action != 'alert' )
+ return cb(new common.ProtocolError(
+ 'unexpected sync state for URI "' + uri + '": action=' + ds.action));
+ ds.action = common.oneWayIn(session, ds.mode) ? 'save' : 'send';
+ }
}
- }
- });
+ return session.context.synchronizer.reactions(session, commands, cb);
+ });
+ },
- // private
- function updatePowerStatus(status) {
- if (powered === status) {
- return;
- }
- if (!status) {
- updateIsNear(_data.isDetectTag, false);
- _data.listener.onTagDetected = null;
- _data.listener.onPeerDetected = null;
- _data.listener.onNDEFReceived = null;
- _data.listener.onCardEmulationChanged = null;
+ //-------------------------------------------------------------------------
+ _consume_xnode2item: function(session, lastcmds, store, xsync, xnode, cb) {
+ var ctype = xnode.findtext('Meta/Type');
+ // todo: can the version be specified in the Meta tag?... maybe create an
+ // extension to SyncML to communicate this?...
+ var ctver = null;
+ var format = xnode.findtext('Meta/Format');
+ var xitem = xnode.findall('Item/Data');
+ if ( xitem.length > 1 )
+ return cb(new common.ProtocolError(
+ '"' + xnode.tag + '" command with non-singular item data nodes'));
+ if ( xitem.length < 1 )
+ return cb(new common.ProtocolError(
+ '"' + xnode.tag + '" command with missing data node'));
+ var xitem = xitem[0];
+ // todo: confirm that getchildren only returns element nodes...
+ if ( xitem.getchildren().length == 1 )
+ data = xitem.getchildren()[0];
+ else
+ {
+ data = xitem.text;
+ if ( format == constant.FORMAT_B64 )
+ data = base64.decode(data);
}
- powered = status;
- updatePollingStatus(status);
+ return store.agent.loadsItem(data, ctype, ctver, cb);
+ },
+
+ //-------------------------------------------------------------------------
+ _consume_sync_add: function(session, lastcmds, store, xsync, xnode, cb) {
+ this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
+ if ( err )
+ return cb(err);
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_ADD,
+ msgID : xsync.findtext('SyncHdr/MsgID'),
+ cmdID : xnode.findtext('CmdID'),
+ source : xnode.findtext('Item/Source/LocURI'),
+ sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
+ targetParent : xnode.findtext('Item/TargetParent/LocURI'),
+ data : item
+ })]);
+ });
+ },
+
+ //-------------------------------------------------------------------------
+ _consume_sync_replace: function(session, lastcmds, store, xsync, xnode, cb) {
+ this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
+ if ( err )
+ return cb(err);
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_REPLACE,
+ msgID : xsync.findtext('SyncHdr/MsgID'),
+ cmdID : xnode.findtext('CmdID'),
+ source : xnode.findtext('Item/Source/LocURI'),
+ sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
+ target : xnode.findtext('Item/Target/LocURI'),
+ targetParent : xnode.findtext('Item/TargetParent/LocURI'),
+ data : item
+ })]);
+ });
+ },
+
+ //-------------------------------------------------------------------------
+ _consume_sync_delete: function(session, lastcmds, store, xsync, xnode, cb) {
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_DELETE,
+ msgID : xsync.findtext('SyncHdr/MsgID'),
+ cmdID : xnode.findtext('CmdID'),
+ source : xnode.findtext('Item/Source/LocURI'),
+ sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
+ target : xnode.findtext('Item/Target/LocURI'),
+ targetParent : xnode.findtext('Item/TargetParent/LocURI')
+ })]);
+ },
+
+ // #----------------------------------------------------------------------------
+ // def makeStatus(self, session, xsync, xnode, status=constant.STATUS_OK, **kw):
+ // return state.Command(
+ // name = constant.CMD_STATUS,
+ // cmdID = session.nextCmdID(),
+ // msgRef = xsync.findtext('SyncHdr/MsgID'),
+ // cmdRef = xnode.findtext('CmdID'),
+ // statusOf = xnode.tag,
+ // statusCode = status,
+ // **kw
+ // )
- event.trigger("nfc-power-changed", [powered]);
+ //-------------------------------------------------------------------------
+ _consume_node_map: function(session, lastcmds, xsync, xnode, cb) {
+ if ( ! session.isServer )
+ return cb(new common.ProtocolError(
+ 'unexpected "Map" command received by client-side SyncML peer'));
+ // TODO: convert the sender-side to support command.items like
+ // this as well...
+ var cmd = state.makeCommand({
+ name : constant.CMD_MAP,
+ msgID : xsync.findtext('SyncHdr/MsgID'),
+ cmdID : xnode.findtext('CmdID'),
+ source : xnode.findtext('Source/LocURI'),
+ target : xnode.findtext('Target/LocURI'),
+ items : []
+ });
+ _.each(xnode.findall('MapItem'), function(xnode) {
+ // todo: support hierarchical sync...
+ cmd.items.push({
+ source : xnode.findtext('Source/LocURI'),
+ // sourceParent : xnode.findtext('SourceParent/LocURI'),
+ target : xnode.findtext('Target/LocURI'),
+ // targetParent : xnode.findtext('TargetParent/LocURI')
+ });
+ });
+ return session.context.synchronizer.reactions(session, [cmd], cb);
}
- function updatePollingStatus(status) {
- if (!powered)
- return;
- if (polling === status) {
- return;
- }
- polling = status;
- event.trigger("nfc-polling-changed", [polling]);
- if (polling) {
- interval = setInterval(poll, _data.INTERVAL);
- } else {
- clearInterval(interval);
- }
- }
- function updateIsNear(isDetectTag, isAttached) {
- _data.isDetectTag = isDetectTag;
- _data.isNear = isAttached;
- if (!_data.isNear) {
- _data.connectedState = false;
- event.trigger("nfc-connectedState-changed", [false]);
- }
- }
+});
- function poll() {
- if (!_data.isNear) {
- return;
- }
- if (!_data.connectedState) {
- _data.connectedState = true;
- event.trigger("nfc-connectedState-changed", [true]);
- }
- }
+return exports;
- // public
- // Turns NFC adapter on or off.
- function setPowered(state, successCallback, errorCallback) {
- if (!_security.setPowered) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+})();
- t.NFCAdapter("setPowered", arguments);
+module.exports = _self;
- window.setTimeout(function () {
- updatePowerStatus(state);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/router', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.router
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/04
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- // Registers a callback function to invoke when NFC tag is detected.
- function setTagListener(detectCallback, tagFilter) {
- if (!_security.setTagListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
+ matcher = require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
+ stablematch = require('ripple/platform/tizen/2.0/syncml-js-lib/stablematch'),
+ _self;
- t.NFCAdapter("setTagListener", arguments);
+_self = (function () {
- //TODO: tagFilter support
- if (!powered) {
- return;
- }
- _data.listener.onTagDetected = detectCallback;
- }
+ var exports = {};
- // Registers a callback function to be invoked when NFC peer-to-peer target is detected.
- function setPeerListener(detectCallback) {
- if (!_security.setPeerListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //---------------------------------------------------------------------------
+ exports.Router = common.Base.extend({
- t.NFCAdapter("setPeerListener", arguments);
+ //-------------------------------------------------------------------------
+ constructor: function(options) {
+ },
- if (!powered) {
- return;
- }
- _data.listener.onPeerDetected = detectCallback;
+ //-------------------------------------------------------------------------
+ getTargetUri: function(adapter, peer, sourceUri) {
+ var pmodel = peer._getModel();
+ for ( var idx=0 ; idx<pmodel.routes.length ; idx++ )
+ {
+ var route = pmodel.routes[idx];
+ if ( route.localUri == sourceUri )
+ return route.remoteUri;
+ }
+ for ( var idx=0 ; idx<pmodel.stores.length ; idx++ )
+ {
+ var store = pmodel.stores[idx];
+ if ( store.binding && store.binding.uri == sourceUri )
+ return store.uri;
}
+ return null;
+ },
- // Unregisters the listener for detecting an NFC tag.
- function unsetTagListener() {
- if (!_security.unsetTagListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ recalculate: function(adapter, peer, cb) {
+ // the non-"SmartRouter" only connects manually-configured routes...
+ var routes = _.filter(peer._getModel().routes,
+ function(r) { return ! r.autoMapped; });
+ return this._setupRoutes(adapter, peer, routes, cb);
+ },
- if (!powered || !_data.listener.onTagDetected) {
- return;
- }
+ //-------------------------------------------------------------------------
+ _setupRoutes: function(adapter, peer, routes, cb) {
+ // available local URIs
+ var lset = _.map(adapter._getModel().stores,
+ function(s) { return adapter.normUri(s.uri); });
+ // available remote URIs
+ var rset = _.map(peer._getModel().stores,
+ function(s) { return peer.normUri(s.uri); });
- _data.listener.onTagDetected = null;
- }
+ // break all routes not listed
+ var ruris = _.map(routes, function(r) { return r.remoteUri; });
+ var xrset = _.filter(rset, function(uri) {
+ return _.indexOf(ruris, uri) < 0;
+ });
+ _.each(xrset, function(uri) {
+ var smodel = peer.getStore(uri)._getModel();
+ if ( ! smodel.binding )
+ return;
+ smodel.binding = null;
+ });
- // Unregisters the listener for detecting an NFC peer-to-peer target.
- function unsetPeerListener() {
- if (!_security.unsetPeerListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ var err = null;
+ _.each(routes, function(route) {
+ if ( err )
+ return;
- if (!powered || !_data.listener.onPeerDetected) {
+ route.localUri = adapter.normUri(route.localUri);
+ route.remoteUri = peer.normUri(route.remoteUri);
+ if ( _.indexOf(rset, route.remoteUri) < 0
+ || _.indexOf(lset, route.localUri) < 0 )
+ {
+ err = 'unable to route from "' + route.localUri
+ + '" (here) to "' + route.remoteUri
+ + '" (peer): no such stores or already routed elsewhere';
return;
- }
-
- _data.listener.onPeerDetected = null;
- }
+ }
- // Gets NDEF message cached when the tag is detected.
- function getCachedMessage() {
- if (!_security.getCachedMessage) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ lset = _.filter(lset, function(uri) { return uri != route.localUri; });
+ rset = _.filter(rset, function(uri) { return uri != route.remoteUri; });
- t.NFCAdapter("getCachedMessage", arguments);
- return _data.pairedNFC || new NDEFMessage([]);
- }
+ var smodel = peer.getStore(route.remoteUri)._getModel();
+ if ( smodel.binding && smodel.binding.uri == route.localUri )
+ return;
+ smodel.binding = {
+ uri : route.localUri,
+ autoMapped : route.autoMapped,
+ localAnchor : null,
+ remoteAnchor : null
+ };
+ });
- nfcAdapterPrototype = {
- setPowered: setPowered,
- setTagListener: setTagListener,
- setPeerListener: setPeerListener,
- unsetTagListener: unsetTagListener,
- unsetPeerListener: unsetPeerListener,
- getCachedMessage: getCachedMessage
- };
+ if ( err )
+ return cb(err);
- nfcAdapterPrototype.__defineGetter__("powered", function () {
- return powered;
- });
+ return cb();
+ },
- return nfcAdapterPrototype;
-};
+ //-------------------------------------------------------------------------
+ getBestTransmitContentType: function(adapter, peer, uri) {
+ var lstore = adapter.getStore(uri);
+ var rstore = peer.getStore(this.getTargetUri(adapter, peer, uri));
+ return matcher.pickTransmitContentType(lstore, rstore);
+ },
-NFCAdapter = function () {
- this.__defineGetter__("powered", function () {
- return this.__proto__.powered;
});
-};
-NFCAdapter.prototype = new NFCAdapterPrototype();
+ //---------------------------------------------------------------------------
+ exports.SmartRouter = exports.Router.extend({
-NFCTag = function (type, isSupportedNDEF, ndefSize, properties, isConnected, ndefs) {
- var nfcTag, i, j, _ndefs, rec, _records, _ndefs_index = 0;
+ //-------------------------------------------------------------------------
+ recalculate: function(adapter, peer, cb) {
- type = type || null;
- isSupportedNDEF = isSupportedNDEF || false;
- ndefSize = ndefSize || 1;
- properties = null;
- isConnected = isConnected || false;
+ // note: if you don't want smart routing, assign the non-SmartRouter
+ // router (i.e. syncml-js.Router) to the loaded context
- _ndefs = [];
- for (i in ndefs) {
- _records = [];
- for (j in ndefs[i].records) {
- rec = ndefs[i].records[j];
- _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
- rec.id));
- }
- _ndefs.push(new NDEFMessage(_records));
- }
+ // available local URIs
+ var llut = _.object(
+ _.map(adapter._getModel().stores,
+ function(s) { return [adapter.normUri(s.uri), s]; }));
+ var lset = _.keys(llut);
- // Reads NDEF data.
- function readNDEF(readCallback, errorCallback) {
- if (!_security.readNDEF) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // available remote URIs
+ var rlut = _.object(
+ _.map(peer._getModel().stores,
+ function(s) { return [adapter.normUri(s.uri), s]; }));
+ var rset = _.keys(rlut);
- t.NFCTag("readNDEF", arguments);
+ // TODO: i am directly touching the model here.
+ // total i-rep violation.
+ // i'm embarrassed.
+ // fortunately, it's just between syncml-js classes...
+ // but now you know, doh! please don't blackmail me!... ;-)
- window.setTimeout(function () {
- if (!_data.isNear || !isSupportedNDEF ||
- (_ndefs_index >= ndefSize)) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
- _data.pairedNFC = _ndefs[_ndefs_index];
- readCallback(_ndefs[_ndefs_index]);
- _ndefs_index++;
- }, 1);
- }
+ // manual routes
+ var pmodel = peer._getModel();
+ pmodel.routes = _.filter(pmodel.routes,
+ function(r) { return ! r.autoMapped; });
- // Writes NDEF data.
- function writeNDEF(ndefMessage, successCallback, errorCallback) {
- if (!_security.writeNDEF) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // remove manual routes from available routes
+ var uris = _.map(pmodel.routes, function(r) { return r.localUri; });
+ lset = _.filter(lset, function(uri) {
+ return _.indexOf(uris, uri) < 0;
+ });
+ uris = _.map(pmodel.routes, function(r) { return r.remoteUri; });
+ rset = _.filter(rset, function(uri) {
+ return _.indexOf(uris, uri) < 0;
+ });
- t.NFCTag("writeNDEF", arguments, true);
+ // match remaining stores
+ var rankL = function(luri) {
+ var ret = _.rest(rset, 0);
+ ret.sort(function(a, b) {
+ return matcher.cmpStore(llut[luri], rlut[a], rlut[b]);
+ });
+ return ret;
+ };
+ var rankR = function(ruri) {
+ var ret = _.rest(lset, 0);
+ ret.sort(function(a, b) {
+ return matcher.cmpStore(rlut[ruri], llut[a], llut[b]);
+ });
+ return ret;
+ };
+ var matches = stablematch.match(lset, rset, rankL, rankR);
- window.setTimeout(function () {
- if (!_data.isNear || !isSupportedNDEF) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
- db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
- event.trigger("nfc-output-msg", []);
- if (successCallback) {
- successCallback();
+ // add them to the routes (as auto-routed)
+ for ( var idx=0 ; idx<matches.length ; idx++ )
+ {
+ var pair = matches[idx];
+ pmodel.routes.push({
+ localUri : pair[0],
+ remoteUri : pair[1],
+ autoMapped : true
+ });
}
- }, 1);
- }
- // Access the raw format card.
- function transceive(data, dataCallback, errorCallback) {
- if (!_security.transceive) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ return this._setupRoutes(adapter, peer, pmodel.routes, cb);
+ },
- t.NFCTag("transceive", arguments, true);
+ });
- window.setTimeout(function () {
- if (!_data.isNear || isSupportedNDEF) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
- db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, data);
- event.trigger("nfc-output-msg", []);
- dataCallback(ndefs);
- }, 1);
- }
+ return exports;
- // Formats the detected tag that can store NDEF messages.
- /*
- function formatNDEF(successCallback, errorCallback, key) {
+})();
- tizen1_utils.validateCallbackType(successCallback, errorCallback);
+module.exports = _self;
- if (key) {
- tizen1_utils.validateArgumentType(key, "array",
- new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/codec', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// auth: metagriffin <metagriffin@uberdev.org>
+// date: 2012/10/13
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- if (!isConnected || !isSupportedNDEF) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ _self;
- successCallback();
- }
- */
+_self = (function () {
- nfcTag = {
- readNDEF: readNDEF,
- writeNDEF: writeNDEF,
- transceive: transceive
- //formatNDEF: formatNDEF
- };
+ var exports = {};
- nfcTag.__defineGetter__("type", function () {
- return type;
- });
+ //---------------------------------------------------------------------------
+ exports.Codec = common.Base.extend({
- nfcTag.__defineGetter__("isSupportedNDEF", function () {
- return isSupportedNDEF;
- });
+ encode: function(xtree, cb) {
+ throw new common.NotImplementedError();
+ },
- nfcTag.__defineGetter__("ndefSize", function () {
- return ndefSize;
- });
+ decode: function(contentType, data, cb) {
+ throw new common.NotImplementedError();
+ },
+ }, {
- nfcTag.__defineGetter__("properties", function () {
- return properties;
- });
+ factory: function(codec) {
+ // todo: should this be converted to callback-based?...
+ if ( codec == constant.CODEC_XML )
+ return new exports.XmlCodec()
+ // TODO
+ // if ( codec == constant.CODEC_WBXML )
+ // return exports.WbxmlCodec()
+ throw new common.UnknownCodec('unknown or unimplemented codec "' + codec + '"')
+ },
- nfcTag.__defineGetter__("isConnected", function () {
- return _data.isNear;
+ autoEncode: function(xtree, codecName, cb) {
+ exports.Codec.factory(codecName).encode(xtree, cb);
+ },
+
+ autoDecode: function(contentType, data, cb) {
+ if ( contentType.indexOf(constant.TYPE_SYNCML + '+') != 0 )
+ return cb('unknown or unimplemented content type "' + contentType + '"');
+ var ct = contentType.slice((constant.TYPE_SYNCML + '+').length).split(';')[0];
+ exports.Codec.factory(ct).decode(contentType, data, function(err, tree) {
+ if ( err )
+ return cb(err);
+ return cb(null, tree, ct);
+ });
+ },
});
- return nfcTag;
-};
+ //---------------------------------------------------------------------------
+ exports.XmlCodec = exports.Codec.extend({
-NFCPeer = function (isConnected) {
- var nfcPeer;
+ name: constant.CODEC_XML,
- isConnected = isConnected || false;
+ encode: function(xtree, cb) {
+ // todo: really enforce this charset...
+ var ctype = constant.TYPE_SYNCML + '+' + this.name + '; charset=UTF-8';
+ var ret = ET.tostring(xtree);
+ if ( ret.charAt(0) == '<' && ret.charAt(1) == '?' )
+ {
+ var idx = ret.indexOf('?>');
+ if ( idx >= 0 )
+ ret = ret.substr(0, idx + 2).replace(/'/g, '"') + ret.substr(idx + 2);
+ }
+ cb(null, ctype, ret);
+ },
- // Registers a callback function to be invoked when NDEF message is received from NFC peer-to-peer target connected.
- function setReceiveNDEFListener(successCallback) {
- if (!_security.setReceiveNDEFListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ decode: function(contentType, data, cb) {
+ var expCT = constant.TYPE_SYNCML + '+' + this.name;
+ if ( contentType.indexOf(expCT) != 0 )
+ cb(new common.ProtocolError(
+ 'received unexpected content-type "' + contentType + '" (expected "'
+ + expCT + '")'));
+ try
+ {
+ return cb(null, ET.parse(data).getroot());
+ }
+ catch(e)
+ {
+ return cb(new common.ProtocolError('could not parse XML: ' + e, e));
+ }
}
- t.NFCPeer("setReceiveNDEFListener", arguments);
+ });
- if (!_data.isPeerConnected) {
- return;
- }
- _data.listener.onNDEFReceived = successCallback;
- }
+ //---------------------------------------------------------------------------
+ // TODO: implement wbxml...
+ // exports.WbXmlCodec = exports.Codec.extend({
+ // encode: function(xtree, cb) {
+ // },
+ // decode: function(contentType, data, cb) {
+ // }
+ // });
- // Unregisters the listener for receiving NDEFMessage from NFC peer-to-peer target connected.
- function unsetReceiveNDEFListener() {
- if (!_security.unsetReceiveNDEFListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ return exports;
- _data.listener.onNDEFReceived = null;
- }
+})();
- // Sends data to NFC peer-to-peer target.
- function sendNDEF(ndefMessage, successCallback, errorCallback) {
- if (!_security.sendNDEF) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+module.exports = _self;
- t.NFCPeer("sendNDEF", arguments, true);
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/stablematch', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// desc: implements a solution to the stable matching problem using a
+// left-optimized algorithm. shamelessly adapted from:
+// https://github.com/paulgb/Python-Gale-Shapley/
+// auth: metagriffin <mg.npmjs@uberdev.org>
+// date: 2012/12/29
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- window.setTimeout(function () {
- if (!_data.isPeerConnected) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
- }
+var _self = (function () {
- db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
- event.trigger("nfc-output-msg", []);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+ var exports = {};
- nfcPeer = {
- setReceiveNDEFListener: setReceiveNDEFListener,
- unsetReceiveNDEFListener: unsetReceiveNDEFListener,
- sendNDEF: sendNDEF
- };
+ // TODO: figure out how to pull this dynamically from package.json...
+ exports.version = '0.0.4';
- nfcPeer.__defineGetter__("isConnected", function () {
- return _data.isPeerConnected;
- });
+ //---------------------------------------------------------------------------
+ exports.match = function(A, B, rankA, rankB) {
+ if ( ! A || ! B || ! A.length || ! B.length ) {
+ return [];
+ }
+ if ( A.length == B.length ) {
+ return exports._match(A, B, rankA, rankB);
+ }
- return nfcPeer;
-};
+ // TODO: this is a brute-force implementation of getting both
+ // lists to be of symmetric length... make this "better".
+ // for example, build this directly into _match() or use
+ // deterministic exclusion of the longer data set.
-function _initialize() {
- _data.nfcAdapter = new NFCAdapter();
-}
+ var sA = _.rest(A, 0);
+ var sB = _.rest(B, 0);
+ var mlen = Math.max(sA, sB);
+ while ( sA.length < mlen )
+ sA.push(null);
+ while ( sB.length < mlen )
+ sB.push(null);
+ var sRA = function(a) {
+ var ret = rankA(a);
+ while ( ret.length < mlen )
+ ret.push(null);
+ return ret;
+ };
+ var sRB = function(b) {
+ var ret = rankB(b);
+ while ( ret.length < mlen )
+ ret.push(null);
+ return ret;
+ };
+ var ret = exports._match(sA, sB, sRA, sRB);
+ return _.filter(ret, function(pair) {
+ return pair[0] != null && pair[1] != null;
+ });
+ };
-_initialize();
+ //---------------------------------------------------------------------------
+ exports._match = function(A, B, rankA, rankB) {
+ // this translates sets A and B to indeces, since _imatch can only work
+ // with sets of elements that can be used as the key in a hash (in this
+ // implementation).
+ var iA = _.range(A.length);
+ var iB = _.range(B.length);
+ var iRA = function(ia) {
+ var ret = rankA(A[ia]);
+ return _.map(ret, function(item) {
+ return _.indexOf(B, item);
+ });
+ };
+ var iRB = function(ib) {
+ var ret = rankB(B[ib]);
+ return _.map(ret, function(item) {
+ return _.indexOf(A, item);
+ });
+ };
+ var ret = exports._imatch(iA, iB, iRA, iRB);
+ return _.map(ret, function(item) {
+ return [A[item[0]], B[item[1]]];
+ });
+ };
+
+ //---------------------------------------------------------------------------
+ exports._imatch = function(A, B, rankA, rankB) {
+ // TODO: improve this... it was a brute-force porting of
+ // https://github.com/paulgb/Python-Gale-Shapley
+ // without any eye on optimal outcome or performance...
+ //: `partners` is a paring hash of { a => [b, rank] }
+ var partners = {};
+ _.each(A, function(a) {
+ partners[a] = [rankA(a)[0], 0];
+ });
+ //: `stable` indicates stability of the current pairing in `partners`
+ var stable = false;
+ while ( ! stable )
+ {
+ stable = true;
+ _.each(B, function(b) {
+ var paired = false;
+ for ( var n=0 ; n<A.length ; n++ )
+ {
+ var a = rankB(b)[n];
+ var pair = partners[a];
+ if ( pair[0] == b )
+ {
+ if ( paired )
+ {
+ stable = false;
+ partners[a] = [rankA(a)[pair[1] + 1], pair[1] + 1];
+ }
+ else
+ paired = true;
+ }
+ }
+ });
+ }
+ return _.map(_.keys(partners), function(a) {
+ return [a, partners[a][0]];
+ });
+ };
+
+ return exports;
+})();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/notification', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+define('ripple/platform/tizen/2.0/syncml-js-lib/common', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// auth: metagriffin <metagriffin@uberdev.org>
+// date: 2012/10/13
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
- _notificationStack,
- _security = {
- "http://tizen.org/privilege/notification": ["post", "update", "remove",
- "removeAll"]
- },
+var constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
_self;
-_self = function () {
- function post(notification) {
- var posted = {};
+_self = (function () {
+ var exports = {};
- if (!_security.post) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //---------------------------------------------------------------------------
+ // object inheritance helper routines shamelessly scrubbed from backbone.js
- t.NotificationManager("post", arguments);
+ // The self-propagating extend function that Backbone classes use.
+ var extend = exports.extend = function (protoProps, classProps) {
+ var child = inherits(this, protoProps, classProps);
+ child.extend = this.extend;
+ return child;
+ };
- if (notification.id !== undefined) {
- return;
- }
- posted.id = Math.uuid(null, 16);
+ // Shared empty constructor function to aid in prototype-chain creation.
+ var ctor = function(){};
- notification.__defineGetter__("id", function () {
- return posted.id;
- });
+ // Helper function to correctly set up the prototype chain, for subclasses.
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
+ // class properties to be extended.
+ var inherits = function(parent, protoProps, staticProps) {
+ var child;
- if (!_notificationStack[notification.id]) {
- posted.postedTime = new Date();
+ // 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 && protoProps.hasOwnProperty('constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ parent.apply(this, arguments); };
+ }
- notification.__defineGetter__("postedTime", function () {
- return posted.postedTime;
- });
+ // Inherit class (static) properties from parent.
+ _.extend(child, parent);
- _notificationStack[notification.id] = t.Notification(notification,
- "+");
- db.saveObject("posted-notifications", _notificationStack);
- event.trigger("refreshNotificationUI", [], true);
- }
- }
+ // Set the prototype chain to inherit from `parent`, without calling
+ // `parent`'s constructor function.
+ ctor.prototype = parent.prototype;
+ child.prototype = new ctor();
- function update(notification) {
- if (!_security.update) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Add prototype properties (instance properties) to the subclass,
+ // if supplied.
+ if (protoProps) _.extend(child.prototype, protoProps);
- t.NotificationManager("update", arguments);
+ // Add static properties to the constructor function, if supplied.
+ if (staticProps) _.extend(child, staticProps);
- if (!_notificationStack[notification.id]) {
- throw new WebAPIException(errorcode.UNKNOWN_ERR);
- }
- _notificationStack[notification.id] = t.Notification(notification,
- "+");
- db.saveObject("posted-notifications", _notificationStack);
- event.trigger("refreshNotificationUI", [], true);
- }
+ // Correctly set child's `prototype.constructor`.
+ child.prototype.constructor = child;
- function remove(id) {
- if (!_security.remove) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // Set a convenience property in case the parent's prototype is needed later.
+ child.__super__ = parent.prototype;
- t.NotificationManager("remove", arguments);
+ return child;
+ };
- if (!_notificationStack[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- delete _notificationStack[id];
- db.saveObject("posted-notifications", _notificationStack);
- event.trigger('refreshNotificationUI', [], true);
- }
+ //-----------------------------------------------------------------------------
+ exports.Base = function() {};
+ exports.Base.extend = extend;
- function removeAll() {
- if (!_security.removeAll) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ //-----------------------------------------------------------------------------
+ var SyncmlError = exports.Base.extend({
+ constructor: function(msg, exception, attrs) {
+ this.message = this.name;
+ if ( msg != undefined )
+ this.message += ': ' + msg;
+ this.exception = exception;
+ if ( attrs )
+ _.extend(this, attrs);
+ },
+ toString: function() {
+ return this.message;
}
+ });
- _notificationStack = {};
- db.saveObject("posted-notifications", _notificationStack);
- event.trigger('refreshNotificationUI', [], true);
- }
-
- function get(id) {
- var n, notification;
+ //---------------------------------------------------------------------------
+ exports.Stream = exports.Base.extend({
- t.NotificationManager("get", arguments);
+ writeln: function(data) {
+ if ( data == undefined )
+ return;
+ return this.write(data + '\n');
+ },
- if (!_notificationStack[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ indented: function(indent) {
+ return new exports.IndentStream(this, indent || this._indent);
}
- n = _notificationStack[id];
- notification = new StatusNotification(n.statusType, n.title, n);
-
- notification.__defineGetter__("id", function () {
- return n.id;
- });
- notification.__defineGetter__("postedTime", function () {
- return n.postedTime;
- });
+ });
- return notification;
- }
+ _.extend(exports, {
- function getAll() {
- var notifications = [];
+ //---------------------------------------------------------------------------
+ // exceptions
+ SyncmlError: SyncmlError.extend({name: 'SyncmlError'}),
+ TypeError: SyncmlError.extend({name: 'TypeError'}),
+ NotImplementedError: SyncmlError.extend({name: 'NotImplementedError'}),
+ ProtocolError: SyncmlError.extend({name: 'ProtocolError'}),
+ InternalError: SyncmlError.extend({name: 'InternalError'}),
+ ConflictError: SyncmlError.extend({name: 'ConflictError'}),
+ FeatureNotSupported: SyncmlError.extend({name: 'FeatureNotSupported'}),
+ LogicalError: SyncmlError.extend({name: 'LogicalError'}),
+ CredentialsRequired: SyncmlError.extend({name: 'CredentialsRequired'}),
+ InvalidCredentials: SyncmlError.extend({name: 'InvalidCredentials'}),
+ InvalidContext: SyncmlError.extend({name: 'InvalidContext'}),
+ InvalidAdapter: SyncmlError.extend({name: 'InvalidAdapter'}),
+ InvalidStore: SyncmlError.extend({name: 'InvalidStore'}),
+ InvalidContentType: SyncmlError.extend({name: 'InvalidContentType'}),
+ InvalidAgent: SyncmlError.extend({name: 'InvalidAgent'}),
+ InvalidContent: SyncmlError.extend({name: 'InvalidContent'}),
+ InvalidItem: SyncmlError.extend({name: 'InvalidItem'}),
+ UnknownCodec: SyncmlError.extend({name: 'UnknownCodec'}),
+ NoSuchRoute: SyncmlError.extend({name: 'NoSuchRoute'}),
+ UnknownAuthType: SyncmlError.extend({name: 'UnknownAuthType'}),
+ UnknownFormatType: SyncmlError.extend({name: 'UnknownFormatType'}),
- utils.forEach(_notificationStack, function (n) {
- var notification;
+ //---------------------------------------------------------------------------
+ // UUID generation
+ makeID: function() {
+ // shamelessly scrubbed from:
+ // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
+ // (adjusted to remove the dashes)
+ // todo: see some of those links on how to make this more "robust"...
+ return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
+ var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
+ return v.toString(16);
+ });
+ },
- notification = new StatusNotification(n.statusType, n.title, n);
+ //-------------------------------------------------------------------------
+ synctype2alert: function(type) {
+ return constant.SyncTypeToAlert[type];
+ },
- notification.__defineGetter__("id", function () {
- return n.id;
- });
+ //-------------------------------------------------------------------------
+ alert2synctype: function(alert) {
+ for ( var key in constant.SyncTypeToAlert )
+ {
+ if ( constant.SyncTypeToAlert[key] == alert )
+ return exports.int(key);
+ }
+ return null;
+ },
- notification.__defineGetter__("postedTime", function () {
- return n.postedTime;
- });
+ //-------------------------------------------------------------------------
+ mode2string: function(code) {
+ switch ( code )
+ {
+ case constant.ALERT_TWO_WAY: return 'two-way';
+ case constant.ALERT_SLOW_SYNC: return 'slow-sync';
+ case constant.ALERT_ONE_WAY_FROM_CLIENT: return 'one-way-from-client';
+ case constant.ALERT_REFRESH_FROM_CLIENT: return 'refresh-from-client';
+ case constant.ALERT_ONE_WAY_FROM_SERVER: return 'one-way-from-server';
+ case constant.ALERT_REFRESH_FROM_SERVER: return 'refresh-from-server';
+ case constant.ALERT_TWO_WAY_BY_SERVER: return 'two-way-by-server';
+ case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER: return 'one-way-from-client-by-server';
+ case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER: return 'refresh-from-client-by-server';
+ case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER: return 'one-way-from-server-by-server';
+ case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER: return 'refresh-from-server-by-server';
+ default: return 'UNKNOWN';
+ }
+ },
- notifications.push(notification);
- });
+ //-------------------------------------------------------------------------
+ state2string: function(state) {
+ switch ( state )
+ {
+ case constant.ITEM_OK: return 'ok';
+ case constant.ITEM_ADDED: return 'added';
+ case constant.ITEM_MODIFIED: return 'modified';
+ case constant.ITEM_DELETED: return 'deleted';
+ case constant.ITEM_SOFTDELETED: return 'soft-deleted';
+ default: return 'UNKNOWN';
+ }
+ },
- return notifications;
- }
+ //-------------------------------------------------------------------------
+ oneWay: function(mode) {
+ switch ( mode )
+ {
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_SLOW_SYNC:
+ return false;
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ return true;
+ // case constant.ALERT_TWO_WAY_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
+ default:
+ throw new exports.InternalError('invalid mode "' + mode + '"');
+ }
+ },
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ //-------------------------------------------------------------------------
+ oneWayIn: function(session, mode) {
+ switch ( mode )
+ {
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_SLOW_SYNC:
+ return false;
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ return !! session.isServer;
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ return ! session.isServer;
+ // case constant.ALERT_TWO_WAY_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
+ default:
+ throw new exports.InternalError('invalid mode "' + mode + '"');
+ }
+ },
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
+ //-------------------------------------------------------------------------
+ oneWayOut: function(session, mode) {
+ switch ( mode )
+ {
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_SLOW_SYNC:
+ return false;
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ return ! session.isServer;
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ return !! session.isServer;
+ // case constant.ALERT_TWO_WAY_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
+ default:
+ throw new exports.InternalError('invalid mode "' + mode + '"');
}
- }
- }
-
- var notification = {
- post: post,
- update: update,
- remove: remove,
- removeAll: removeAll,
- get: get,
- getAll: getAll,
- handleSubFeatures: handleSubFeatures
- };
+ },
- return notification;
-};
+ //-------------------------------------------------------------------------
+ cascade: function(list, iterator, cb) {
+ if ( ! cb && iterator )
+ {
+ cb = iterator;
+ iterator = null;
+ }
+ if ( ! list )
+ return cb();
+ var cur = 0;
+ var next = function() {
+ if ( cur >= list.length )
+ return cb();
+ var curcb = function(err) {
+ if ( err )
+ return cb(err);
+ cur += 1;
+ var args = [];
+ for ( var idx=1 ; idx<arguments.length ; idx++ )
+ args.push(arguments[idx]);
+ return next.apply(null, args);
+ };
+ var func = iterator || list[cur];
+ var args = [];
+ if ( iterator )
+ args.push(list[cur]);
+ for ( var idx=0 ; idx<arguments.length ; idx++ )
+ args.push(arguments[idx]);
+ args.push(curcb);
+ return func.apply(null, args);
+ };
+ return next();
+ },
-function _initilize() {
- _notificationStack = db.retrieveObject("posted-notifications") || {};
+ //-------------------------------------------------------------------------
+ ts: function() {
+ return Math.floor((new Date()).getTime() / 1000);
+ },
- utils.forEach(_notificationStack, function (n) {
- n.postedTime = new Date(n.postedTime);
- });
+ //-------------------------------------------------------------------------
+ j: function(obj) {
+ return JSON.stringify(obj);
+ },
- event.on("refreshNotificationStack", function () {
- _notificationStack = db.retrieveObject("posted-notifications");
- });
-}
+ //-------------------------------------------------------------------------
+ noop: function(cb) {
+ return cb();
+ },
-_initilize();
+ //-------------------------------------------------------------------------
+ platformBits: function() {
-module.exports = _self;
+ // TODO: implement this!...
-});
-define('ripple/platform/tizen/2.0/package', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ return 32;
+ },
-var db = require('ripple/db'),
- app = require('ripple/app'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
- _security = {
- "http://tizen.org/privilege/packagemanager.install": ["install", "uninstall"],
- "http://tizen.org/privilege/package.info": ["getPackagesInfo", "getPackageInfo",
- "setPackageInfoEventListener", "unsetPackageInfoEventListener"]
- },
- DB_PACKAGE_KEY = "tizen-db-package",
- _listeners = [],
- _data = {
- packageList: {},
- installedList: {}
- },
- INTERVAL = 1000, // INTERVAL = 1sec
- INSTALL_AMOUNT = 3072, // installation speed amount = 3072 (KB/sec)
- PSEUDO_PACKAGE_ID = "pseudopack00",
- PSEUDO_APP_ID = "pseudoapp00",
- _self;
+ //-------------------------------------------------------------------------
+ getMaxMemorySize: function(context) {
-function _get() {
- _data = db.retrieveObject(DB_PACKAGE_KEY);
-}
+ // Returns the maximum size of a memory object. By default this
+ // is, set to ``sys.maxint``, however the `context` may override
+ // this behavior.
-function _save() {
- db.saveObject(DB_PACKAGE_KEY, _data);
-}
+ // NOTE: currently, this is being hardcoded to a maximum of 2GB for
+ // compatibility with funambol servers, which croak above that
+ // value.
-function _exec(callback, name, id, arg1) {
- switch (name) {
- case "onprogress":
- callback[name](id, arg1);
- break;
- case "oncomplete":
- callback[name](id);
- break;
- default:
- break;
- }
-}
+ // TODO: allow the context to control this, or implement auto-detect to
+ // determine what the remote peer can support...
-function _setupCurrentPackage() {
- var info, id, item, tizenAppId;
- info = app.getInfo();
- tizenAppId = info.tizenAppId || PSEUDO_APP_ID;
- id = info.tizenPackageId;
- if (id !== undefined) {
- if (_data.installedList[id]) {
- // already installed
- return;
- }
+ return Math.min(Math.pow(2, exports.platformBits() - 1) - 1,
+ Math.pow(2, 31) - 1);
+ },
- item = null;
- utils.forEach(_data.packageList, function (p) {
- if (p.id === id) {
- item = p;
+ //-------------------------------------------------------------------------
+ normpath: function(path) {
+ if ( path == undefined )
+ return null;
+ if ( path.length <= 0 )
+ return '';
+ if ( path.indexOf('/') < 0 )
+ path = path.replace('\\', '/');
+ var ret = [];
+ var plist = path.split('/');
+ for ( var idx=0 ; idx<plist.length ; idx++ )
+ {
+ var item = plist[idx];
+ if ( item.length <= 0 || item == '.' )
+ continue;
+ if ( item != '..' || ret.length <= 0 || ret[ret.length - 1] == '..' )
+ {
+ ret.push(item);
+ continue;
+ }
+ ret.pop();
}
- });
-
- if (item) {
- _data.installedList[item.id] = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, new Date(),
- item.author, item.description, item.appIds
- );
- event.trigger("install-current-package", [_data.installedList[item.id]]);
- } else {
- _data.installedList[id] = new PackageInformation(
- id, "Tizen pseudo package", "icon.png", "2.2",
- 8264, 50, new Date(),
- "TizenDev", "This is a description which is used in tests.", [tizenAppId]
- );
- event.trigger("install-current-package", [_data.installedList[id]]);
- }
- } else {
- _data.installedList[PSEUDO_PACKAGE_ID] = new PackageInformation(
- PSEUDO_PACKAGE_ID, "Tizen pseudo package", "icon.png", "2.2",
- 8264, 50, new Date(),
- "TizenDev", "This is a description which is used in tests.", [tizenAppId]
- );
- event.trigger("install-current-package", [_data.installedList[PSEUDO_PACKAGE_ID]]);
- }
-}
+ ret = ret.join('/');
+ if ( path.charAt(0) != '/' )
+ return ret;
+ return '/' + ret;
+ },
-function _updatePackage(path, updateFlag) {
- var item, p, info;
+ //-------------------------------------------------------------------------
+ int: function(str, defval) {
+ if ( ! str )
+ return defval;
+ return parseInt(str, 10);
+ },
- if (!_data.packageList[path]) {
- return;
- }
- _get();
- p = _data.packageList[path];
- item = _data.installedList[p.id];
- utils.forEach(_listeners, function (listener) {
- info = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, item.lastModified,
- item.author, item.description, item.appIds);
- if (!updateFlag) {
- listener.oninstalled(info);
- } else {
- listener.onupdated(info);
- }
- });
-}
+ //-------------------------------------------------------------------------
+ cmp: function(a, b) {
+ if ( a < b )
+ return -1;
+ if ( a > b )
+ return 1;
+ return 0;
+ },
-function _initialize() {
- _get();
+ //-------------------------------------------------------------------------
+ // partially emulates python's string.split() method
+ splitn: function(str, sep, limit) {
+ var ret = str.split(sep);
+ if ( ret.length <= ( limit + 1 ) )
+ return ret;
+ var tmp = ret.slice(0, limit);
+ tmp.push(ret.slice(limit).join(sep));
+ return tmp;
+ },
- if (!_data)
- return;
+ //-------------------------------------------------------------------------
+ prettyJson: function(obj, indent) {
+ indent = indent || '';
+ var ret = '';
+ if ( _.isArray(obj) )
+ {
+ if ( obj.length <= 0 )
+ return '[]';
+ ret = '[\n' + indent;
+ _.each(obj, function(el, idx) {
+ ret += ' ' + exports.prettyJson(el, indent + ' ');
+ if ( idx + 1 < obj.length )
+ ret += ',';
+ ret += '\n' + indent;
+ });
+ return ret + ']';
+ }
+ if ( _.isObject(obj) )
+ {
+ var keys = _.keys(obj);
+ if ( keys.length <= 0 )
+ return '{}';
+ keys.sort();
+ ret = '{\n' + indent;
+ _.each(keys, function(key, idx) {
+ ret += ' ' + exports.prettyJson(key)
+ + ': ' + exports.prettyJson(obj[key], indent + ' ');
+ if ( idx + 1 < keys.length )
+ ret += ',';
+ ret += '\n' + indent;
+ });
+ return ret + ( indent.length <= 0 ? '}\n' : '}' );
+ }
+ return JSON.stringify(obj);
+ },
- utils.forEach(_data.installedList, function (item) {
- item.lastModified = new Date(item.lastModified);
- });
+ //-------------------------------------------------------------------------
+ urlEncode: function(dat) {
+ return ( dat == undefined ? dat : encodeURIComponent(dat) );
+ },
- _setupCurrentPackage();
+ //-------------------------------------------------------------------------
+ /*
+ rmfr: function(path, cb) {
+ fs.stat(path, function(err, stats) {
+ if ( err && err.code == 'ENOENT' )
+ return cb();
+ if ( err )
+ return cb(err);
+ if ( ! stats.isDirectory() )
+ return fs.unlink(path, cb);
+ fs.readdir(path, function(err, files) {
+ exports.cascade(files, function(file, cb) {
+ var curpath = pathmod.join(path, file);
+ return exports.rmfr(curpath, cb);
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ fs.rmdir(path, cb);
+ });
+ });
+ });
+ },
+ */
+ //-------------------------------------------------------------------------
+ /*
+ makedirs: function(path, cb) {
+ // node sucks. i can't believe it doesn't provide a fs.makedirs(). wtf.
+ // clean up the path
+ path = pathmod.normalize(path.split(/[\\\/]/).join('/'));
+ var paths = path.split('/');
+ paths = _.map(paths, function(p, idx) {
+ return paths.slice(0, idx + 1).join('/');
+ });
+ if ( path.charAt(0) == '/' )
+ paths.shift();
+ exports.cascade(paths, function(path, cb) {
+ fs.stat(path, function(err, stats) {
+ if ( err && err.code == 'ENOENT' )
+ return fs.mkdir(path, cb);
+ if ( err )
+ return cb(err);
+ if ( stats.isDirectory() )
+ return cb();
+ // this probably won't work, but let's get the error anyhow...
+ return fs.mkdir(path, cb);
+ });
+ }, cb);
+ },
+ */
- event.on("install-packge", function (path) {
- _updatePackage(path, false);
- });
- event.on("update-package", function (path) {
- _updatePackage(path, true);
- });
+ //-------------------------------------------------------------------------
+ StringStream: exports.Stream.extend({
- event.on("uninstall-package", function (id) {
- _get();
- utils.forEach(_listeners, function (listener) {
- listener.onuninstalled(id);
- });
- });
-}
+ constructor: function(initData) {
+ this._data = initData || '';
+ },
-_self = function () {
- var package;
+ write: function(data) {
+ if ( data == undefined )
+ return;
+ this._data += data;
+ },
- // public
- function install(path, progressCallback, errorCallback) {
- if (!_security.install) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ getData: function() {
+ return this._data;
}
- t.PackageManager("install", arguments);
+ }),
- window.setTimeout(function () {
- var intervalId, installedSize = 0, packageSize, updateFlag = false,
- item, info, progress;
+ //-------------------------------------------------------------------------
+ IndentStream: exports.Stream.extend({
- if (!_data.packageList[path]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ //-----------------------------------------------------------------------
+ constructor: function(stream, indent, options) {
+ options = options || {};
+ this._stream = stream;
+ this._indent = indent || ' ';
+ this._cleared = true;
+ this._stayBlank = !! options.stayBlank;
+ },
+
+ //-----------------------------------------------------------------------
+ write: function(data) {
+ var self = this;
+ if ( data == undefined )
+ return;
+ // if ( ! data || ! data.length || data.length <= 0 )
+ // return;
+ var lines = data.split('\n');
+ if ( self._cleared )
+ self._stream.write(self._indent);
+ self._cleared = false;
+ for ( var idx=0 ; idx<lines.length ; idx++ )
+ {
+ var line = lines[idx];
+ if ( line == '' )
+ {
+ if ( idx + 1 >= lines.length )
+ self._cleared = true;
+ else
+ {
+ if ( idx != 0 && ! self._stayBlank )
+ self._stream.write(self._indent);
}
- return;
}
- item = _data.packageList[path];
- if (_data.installedList[item.id]) {
- updateFlag = true;
+ else
+ {
+ if ( idx != 0 || self._cleared )
+ self._stream.write(self._indent);
+ self._stream.write(line);
}
- packageSize = item.totalSize;
- intervalId = setInterval(function () {
- if (installedSize >= packageSize) {
- // Install complete
- _data.installedList[item.id] = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, new Date(),
- item.author, item.description, item.appIds
- );
- event.trigger("install-apps", [item.appIds]);
- _save();
- _exec(progressCallback, "oncomplete", item.id);
- clearInterval(intervalId);
- item = _data.installedList[item.id];
- utils.forEach(_listeners, function (listener) {
- info = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, item.lastModified,
- item.author, item.description, item.appIds);
- if (!updateFlag) {
- listener.oninstalled(info);
- } else {
- listener.onupdated(info);
- }
- });
- event.trigger("installedList-updated");
- } else {
- installedSize += INSTALL_AMOUNT;
- progress = (installedSize > packageSize) ? 100 :
- Math.floor(installedSize * 100 / packageSize);
- _exec(progressCallback, "onprogress", item.id, progress);
- }
- }, INTERVAL);
- }, 1);
- }
-
- function uninstall(id, progressCallback, errorCallback) {
- if (!_security.uninstall) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ if ( idx + 1 < lines.length )
+ self._stream.write('\n');
}
-
- t.PackageManager("uninstall", arguments);
-
- window.setTimeout(function () {
- var intervalId, removedSize = 0, packageSize, item, progress;
-
- if (!_data.installedList[id]) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
- }
- return;
- }
- item = _data.installedList[id];
- packageSize = item.totalSize;
- intervalId = setInterval(function () {
- if (removedSize >= packageSize) {
- utils.forEach(_data.packageList, function (package) {
- if (package.id === id) {
- event.trigger("remove-apps", [package.appIds]);
- }
- });
- delete _data.installedList[item.id];
- _save();
- _exec(progressCallback, "oncomplete", item.id);
- clearInterval(intervalId);
- item = _data.installedList[item.id];
- utils.forEach(_listeners, function (listener) {
- listener.onuninstalled(id);
- });
- event.trigger("installedList-updated");
- } else {
- removedSize += INSTALL_AMOUNT * 10;
- progress = (removedSize > packageSize) ? 100 :
- Math.floor(removedSize * 100 / packageSize);
- _exec(progressCallback, "onprogress", item.id, progress);
- }
- }, INTERVAL);
- }, 1);
- }
-
- function getPackagesInfo(successCallback, errorCallback) {
- if (!_security.getPackagesInfo) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
}
- t.PackageManager("getPackagesInfo", arguments);
-
- window.setTimeout(function () {
- var packageArray = [];
+ })
- utils.forEach(_data.installedList, function (item) {
- var i;
- i = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, item.lastModified,
- item.author, item.description, item.appIds
- );
- packageArray.push(i);
- });
- successCallback(packageArray);
- }, 1);
- }
+ });
- function getPackageInfo(id) {
- var p, item;
+ return exports;
+})();
- if (!_security.getPackageInfo) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+module.exports = _self;
- t.PackageManager("getPackageInfo", arguments);
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/useragent', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.useragent
+// auth: griffin <griffin@uberdev.org>
+// date: 2013/06/07
+// copy: (C) CopyLoose 2013 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- id = id || "api1pack00";
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ _self;
- if (!_data.installedList[id]) {
- throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- }
- item = _data.installedList[id];
- p = new PackageInformation(item.id, item.name, item.iconPath,
- item.version, item.totalSize, item.dataSize, item.lastModified,
- item.author, item.description, item.appIds);
+_self = (function () {
+ var exports = {};
- return p;
- }
+ //---------------------------------------------------------------------------
+ exports.UserAgent = common.Base.extend({
+ // primary handlers:
+ acceptSyncModeSwitch: null, // function(EVENT, CALLBACK(ERR))
+ acceptDevInfoSwap: null, // function(EVENT, CALLBACK(ERR))
+ chooseRefreshRequired: null, // function(EVENT, CALLBACK(ERR, TYPE))
+ fetchCredentials: null, // function(EVENT, CALLBACK(ERR, AUTH))
+ // fallback handlers:
+ accept: null, // function(TYPE, EVENT, CALLBACK(ERR))
+ choose: null, // function(TYPE, EVENT, CALLBACK(ERR, CHOICE))
+ fetch: null, // function(TYPE, EVENT, CALLBACK(ERR, STRUCT))
+ // catchall handler:
+ handle: null // function(ACTION, TYPE, EVENT, CALLBACK(ERR, RESULT...))
+ });
- function setPackageInfoEventListener(eventCallback) {
- if (!_security.setPackageInfoEventListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //---------------------------------------------------------------------------
+ exports.UserAgentMultiplexer = common.Base.extend({
- t.PackageManager("setPackageInfoEventListener", arguments);
+ //-------------------------------------------------------------------------
+ constructor: function(uaList) {
+ this.ualist = uaList;
+ },
- _listeners.push(eventCallback);
+ //-------------------------------------------------------------------------
+ _getHandler: function(name) {
+ for ( var idx=0 ; idx<this.ualist.length ; idx++ )
+ {
+ var ua = this.ualist[idx];
+ if ( ua && _.isFunction(ua[name]) )
+ return ua[name];
}
+ return null;
+ },
- function unsetPackageInfoEventListener() {
- if (!_security.unsetPackageInfoEventListener) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ hasHandler: function(name) {
+ return !! this._getHandler(name);
+ },
- t.PackageManager("unsetPackageInfoEventListener", arguments);
+ //-------------------------------------------------------------------------
+ acceptSyncModeSwitch: function(event, cb) {
+ return this._handle({
+ handler: 'acceptSyncModeSwitch',
+ action: 'accept',
+ type: 'sync.mode.switch'
+ }, event, cb);
+ },
- _listeners = [];
- }
+ //-------------------------------------------------------------------------
+ acceptDevInfoSwap: function(event, cb) {
+ return this._handle({
+ handler: 'acceptDevInfoSwap',
+ action: 'accept',
+ type: 'dev.info.swap'
+ }, event, cb);
+ },
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ //-------------------------------------------------------------------------
+ chooseRefreshRequired: function(event, cb) {
+ return this._handle({
+ handler: 'chooseRefreshRequired',
+ action: 'choose',
+ type: 'refresh.required',
+ choices: [
+ {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
+ {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
+ {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
+ ]
+ }, event, function(err, choice) {
+ if ( err )
+ return cb(err);
+ // todo: catch the condition where `choice` is not a valid synctype
+ return cb(err, common.synctype2alert(choice));
+ });
+ },
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
+ //-------------------------------------------------------------------------
+ fetchCredentials: function(event, cb) {
+ return this._handle({
+ handler: 'fetchCredentials',
+ action: 'fetch',
+ type: 'auth.challenge',
+ choices: [
+ {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
+ {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
+ {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
+ ]
+ }, event, cb);
+ },
+
+ //-------------------------------------------------------------------------
+ _handle: function(spec, event, cb) {
+ event = _.extend({}, spec, event, {
+ type : spec.type,
+ context : event.session.context,
+ adapter : event.session.adapter,
+ peer : event.session.peer,
+ ua_handler : spec.handler,
+ ua_action : spec.action
+ });
+ var handler = this._getHandler(spec.handler);
+ if ( handler )
+ return handler(event, cb);
+ handler = this._getHandler(spec.action);
+ if ( handler )
+ return handler(spec.type, event, cb);
+ handler = this._getHandler('handle');
+ if ( handler )
+ return handler(spec.action, spec.type, event, cb);
+ if ( spec.action == 'accept' )
+ {
+ return cb();
+ }
+ if ( spec.action == 'choose'
+ && event.choices && event.choices.length > 0 )
+ {
+ var choice = _.find(event.choices, function(c) { return c.default; });
+ if ( ! choice )
+ choice = event.choices[0];
+ if ( choice.value )
+ choice = choice.value;
+ return cb(null, choice);
}
+ if ( spec.type == 'auth.challenge' )
+ return cb();
+ return cb(new common.NotImplementedError(
+ 'user-agent handler for event type "' + spec.type + '" (action: "'
+ + spec.action + '") not found or defined'));
}
- }
- package = {
- install: install,
- uninstall: uninstall,
- getPackagesInfo: getPackagesInfo,
- getPackageInfo: getPackageInfo,
- setPackageInfoEventListener: setPackageInfoEventListener,
- unsetPackageInfoEventListener: unsetPackageInfoEventListener,
- handleSubFeatures: handleSubFeatures
- };
+ });
- return package;
-};
+ return exports;
-_initialize();
+})();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/pendingObject', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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 = function (pendingObj) {
- var cancelFlag = true;
- this.setCancelFlag = function (flag) {
- cancelFlag = flag;
- };
- this.getCancelFlag = function () {
- return cancelFlag;
- };
- this.userCancel = null;
- this.pendingID = null;
-};
-
-});
-define('ripple/platform/tizen/2.0/pendingoperation', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+define('ripple/platform/tizen/2.0/syncml-js-lib/adapter', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.adapter
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/10/22
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
-module.exports = function (pendingObj) {
- var pending = true;
- this.cancel = function () {
- if (pending === true) {
- if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
- pending = false;
- // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
- clearTimeout(pendingObj.pendingID);
- return false;
- }
- if (typeof (pendingObj.userCancel) === "function") {
- pendingObj.userCancel();
- }
- clearTimeout(pendingObj.pendingID);
- pending = false;
- return true;
- } else {
- return false;
- }
- };
-};
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store');
-});
-define('ripple/platform/tizen/2.0/poi', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 _self = (function () {
-var OpenMapQuestProvider = require('ripple/platform/tizen/2.0/poiBackend_openmapquest'), // opne.MapQuest.xapi service
- _providers,
- _security = {
- "http://tizen.org/api/poi": [],
- "http://tizen.org/api/poi.read": ["find"],
- "http://tizen.org/api/poi.write": ["add", "remove", "update"],
- all: true
- },
- _self;
+ var exports = {};
-function _initialize() {
- _providers = [new OpenMapQuestProvider({name : "MapQuest", connectivity : "ONLINE", metaData : _security})];
-}
+ //---------------------------------------------------------------------------
+ exports.Adapter = common.Base.extend({
-_self = function () {
- var poi;
+ // //-------------------------------------------------------------------------
+ // constructor: function(context, options, devInfo) {
- poi = {
- getDefaultProvider : function () {
- return _providers[0];
+ //-------------------------------------------------------------------------
+ normUri: function(uri) {
+ return common.normpath(uri);
},
- getProviders : function () {
- return _providers;
+
+ //-------------------------------------------------------------------------
+ getStores: function() {
+ return _.values(this._stores);
},
- handleSubFeatures: function (subFeatures) {
- var i, subFeature;
- for (subFeature in subFeatures) {
- if (_security[subFeature].length === 0) {
- _security.all = true;
- break;
- }
- _security.all = false;
- for (i = 0; i < _security[subFeature].length; i++) {
- _security[_security[subFeature][i]] = true;
- }
- }
- _initialize();
- }
- };
- return poi;
-};
+ //-------------------------------------------------------------------------
+ getStore: function(uri) {
+ return this._stores[this.normUri(uri)];
+ },
-module.exports = _self;
+ //-------------------------------------------------------------------------
+ addStore: function(store, cb) {
+ var self = this;
+ if ( store instanceof storemod.Store )
+ {
+ store.uri = self.normUri(store.uri);
+ store._a = self;
+ }
+ else
+ store = new storemod.Store(this, store);
+ store._updateModel(function(err) {
+ if ( err )
+ return cb(err);
+ self._stores[store.uri] = store;
-});
-define('ripple/platform/tizen/2.0/poiBackend_openmapquest', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ // TODO: remove this sensitivity...
+ if ( ! self.isLocal )
+ return cb();
-var lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
- SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- _security;
+ self._save(self._c._txn(), function(err) {
+ if ( err )
+ return cb(err);
+ cb(null, store);
+ });
+ });
+ },
-function POIPublic(prop) {
- /* This is created for public use */
- var _self, i, copy, attr, _id = null, _providerName = null;
- if (prop.id) {
- _id = prop.id;
- }
- if (prop.providerName) {
- _providerName = prop.providerName;
- }
- _self = {
- name : null,
- categories : [],
- address : null,
- phoneNumbers : [],
- geometry : null,
- urls : [],
- rating : null,
- tags : null,
- toGeoJSON : function () {
- throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
- }
- };
+ //-------------------------------------------------------------------------
+ removeStore: function(uri, cb) {
+ var self = this;
+ if ( ! self.isLocal )
+ // todo: implement
+ return cb(new common.LogicalError(
+ 'cannot remove remote store "' + uri + '": remote peer responsibility'));
+ if ( ! self._stores[uri] )
+ return cb(new common.InternalError(
+ 'cannot remove store "' + uri + '": no such store'));
+ delete self._stores[uri];
+ var model = self._getModel();
+ model.stores = _.filter(model.stores, function(store) {
+ return store.uri != uri;
+ });
+ _.each(model.peers, function(peer) {
+ peer.routes = _.filter(peer.routes, function(route) {
+ return route.localUri != uri;
+ });
+ _.each(peer.stores, function(store) {
+ if ( store.binding && store.binding.uri == uri )
+ store.binding = null;
+ });
+ });
+ return cb();
+ },
- _self.__defineGetter__("id", function () {
- return _id;
- });
+ //-------------------------------------------------------------------------
+ _isMapper: function() {
+ // indicates whether or not this adapter is capable of mapping
+ // items. in the standard SyncML peer model, only the server
+ // ever does mapping, but in the dream-land of syncml-js, all
+ // peers can be mappers, or even better, implements an extension
+ // "is-uuid/adopted" that does not require mapping. so, since
+ // that is just a dream-land for now, this will try to identify
+ // if this adapter represents a server...
+ // todo: enhance syncml-js so that it is not needed!...
+ if ( ! this.isLocal )
+ return this.url && this.url.length > 0;
+ return this.devInfo && this.devInfo.devType == constant.DEVTYPE_SERVER;
+ },
- _self.__defineGetter__("providerName", function () {
- return _providerName;
- });
+ //-------------------------------------------------------------------------
+ describe: function(stream, cb) {
+ var self = this;
+ if ( self.url )
+ stream.writeln('URL: ' + self.url);
+ stream.writeln('Device ID: ' + self.devID);
+ var s1 = stream.indented();
+ var s2 = s1.indented();
- if (prop) {
- if (prop.name) {
- _self.name = String(prop.name);
- }
- if (tizen1_utils.isValidArray(prop.categories)) {
- _self.categories = [];
- for (i in prop.categories) {
- _self.categories.push(String(prop.categories[i]));
- }
- }
- if (prop.address) {
- if (typeof prop.address === "string") {
- _self.address = String(prop.address);
- } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
- copy = prop.address.constructor();
- for (attr in prop.address) {
- if (prop.address.hasOwnProperty(attr)) {
- copy[attr] = prop.address[attr];
- }
+ var describe_stores = function(cb) {
+ var stores = self.getStores();
+ if ( stores.length <= 0 )
+ {
+ stream.writeln('Data stores: (none)');
+ return cb();
}
- _self.address = copy;
- }
- }
- if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
- _self.phoneNumbers = [];
- for (i in prop.phoneNumbers) {
- _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
- }
- }
- if (prop.geometry) {
- _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
- }
- if (tizen1_utils.isValidArray(prop.urls)) {
- _self.urls = [];
- for (i in prop.urls) {
- _self.urls.push(String(prop.urls[i]));
- }
- }
- if (typeof prop.rating === "number") {
- _self.rating = prop.rating;
- }
- if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
- copy = prop.tags.constructor();
- for (attr in prop.tags) {
- if (prop.tags.hasOwnProperty(attr)) {
- copy[attr] = prop.tags[attr];
+ stream.writeln('Data stores:');
+ common.cascade(stores, function(store, cb) {
+ s1.writeln(( store.displayName || store.uri ) + ':');
+ store.describe(s2, cb);
+ }, cb);
+ };
+
+ var describe_peers = function(cb) {
+ if ( ! self.getPeers )
+ return cb();
+ var peers = self.getPeers();
+ if ( peers.length <= 0 )
+ {
+ stream.writeln('Known peers: (none)');
+ return cb();
}
+ stream.writeln('Known peers:');
+ common.cascade(peers, function(peer, cb) {
+ s1.writeln(( peer.displayName || peer.url ) + ':');
+ peer.describe(s2, cb);
+ }, cb);
}
- _self.tags = copy;
+
+ describe_stores(function(err) {
+ if ( err )
+ return cb(err);
+ describe_peers(cb);
+ });
}
- }
- return _self;
-}
+ });
-module.exports = function (prop) {
+ return exports;
- var _self = new lbs.LocationServiceProvider(prop);
+ })();
- if (prop.metaData) {
- _security = prop.metaData;
- }
+ module.exports = _self;
- _self.__defineGetter__("supportedFilterTypes", function () {
- return [];
- });
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.synchronizer
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/05
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
- _self.__defineGetter__("supportedPOIFilterAttributes", function () {
- return [];
- });
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
+ state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
+ protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
+ storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
+ _self;
- _self.__defineGetter__("supportedCategories", function () {
- /* reference: http://wiki.openstreetmap.org/wiki/Map_Features#Amenity */
- return ["bar", "bbq", "biergarten", "cafe", "drinking_water", "fast_food", "food_court", "ice_cream",
- "pub", "restaurant", "college", "kindergarten", "library", "school", "university",
- "bicycle_parking", "bicycle_rental", "bus_station", "car_rental", "car_sharing", "car_wash",
- "ev_charging", "ferry_terminal", "fuel", "grit_bin", "parking", "parking_entrance",
- "parking_space", "taxi", "atm", "bank", "bureau_de_change", "baby_hatch", "clinic",
- "dentist", "doctors", "hospital", "nursing_home", "pharmacy", "social_facility", "veterinary",
- "arts_centre", "cinema", "community_centre", "fountain", "nightclub", "social_centre",
- "stripclub", "studio", "swingerclub", "theatre", "bench", "brothel", "clock", "courthouse",
- "crematorium", "embassy", "fire_station", "grave_yard", "hunting_stand", "marketplace",
- "place_of_worship", "police", "post_box", "post_office", "prison", "public_building",
- "recycling", "sauna", "shelter", "shower", "telephone", "toilets", "townhall", "vending_machine",
- "waste_basket", "waste_disposal", "watering_place"];
- });
+_self = (function () {
- _self.__defineGetter__("capabilities", function () {
- /* The set is empty, indicating that this provider supports only 'find' operations */
- return [];
- });
+ var exports = {};
+ var badStatus = protocol.badStatus;
- _self.find = function (point, successCallback, errorCallback, options) {
- /* This provider only supports searching by "GeoRectBounds" due to MapQuest XAPI limitation */
+ //---------------------------------------------------------------------------
+ exports.Synchronizer = common.Base.extend({
- function _find() {
- var searchStr, pois = [], isTypeOK = false,
- id, providerName, name, categories = [], geometry;
+ //-------------------------------------------------------------------------
+ constructor: function(options) {
+ },
- if (Object.prototype.toString.call(point) === "[object Object]") {
- if (point.southWest && point.northEast) {
- if (typeof point.southWest.latitude === "number" &&
- typeof point.southWest.longitude === "number" &&
- typeof point.northEast.latitude === "number" &&
- typeof point.northEast.longitude === "number") {
- isTypeOK = true;
+ //-------------------------------------------------------------------------
+ initStoreSync: function(session, cb) {
+ async.eachSeries(session.peer._getModel().stores, function(rstore, cb) {
+ // TODO: should the server-side be doing this? probably not
+ // since store mapping is a client-side decision...
+ var ruri = session.peer.normUri(rstore.uri);
+ if ( session.info.dsstates[ruri] || ! rstore.binding )
+ return cb();
+ var lstore = session.adapter.getStore(rstore.binding.uri);
+ if ( ! lstore || ! lstore.agent )
+ return cb();
+ var ds = state.makeStoreSyncState({
+ uri : lstore.uri,
+ peerUri : ruri,
+ lastAnchor : rstore.binding.localAnchor,
+ mode : session.info.mode || constant.ALERT_TWO_WAY,
+ action : 'alert'
+ });
+ if ( ! ds.lastAnchor )
+ {
+ switch ( ds.mode )
+ {
+ case constant.ALERT_SLOW_SYNC:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ {
+ break;
+ }
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ {
+ if ( session.info.mode == constant.SYNCTYPE_AUTO )
+ {
+ ds.mode = constant.ALERT_SLOW_SYNC;
+ break;
+ }
+ var uaEvent = {
+ session : session,
+ store : lstore,
+ peerStore : rstore,
+ modeReq : ds.mode
+ };
+ return session.ua.chooseRefreshRequired(uaEvent, function(err, mode) {
+ if ( err )
+ return cb(err);
+ if ( ! _.contains([constant.ALERT_SLOW_SYNC,
+ constant.ALERT_REFRESH_FROM_CLIENT,
+ constant.ALERT_REFRESH_FROM_SERVER], mode) )
+ return cb(new common.TypeError(
+ 'invalid mode chosen for refresh: ' + common.j(mode)));
+ ds.mode = mode;
+ session.info.dsstates[ds.uri] = ds;
+ return cb();
+ });
+ }
+ default:
+ {
+ return cb(new common.InternalError(
+ 'unexpected sync mode "' + ds.mode + '" requested'));
}
- }
}
-
- if (!isTypeOK) {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
+ session.info.dsstates[ds.uri] = ds;
+ return cb();
+ }, cb);
+ },
- searchStr = "http://open.mapquestapi.com/xapi/api/0.6/node";
- if (options && tizen1_utils.isValidArray(options.categories) &&
- options.categories.length > 0 && typeof options.categories[0] === "string") {
- /* xapi support single amenity only */
- searchStr += "[amenity=" + options.categories[0] + "]";
- }
- searchStr += "[bbox=" + point.southWest.longitude + "," + point.southWest.latitude + "," +
- point.northEast.longitude + "," + point.northEast.latitude + "]";
+ //-------------------------------------------------------------------------
+ // SYNCHRONIZATION PHASE: ACTION
+ //-------------------------------------------------------------------------
- /* use Open MapQuest online xapi service. (http://open.mapquestapi.com/xapi/) */
- $.ajax({
- type: "GET",
- url: searchStr,
- dataType: "xml",
- timeout: 15000, /* 15 secs timeout */
- success: function (xml) {
- providerName = $(xml).find("osm").attr("generator");
- $(xml).find("node").each(function () {
- var $item = $(this);
- categories = [];
- id = $item.attr("id");
- geometry = new POIGeometry(new SimpleCoordinates($item.attr("lat"), $item.attr("lon")));
- $item.find("tag").each(function () {
- if ($(this).attr("k") === "name") {
- name = $(this).attr("v");
- } else if ($(this).attr("k") === "amenity") {
- categories.push($(this).attr("v"));
- }
- });
- pois.push(new POIPublic({id: id, providerName: providerName, name: name,
- categories: categories, geometry: geometry}));
- });
- successCallback(pois);
- },
- error: function (obj, msg) {
- if (errorCallback) {
- if (msg === "timeout") {
- setTimeout(function () {
- errorCallback(new WebAPIError(errorcode.TIMEOUT_ERR));
- }, 1);
- } else {
- setTimeout(function () {
- errorCallback(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- }
- }
+ //-------------------------------------------------------------------------
+ actions: function(session, commands, cb) {
+ var self = this;
+ common.cascade(_.keys(session.info.dsstates), function(uri, cb) {
+ var ds = session.info.dsstates[uri];
+ if ( ds.action == 'done' )
+ return cb();
+ // TODO: is this the right handling of an "error" dsstate?...
+ if ( ds.action == 'error' )
+ return cb();
+ var func = self['_action_' + ds.action.toLowerCase()];
+ if ( ! func )
+ return cb(new common.InternalError(
+ 'unexpected store action "' + ds.action + '"'));
+ try{
+ func.call(self, session, ds, function(err, cmds) {
+ if ( err )
+ return cb(err);
+ _.each(cmds, function(cmd) { commands.push(cmd); });
+ return cb();
+ });
+ }catch(e){
+ return cb(new common.InternalError(
+ 'failed invoking synchronizer action: ' + e, e));
+ }
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, commands);
});
- }
-
- if (!_security.all && !_security.find) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
-
- tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
- };
+ },
- _self.update = function (poi, successCallback, errorCallback) {
- if (!_security.all && !_security.update) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ _action_alert: function(session, dsstate, cb) {
- throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
- };
+ var src = session.adapter.getStore(dsstate.uri);
+ var tgt = session.peer.getStore(dsstate.peerUri);
- _self.add = function (poi, successCallback, errorCallback) {
- if (!_security.all && !_security.add) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
+ // TODO: ensure that mode is acceptable...
- throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
- };
+ // todo: perhaps i should only specify maxObjSize if it differs from
+ // adapter.maxObjSize?...
- _self.remove = function (poi, successCallback, errorCallback) {
- if (!_security.all && !_security.remove) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_ALERT,
+ cmdID : session.nextCmdID(),
+ data : dsstate.mode,
+ source : src.uri,
+ target : tgt.uri,
+ lastAnchor : dsstate.lastAnchor,
+ nextAnchor : dsstate.nextAnchor,
+ maxObjSize : src.maxObjSize,
+ })]);
- throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
- };
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ _action_send: function(session, dsstate, cb) {
+ var store = session.adapter.getStore(dsstate.uri);
+ var agent = store.agent;
+ var peerStore = session.peer.getStore(dsstate.peerUri);
-});
-define('ripple/platform/tizen/2.0/power', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 event = require('ripple/event'),
- constants = require('ripple/constants'),
- deviceSettings = require('ripple/deviceSettings'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- _POWER_RESOURCE = constants.POWER_RESOURCE,
- _SCREEN_STATE = constants.POWER_RESOURCE.SCREEN.STATE,
- ScreenState = {"previous" : null, "current" : null},
- _listeners = [],
- _isScreenResourceOccupied = false,
- _originalBrightness,
- _isCPUAwake = false,
- _isScreenOn = true,
- _normalBrightness,
- _minimal_screen_state = null,
- _security = {
- "http://tizen.org/privilege/power": ["request", "setScreenBrightness", "turnScreenOn", "turnScreenOff"]
- },
- _self;
+ var cmd = state.makeCommand({
+ name : constant.CMD_SYNC,
+ cmdID : session.nextCmdID(),
+ source : dsstate.uri,
+ // target : adapter.router.getTargetUri(uri),
+ target : dsstate.peerUri
+ });
-/**initialize**/
-function initState() {
- _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
- updateResourceState();
-}
+ switch ( dsstate.mode )
+ {
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_SLOW_SYNC:
+ case constant.ALERT_ONE_WAY_FROM_CLIENT:
+ case constant.ALERT_REFRESH_FROM_CLIENT:
+ case constant.ALERT_ONE_WAY_FROM_SERVER:
+ case constant.ALERT_REFRESH_FROM_SERVER:
+ // todo: these should only be received out-of-band, right?...
+ // case constant.ALERT_TWO_WAY_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
+ // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
+ // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
+ {
+ break;
+ }
+ default:
+ {
+ return cb(new common.InternalError(
+ 'unexpected sync mode "' + common.mode2string(dsstate.mode) + '"'));
+ }
+ }
-function getResourceState(value) {
- var state;
- value = Number(value);
- if (value <= _SCREEN_STATE.SCREEN_OFF.MAX) {
- state = _SCREEN_STATE.SCREEN_OFF.NAME;
- } else if (value < _SCREEN_STATE.SCREEN_DIM.MAX) {
- state = _SCREEN_STATE.SCREEN_DIM.NAME;
- } else if (value < _SCREEN_STATE.SCREEN_NORMAL.MAX) {
- state = _SCREEN_STATE.SCREEN_NORMAL.NAME;
- } else {
- state = _SCREEN_STATE.SCREEN_BRIGHT.NAME;
- }
- return state;
-}
+ if ( session.isServer )
+ {
+ if ( dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT
+ || dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT )
+ {
+ cmd.noc = 0;
+ return cb(null, [cmd]);
+ }
+ }
-function updateResourceState() {
- var brightness, actualState;
- brightness = deviceSettings.retrieve("DISPLAY.brightness");
- actualState = getResourceState(brightness);
- ScreenState.previous = ScreenState.current;
- ScreenState.current = actualState;
-}
+ if ( ! session.isServer )
+ {
+ if ( dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER
+ || dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER )
+ {
+ cmd.noc = 0;
+ return cb(null, [cmd]);
+ }
+ }
-function callListeners(listeners, previousState, changedState) {
- listeners.forEach(function (listener) {
- setTimeout(function () {
- listener(previousState, changedState);
- }, 1);
- });
-}
+ switch ( dsstate.mode )
+ {
-function triggerListenerCB(stateObj) {
- if (stateObj.previous !== stateObj.current) {
- callListeners(_listeners, stateObj.previous, stateObj.current);
- }
-}
+ case constant.ALERT_TWO_WAY:
+ case constant.ALERT_ONE_WAY_FROM_CLIENT: // when ! session.isServer
+ case constant.ALERT_ONE_WAY_FROM_SERVER: // when session.isServer
+ {
+ // send local changes
-_self = function () {
- function request(resource, state) {
- if (!_security.request) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
- if (typeof resource !== 'string' || typeof state !== 'string') {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
- //Check resource
- if (!_POWER_RESOURCE.hasOwnProperty(resource)) {
- throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
- }
- //Check state
- if (!_POWER_RESOURCE[resource].STATE.hasOwnProperty(state)) {
- throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
- }
- // Exception check: SCREEN_OFF is a state cannot be requested
- if (resource === "SCREEN" && state === "SCREEN_OFF") {
- throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
- }
- switch (resource) {
- case "SCREEN" :
- if ((_minimal_screen_state === null) ||
- (_minimal_screen_state === "SCREEN_DIM" && (state === "SCREEN_NORMAL" || state === "SCREEN_BRIGHT")) ||
- (_minimal_screen_state === "SCREEN_NORMAL" && state === "SCREEN_BRIGHT")) {
- _minimal_screen_state = state;
- }
- break;
- case "CPU" :
- _isCPUAwake = true;
- break;
- default:
- break;
- }
- }
+ storage.getAll(
+ session.context,
+ session.txn().objectStore('change').index('store_id'),
+ {only: peerStore.id},
+ function(err, changes) {
+ if ( err )
+ return cb(err);
+ var ctype = session.context.router.getBestTransmitContentType(
+ session.adapter, session.peer, dsstate.uri);
+ cmd.data = [];
- function release(resource) {
- switch (resource) {
- case "SCREEN" :
- if (_isScreenResourceOccupied) {
- _isScreenResourceOccupied = false;
- deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
- event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
- updateResourceState();
- triggerListenerCB(ScreenState);
- }
- _minimal_screen_state = null;
- break;
- case "CPU" :
- _isCPUAwake = false;
- break;
- default:
- if (typeof resource === "string") {
- throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
- } else {
- throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- }
- }
- }
+ // TODO: add support for hierarchical operations...
+ // including MOVE, COPY, etc.
- function setScreenStateChangeListener(listener) {
- tizen1_utils.validateArgumentType(listener, "function",
- new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
- _listeners.push(listener);
- }
+ // TODO: this assumes that the entire object set can fit in memory...
+ // perhaps, as a work-around, just keep a reference to the object
+ // and then stream-based serialize it actually gets converted to
+ // XML.
- function unsetScreenStateChangeListener() {
- _listeners = [];
- }
+ common.cascade(changes, function(change, cb) {
- function getScreenBrightness() {
- var brightness = deviceSettings.retrieve("DISPLAY.brightness");
- return brightness;
- }
+ if ( dsstate.conflicts && _.indexOf(dsstate.conflicts, change.item_id) >= 0 )
+ return cb();
- function setScreenBrightness(brightness) {
- if (!_security.setScreenBrightness) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
- if (typeof brightness !== 'number') {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
- }
- if (brightness < 0 || brightness > 1) {
- throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
- }
- if (!_isScreenResourceOccupied) {
- _originalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
- _isScreenResourceOccupied = true;
- }
- deviceSettings.persist("DISPLAY.brightness", brightness);
- event.trigger("DisplayBrightnessChangedByPower", [brightness]);
- updateResourceState();
- triggerListenerCB(ScreenState);
- }
+ var scmdtype = null;
+ switch ( change.state )
+ {
+ case constant.ITEM_ADDED: scmdtype = constant.CMD_ADD; break;
+ case constant.ITEM_MODIFIED: scmdtype = constant.CMD_REPLACE; break;
+ case constant.ITEM_DELETED: scmdtype = constant.CMD_DELETE; break;
+ default:
+ {
+ return cb();
+ }
+ }
- function isScreenOn() {
- return _isScreenOn;
- }
+ // todo: do something with the ctype version (ie. ctype[1])?...
+ var scmd = state.makeCommand({
+ name : scmdtype,
+ cmdID : session.nextCmdID(),
+ format : constant.FORMAT_AUTO,
+ type : change.state != constant.ITEM_DELETED ? ctype[0] : null,
+ uri : dsstate.uri
+ });
- function restoreScreenBrightness() {
- if (_isScreenResourceOccupied) {
- _isScreenResourceOccupied = false;
- deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
- event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
- updateResourceState();
- triggerListenerCB(ScreenState);
- }
- }
+ // TODO: need to add hierarchical addition support here...
- function turnScreenOn() {
- var brightness, value, flag = false;
- if (!_security.turnScreenOn) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
- brightness = deviceSettings.retrieve("DISPLAY.brightness");
- switch (_minimal_screen_state) {
- case "SCREEN_DIM":
- if (brightness <= _SCREEN_STATE.SCREEN_OFF.VALUE) {
- if (!_isScreenResourceOccupied) {
- _originalBrightness = brightness;
- _isScreenResourceOccupied = true;
- }
- value = _SCREEN_STATE.SCREEN_DIM.VALUE;
- flag = true;
- }
- break;
- case "SCREEN_NORMAL":
- if (brightness < _SCREEN_STATE.SCREEN_NORMAL.MIN) {
- if (!_isScreenResourceOccupied) {
- _originalBrightness = brightness;
- _isScreenResourceOccupied = true;
- }
- value = _normalBrightness;
- flag = true;
- }
- break;
- case "SCREEN_BRIGHT":
- if (brightness < _SCREEN_STATE.SCREEN_BRIGHT.MIN) {
- if (!_isScreenResourceOccupied) {
- _originalBrightness = brightness;
- _isScreenResourceOccupied = true;
- }
- value = _SCREEN_STATE.SCREEN_BRIGHT.VALUE;
- flag = true;
- }
- break;
- }
- if (flag) {
- deviceSettings.persist("DISPLAY.brightness", value);
- event.trigger("DisplayBrightnessChangedByPower", [value]);
- updateResourceState();
- triggerListenerCB(ScreenState);
- }
- _isScreenOn = true;
- }
+ var set_data = scmdtype == constant.CMD_DELETE ? common.noop : function(cb) {
- function turnScreenOff() {
- if (!_security.turnScreenOff) {
- throw new WebAPIError(errorcode.SECURITY_ERR);
- }
- _isScreenOn = false;
- }
+ agent.getItem(change.item_id, function(err, item) {
+ if ( err )
+ return cb(err);
+ agent.dumpsItem(item, ctype[0], ctype[1], function(err, data, nct, nv) {
+ if ( err )
+ return cb(err);
+ scmd.data = data;
+ scmd.type = nct || scmd.type;
+ // todo: what to do with the content-type version?... eg.
+ // scmd.version = nv || scmd.version;
+ // TODO: support hierarchical sync
+ // if ( agent.hierarchicalSync && item.parent )
+ // scmd.sourceParent = '' + item.parent
+ return cb();
+ });
+ });
+ };
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ var set_target = scmdtype == constant.CMD_ADD ? function(cb) {
+ scmd.source = change.item_id;
+ cb();
+ } : function(cb) {
+ if ( ! session.isServer )
+ {
+ scmd.source = change.item_id;
+ return cb();
+ }
+ peerStore._getMapping(change.item_id, function(err, luid) {
+ if ( err )
+ return cb(err);
+ if ( luid )
+ scmd.target = luid;
+ else
+ scmd.source = change.item_id;
+ cb();
+ });
+ };
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+ set_data(function(err) {
+ if ( err )
+ return cb(err);
+ set_target(function(err) {
+ if ( err )
+ return cb(err);
+ cmd.data.push(scmd);
+ return cb();
+ });
+ });
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ cmd.noc = cmd.data.length;
+ return cb(null, [cmd]);
+ });
+ }
+ );
+ return;
+ }
+ case constant.ALERT_SLOW_SYNC:
+ case constant.ALERT_REFRESH_FROM_SERVER: // when session.isServer
+ case constant.ALERT_REFRESH_FROM_CLIENT: // when ! session.isServer
+ {
+ // todo: this approach assumes that the entire object set can fit
+ // in memory... perhaps move to an iterator-based approach?...
+ cmd.data = [];
- var power = {
- request: request,
- release: release,
- setScreenStateChangeListener: setScreenStateChangeListener,
- unsetScreenStateChangeListener: unsetScreenStateChangeListener,
- getScreenBrightness: getScreenBrightness,
- setScreenBrightness: setScreenBrightness,
- isScreenOn: isScreenOn,
- restoreScreenBrightness: restoreScreenBrightness,
- turnScreenOn: turnScreenOn,
- turnScreenOff: turnScreenOff,
- handleSubFeatures : handleSubFeatures
- };
+ agent.getAllItems(function(err, items) {
- return power;
-};
+ if ( err )
+ return cb(err);
-initState();
-event.on("CpuLoadChanged", function (value) {
- var load;
- if (_isCPUAwake && Number(value) === 0) {
- load = _POWER_RESOURCE.CPU.STATE.CPU_AWAKE.DEFAULT_VALUE;
- deviceSettings.persist("CPU.load", load);
- event.trigger("CpuLoadChangedByPower", [load]);
- }
-});
-event.on("DisplayBrightnessChanged", function () {
- _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
- updateResourceState();
- triggerListenerCB(ScreenState);
-});
+ // TODO: support hierarchical sync...
-module.exports = _self;
+ if ( agent.hierarchicalSync )
+ {
+ return cb(new common.NotImplementedError('hierarchical-sync'));
+ // orditems = [] # the ordered items
+ // dunitems = dict() # lut of the ordered items
+ // curitems = dict() # lut of current items (for loop detection)
+ // lutitems = dict([(item.id, item) for item in items])
+ // def appenditem(item):
+ // if item.id in dunitems:
+ // return
+ // if item.id in curitems:
+ // raise common.LogicalError('recursive item hierarchy detected at item %r' % (item,))
+ // curitems[item.id] = True
+ // if item.parent is not None:
+ // appenditem(lutitems[item.parent])
+ // orditems.append(item)
+ // dunitems[item.id] = item
+ // for item in items:
+ // curitems = dict()
+ // appenditem(item)
+ }
-});
-define('ripple/platform/tizen/2.0/push', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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 ctype = session.context.router.getBestTransmitContentType(
+ session.adapter, session.peer, dsstate.uri);
-var event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- Notification = require('ripple/platform/tizen/2.0/notification'),
- StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- PushMessage,
- _data = {
- service: {
-/* "ID_APPLICATION_0": {
- * appId: null,
- * registrationId: null,
- * appControl: null,
- * isRegistered: false,
- * isConnected: false,
- * onpushed: null
- * }
- */
- }
- },
- _security = {
- "http://tizen.org/privilege/push": ["registerService",
- "unregisterService", "connectService", "disconnectService",
- "getRegistrationId"]
- },
- _self;
+ common.cascade(items, function(item, cb) {
-function _initialize() {
- event.on("PushNotified", function (appId, pushMessage) {
- var appService, notificationDict, statusNotification, notification;
+ // TODO: these should all be non-deleted items, right?...
- appService = _data.service[appId];
+ if ( _.indexOf(dsstate.conflicts, '' + item.id) >= 0 )
+ return cb();
- if (!appService)
- return;
+ // note: need to check for mappings since on slow-sync, the
+ // server will already have received the client's "add" commands
+ // at this point (and therefore should not send them back...)
+ var check_sync = function(cb) {
+ if ( ! session.isServer )
+ return cb(null, true);
+ peerStore._getMapping(item.id, function(err, luid) {
+ return cb(err, luid ? false : true);
+ });
+ };
- if (appService.isConnected) {
- appService.onpushed(new PushMessage(pushMessage));
- } else {
- notificationDict = {
- content: pushMessage.appData,
- appControl: appService.appControl,
- appId: appId
- };
- statusNotification = new StatusNotification("SIMPLE",
- pushMessage.alertMessage, notificationDict);
- notification = new Notification();
+ check_sync(function(err, dosync) {
+ if ( err )
+ return cb(err);
- notification.post(statusNotification);
- }
- });
-}
+ if ( ! dosync )
+ return cb();
-function _getCurrentApplicationId() {
- return "ID_APPLICATION_0";
-}
+ agent.dumpsItem(
+ item, ctype[0], ctype[1],
+ function(err, data, new_ct, new_v) {
-_self = function () {
- var push;
+ if ( err )
+ return cb(err);
- function registerService(appControl, successCallback, errorCallback) {
- if (!_security.registerService) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // todo: do something with the content-type version...
+ var scmd = state.makeCommand({
+ name : constant.CMD_ADD,
+ cmdID : session.nextCmdID(),
+ format : constant.FORMAT_AUTO,
+ type : new_ct || ctype[0],
+ uri : dsstate.uri,
+ source : '' + item.id,
+ data : data
+ });
- t.PushManager("registerService", arguments, true);
+ if ( agent.hierarchicalSync )
+ {
+ // TODO: support hierarchical sync...
+ // if agent.hierarchicalSync and item.parent is not None:
+ // scmd.sourceParent = str(item.parent)
+ return cb(new common.NotImplementedError('hierarchical-sync'));
+ }
- window.setTimeout(function () {
- var appId, appService;
+ cmd.data.push(scmd);
+ return cb();
+ });
- appId = _getCurrentApplicationId();
- appService = {
- appId: appId,
- registrationId: null,
- appControl: appControl,
- isRegistered: false
- };
- _data.service[appId] = appService;
+ });
- event.trigger("PushRequest", ["REGISTER", appService], true);
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ cmd.noc = cmd.data.length;
+ return cb(null, [cmd]);
+ });
- if (appService.registrationId === null) {
- if (errorCallback) {
- errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
- }
- return;
+ });
+ return;
+ }
}
- appService.isRegistered = true;
- successCallback(appService.registrationId);
- }, 1);
- }
+ return cb(new common.InternalError(
+ 'unexpected sync situation (action=' + dsstate.action
+ + ', mode=' + common.mode2string(dsstate.mode)
+ + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));
+ },
- function unregisterService(successCallback, errorCallback) {
- if (!_security.unregisterService) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ //-------------------------------------------------------------------------
+ _action_save: function(session, dsstate, cb) {
+ if ( ! session.isServer )
+ // TODO: for now, only servers should take the "save" action - the client
+ // will explicitly do this at the end of the .sync() method.
+ // ... mostly because clients don't call synchronizer.actions()
+ // one final time ...
+ // *BUT* perhaps that should be changed?... for example, .sync()
+ // could call synchronizer.actions() to cause action_save's to occur
+ // *AND* verify that synchronizer.actions() does not return anything...
+ return cb(new common.InternalError(
+ 'unexpected sync save situation (action=' + dsstate.action
+ + ', mode=' + common.mode2string(dsstate.mode)
+ + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));
- t.PushManager("unregisterService", arguments);
+ var peerStore = session.peer.getStore(dsstate.peerUri);
+ var binding = peerStore._getBinding();
+ binding.localAnchor = dsstate.nextAnchor;
+ binding.remoteAnchor = dsstate.peerNextAnchor;
+ return cb(null);
+ },
- window.setTimeout(function () {
- var appId;
+ //-------------------------------------------------------------------------
+ // SYNCHRONIZATION PHASE: REACTION
+ //-------------------------------------------------------------------------
- appId = _getCurrentApplicationId();
- delete _data.service[appId];
- event.trigger("PushRequest", ["UNREGISTER", appId]);
- if (successCallback) {
- successCallback();
- }
- }, 1);
- }
+ //-------------------------------------------------------------------------
+ reactions: function(session, commands, cb) {
+ var self = this;
+ var ret = [];
+ session.hierlut = null;
+ common.cascade(commands, function(cmd, cb) {
+ var func = self['_reaction_' + cmd.name.toLowerCase()];
+ if ( ! func )
+ return cb(new common.InternalError(
+ 'unexpected store reaction "' + cmd.name + '"'));
+ try{
+ func.call(self, session, cmd, function(err, cmds) {
+ if ( err ) {
+ return cb(err);
+ }
+ _.each(cmds, function(cmd) { ret.push(cmd); });
+ return cb();
+ });
+ }catch(e){
+ return cb(new common.InternalError(
+ 'failed invoking synchronizer reaction: ' + e, e));
+ }
+ }, function(err) {
+ session.hierlut = null;
+ if ( err )
+ return cb(err);
+ return cb(null, ret);
+ });
+ },
+
+ //-------------------------------------------------------------------------
+ _reaction_sync: function(session, command, cb) {
+ var self = this;
+ var ret = [state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : command.msgID,
+ cmdRef : command.cmdID,
+ targetRef : command.target,
+ sourceRef : command.source,
+ statusOf : command.name,
+ statusCode : constant.STATUS_OK
+ })];
+ var store = session.adapter.getStore(session.adapter.normUri(command.target));
+ var dsstate = session.info.dsstates[store.uri];
+ if ( ! store.agent )
+ {
+ // todo: this is a bit different handling than anywhere else...
+ // should everywhere else be like here, or the other way
+ // round?...
+ // the "REAL BIG ISSUE" is that atomicity of the changes
+ // is a little vague at this point...
+ dsstate.stats.hereErr += 1;
+ dsstate.action = 'error';
+ dsstate.error = {
+ message: 'Sync agent for store "' + store.uri + '" not available',
+ code: 'syncml-js.TypeError'
+ };
+ ret[0].statusCode = constant.STATUS_SERVICE_UNAVAILABLE;
+ ret[0].errorMsg = dsstate.error.message;
+ ret[0].errorCode = dsstate.error.code;
+ return cb(null, ret);
+ }
- function connectService(notificationCallback) {
- var appId, appService;
+ if ( store.agent.hierarchicalSync )
+ session.hierlut = {};
- if (!_security.connectService) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ var preprocess = common.noop;
- t.PushManager("connectService", arguments);
+ if ( ( ! session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER )
+ || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) )
+ {
+ // delete all local items
+ preprocess = function(cb) {
+ store.agent.getAllItems(function(err, items) {
+ if ( err )
+ return cb(err);
+ common.cascade(items, function(item, cb) {
+ store.agent.deleteItem(item.id, function(err) {
+ if ( err )
+ return cb(err);
+ dsstate.stats.hereDel += 1;
+ if ( ! session.isServer )
+ return cb();
+ store.registerChange(item.id, constant.ITEM_DELETED,
+ {excludePeerID: session.peer.id}, cb);
+ });
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ return store.getPeerStore(session.peer)._delChange({}, cb);
+ });
+ });
+ };
+ }
- appId = _getCurrentApplicationId();
- appService = _data.service[appId];
- if (!appService || !appService.isRegistered) {
- throw new WebAPIException(errorcode.UNKNOWN_ERR);
- }
+ if ( dsstate.mode == constant.ALERT_SLOW_SYNC
+ || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
+ {
+ // delete all mappings and pending changes
+ var peerStore = store.getPeerStore(session.peer);
+ var prepreprocess = preprocess;
+ preprocess = function(cb) {
+ prepreprocess(function(err) {
+ if ( err )
+ return cb(err);
+ peerStore._delChange({}, function(err) {
+ if ( err )
+ return cb(err);
+ peerStore._clearAllMappings(cb);
+ });
+ });
+ };
+ }
- appService.isConnected = true;
- appService.onpushed = notificationCallback;
- event.trigger("PushRequest", ["CONNECT", appId]);
- }
+ preprocess(function(err) {
+ if ( err )
+ return cb(err);
- function disconnectService() {
- var appId, appService;
+ if ( command.data.length <= 0 )
+ return cb(null, ret);
- if (!_security.disconnectService) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ // paranoia: verify that i should be receiving data...
+ if ( ! ( dsstate.mode == constant.ALERT_TWO_WAY
+ || dsstate.mode == constant.ALERT_SLOW_SYNC
+ || ( ! session.isServer
+ && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER
+ || dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
+ || ( session.isServer
+ && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT
+ || dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) ) ) )
+ return cb(new common.ProtocolError(
+ 'unexpected sync data (role="'
+ + ( session.isServer ? 'server' : 'client' )
+ + '", mode="' + common.mode2string(dsstate.mode)
+ + '")'));
- t.PushManager("disconnectService", arguments);
+ common.cascade(command.data, function(cmd, cb) {
- appId = _getCurrentApplicationId();
- appService = _data.service[appId];
- if (!appService || !appService.isRegistered ||
- !appService.isConnected) {
- return;
- }
+ // NOTE: commented this paranoia setting out, since the server
+ // *may* decide to update/delete a client item...
+ // e.g. conflict-resolved-merge (207)
+ // TODO: perhaps i should only allow non-ADDs for those items
+ // that i received a conflict-resolved-merge (207) for?...
- appService.onpushed = null;
- appService.isConnected = false;
- event.trigger("PushRequest", ["DISCONNECT", appId]);
- }
+ // // paranoia: non-'add' sync commands should only be received in non-refresh modes
+ // if ( cmd.name != constant.CMD_ADD
+ // && _.indexOf([constant.ALERT_TWO_WAY,
+ // constant.ALERT_ONE_WAY_FROM_SERVER,
+ // constant.ALERT_ONE_WAY_FROM_CLIENT], dsstate.mode) < 0 )
+ // return cb(new common.ProtocolError(
+ // 'unexpected non-add sync command (role="'
+ // + ( session.isServer ? 'server' : 'client' )
+ // + '", mode="' + common.mode2string(dsstate.mode)
+ // + '", command="' + cmd.name
+ // + '")'));
- function getRegistrationId() {
- var appService;
+ self._reaction_syncdispatch(session, cmd, store, dsstate, function(err, cmds) {
+ if ( err )
+ return cb(err);
+ _.each(cmds, function(cmd) { ret.push(cmd); });
+ return cb();
+ });
- if (!_security.getRegistrationId) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, ret);
+ });
+ });
+ },
- t.PushManager("getRegistrationId", arguments);
+ //-------------------------------------------------------------------------
+ _reaction_syncdispatch: function(session, cmd, store, dsstate, cb) {
- appService = _data.service[_getCurrentApplicationId()];
- if (!appService || !appService.isRegistered) {
- return null;
- }
+ var self = this;
+ var func = self['_reaction_sync_' + cmd.name.toLowerCase()];
+ if ( ! func )
+ return cb(new common.ProtocolError(
+ 'unexpected reaction requested for sync command "' + cmd.name + '"'));
- return appService.registrationId;
- }
+ var check_for_conflicts = common.noop;
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ if ( session.isServer
+ && cmd.name != constant.CMD_ADD
+ && dsstate.mode != constant.ALERT_REFRESH_FROM_CLIENT )
+ {
+ // server, non-add, non-slowsync, non-refresh commands: check for conflicts.
+ // note that certain types of content could be a conflict even if it is an
+ // "Add" command; for example, two files with the same name cannot be added
+ // from separate clients.
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+ check_for_conflicts = function(cb) {
- push = {
- registerService: registerService,
- unregisterService: unregisterService,
- connectService: connectService,
- disconnectService: disconnectService,
- getRegistrationId: getRegistrationId,
- handleSubFeatures: handleSubFeatures
- };
+ // todo: allow agents to raise a ConflictError...
+ // ==> perhaps this is already covered by the .matchItem() API?...
- return push;
-};
+ var policy = store.conflictPolicy || session.adapter.conflictPolicy;
+ var peerStore = session.peer.getStore(dsstate.peerUri);
+ self.getSourceMapping(
+ session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
+ function(err, itemID) {
-_initialize();
+ if ( err )
+ return cb(err);
+ if ( ! itemID )
+ // this shouldn't happen...
+ return cb();
-PushMessage = function (pushMessageInitDict) {
- var appData, alertMessage, date;
+ peerStore._getChange(itemID, function(err, change) {
+ if ( err )
+ return cb(err);
+ if ( ! change )
+ return cb();
- this.__defineGetter__("appData", function () {
- return appData;
- });
+ var retcmd = state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : cmd.msgID,
+ cmdRef : cmd.cmdID,
+ sourceRef : cmd.source,
+ targetRef : cmd.target,
+ statusOf : cmd.name,
+ // todo: make this error message a bit more descriptive...
+ errorMsg : 'command "' + cmd.name + '" conflict for item ID "'
+ + itemID + '" (state: ' + common.state2string(change.state) + ')'
+ });
- this.__defineGetter__("alertMessage", function () {
- return alertMessage;
- });
- this.__defineGetter__("date", function () {
- return date;
- });
+ // four possible states: mod-mod, mod-del, del-mod, del-del
+ if ( ! dsstate.conflicts )
+ dsstate.conflicts = [];
- appData = pushMessageInitDict.appData || "";
- alertMessage = pushMessageInitDict.alertMessage || "";
- date = pushMessageInitDict.date || new Date();
-};
+ // handle mod-mod (but only if change-tracking is enabled)
+ if ( change.state == constant.ITEM_MODIFIED
+ && cmd.name == constant.CMD_REPLACE )
+ {
+ cmd._conflict = retcmd;
+ cmd._change = change;
+ return cb();
+ }
-module.exports = _self;
+ // handle del-del
+ if ( change.state == constant.ITEM_DELETED
+ && cmd.name == constant.CMD_DELETE )
+ {
+ // both changes are deletes... that's not a conflict.
+ // TODO: should i really be doing all this here?... it does not
+ // follow the pattern..
+ peerStore._delChange({
+ itemID: change.item_id,
+ state: change.state
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ dsstate.stats.peerDel += 1;
+ dsstate.stats.hereDel += 1;
+ dsstate.stats.merged += 1;
+ retcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE;
+ retcmd.errorCode = null;
+ retcmd.errorMsg = null;
+ return cb(null, [retcmd]);
+ });
+ return;
+ }
-});
-define('ripple/platform/tizen/2.0/route', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ // handle del-mod or mod-del
+ if ( ( change.state == constant.ITEM_DELETED
+ || cmd.name == constant.CMD_DELETE )
+ && policy != constant.POLICY_ERROR )
+ {
+ // one of them is a delete and a conflict that can be solved
+ // by the framework
+ cmd._conflict = retcmd;
+ cmd._change = change;
+ return cb();
+ }
-var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- ProviderNominatim = require('ripple/platform/tizen/2.0/routeBackend_navigation'), // navigation route service
- _getProviders,
- _providers,
- _self;
+ dsstate.conflicts.push(itemID);
+ dsstate.stats.peerErr += 1;
+ dsstate.stats.conflicts += 1;
+ retcmd.statusCode = constant.STATUS_UPDATE_CONFLICT;
+ retcmd.errorCode = 'syncml-js.synchronizer.RSd.10';
+ return cb(null, [retcmd]);
+ });
+ }
+ );
+ };
+ }
-function _initialize() {
- _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})];
-}
+ check_for_conflicts(function(err, cmds) {
+ if ( err || cmds )
+ return cb(err, cmds);
+ try{
+ func.call(self, session, cmd, store, dsstate, cb);
+ }catch(e){
+ return cb(new common.InternalError(
+ 'failed invoking synchronizer sync reaction: ' + e, e));
+ }
+ });
-_initialize();
+ },
-_self = {
- getDefaultProvider : function () {
- if (arguments.length !== 0) {
- throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return _providers[0];
- },
- getProviders : function () {
- if (arguments.length !== 0) {
- throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
- }
- return _providers;
- }
-};
+ //-------------------------------------------------------------------------
+ _reaction_sync_add: function(session, cmd, store, dsstate, cb) {
+ var curitem = null;
+ var item = null;
+ if ( store.agent.hierarchicalSync )
+ {
+ if ( cmd.targetParent )
+ cmd.data.parent = cmd.targetParent;
+ else if ( cmd.sourceParent )
+ cmd.data.parent = session.hierlut[cmd.sourceParent];
+ }
-module.exports = _self;
+ var matcher = common.noop;
+ if ( session.isServer && dsstate.mode == constant.ALERT_SLOW_SYNC )
+ {
+ // TODO: if the matched item is already mapped to another client-side
+ // object, then this should cancel the matching...
+ matcher = function(cb) {
+ store.agent.matchItem(cmd.data, function(err, match) {
+ if ( err )
+ return cb(err);
+ if ( ! match || ! match.compare )
+ return cb();
+ curitem = match;
+ if ( match.compare(cmd.data) == 0 )
+ return cb();
+ store.agent.mergeItems(curitem, cmd.data, null, function(err) {
+ // TODO: if there is a common.ConflictError, set
+ // curitem to null and continue without error...
+ if ( err )
+ return cb(err);
+ store.registerChange(curitem.id, constant.ITEM_MODIFIED,
+ {changeSpec: cspec, excludePeerID: session.peer.id},
+ cb);
+ });
+ });
+ };
+ }
-});
-define('ripple/platform/tizen/2.0/routeBackend_local', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ matcher(function(err) {
+ if ( err )
+ return cb(err);
+ var adder = common.noop;
+ if ( ! curitem )
+ adder = function(cb) {
+ store.agent.addItem(cmd.data, function(err, newitem) {
+ if ( err )
+ return cb(err);
+ item = newitem;
+ dsstate.stats.hereAdd += 1;
+ store.registerChange(item.id, constant.ITEM_ADDED,
+ {excludePeerID: session.peer.id}, cb);
+ });
+ };
+ else
+ item = curitem;
+ return adder(function(err) {
+ if ( err )
+ return cb(err);
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- lbs = require('ripple/platform/tizen/2.0/lbs'),
- LocationServiceProvider = {},
- RouteWaypoint,
- RouteDistance,
- RouteDuration,
- RouteStep,
- RouteSegment,
- RouteRequestOptions,
- RouteResultSummary,
- RouteResult,
- _data = {
- DB_ROUTE_LOCATION_KEY: "tizen1-db-route",
- DB_ROUTE_COLLEAGE_KEY: "tizen2-db-route",
- routeProvider: {},
- routes: [],
- RouteDistanceUnit: ["M", "KM", "MI", "FT"],
- providers: [],
- path: []
- },
- _self;
+ if ( store.agent.hierarchicalSync )
+ session.hierlut[cmd.source] = item.id;
-// The RouteWaypoint object
-RouteWaypoint = function () {
- return {
- position: {
- latitude: 0,
- longitude: 0
- },
- isStopover: true
- };
-};
+ var ret = [state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : cmd.msgID,
+ cmdRef : cmd.cmdID,
+ sourceRef : cmd.source,
+ statusOf : cmd.name,
+ statusCode : ( curitem
+ ? constant.STATUS_ALREADY_EXISTS
+ : constant.STATUS_ITEM_ADDED )
+ })];
-// The RouteDistance object
-RouteDistance = function () {
- return {
- text: "",
- value: 0,
- unit: "KM"
- };
-};
+ if ( ! session.isServer )
+ {
+ ret.push(state.makeCommand({
+ name : constant.CMD_MAP,
+ cmdID : session.nextCmdID(),
+ source : store.uri,
+ target : dsstate.peerUri,
+ sourceItem : item.id,
+ targetItem : cmd.source
+ }));
+ return cb(null, ret);
+ }
-// The RouteDuration object
-RouteDuration = function () {
- return {
- text: "",
- value: 0 // The duration in a seconds
- };
-};
+ var peerStore = session.peer.getStore(dsstate.peerUri);
+ peerStore._setMapping(item.id, cmd.source, function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, ret);
+ });
-// The RouteStep object
-RouteStep = function () {
- var _self = {
- mode: "", // The way of the travel, for example: car, bike, foot
- instruction: "", // The instruction of this step
- points: [] // The points of this step
- };
+ });
+ });
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.distance = new RouteDistance();
- _self.duration = new RouteDuration();
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ getSourceMapping: function(session, cmdctxt, cmd, peerStore, luid, cb) {
+ peerStore._getReverseMapping(luid, function(err, guid) {
-// The RouteSegment object
-RouteSegment = function () {
- var _self = {
- steps: []
- };
+ if ( err )
+ return cb(err);
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.distance = new RouteDistance();
- _self.duration = new RouteDuration();
+ if ( guid )
+ return cb(null, guid);
- return _self;
-};
+ return cb(new common.InvalidItem(
+ 'unexpected "' + cmdctxt + '/' + cmd.name
+ + '" request for unmapped item ID "' + luid + '"'));
-// The RouteRequestOptions object
-RouteRequestOptions = function () {
- return {
- mode: "", // CAR, BIKE
- unit: "KM",
- routeGoal: "SHORTEST",
- constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
- wayPoints: [],
- maxResults: 1
- };
-};
+ // todo: pysyncml generates a nice cmd-specific error node:
+ // (which is probably over-kill)
-// The RouteResultSummary object
-RouteResultSummary = function () {
- var _self = {};
+ // curmap = adapter._context._model.Mapping.q(store_id=peerStore.id, luid=luid).one()
+ // return str(curmap.guid)
+ // except NoResultFound:
+ // msg = 'unexpected "%s/%s" request for unmapped item ID: %r' % (cmdctxt, cmd.name, luid)
+ // # todo: this is a bit of a hack when cmdctxt == 'Status'...
+ // return state.Command(
+ // name = constant.CMD_STATUS,
+ // cmdID = session.nextCmdID(),
+ // msgRef = cmd.msgID,
+ // cmdRef = cmd.cmdID,
+ // sourceRef = cmd.source,
+ // targetRef = cmd.target,
+ // statusOf = cmd.name if cmdctxt != constant.CMD_STATUS else cmdctxt,
+ // statusCode = constant.STATUS_COMMAND_FAILED,
+ // errorCode = __name__ + '.' + self.__class__.__name__ + '.GSM.10',
+ // errorMsg = msg,
+ // )
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.totalDistance = new RouteDistance();
- _self.totalDuration = new RouteDuration();
+ });
+ },
- return _self;
-};
+ //-------------------------------------------------------------------------
+ _reaction_sync_replace: function(session, cmd, store, dsstate, cb) {
-// The RouteResult object
-RouteResult = function () {
- var _self = {
- segments: []
- };
+ // TODO: handle hierarchical-sync...
+ var self = this;
+ var item = cmd.data;
+ var get_item_id = ( ! session.isServer ) ? function(cb) {
+ item.id = cmd.target;
+ return cb();
+ } : function(cb) {
+ var peerStore = session.peer.getStore(dsstate.peerUri);
+ self.getSourceMapping(
+ session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
+ function(err, guid) {
- _self.summary = new RouteResultSummary();
+ if ( err )
+ return cb(err);
- return _self;
-};
+ // todo: what if guid is null?...
-// Floyd arithmetic in Mathematics, solving the optimal way
-function floyd(e, n, startIndex, endIndex) {
- var MAX = Infinity,
- a = new Array(n), i, j, k, p = new Array(n),
- paths, pathWay = [];
+ item.id = guid;
+ return cb();
+ }
+ );
+ };
- for (i = 1; i < n + 1; i++) {
- a[i] = new Array(n);
- }
- for (i = 1; i < n + 1; i++) {
- p[i] = new Array(n);
- }
- for (i = 1; i < n + 1; i++) {
- for (j = 1; j < n + 1; j++) {
- if (i === j || e[i][j] === "MIN") {
- a[i][j] = 0;
- } else if (e[i][j] !== 0 && e[i][j] !== "MIN") {
- a[i][j] = e[i][j];
- } else {
- a[i][j] = MAX;
- }
- p[i][j] = 0;
- }
- }
- for (i = 1; i < n + 1; i++) {
- a[i][i] = 0;
- }
- for (k = 1; k < n + 1; k++) {
- for (i = 1; i < n + 1; i++) {
- for (j = 1; j < n + 1; j++) {
- if (parseInt(a[i][k], 10) + parseInt(a[k][j], 10) < a[i][j]) {
- a[i][j] = parseInt(a[i][k], 10) + parseInt(a[k][j], 10);
- p[i][j] = k;
- }
- }
- }
- }
- _data.path = [];
- paths = findPath(startIndex, endIndex, p);
- pathWay = [];
- pathWay.push(startIndex);
- for (i = 0; i < paths.length; i++) {
- pathWay.push(paths[i]);
- }
- pathWay.push(endIndex);
+ var okcmd = state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : cmd.msgID,
+ cmdRef : cmd.cmdID,
+ targetRef : cmd.target,
+ sourceRef : cmd.source,
+ statusOf : cmd.name,
+ statusCode : constant.STATUS_OK
+ });
- return pathWay;
-}
+ var handle_conflict = ( ! cmd._conflict ) ? common.noop : function(cb) {
-// Find the best way in the locations
-function findPath(i, j, p) {
- var k = p[i][j];
+ // if cmd._conflict is not None:
+ // try:
+ // if cmd._change.state == constant.ITEM_DELETED:
+ // raise common.ConflictError('item deleted')
+ // if cmd._change.changeSpec is None:
+ // raise common.ConflictError('no change tracking enabled - falling back to policy')
+ // cspec = store.agent.mergeItems(store.agent.getItem(item.id), item, cmd._change.changeSpec)
+ // dsstate.stats.hereMod += 1
+ // store.registerChange(item.id, constant.ITEM_MODIFIED,
+ // changeSpec=cspec, excludePeerID=adapter.peer.id)
+ // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE
+ // # NOTE: *not* suppressing the change that is registered from server
+ // # to client, since the merge may have resulted in an item that
+ // # is not identical to the one on the client.
+ // return [okcmd]
+ // except common.ConflictError, e:
+ // # conflict types: client=mod/server=mod or client=mod/server=del
+ // if store.conflictPolicy == constant.POLICY_CLIENT_WINS:
+ // adapter._context._model.session.delete(cmd._change)
+ // dsstate.stats.merged += 1
+ // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
+ // if cmd._change.state == constant.ITEM_DELETED:
+ // # todo: this "re-creation" of a new item is detrimental to
+ // # clients that are tracking changes to an item (for
+ // # example, a SyncML svn client bridge...). but then, to
+ // # them, this item may already have been deleted. ugh.
+ // dsstate.stats.hereMod += 1
+ // item = store.agent.addItem(item)
+ // peerStore = store.peer
+ // adapter._context._model.Mapping.q(store_id=peerStore.id, guid=item.id).delete()
+ // newmap = adapter._context._model.Mapping(store_id=peerStore.id,
+ // guid=item.id,
+ // luid=cmd.source)
+ // adapter._context._model.session.add(newmap)
+ // store.registerChange(item.id, constant.ITEM_ADDED,
+ // excludePeerID=adapter.peer.id)
+ // return [okcmd]
+ // # falling back to standard handling...
+ // elif store.conflictPolicy == constant.POLICY_SERVER_WINS:
+ // dsstate.stats.merged += 1
+ // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
+ // return [okcmd]
+ // else:
+ // # store.conflictPolicy == constant.POLICY_ERROR or other...
+ // dsstate.stats.peerErr += 1
+ // dsstate.stats.conflicts += 1
+ // cmd._conflict.errorMsg += ', agent failed merge: ' + str(e)
+ // cmd._conflict.statusCode = constant.STATUS_UPDATE_CONFLICT
+ // cmd._conflict.errorCode = common.fullClassname(self) + '.RSR.10'
+ // dsstate.conflicts.append(str(item.id))
+ // return [cmd._conflict]
- if (k === 0 || i === j) {
- return _data.path;
- }
- findPath(i, k, p);
- _data.path.push(k);
+ cb();
- return findPath(k, j, p);
-}
+ };
-// Find the index in the locations by string
-function findIndexByStr(str, locations) {
- for (var i in locations) {
- if (locations[i].name === str) {
- return parseInt(i, 10) + 1;
- }
- }
- return -1;
-}
+ // TODO: support hierarchical-sync...
+ // if ( store.agent.hierarchicalSync )
+ // session.hierlut[cmd.source] = item.id;
-// Find the index in the colleages by name1 and name2
-function findValueByStr(start, end, locations, colleages) {
- for (var i in colleages) {
- if (colleages[i].name1 === locations[start - 1].name && colleages[i].name2 === locations[end - 1].name) {
- return parseInt(i, 10);
- } else if (colleages[i].name2 === locations[start - 1].name && colleages[i].name1 === locations[end - 1].name) {
- return parseInt(i, 10);
- }
- }
- return -1;
-}
+ get_item_id(function(err) {
+ if ( err )
+ return cb(err);
+ handle_conflict(function(err) {
+ if ( err )
+ return cb(err);
+ store.agent.replaceItem(item, session.isServer, function(err, cspec) {
+ if ( err )
+ return cb(err);
+ dsstate.stats.hereMod += 1;
+ store.registerChange(
+ item.id, constant.ITEM_MODIFIED,
+ {changeSpec: cspec, excludePeerID: session.peer.id},
+ function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, [okcmd]);
+ }
+ );
+ });
+ });
+ });
-// Find the index in the locations by latitude and longitude
-function searchIndexBycoodinates(latitude, longitude, locations) {
- if (latitude !== null && longitude !== null) {
- for (var i in locations) {
- if (locations[i].latitude === latitude && locations[i].longitude === longitude) {
- return parseInt(i, 10) + 1;
- }
- }
- }
- return -1;
-}
+ },
-// Get the relation among the locations
-function getRelation(n, colleages, locations, goal) {
- var i, j, start, end, relation = new Array(n + 1);
- for (i = 1; i < n + 2; i++) {
- relation[i] = new Array(n + 1);
- }
- for (i = 1; i < n + 1; i++) {
- for (j = 1; j < n + 1; j++) {
- relation[i][j] = 0;
- }
- }
- for (i in colleages) {
- start = findIndexByStr(colleages[i].name1, locations);
- end = findIndexByStr(colleages[i].name2, locations);
- if (start !== -1 && end !== -1 && start !== end) {
- switch (goal) {
- case "distance":
- relation[start][end] = colleages[i].distance;
- relation[end][start] = colleages[i].distance;
- break;
+ //-------------------------------------------------------------------------
+ _reaction_sync_delete: function(session, cmd, store, dsstate, cb) {
- case "duration":
- relation[start][end] = colleages[i].duration;
- relation[end][start] = colleages[i].duration;
- break;
+ var self = this;
+ var status = constant.STATUS_OK;
+ var itemID = null;
- case "simple":
- relation[start][end] = 1;
- relation[end][start] = 1;
- break;
+ var get_item_id = ( ! session.isServer ) ? function(cb) {
+ itemID = cmd.target;
+ return cb();
+ } : function(cb) {
+ var peerStore = session.peer.getStore(dsstate.peerUri);
+ self.getSourceMapping(
+ session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
+ function(err, guid) {
- case "scenic":
- if (colleages[i].addition.scenic === "SCENIC") {
- relation[start][end] = 1;
- relation[start][end] = 1;
- } else if (colleages[i].addition.scenic === "") {
- relation[start][end] = "MIN";
- relation[start][end] = "MIN";
- }
- break;
+ // if not isinstance(itemID, basestring):
+ // return [itemID]
- case "cheap":
- if (colleages[i].addition.toll === "TOLL") {
- relation[start][end] = 1;
- relation[end][start] = 1;
- } else if (colleages[i].addition.toll === "") {
- relation[start][end] = "MIN";
- relation[start][end] = "MIN";
- }
- break;
+ if ( err )
+ return cb(err);
- case "safe":
- if (colleages[i].addition.hazardous === "HAZARDOUS") {
- relation[start][end] = 1;
- relation[end][start] = 1;
- } else if (colleages[i].addition.hazardous === "") {
- relation[start][end] = "MIN";
- relation[end][start] = "MIN";
- }
- break;
+ // todo: what if guid is null?...
- default:
- return null;
- }
- }
- }
+ itemID = guid;
+ if ( ! cmd._conflict )
+ return cb();
+ var policy = store.conflictPolicy || session.adapter.conflictPolicy;
+ switch ( policy )
+ {
- return relation;
-}
+ case constant.POLICY_CLIENT_WINS:
+ {
-// Get the distance relationship among the locations
-function distanceRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "distance");
-}
-// Get the duration relationship among the locations
-function durationRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "duration");
-}
+ // TODO ::: implement these...
-// Get the simple relationship among the locations
-function simpleRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "simple");
-}
+ // // adapter._context._model.session.delete(cmd._change)
+ // // status = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
+ // // session.dsstates[store.uri].stats.merged += 1
+ // // # falling back to standard handling...
-// Get the cheap relationship among the locations
-function cheapRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "cheap");
-}
+ // break;
-// Get the safe relationship among the locations
-function safeRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "safe");
-}
+ }
+ case constant.POLICY_SERVER_WINS:
+ {
-// Get the scenic relationship among the locations
-function scenicRelation(n, colleages, locations) {
- return getRelation(n, colleages, locations, "scenic");
-}
-// Get the shortest way by origin, destination, locations and colleages
-function optimalWay(origin, destination, locations, colleages, relation) {
- var n = locations.length, i, steps = [], step, relations, routeLocations,
- originIndex, destinationIndex, startIndex, endIndex, colleageIndex,
- originLatitude, originLongitude, destinationLatitude, destinationLongitude,
- startLatitude, startLongitude, endLatitude, endLongitude,
- originLocation, destinationLocation, segment, result;
+ // // adapter._context._model.session.delete(cmd._change)
+ // // store.peer.registerChange(itemID, constant.ITEM_ADDED)
+ // // session.dsstates[store.uri].stats.merged += 1
+ // // cmd._conflict.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
+ // // cmd._conflict.errorCode = None
+ // // cmd._conflict.errorMsg = None
+ // // return [cmd._conflict]
- originLatitude = origin.latitude;
- originLongitude = origin.longitude;
- originIndex = searchIndexBycoodinates(originLatitude, originLongitude, locations);
+ // break;
- destinationLatitude = destination.latitude;
- destinationLongitude = destination.longitude;
- destinationIndex = searchIndexBycoodinates(destinationLatitude, destinationLongitude, locations);
+ }
- relations = relation(n, colleages, locations);
+ default:
+ {
+ // a constant.POLICY_ERROR policy should have been handled by the dispatch
+ return cb(new common.InternalError(
+ 'unexpected conflictPolicy: %s', '' + policy));
+ }
+ }
+ }
+ );
- if (originIndex !== -1 && destinationIndex !== -1) {
- routeLocations = floyd(relations, n, parseInt(originIndex, 10), parseInt(destinationIndex, 10));
+ };
- for (i = 0; i < routeLocations.length - 1; i++) {
- colleageIndex = findValueByStr(routeLocations[i], routeLocations[i + 1], locations, colleages);
+ get_item_id(function(err) {
+ if ( err )
+ return cb(err);
+ store.agent.deleteItem(itemID, function(err) {
+ if ( err )
+ return cb(err);
+ dsstate.stats.hereDel += 1;
+ store.registerChange(
+ itemID, constant.ITEM_DELETED, {excludePeerID: session.peer.id},
+ function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : cmd.msgID,
+ cmdRef : cmd.cmdID,
+ targetRef : cmd.target,
+ sourceRef : cmd.source,
+ statusOf : cmd.name,
+ // todo: should this return DELETE_WITHOUT_ARCHIVE instead of OK?...
+ // statusCode = constant.STATUS_DELETE_WITHOUT_ARCHIVE,
+ statusCode : status
+ })]);
+ }
+ );
+ });
+ });
- if (colleageIndex !== -1) {
- step = new RouteStep();
- startIndex = parseInt(routeLocations[i], 10) - 1;
- endIndex = parseInt(routeLocations[i + 1], 10) - 1;
+ },
- startLatitude = locations[startIndex].latitude;
- startLongitude = locations[startIndex].longitude;
- originLocation = new SimpleCoordinates(startLatitude, startLongitude);
+ //-------------------------------------------------------------------------
+ _reaction_map: function(session, command, cb) {
+ var peerStore = session.peer.getStore(command.source);
+ if ( command.target != peerStore._getBinding().uri )
+ return cb(new common.NoSuchRoute(
+ 'unexpected "Map" event for unbound stores (local: "'
+ + command.target + ', remote: "' + command.source + '")'));
+ common.cascade(command.items, function(item, cb) {
+ // todo: support hierarchical sync...
+ peerStore._setMapping(item.target, item.source, cb);
+ }, function(err) {
+ if ( err )
+ return cb(err);
+ return cb(null, [state.makeCommand({
+ name : constant.CMD_STATUS,
+ cmdID : session.nextCmdID(),
+ msgRef : command.msgID,
+ cmdRef : command.cmdID,
+ targetRef : command.target,
+ sourceRef : command.source,
+ statusOf : command.name,
+ statusCode : constant.STATUS_OK
+ })]);
+ });
+ },
- endLatitude = locations[endIndex].latitude;
- endLongitude = locations[endIndex].longitude;
- destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);
+ //-------------------------------------------------------------------------
+ // SYNCHRONIZATION PHASE: SETTLE
+ //-------------------------------------------------------------------------
- step.origin = originLocation;
- step.destination = destinationLocation;
- step.distance = colleages[colleageIndex].distance;
- step.duration = colleages[colleageIndex].duration;
- step.mode = colleages[colleageIndex].mode;
- step.addition = colleages[colleageIndex].addition;
+ //-------------------------------------------------------------------------
+ settle: function(session, cmd, chkcmd, xnode, cb) {
- steps.push(step);
- } else if (colleageIndex === -1) {
- return null;
- }
- }
+ // TODO: remove the "xnode" parameter... it is a hack so that i can
+ // call badStatus() the same way as in protocol.js
+ // todo: there is a bit of a disconnect between how action and reaction
+ // phases are called (for a list of commands), whereas the settle
+ // phase is called on a per-item basis... not ideal, but the protocol
+ // is really set up that way :(
+ // TODO: check all valid values of ``data``...
+ // todo: anything else in common?...
+ // todo: trap errors...
- segment = new RouteSegment();
- segment.steps = steps;
- result = new RouteResult();
- result.segments[0] = segment;
+ var func = this['_settle_' + cmd.name.toLowerCase()];
+ if ( ! func )
+ return cb(new common.ProtocolError('unexpected settle command "' + cmd.name + '"'));
+ return func.call(this, session, cmd, chkcmd, xnode, cb);
+ },
- return result;
- }
- return null;
-}
+ //-------------------------------------------------------------------------
+ _settle_add: function(session, cmd, chkcmd, xnode, cb) {
+ switch ( cmd.data )
+ {
+ default:
+ {
+ return cb(badStatus(xnode));
+ }
+ case constant.STATUS_OK:
+ case constant.STATUS_ITEM_ADDED:
+ case constant.STATUS_CONFLICT_RESOLVED_DUPLICATE:
+ {
+ session.info.dsstates[chkcmd.uri].stats.peerAdd += 1;
+ break;
+ }
+ case constant.STATUS_ALREADY_EXISTS:
+ case constant.STATUS_CONFLICT_RESOLVED_MERGE:
+ // todo: should this conflict-resolved-merge status be stored so
+ // that only this item can have a non-"ADD" during initial
+ // sync?...
+ case constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA:
+ {
+ session.info.dsstates[chkcmd.uri].stats.merged += 1;
+ break;
+ }
+ }
-// Get the shortest way by origin, destination, locations and colleages
-function shortestWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, distanceRelation);
-}
+ var peerStore = session.peer.getStore(
+ session.context.router.getTargetUri(
+ session.adapter, session.peer, chkcmd.uri));
-// Get the fastest way by origin, destination, locations and colleages
-function fastestWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, durationRelation);
-}
+ peerStore._delChange({
+ itemID: chkcmd.source,
+ state: constant.ITEM_ADDED
+ }, cb);
+ },
-// Get the simplest way by origin, destination, locations and colleages
-function simplestWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, simpleRelation);
-}
+ //-------------------------------------------------------------------------
+ _settle_replace: function(session, cmd, chkcmd, xnode, cb) {
-// Get the most scenic way by origin, destination, locations and colleages
-function mostScenicWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, scenicRelation);
-}
+ var self = this;
+ var dsstate = session.info.dsstates[chkcmd.uri];
-// Get the cheapest way by origin, destination, locations and colleages
-function cheapestWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, cheapRelation);
-}
+ if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
+ {
+ dsstate.stats.hereErr += 1;
+ dsstate.stats.conflicts += 1;
+ return cb();
+ }
+ if ( cmd.data != constant.STATUS_OK
+ && cmd.data != constant.STATUS_CONFLICT_RESOLVED_MERGE
+ && cmd.data != constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
+ && cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
+ return cb(badStatus(xnode));
+ if ( cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE
+ || cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
+ || cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
+ dsstate.stats.merged += 1;
+ if ( cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
+ dsstate.stats.peerMod += 1;
-// Get the safest way by origin, destination, locations and colleages
-function safestWay(origin, destination, locations, colleages) {
- return optimalWay(origin, destination, locations, colleages, safeRelation);
-}
+ var peerStore = session.peer.getStore(
+ session.context.router.getTargetUri(
+ session.adapter, session.peer, chkcmd.uri));
-// Uniquelize the array
-function uniquelize(array) {
- var temp = {}, result = [], i;
- for (i = array.length; i--;) {
- temp[array[i]] = array[i];
- }
- for (i in temp) {
- result.push(temp[i]);
- }
- return result;
-}
+ var get_item_id = ( ! session.isServer ) ? function(cb) {
+ return cb(null, chkcmd.source);
+ } : function(cb) {
+ // if not isinstance(locItemID, basestring):
+ // return locItemID
-// Is it intersect between the Array a and b
-function intersect(a, b) {
- var i, j;
+ self.getSourceMapping(
+ session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
+ function(err, guid) { return cb(err, guid); }
+ );
+ };
- a = uniquelize(a);
- if (a.length === 0 && b.length === 0) {
- return true;
- }
- for (i in a) {
- for (j in b) {
- if (a[i] === b[j])
- return true;
- }
- }
- return false;
-}
+ get_item_id(function(err, locItemID) {
-function getConstrains(result) {
- var steps = result.segments[0].steps, constrains = [];
+ if ( err )
+ return cb(err);
- utils.forEach(steps, function (item, index) {
- if (item.addition.highway === "HIGHWAY") {
- constrains.push("HIGHWAY");
- }
- if (item.addition.toll === "TOLL") {
- constrains.push("TOLL");
- }
- if (item.addition.bridge === "BRIDGE") {
- constrains.push("BRIDGE");
- }
- if (item.addition.hazardous === "HAZARDOUS") {
- constrains.push("HAZARDOUS");
- }
- if (item.addition.scenic === "SCENIC") {
- constrains.push("SCENIC");
- }
- });
- if (constrains.length > 0) {
- return uniquelize(constrains);
- }
- return constrains;
-}
+ // todo: this is *technically* subject to a race condition... but the
+ // same peer should really not be synchronizing at the same time...
+ // todo: also potentially check Change.registered...
+ // TODO: this could be solved by:
+ // a) never updating a Change record (only deleting and replacing)
+ // b) deleting Change records by ID instead of by store/item/state...
-module.exports = function (prop) {
- var _self = new lbs.LocationServiceProvider(prop);
- _self.find = function (origin, destination, successCallback, errorCallback, options) {
- function _find() {
- var locations, colleages, i, result = {}, emptyResult = [], modes = [], resultModes = [], constrains = [], resultconstrains = [];
+ peerStore._delChange({
+ itemID : locItemID,
+ state : constant.ITEM_MODIFIED,
+ }, cb);
- locations = db.retrieveObject(_data.DB_ROUTE_LOCATION_KEY);
- colleages = db.retrieveObject(_data.DB_ROUTE_COLLEAGE_KEY);
+ });
- modes = options.modes;
- constrains = options.constrains;
- if (locations.length > 0 && colleages.length > 0) {
- switch (options.routeGoal) {
- case "SHORTEST":
- result = shortestWay(origin, destination, locations, colleages);
- break;
+ },
- case "FASTEST":
- result = fastestWay(origin, destination, locations, colleages);
- break;
+ //-------------------------------------------------------------------------
+ _settle_delete: function(session, cmd, chkcmd, xnode, cb) {
+ var self = this;
+ var dsstate = session.info.dsstates[chkcmd.uri];
+ if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
+ {
+ dsstate.stats.hereErr += 1;
+ dsstate.stats.conflicts += 1;
+ return cb();
+ }
+ if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE )
+ {
+ dsstate.stats.hereDel += 1;
+ dsstate.stats.peerDel += 1;
+ dsstate.stats.merged += 1;
+ }
+ else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA )
+ {
+ dsstate.stats.peerDel += 1;
+ dsstate.stats.merged += 1;
+ }
+ else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
+ dsstate.stats.merged += 1;
+ else if ( cmd.data == constant.STATUS_ITEM_NOT_DELETED )
+ {
+ // note: the reason that this *may* be ok is that some servers (funambol)
+ // will report ITEM_NOT_DELETED when the item did not exist, thus this
+ // is "alright"...
+ // todo: perhaps this should be raised as an error if the
+ // remote peer != funambol?...
+ }
+ else if ( cmd.data == constant.STATUS_OK )
+ dsstate.stats.peerDel += 1;
+ else
+ return cb(badStatus(xnode));
- case "SIMPLEST":
- result = simplestWay(origin, destination, locations, colleages);
- break;
+ var peerStore = session.peer.getStore(
+ session.context.router.getTargetUri(
+ session.adapter, session.peer, chkcmd.uri));
- case "MOST_SCENIC":
- result = mostScenicWay(origin, destination, locations, colleages);
- break;
+ // todo: handle hierarchical sync...
+ var get_locItemID = ( ! chkcmd.target ) ? function(cb) {
+ cb(null, chkcmd.source);
+ } : function(cb) {
+ self.getSourceMapping(
+ session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
+ function(err, guid) { return cb(err, guid); }
+ );
+ };
- case "CHEAPEST":
- result = cheapestWay(origin, destination, locations, colleages);
- break;
+ // todo: this is *technically* subject to a race condition... but the
+ // same peer should really not be synchronizing at the same time...
+ // todo: also potentially check Change.registered...
+ // TODO: this could be solved by:
+ // a) never updating a Change record (only deleting and replacing)
+ // b) deleting Change records by ID instead of by store/item/state...
- case "SAFEST":
- result = safestWay(origin, destination, locations, colleages);
- break;
+ get_locItemID(function(err, locItemID) {
+ if ( err )
+ return cb(err);
+ peerStore._delChange({
+ itemID : locItemID,
+ state : constant.ITEM_DELETED,
+ }, cb);
+ });
- default:
- result = shortestWay(origin, destination, locations, colleages);
- break;
- }
- if (result !== null) {
- for (i in result.segments[0].steps) {
- resultModes.push(result.segments[0].steps[i].mode);
- }
- resultconstrains = getConstrains(result);
- if (intersect(resultModes, modes) && intersect(resultconstrains, constrains)) {
- successCallback(result);
- } else {
- successCallback(null);
}
- }
- } else {
- successCallback(emptyResult);
- }
- }
- tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
- };
- return _self;
-};
-});
-define('ripple/platform/tizen/2.0/routeBackend_navigation', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- lbs_utils = require('ripple/platform/tizen/2.0/lbs_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
- SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
- RouteWaypoint,
- RouteDistance,
- RouteDuration,
- RouteStep,
- RouteSegment,
- RouteRequestOptions,
- RouteResultSummary,
- RouteResult,
- _data = {
- positionDistance: {},
- positionDuration: {},
- routeProvider: {},
- routes: [],
- RouteDistanceUnit: ["M", "KM", "MI", "FT"],
- providers: [],
- path: []
- },
- _self;
+ return exports;
-// The RouteWaypoint object
-RouteWaypoint = function () {
- return {
- position: {
- latitude: 0,
- longitude: 0
- },
- isStopover: true
- };
-};
+})();
-// The RouteDistance object
-RouteDistance = function () {
- return {
- text : "Distance",
- value : "0",
- unit : "KM "
- };
-};
+module.exports = _self;
-// The RouteDuration object
-RouteDuration = function () {
- return {
- text : "Duration",
- value : "0" // The duration in a seconds
- };
-};
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/store', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.store
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/11/04
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
-// The RouteStep object
-RouteStep = function () {
- var _self = {
- mode: "", // The way of the travel, for example: car, bike, foot
- instruction: "", // The instruction of this step
- points: [] // The points of this step
- };
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.distance = new RouteDistance();
- _self.duration = new RouteDuration();
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
+ ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
+ storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
+ ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree');
- return _self;
-};
-// The RouteSegment object
-RouteSegment = function () {
- var _self = {
- steps: []
- };
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.distance = new RouteDistance();
- _self.duration = new RouteDuration();
+var _self = (function () {
+ var exports = {};
- return _self;
-};
+ //---------------------------------------------------------------------------
+ exports.Store = common.Base.extend({
-// The RouteRequestOptions object
-RouteRequestOptions = function () {
- return {
- mode: "", // CAR, BIKE
- unit: "KM",
- routeGoal: "SHORTEST",
- constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
- wayPoints: [],
- maxResults: 1
- };
-};
+ //-------------------------------------------------------------------------
+ constructor: function(adapter, options) {
-// The RouteResultSummary object
-RouteResultSummary = function () {
- var _self = {};
+ // todo: some of these attributes should be modifiable...
- _self.origin = new SimpleCoordinates(0, 0);
- _self.destination = new SimpleCoordinates(0, 0);
- _self.totalDistance = new RouteDistance();
- _self.totalDuration = new RouteDuration();
+ //: for local stores, specifies the agent that will implement
+ //: the actual item operations -- it must implement the
+ //: syncml-js.Agent API.
+ this.agent = options.agent || null;
- return _self;
-};
+ //: [read-only] specifies the SyncML URI that this store is bound to.
+ this.uri = ( adapter ? adapter.normUri(options.uri) : options.uri ) || null;
-// The RouteResult object
-RouteResult = function () {
- var _self, jsonStr, jsonObj;
- jsonObj = {
- "type" : "Point",
- "coordinates" : []
- };
- jsonStr = JSON.stringify(jsonObj);
- _self = {
- segments : [],
- toGeoJSON : function () {
- return jsonStr;
- }
- };
- _self.summary = new RouteResultSummary();
- return _self;
-};
+ //: [read-only] specifies the human-readable name for this store.
+ //: if undefined, defaults to URI.
+ this.displayName = options.displayName || this.uri || null;
-function calcDegree(distance) {
- return distance * Math.PI / 180.0;
-}
+ //: [read-only] specifies the maximum GUID size for items in this store.
+ //: if undefined, defaults to adapter setting.
+ this.maxGuidSize = options.maxGuidSize || null;
-//calcute the distance
-function calculateDistance(lat1, lat2, lon1, lon2) {
- var R = 6371, dLat, dLon, a, c, distance; // km
- dLat = calcDegree(parseFloat(lat2) - parseFloat(lat1));
- dLon = calcDegree(parseFloat(lon2) - parseFloat(lon1));
+ //: [read-only] specifies the maximum object size for items in this store.
+ //: if undefined, defaults to adapter setting.
+ this.maxObjSize = options.maxObjSize || null;
- lat1 = calcDegree(lat1);
- lat2 = calcDegree(lat2);
+ //: [read-only] specifies conflict resolution policy for this store.
+ //: if undefined, defaults to adapter setting.
+ this.conflictPolicy = options.conflictPolicy || null;
- a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
- Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
- c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
- distance = R * c;
- return distance;
-}
+ //: [read-only] specifies which syncTypes this store supports.
+ //: (defaults to all.)
+ this.syncTypes = options.syncTypes;
+ if ( this.syncTypes == undefined || this.syncTypes.length <= 0 )
+ {
+ this.syncTypes = [
+ constant.SYNCTYPE_TWO_WAY,
+ constant.SYNCTYPE_SLOW_SYNC,
+ constant.SYNCTYPE_ONE_WAY_FROM_CLIENT,
+ constant.SYNCTYPE_REFRESH_FROM_CLIENT,
+ constant.SYNCTYPE_ONE_WAY_FROM_SERVER,
+ constant.SYNCTYPE_REFRESH_FROM_SERVER,
+ constant.SYNCTYPE_SERVER_ALERTED
+ ];
+ }
-function calculateDuration(mode, distance) {
- var duration, v;
- switch (mode) {
- case "motorcar" :
- v = 50;
- duration = distance / v;
- break;
- case "bicycle" :
- v = 20;
- duration = distance / v;
- break;
- case "foot" :
- v = 5;
- duration = distance / v;
- break;
- default:
- duration = 0;
- }
- return duration;
-}
+ ctypes = options.contentTypes;
+ if ( ! ctypes && options.agent )
+ ctypes = options.agent.getContentTypes();
-function optimalWay(points, mode) {
- var steps = [], startLatitude, startLongitude, originLocation, endLatitude, endLongitude,
- destinationLocation, step, distance, i, routeDistance, routeDuration;
- for (i = 0;i < points.length - 1;i++) {
- startLatitude = points[i].lat;
- startLongitude = points[i].lon;
- originLocation = new SimpleCoordinates(startLatitude, startLongitude);
- endLatitude = points[i + 1].lat;
- endLongitude = points[i + 1].lon;
- destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);
- step = new RouteStep();
- step.origin = originLocation;
- step.destination = destinationLocation;
- distance = calculateDistance(startLatitude, endLatitude, startLongitude, endLongitude);
- routeDistance = new RouteDistance();
- routeDistance.value = distance;
- routeDistance.unit = "km";
- step.distance = routeDistance;
- routeDuration = new RouteDuration();
- routeDuration.value = calculateDuration(mode, distance);
- step.duration = routeDuration;
- steps.push(step);
- }
- return steps;
-}
+ this.contentTypes = _.map(ctypes, function(e) {
+ if ( e instanceof ctype.ContentTypeInfo ) {
+ return e;
+ }
+ return ctype.ContentTypeInfo.fromStruct(e);
+ });
-function existInSupports(str, array) {
- for (var i in array) {
- if (str === array[i]) {
- return true;
- }
- }
- return false;
-}
+ // --- private attributes
+ this.id = options.id || common.makeID();
+ this._a = adapter;
+ },
-function navigation(searchStr, flat, flon, tlat, tlon, v, fast) {
- var positions = [];
+ //-------------------------------------------------------------------------
+ _load: function(cb) {
+ cb();
+ },
- _data.positionDistance = {};
- _data.positionDuration = {};
- jQuery.ajax({
- type : "get",
- async : false,
- url : searchStr,
- data : {
- flat : flat,
- flon : flon,
- tlat : tlat,
- tlon : tlon,
- v : v,
- fast : fast,
- layer : 'mapnik',
- format : "geojson"
+ //-------------------------------------------------------------------------
+ _getModel: function() {
+ var self = this;
+ var uri = self._a.normUri(self.uri);
+ return _.find(this._a._getModel().stores,
+ function(s) { return self._a.normUri(s.uri) == uri; });
},
- contentType : "application/json; charset=utf-8",
- dataType : "json",
- cache : false,
- success : function (data) {
- $.each(data.coordinates, function (i, item) {
- var point = {};
- point.lon = item[0];
- point.lat = item[1];
- positions.push(point);
- });
- $.each(data.properties, function (i, item) {
- if (typeof item === "number") {
- _data.positionDistance = new RouteDistance();
- _data.positionDistance.value = item;
- _data.positionDistance.unit = "km";
- _data.positionDuration = new RouteDuration();
- _data.positionDuration.value = calculateDuration(v, item);
- }
+
+ //-------------------------------------------------------------------------
+ _updateModel: function(cb) {
+ if ( ! this._a._model || ! this._a._model.stores )
+ return cb('store created on un-initialized adapter');
+ // TODO: this squashes any data that may already be there, such
+ // as *BINDING* info!...
+ this._a._model.stores = _.filter(this._a._model.stores, function(e) {
+ return e.uri != this.uri;
+ }, this);
+ this._a._model.stores.push({
+ id : this.id,
+ uri : this.uri,
+ displayName : this.displayName,
+ syncTypes : this.syncTypes,
+ maxGuidSize : this.maxGuidSize,
+ maxObjSize : this.maxObjSize,
+ conflictPolicy : this.conflictPolicy,
+ contentTypes : _.map(this.contentTypes, function(e) { return e.toStruct(); })
});
+ cb();
},
- error : function (errorCB) {
- if (errorCB) {
- setTimeout(function () {
- errorCB(new WebAPIError(errorcode.NETWORK_ERR));
- }, 1);
- }
- }
- });
- return positions;
-}
+ //-------------------------------------------------------------------------
+ _getBinding: function() {
+ return this._getModel().binding;
+ },
-function filterWaypoints(routeWaypoints) {
- var mathWaypoints = [], i;
- for (i in routeWaypoints) {
- if (routeWaypoints[i].position.latitude !== "" &&
- routeWaypoints[i].position.latitude !== undefined &&
- routeWaypoints[i].position.latitude !== null &&
- routeWaypoints[i].position.longitude !== null &&
- routeWaypoints[i].position.longitude !== "" &&
- routeWaypoints[i].position.longitude !== undefined) {
- mathWaypoints.push(routeWaypoints[i]);
- }
- }
- return mathWaypoints;
-}
-
-module.exports = function (prop) {
- var _self = new lbs_utils.LocationServiceProvider(prop);
+ //-------------------------------------------------------------------------
+ _setBinding: function(binding) {
+ this._getModel().binding = binding;
+ },
- _self.supportedGoals = ["SHORTEST", "FASTEST", "MOST_SCENIC", "SIMPLEST", "CHEAPEST", "SAFEST" ];
- _self.supportedModes = ["motorcar", "bicycle", "foot"];
- _self.supportedConstraints = ["HIGHWAY", "TOLL", "UNPAVED", "BORDER", "GRAVEL_PAVING", "TUNNEL", "BRIDGE", "LEFT_TURN", "CARPOOL", "HAZARDOUS_CARGO" ];
- _self.supportsWayPoints = true;
- _self.find = function (origin, destination, successCallback, errorCallback, options) {
- function _find() {
- var flat, flon, tlat, tlon, v, fast, searchStr, result,
- routeWaypoints = [],
- segmentPositions = [],
- positions = [],
- segments = [],
- totalDistances = 0, totalDurations = 0,
- k, key, segment, startPosition, endPosition,
- summary, distance, duration;
+ //-------------------------------------------------------------------------
+ getContentTypes: function() {
+ if ( this.agent != undefined ) {
+ return this.agent.getContentTypes();
+ }
+ return this.contentTypes;
+ },
- v = options.mode;
- //init
- if (!existInSupports(v, _self.supportedModes)) {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ //-------------------------------------------------------------------------
+ getPeerStore: function(peer) {
+ var peerUri = null;
+ if ( this._a.isLocal ) {
+ peerUri = this._a._c.router.getTargetUri(this._a, peer, this.uri);
}
- if (!existInSupports(options.routeGoal, _self.supportedGoals)) {
- throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ else {
+ var binding = this.getBinding();
+ peerUri = binding ? binding.uri : null;
}
- switch (options.routeGoal) {
- case "SHORTEST":
- fast = 0;
- break;
+ if ( ! peerUri ) {
+ return null;
+ }
+ return peer.getStore(peerUri);
+ },
- case "FASTEST":
- fast = 1;
- break;
+ //-------------------------------------------------------------------------
+ merge: function(store, cb) {
+ if ( this.uri != store.uri )
+ return cb(new common.InternalError(
+ 'unexpected merging of stores with different URIs ("' + this.uri
+ + '" != "' + store.uri + '")'));
+ if ( ! _.isEqual(this.contentTypes, store.contentTypes) )
+ {
+ // todo: this is a bit drastic... perhaps have an operational setting
+ // which controls how paranoid to be?...
+ this._setBinding(null);
+ }
+ this.displayName = store.displayName;
+ this.contentTypes = _.rest(store.contentTypes, 0);
+ this.syncTypes = _.rest(store.syncTypes, 0);
+ this.maxGuidSize = store.maxGuidSize;
+ this.maxObjSize = store.maxObjSize;
+ this.agent = store.agent;
+ this.conflictPolicy = store.conflictPolicy;
+ return cb();
+ },
- case "SIMPLEST":
- break;
+ //-------------------------------------------------------------------------
+ _clearAllMappings: function(cb) {
+ if ( this._a.isLocal )
+ return cb(new common.InternalError(
+ 'unexpected mapping request for local store'));
+ var mapping = this._a._c._txn().objectStore('mapping');
+ storage.deleteAll(mapping, {store_id: this.id}, cb);
+ },
- case "MOST_SCENIC":
- break;
+ //-------------------------------------------------------------------------
+ _setMapping: function(guid, luid, cb) {
+ var self = this;
+ if ( this._a.isLocal )
+ return cb(new common.InternalError(
+ 'unexpected mapping request for local store'));
+ // delete all previous mappings for this guid/store (there should
+ // be at most one)... but paranoia rules.
+ var mapping = this._a._c._txn().objectStore('mapping');
+ storage.deleteAll(mapping, {store_id: this.id, guid: guid}, function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ storage.put(mapping, {store_id: self.id, guid: guid, luid: luid}, function(err) {
+ if ( err ) {
+ return cb(err);
+ }
+ cb();
+ });
+ });
+ },
- case "CHEAPEST":
- break;
+ //-------------------------------------------------------------------------
+ _getMapping: function(guid, cb) {
+ if ( this._a.isLocal )
+ return cb(new common.InternalError(
+ 'unexpected mapping request for local store'));
+ // todo: there must be a way to use IndexedDB since i have everything
+ // needed to generate the keyPath!... eg:
+ // objectStore.get({store_id:X,guid:Y})?...
+ var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
+ storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
+ if ( err ) {
+ return cb(err);
+ }
+ var item = _.find(list, function(item) {
+ return item.guid == guid;
+ });
+ return cb(null, item ? item.luid : null);
+ });
+ },
- case "SAFEST":
- break;
+ //-------------------------------------------------------------------------
+ _getMappings: function(cb) {
+ if ( this._a.isLocal )
+ return cb(new common.InternalError(
+ 'unexpected mapping request for local store'));
+ var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
+ storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
+ if ( err )
+ return cb(err);
+ return cb(null, _.map(list, function(item) {
+ return [item.guid, item.luid];
+ }));
+ });
+ },
- default:
- fast = 0;
- }
- searchStr = "http://www.yournavigation.org/api/dev/gosmore.php";
- routeWaypoints = options.wayPoints;
- routeWaypoints = filterWaypoints(routeWaypoints);
- segmentPositions.push(origin);
+ //-------------------------------------------------------------------------
+ _getReverseMapping: function(luid, cb) {
+ if ( this._a.isLocal )
+ return cb(new common.InternalError(
+ 'unexpected mapping request for local store'));
+ // todo: there must be a way to use IndexedDB since i have everything
+ // needed to generate the keyPath!... eg:
+ // objectStore.get({store_id:X,guid:Y})?...
+ var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
+ storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
+ if ( err )
+ return cb(err);
+ var item = _.find(list, function(item) {
+ return item.luid == luid;
+ });
+ return cb(null, item ? item.guid : null);
+ });
+ },
- if (routeWaypoints.length > 0) {
- for (k in routeWaypoints) {
- segmentPositions.push(routeWaypoints[k].position);
- }
- }
- segmentPositions.push(destination);
+ //-------------------------------------------------------------------------
+ registerChange: function(itemID, state, options, cb) {
+ // options can include:
+ // - changeSpec (string)
+ // - excludePeerID (string)
- for (key = 0; key < segmentPositions.length - 1; key++) {
- segment = new RouteSegment();
- startPosition = segmentPositions[key];
- endPosition = segmentPositions[key + 1];
- segment.origin = startPosition;
- segment.destination = endPosition;
- flat = startPosition.latitude;
- flon = startPosition.longitude;
- tlat = endPosition.latitude;
- tlon = endPosition.longitude;
- positions = navigation(searchStr, flat, flon, tlat, tlon, v, fast);
- segment.steps = optimalWay(positions, v);
- segment.distance = _data.positionDistance;
- totalDistances += _data.positionDistance.value;
- segment.duration = _data.positionDuration;
- totalDurations += _data.positionDuration.value;
- segments.push(segment);
- }
- result = new RouteResult();
- summary = new RouteResultSummary();
- summary.origin = segmentPositions[0];
- summary.destination = segmentPositions[segmentPositions.length - 1];
- distance = new RouteDistance();
- distance.value = totalDistances;
- distance.unit = "km";
- summary.totalDistance = distance;
- duration = new RouteDuration();
- duration.value = totalDurations;
- summary.totalDuration = duration;
- result.segments = segments;
- result.summary = summary;
- successCallback(result);
- }
+ if ( ! _.contains([constant.ITEM_ADDED, constant.ITEM_MODIFIED,
+ constant.ITEM_DELETED], state) )
+ return cb(new common.TypeError(
+ 'registerChange: invalid state "' + state + '"'));
- tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
- };
+ options = options || {};
+ var self = this;
+ if ( self._a.isLocal )
+ {
+ // TODO: THIS NEEDS TO BE SIGNIFICANTLY OPTIMIZED!... either:
+ // a) optimize this reverse lookup, or
+ // b) use a query that targets exactly the set of stores needed
+ // note that a pre-emptive model.session.flush() may be necessary.
+ common.cascade(self._a.getPeers(), function(peer, cb) {
+ if ( options.excludePeerID && options.excludePeerID == peer.id )
+ return cb();
+ common.cascade(peer.getStores(), function(store, cb) {
+ var binding = store._getBinding()
+ if ( ! binding || binding.uri != self.uri )
+ return cb();
+ store.registerChange(itemID, state, options, cb);
+ }, cb);
+ }, cb);
+ return;
+ }
- return _self;
-};
+ // todo: a non-ADD change event for an ID that has never been
+ // seen does not create an error... should it??? that would mean
+ // that syncml-js needs to track that. not a good idea.
-});
-define('ripple/platform/tizen/2.0/sensors', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ itemID = '' + itemID;
+ var handled = false;
-var utils = require('ripple/utils'),
- sensors = require('ripple/platform/tizen/2.0/spec/sensor'),
- _sensors = ["Accelerometer", "MagneticField", "Rotation", "Orientation"],
- _permission = true,
- _isWriteable = false,
- _self;
+ // paranoia
+ if ( options.changeSpec && state != constant.ITEM_MODIFIED )
+ {
+ options.changeSpec = null;
+ }
-function SensorError(code, msg) {
- this.__defineGetter__("message", function () {
- return msg;
- });
- this.__defineGetter__("code", function () {
- return code;
- });
+ var check_update = function(cb) {
+ self._getChange(itemID, function(err, change) {
+ if ( err )
+ return cb(err);
+ if ( ! change)
+ return cb();
+ var badstate = function(action) {
+ };
+ // note: many of the following change.state / state combinations
+ // should never occur. the following tries to recover gracefully.
+ // todo: should i raise an error for "illogical" conditions?
+ switch ( change.state )
+ {
+ case constant.ITEM_ADDED:
+ {
+ if ( state != constant.ITEM_DELETED )
+ {
+ // ADD + anything except DELETE stays ADD
+ handled = true;
+ return cb();
+ }
+ // ADD + DELETE cancels out
+ handled = true;
+ var changeTab = self._a._c._txn().objectStore('change');
+ storage.deleteAll(changeTab, change, function(err) {
+ if ( err )
+ return cb(err);
+ return cb();
+ });
+ return;
+ }
+ case constant.ITEM_MODIFIED:
+ {
+ if ( state == constant.ITEM_ADDED )
+ {
+ badstate('squelching changeSpec');
+ delete change.changeSpec;
+ break;
+ }
+ if ( state == constant.ITEM_DELETED )
+ {
+ change.state = state;
+ delete change.changeSpec;
+ break;
+ }
+ if ( change.changeSpec )
+ {
+ if ( options.changeSpec )
+ change.changeSpec += ';' + options.changeSpec;
+ else
+ delete change.changeSpec;
+ }
+ break;
+ }
+ case constant.ITEM_DELETED:
+ {
+ if ( state == constant.ITEM_DELETED )
+ {
+ badstate('ignoring');
+ handled = true;
+ return cb();
+ }
+ badstate('reverting to modified');
+ change.state = constant.ITEM_MODIFIED;
+ delete change.changeSpec;
+ break;
+ }
+ default:
+ {
+ return cb(new common.InternalError(
+ 'unexpected recorded change state "' + change.state
+ + '" for item ID "' + itemID + '"'));
+ }
+ }
+ // update the change
+ // todo: do i need to delete it first?
+ handled = true;
+ return storage.put(
+ self._a._c._txn().objectStore('change'),
+ change,
+ cb);
+ });
+ };
- this.PERMISSION_DENIED = -100;
-}
+ var check_mapping = ( self._a._isMapper() || state == constant.ITEM_ADDED )
+ ? common.noop
+ : function(cb) {
+ // doing a `_getMapping` for non-add events to make sure that
+ // the remote peer actually has this object before we tell it
+ // to modify or delete an item...
+ self._getMapping(itemID, function(err, luid) {
+ if ( err )
+ return cb(err);
+ if ( luid )
+ return cb();
+ // this item does not exist as (or has not been mapped to) an
+ // item on the remote peer and is not an `ADD` event, so can
+ // therefore be ignored - mark it as "handled".
+ handled = true;
+ return cb();
+ });
+ };
-function SensorRequest() {
- var _self = {
- result: [],
- error: null,
- readyState: "processing"
- };
+ // todo: there is a weirdness here wrt `handled` in the case
+ // of check_mapping and deletes... ie. there is a bit of
+ // a responsibility violation (handled does not actually
+ // mean handled...)
- this.__defineGetter__("result", function () {
- return _self.result;
- });
- this.__defineSetter__("result", function (resultData) {
- if (_isWriteable) {
- _self.result = utils.copy(resultData);
- _isWriteable = false;
- return;
- }
- });
+ check_update(function(err) {
+ if ( err )
+ return cb(err);
+ if ( handled )
+ return cb();
+ check_mapping(function(err) {
+ if ( err )
+ return cb(err);
+ if ( handled && state != constant.ITEM_DELETED )
+ return cb();
+ // note: if it is a delete event, and it has not been mapped
+ // yet, so does not yet exist on the peer, therefore
+ // propagate nothing -- continuing just to execute the
+ // deleteAll().
+ var changeTab = self._a._c._txn().objectStore('change');
+ change = {store_id: self.id, item_id: itemID};
+ // todo: is this deleteAll really necessary?... paranoia rules!
+ storage.deleteAll(changeTab, change, function(err) {
+ if ( err )
+ return cb(err);
+ if ( handled )
+ return cb();
+ change.state = state;
+ change.changeSpec = options.changeSpec;
+ storage.put(changeTab, change, cb);
+ });
+ });
+ });
+ },
- this.__defineGetter__("error", function () {
- return _self.error;
- });
- this.__defineSetter__("error", function (errorData) {
- if (_isWriteable) {
- _self.error = utils.copy(errorData);
- _isWriteable = false;
- return;
- }
- });
+ //-------------------------------------------------------------------------
+ _getChange: function(itemID, cb) {
+ // returns cb(null, CHANGE)
+ // change ::= { store_id: ID, item_id: GUID, state: STATE, changeSpec: SPEC }
+ itemID = '' + itemID;
+ var self = this;
+ // todo: there must be a way to use IndexedDB since i have everything
+ // needed to generate the keyPath!... eg:
+ // objectStore.get({store_id:X,guid:Y})?...
+ var changedb = self._a._c._txn().objectStore('change').index('store_id');
+ storage.getAll(self._a._c, changedb, {only: self.id}, function(err, changes) {
+ if ( err )
+ return cb(err);
+ var change = _.find(changes, function(change) {
+ return change.item_id == itemID;
+ });
+ return cb(null, change);
+ });
+ },
- this.__defineGetter__("readyState", function () {
- return _self.readyState;
- });
- this.__defineSetter__("readyState", function (readyStateData) {
- if (_isWriteable) {
- _self.readyState = readyStateData;
- _isWriteable = false;
- return;
- }
- });
-}
+ //-------------------------------------------------------------------------
+ _delChange: function(options, cb) {
+ // - if options is null/empty, delete all changes recorded
+ // for this store
-_self = {
- findSensors: function (type) {
- var sensorRequest = new SensorRequest(), index, sensorName = "";
+ // // todo: this is *technically* subject to a race condition... but the
+ // // same peer should really not be synchronizing at the same time...
+ // // todo: also potentially check Change.registered...
+ // // TODO: this could be solved by:
+ // // a) never updating a Change record (only deleting and replacing)
+ // // b) deleting Change records by ID instead of by store/item/state...
- setTimeout(function () {
- if (_permission) {
- for (index = 0; index < _sensors.length; index++) {
- sensorName = _sensors[index];
- if (type === null || type === undefined || type === sensorName) {
- _isWriteable = true;
- sensorRequest.result.push(sensors[sensorName]);
- }
- }
+ // var objstore = session.context._txn().objectStore('change');
+ // storage.iterateCursor(
+ // objstore.index('store_id').openCursor(peerStore.id),
+ // function(value, key, cb) {
+ // if ( value.itemID != chkcmd.source || value.state != constant.ITEM_ADDED )
+ // return;
+ // storage.delete(objstore, key, cb);
+ // }, cb);
- _isWriteable = true;
- sensorRequest.readyState = "done";
+ var dbstore = this._a._c._txn().objectStore('change');
+ var matches = {store_id: this.id};
+ if ( options.itemID )
+ matches.item_id = options.itemID;
+ if ( options.state )
+ matches.state = options.state;
+ storage.deleteAll(dbstore, matches, cb);
+ },
- if (sensorRequest.onsuccess) {
- sensorRequest.onsuccess();
- }
- }
- else {
- // error event on the request with error code PERMISSION_DENIED must be fired.
- sensorRequest.error = new SensorError(-100, "permission denied!");
- if (sensorRequest.onerror) {
- sensorRequest.onerror();
- }
+ //-------------------------------------------------------------------------
+ toSyncML: function() {
+ var xstore = ET.Element('DataStore');
+ if ( this.uri )
+ ET.SubElement(xstore, 'SourceRef').text = this.uri;
+ if ( this.displayName )
+ ET.SubElement(xstore, 'DisplayName').text = this.displayName;
+ if ( this.maxGuidSize )
+ {
+ // todo: this should ONLY be sent by the client... (according to the
+ // spec, but not according to funambol behavior...)
+ ET.SubElement(xstore, 'MaxGUIDSize').text = this.maxGuidSize;
}
- }, 1);
-
- return sensorRequest;
- }
-};
-
-module.exports = _self;
+ if ( this.maxObjSize )
+ ET.SubElement(xstore, 'MaxObjSize').text = this.maxObjSize;
+ var ctypes = this.getContentTypes();
-});
-define('ripple/platform/tizen/2.0/spec/config', function (require, exports, module) {
-/*
- * Copyright 2011 Research In Motion Limited.
- * Copyright 2011 Intel Corporation.
- *
- * 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 utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants');
+ if ( ctypes && ctypes.length > 0 )
+ {
+ var pref = _.filter(ctypes, function(ct) { return ct.receive && ct.preferred; });
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- // no xmlns:JIL in wac 2.0 spec
- valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
+ // todo: should i just take the first one?...
+ if ( pref.length > 1 )
+ throw new Error('agents can prefer at most one receive content-type');
- return valid;
- },
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
- }
+ if ( pref.length == 1 )
+ {
+ pref = pref[0].toSyncML('Rx', true);
+ pref[0].tag = 'Rx-Pref';
+ _.each(pref, function(xnode) { xstore.append(xnode); });
+ }
- var widgetInfo = {},
- configFeatures,
- configPreferences,
- preferenceName,
- platform, rst, i, j,
- settingRst = {
- 'screen-orientation': 'portrait',
- 'context-menu': 'enable',
- 'background-support': 'disable',
- encryption: 'disable',
- 'install-location': 'auto',
- 'hwkey-event': 'enable'
- };
+ _.each(
+ _.filter(ctypes, function(ct) { return ct.receive && ! ct.preferred; }),
+ function(ct) {
+ _.each(ct.toSyncML('Rx', true), function(xnode) {
+ xstore.append(xnode);
+ });
+ });
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
- if (configValidationObject.widget.children.application.validationResult[0].valid) {
- widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
- widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
- }
+ var pref = _.filter(ctypes, function(ct) { return ct.transmit && ct.preferred; });
- widgetInfo.features = {};
+ // todo: should i just take the first one?...
+ if ( pref.length > 1 )
+ throw new Error('agents can prefer at most one transmit content-type');
- if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
- rst = configValidationObject.widget.children.setting.validationResult;
- // the first one has higher priority per platform implementation
- for (i = rst.length -1 ; i >= 0; i--) {
- if (rst[i].valid === true) {
- for (j in rst[i].attributes) {
- if (rst[i].attributes[j].value !== undefined) {
- settingRst[j] = rst[i].attributes[j].value;
- }
- }
+ if ( pref.length == 1 )
+ {
+ pref = pref[0].toSyncML('Tx', true);
+ pref[0].tag = 'Tx-Pref';
+ _.each(pref, function(xnode) { xstore.append(xnode); });
}
- }
- db.save("layout", settingRst["screen-orientation"]);
- }
-
- configFeatures = configValidationObject.widget.children.feature.validationResult;
- utils.forEach(configFeatures, function (f) {
- if (f.valid === true) {
- var feature = {id: f.attributes.name.value,
- required: f.attributes.required.valid};
- widgetInfo.features[feature.id] = feature;
- }
- });
-
- widgetInfo.preferences = {};
-
- configPreferences = configValidationObject.widget.children.preference.validationResult;
- platform = require('ripple/platform');
- utils.forEach(configPreferences, function (preference) {
- preferenceName = preference.attributes.name.value;
- if (preferenceName) {
- widgetInfo.preferences[preferenceName] = {
- "key": preferenceName,
- "value": preference.attributes.value.value || "",
- "readonly": preference.attributes.readonly.value === "true"
- };
+ _.each(
+ _.filter(ctypes, function(ct) { return ct.transmit && ! ct.preferred; }),
+ function(ct) {
+ _.each(ct.toSyncML('Tx', true), function(xnode) {
+ xstore.append(xnode);
+ });
+ });
- db.save(preferenceName,
- widgetInfo.preferences[preferenceName].value,
- platform.getPersistencePrefix(widgetInfo.id));
}
- });
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:tizen": {
- attributeName: "xmlns:tizen",
- required: false,
- type: "list",
- listValues: ["http://tizen.org/ns/widgets"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
- },
- defaultlocale: {
- attributeName: "defaultlocale",
- required: false,
- type: "iso-language"
- },
- },
- children: {
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- "short": {
- attributeName: "short",
- required: false,
- type: "string"
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- required: false,
- type: "regex",
- regex: constants.REGEX.URL
- },
- email: {
- attributeName: "email",
- required: false,
- type: "regex",
- regex: constants.REGEX.EMAIL
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- encoding: {
- attributeName: "encoding",
- required: false,
- type: "string"
- },
- type: {
- attributeName: "type",
- required: false,
- type: "string"
- }
- }
- },
- setting: {
- nodeName: "tizen:setting",
- required: false,
- occurrence: 0,
- attributes: {
- 'screen-orientation': {
- attributeName: "screen-orientation",
- required: false,
- type: "list",
- listValues: ['portrait', 'landscape', 'auto']
- },
- 'context-menu': {
- attributeName: "context-menu",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'background-support': {
- attributeName: "background-support",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'encryption': {
- attributeName: "encryption",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- },
- 'install-location': {
- attributeName: "install-location",
- required: false,
- type: "list",
- listValues: ['auto', 'internal-only', 'perfer-external']
- },
- 'hwkey-event': {
- attributeName: "hwkey-event",
- required: false,
- type: "list",
- listValues: ['enable', 'disable']
- }
- }
- },
- application: {
- nodeName: "tizen:application",
- required: true,
- occurrence: 1,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- },
- required_version: {
- attributeName: "required_version",
- required: true,
- type: "list",
- listValues: ['1.0', '2.0', '2.1', '2.2']
- },
- package: {
- attributeName: "package",
- required: false,
- type: "string"
- }
- }
- },
- "tizen:content": {
- nodeName: "tizen:content",
- required: false,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- }
- }
- },
- control: {
- nodeName: "tizen:app-control",
- required: false,
- occurrence: 0,
- children: {
- src: {
- nodeName: "tizen:src",
- required: true,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- operation: {
- nodeName: "tizen:operation",
- required: true,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- uri: {
- nodeName: "tizen:uri",
- required: false,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- },
- mime: {
- nodeName: "tizen:mime",
- required: false,
- occurence: 0,
- attributes: {
- name: {
- attributeName: "name",
- required: false,
- type: "string"
- }
- }
- }
- }
- },
- "app-widget": {
- nodeName: "tizen:app-widget",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- },
- primary: {
- attributeName: "primary",
- required: true,
- type: "list",
- listValues: ['true', 'false']
- },
- "auto-launch": {
- attributeName: "auto-launch",
- required: false,
- type: "list",
- listValues: ['true', 'false']
- },
- "update-period": {
- attributeName: "update-period",
- required: false,
- type: "integer"
- }
- },
- children: {
- "box-label": {
- nodeName: "tizen:box-label",
- required: true,
- occurence: 1
- },
- "box-icon": {
- nodeName: "tizen:box-icon",
- required: true,
- occurence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- }
- }
- },
- "box-content": {
- nodeName: "tizen:box-content",
- required: true,
- occurence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- "mouse-event": {
- attributeName: "mouse-event",
- required: false,
- type: "string"
- },
- "touch-event": {
- attributeName: "touch-event",
- required: false,
- type: "string"
- }
- },
- children: {
- "box-size": {
- nodeName: "tizen:box-size",
- required: false,
- occurence: 1,
- attributes: {
- "preview": {
- attributeName: "preview",
- required: false,
- type: "string"
- }
- }
- },
- pd: {
- nodeName: "tizen:pd",
- required: false,
- occurence: 1,
- attributes: {
- "src": {
- attributeName: "src",
- required: true,
- type: "string"
- },
- "width": {
- attributeName: "width",
- required: true,
- type: "integer"
- },
- "height": {
- attributeName: "height",
- required: true,
- type: "integer"
- }
- }
- }
- }
- }
- }
- },
- account: {
- nodeName: "tizen:account",
- required: false,
- occurrence: 0,
- attributes: {
- "multiple-account-support": {
- attributeName: "multiple-account-support",
- required: true,
- type: "list",
- listValues: ['true', 'false']
- }
- },
- children: {
- icon: {
- nodeName: "tizen:icon",
- required: false,
- occurence: 1,
- attributes: {
- section: {
- attributeName: "section",
- required: true,
- type: "string"
- }
- }
- },
- "display-name": {
- nodeName: "tizen:display-name",
- required: false,
- occurence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "string"
- }
- }
- },
- capability: {
- nodeName: "capability",
- required: false,
- occurence: 1
- }
- }
- },
- feature: {
- nodeName: "tizen:privilege",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/TR/battery-status/",
- "http://www.w3.org/TR/geolocation-API/",
- "http://www.w3.org/TR/touch-events/",
- "http://www.w3.org/TR/vibration/",
- "http://tizen.org/privilege/tizen",
- "http://tizen.org/privilege/alarm",
- "http://tizen.org/privilege/application.launch",
- "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
- "http://tizen.org/privilege/bluetoothmanager", "http://tizen.org/privilege/bluetooth.admin",
- "http://tizen.org/privilege/bluetooth.gap", "http://tizen.org/privilege/bluetooth.spp",
- "http://tizen.org/privilege/bookmark.read", "http://tizen.org/privilege/bookmark.write",
- "http://tizen.org/privilege/calendar.read", "http://tizen.org/privilege/calendar.write",
- "http://tizen.org/privilege/callhistory.read", "http://tizen.org/privilege/callhistory.write",
- "http://tizen.org/privilege/contact.read", "http://tizen.org/privilege/contact.write",
- "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
- "http://tizen.org/privilege/datacontrol.consumer",
- "http://tizen.org/privilege/datasync",
- "http://tizen.org/privilege/download",
- "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
- "http://tizen.org/privilege/messaging.read", "http://tizen.org/privilege/messaging.write",
- "http://tizen.org/privilege/networkbearerselection",
- "http://tizen.org/privilege/nfc.common", "http://tizen.org/privilege/nfc.admin",
- "http://tizen.org/privilege/nfc.tag", "http://tizen.org/privilege/nfc.p2p",
- "http://tizen.org/privilege/notification",
- "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
- "http://tizen.org/privilege/power",
- "http://tizen.org/privilege/push",
- "http://tizen.org/privilege/setting",
- "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
- "http://tizen.org/privilege/time"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- },
- children: {
- param: {
- nodeName: "param",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string",
- },
- value: {
- attributeName: "value",
- required: true,
- type: "string",
- }
- }
- }
- }
- },
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string"
- },
- value: {
- type: "string",
- required: false,
- attributeName: "value"
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
+ if ( this.syncTypes && this.syncTypes.length > 0 )
+ {
+ var xcap = ET.SubElement(xstore, 'SyncCap');
+ for ( var idx=0 ; idx<this.syncTypes.length ; idx++ )
+ ET.SubElement(xcap, 'SyncType').text = this.syncTypes[idx];
+ }
+ return xstore;
+
+ },
+
+ //-------------------------------------------------------------------------
+ describe: function(stream, cb) {
+ stream.writeln('URI: ' + this.uri);
+ stream.writeln('Max ID size: ' + ( this.maxGuidSize || '(none)' ));
+ stream.writeln('Max object size: ' + ( this.maxObjSize || '(none)' ));
+ stream.writeln('Sync types: ' + this.syncTypes.join(', '));
+ var cts = this.getContentTypes();
+ if ( cts.length <= 0 )
+ {
+ stream.writeln('Capabilities: (none)');
+ return cb();
+ }
+ stream.writeln('Capabilities:');
+ var s1 = new common.IndentStream(stream);
+ common.cascade(cts, function(ct, cb) {
+ s1.write('- ');
+ ct.describe(s1);
+ return cb();
+ }, cb);
+ }
+ }, {
+
+ //-------------------------------------------------------------------------
+ fromSyncML: function(xnode) {
+ var options = {
+ uri : xnode.findtext('SourceRef'),
+ displayName : xnode.findtext('DisplayName'),
+ maxGuidSize : common.int(xnode.findtext('MaxGUIDSize')),
+ maxObjSize : common.int(xnode.findtext('MaxObjSize')),
+ contentTypes : [],
+ syncTypes : _.map(xnode.findall('SyncCap/SyncType'), function(e) {
+ return common.int(e.text);
+ })
+ };
+ _.each(xnode.getchildren(), function(child) {
+ if ( _.indexOf(['Rx-Pref', 'Rx', 'Tx-Pref', 'Tx'], child.tag) < 0 )
+ return;
+ var cti = ctype.ContentTypeInfo.fromSyncML(child);
+ var merged = false;
+ _.each(options.contentTypes, function(ct) {
+ if ( merged )
+ return;
+ if ( ct.merge(cti) )
+ merged = true;
+ });
+ if ( ! merged )
+ options.contentTypes.push(cti);
+ });
+ return new exports.Store(null, options);
+ },
+ });
+
+ return exports;
+
+})();
+
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/syncml-js-lib/matcher', function (require, exports, module) {
+// -*- coding: utf-8 -*-
+//-----------------------------------------------------------------------------
+// file: $Id$
+// lib: syncml-js.matcher
+// auth: griffin <griffin@uberdev.org>
+// date: 2012/12/05
+// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
+//-----------------------------------------------------------------------------
+
+var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+ _self;
+
+_self = (function () {
+
+ var exports = {};
+
+ //---------------------------------------------------------------------------
+ exports._cntpref = function(source, target) {
+ return ( source.preferred ? 1 : 0 ) + ( target.preferred ? 1 : 0 );
+ };
+
+ //---------------------------------------------------------------------------
+ exports._pickTransmitContentType = function(source, target, prefcnt, checkVersion) {
+ for ( var sidx=0 ; sidx<source.length ; sidx++ )
+{
+ var sct = source[sidx];
+ for ( var tidx=0 ; tidx<target.length ; tidx++ )
+{
+ var tct = target[tidx];
+ if ( sct.ctype != tct.ctype )
+ continue;
+if ( ! checkVersion )
+{
+ if ( exports._cntpref(sct, tct) >= prefcnt )
+ return [sct.ctype, sct.versions[sct.versions.length - 1]];
+ continue;
+}
+for ( var svidx=sct.versions.length ; svidx>0 ; svidx-- )
+{
+ var sv = sct.versions[svidx - 1]
+ for ( var tvidx=tct.versions.length ; tvidx>0 ; tvidx-- )
+ {
+ var tv = tct.versions[tvidx - 1]
+ if ( sv != tv )
+ continue;
+ if ( exports._cntpref(sct, tct) >= prefcnt )
+ return [sct.ctype, sv];
+ }
+}
+}
+}
+return null;
+};
+
+//---------------------------------------------------------------------------
+exports.pickTransmitContentType = function(source, target) {
+
+ // TODO: this is probably not the most efficient algorithm!...
+ // (but it works... ;-)
+
+ // order of preference:
+ // - transmit => receive, BOTH preferred, VERSION match
+ // - transmit => receive, ONE preferred, VERSION match
+ // - transmit => receive, neither preferred, VERSION match
+ // - transmit => receive, BOTH preferred, no version match
+ // - transmit => receive, ONE preferred, no version match
+ // - transmit => receive, neither preferred, no version match
+ // - tx/rx => tx/rx, BOTH preferred, VERSION match
+ // - tx/rx => tx/rx, ONE preferred, VERSION match
+ // - tx/rx => tx/rx, neither preferred, VERSION match
+ // - tx/rx => tx/rx, BOTH preferred, no version match
+ // - tx/rx => tx/rx, ONE preferred, no version match
+ // - tx/rx => tx/rx, neither preferred, no version match
+
+ // todo: make it explicit (or overrideable) that i am depending on the ordering
+ // of the versions supported to give an indicator of preference...
+
+ var sct = source.getContentTypes();
+ var tct = target.getContentTypes();
+
+ var fct = function(cts, transmit) {
+ return _.filter(cts, function(ct) {
+ return transmit ? ct.transmit : ct.receive;
+ });
+ };
+
+ return exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, true)
+ || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, true)
+ || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, true)
+ || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, false)
+ || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, false)
+ || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, false)
+ || exports._pickTransmitContentType(sct, tct, 2, true)
+ || exports._pickTransmitContentType(sct, tct, 1, true)
+ || exports._pickTransmitContentType(sct, tct, 0, true)
+ || exports._pickTransmitContentType(sct, tct, 2, false)
+ || exports._pickTransmitContentType(sct, tct, 1, false)
+ || exports._pickTransmitContentType(sct, tct, 0, false)
+ || null;
+
+};
+
+// TODO: OH MY GOD.
+// this is insanely inefficient.
+// i'm embarrassed.
+// fortunately, it's hidden really low-level...
+// but now you know, doh! please don't blackmail me!... ;-)
+
+// TODO: this currently requires that both tx and rx match in both
+// directions with the same velocity... it should prioritize
+// that, but then fallback to giving simplex matches priority.
+
+//---------------------------------------------------------------------------
+var has_ct = function(a, b, checkVersion, transmit, wildcard) {
+ a = _.filter(a, function(e) { return transmit ? e.transmit : e.receive });
+ b = _.filter(b, function(e) { return transmit ? e.transmit : e.receive });
+ for ( var aidx=0 ; aidx<a.length ; aidx++ )
+ {
+ var ct_a = a[aidx];
+ for ( var bidx=0 ; bidx<b.length ; bidx++ )
+ {
+ var ct_b = b[bidx];
+ if ( ct_a.ctype != ct_b.ctype )
+ continue;
+ if ( ! checkVersion )
+ return true;
+ for ( var vaidx=0 ; vaidx<ct_a.versions.length ; vaidx++ )
+ {
+ var va = ct_a.versions[vaidx];
+ for ( var vbidx=0 ; vbidx<ct_b.length ; vbidx++ )
+ {
+ var vb = ct_b.versions[vbidx];
+ if ( va == vb )
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+};
+
+//---------------------------------------------------------------------------
+var has_ct_both = function(a, b, checkVersion, wildcard) {
+ return has_ct(a, b, checkVersion, true, wildcard)
+ && has_ct(a, b, checkVersion, false, wildcard);
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_ct_set_crit = function(base, ds1, ds2, checkVersion, wildcard) {
+ var bds1 = has_ct_both(base, ds1, checkVersion, wildcard);
+ var bds2 = has_ct_both(base, ds2, checkVersion, wildcard);
+ if ( bds1 && bds2 )
+ return 0;
+ if ( bds1 )
+ return -1;
+ if ( bds2 )
+ return 1;
+ return 0;
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_ct_set = function(base, ds1, ds2) {
+ var ret = cmpStore_ct_set_crit(base, ds1, ds2, true, false);
+ if ( ret != 0 )
+ return ret;
+ ret = cmpStore_ct_set_crit(base, ds1, ds2, false, false);
+ if ( ret != 0 )
+ return ret;
+ ret = cmpStore_ct_set_crit(base, ds1, ds2, true, true);
+ if ( ret != 0 )
+ return ret;
+ ret = cmpStore_ct_set_crit(base, ds1, ds2, false, true);
+ if ( ret != 0 )
+ return ret;
+ return 0;
+};
+
+//---------------------------------------------------------------------------
+var getct = function(store) {
+ return store.getContentTypes ? store.getContentTypes() : store.contentTypes;
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_ct_pref = function(base, ds1, ds2) {
+ var basect = _.filter(getct(base), function(ct) { return ct.preferred; });
+ var ds1ct = _.filter(getct(ds1), function(ct) { return ct.preferred; });
+ var ds2ct = _.filter(getct(ds2), function(ct) { return ct.preferred; });
+ return cmpStore_ct_set(basect, ds1ct, ds2ct);
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_ct_all = function(base, ds1, ds2) {
+ return cmpStore_ct_set(getct(base), getct(ds1), getct(ds2));
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_ct = function(base, ds1, ds2) {
+ var ret = cmpStore_ct_pref(base, ds1, ds2)
+ if ( ret != 0 )
+ return ret;
+ return cmpStore_ct_all(base, ds1, ds2);
+};
+
+//---------------------------------------------------------------------------
+var cmpStore_uri = function(base, ds1, ds2) {
+ var ret = difflib.getCloseMatches(base.uri, [ds1.uri, ds2.uri], 1, 0.5);
+ if ( ret.length <= 0 )
+ return 0;
+ if ( ret[0] == ds1.uri )
+ return -1;
+ return 1;
+};
+
+//---------------------------------------------------------------------------
+exports.cmpStore = function(base, ds1, ds2) {
+ var ret = cmpStore_ct(base, ds1, ds2);
+ if ( ret != 0 )
+ return ret;
+ return cmpStore_uri(base, ds1, ds2);
+};
+
+return exports;
+
+})();
+
+module.exports = _self;
+
+
+});
+define('ripple/platform/tizen/2.0/NDEFMessage', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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 t = require('ripple/platform/tizen/2.0/typecast'),
+ NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecord'),
+ NDEFRecordText = require('ripple/platform/tizen/2.0/NDEFRecordText'),
+ NDEFRecordURI = require('ripple/platform/tizen/2.0/NDEFRecordURI'),
+ NDEFRecordMedia = require('ripple/platform/tizen/2.0/NDEFRecordMedia'),
+ NDEFRecordFactory,
+ NDEFMessage;
+
+NDEFRecordFactory = function (ndefRecord) {
+ var record;
+
+ if (ndefRecord instanceof NDEFRecordText) {
+ record = new NDEFRecordText(ndefRecord.text, ndefRecord.languageCode,
+ ndefRecord.encoding || null);
+ } else if (ndefRecord instanceof NDEFRecordURI) {
+ record = new NDEFRecordURI(ndefRecord.url);
+ } else if (ndefRecord instanceof NDEFRecordMedia) {
+ record = new NDEFRecordMedia(ndefRecord.mimeType, ndefRecord.payload);
+ } else {
+ record = new NDEFRecord(ndefRecord.tnf, ndefRecord.type,
+ ndefRecord.payload, ndefRecord.id || null);
+ }
+
+ return record;
+};
+
+NDEFMessage = function () {
+ var voc, records = [];
+
+ // private
+ function construct() {
+ this.__defineGetter__("recordCount", function () {
+ return this.records.length;
+ });
+
+ this.__defineGetter__("records", function () {
+ return records;
+ });
+
+ this.__defineSetter__("records", function (val) {
+ try {
+ t.NDEFRecord(val, "[]");
+ records = val;
+ } catch (e) {
+ }
+ });
+
+ this.toByte = function () {
+ var result = [], i, j, space = " ".charCodeAt(0);
+
+ for (i in this.records) {
+ for (j = 0; j < this.records[i].payload.length; j++) {
+ result.push(this.records[i].payload.charCodeAt(j));
+ }
+ if (i < this.records.length - 1) {
+ result.push(space);
}
}
+
+ return result;
+ };
+ }
+
+ // constructor
+ function NDEFMessage_NDEFRecords(ndefRecords) {
+ var i;
+
+ construct.apply(this);
+
+ for (i = 0; i < ndefRecords.length; i++) {
+ records[i] = new NDEFRecordFactory(ndefRecords[i]);
}
}
+
+ function NDEFMessage_bytes(rawData) {
+ //TODO: NDEFMessage doesn't support rawData constructor
+ construct.apply(this);
+ }
+
+ function NDEFMessage_void() {
+ construct.apply(this);
+ }
+
+ voc = [NDEFMessage_NDEFRecords, NDEFMessage_bytes, NDEFMessage_void];
+ t.NDEFMessage(arguments, this, voc);
};
+module.exports = NDEFMessage;
+
});
-define('ripple/platform/tizen/2.0/spec/device', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/bluetooth', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- utils = require('ripple/utils'),
- StorageTypeTable = {
- "UNKNOWN": "UNKNOWN",
- "INTERNAL": "INTERNAL",
- "MMC": "MMC",
- "USB_HOST": "USB_HOST"
- },
- NetworkTypeTable = {
- "NONE": "NONE",
- "2G": "2G",
- "2.5G": "2.5G",
- "3G": "3G",
- "4G": "4G",
- "WIFI": "WIFI",
- "ETHERNET": "ETHERNET",
- "UNKNOWN": "UNKNOWN"
+
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BluetoothDevice = require('ripple/platform/tizen/2.0/BluetoothDevice'),
+ BluetoothClassDeviceMajor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor'),
+ BluetoothClassDeviceMinor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor'),
+ BluetoothClassDeviceService = require('ripple/platform/tizen/2.0/BluetoothClassDeviceService'),
+ BluetoothServiceHandler = require('ripple/platform/tizen/2.0/BluetoothServiceHandler'),
+ BluetoothAdapter,
+ _data = {
+ DB_BLUETOOTH_KEY: "tizen1-db-bluetooth_adapter-name",
+ DEFAULT_ADAPTER_NAME: "Tizen BT Adapter",
+ DEFAULT_ADAPTER_ADDRESS: "12:34:56:78:90:AB",
+ availableDevsChanging: false,
+ DEFAULT_VISIBLE_TIME: 180000,
+ DISCOVER_TIME: 10000,
+ DISCOVER_INTERVAL: 1000,
+ bluetoothClassDeviceMajor: {},
+ bluetoothClassDeviceMinor: {},
+ bluetoothClassDeviceService: {},
+ adapter: {},
+ historyDevs: {},
+ availableDevs: {},
+ localServices: {}
},
- LocaleTable = {
- "eng_USA": "eng_USA",
- "eng_CAN": "eng_CAN",
- "deu_DEU": "deu_DEU",
- "jpn_JPN": "jpn_JPN",
- "zho_CHN": "zho_CHN",
- "UNKNOWN": "UNKNOWN"
+ _security = {
+ "http://tizen.org/privilege/bluetoothmanager": ["setVisible"],
+ "http://tizen.org/privilege/bluetooth.admin": ["setName", "setPowered"],
+ "http://tizen.org/privilege/bluetooth.gap": ["getDefaultAdapter",
+ "discoverDevices", "stopDiscovery", "getKnownDevices",
+ "getDevice", "createBonding", "destroyBonding", "hasService"],
+ "http://tizen.org/privilege/bluetooth.spp":
+ ["registerRFCOMMServiceByUUID", "connectToServiceByUUID",
+ "writeData", "readData", "close", "unregister"]
},
- SimStateTable = {
- "ABSENT": "ABSENT",
- "INITIALIZING": "INITIALIZING",
- "READY": "READY",
- "PIN_REQUIRED": "PIN_REQUIRED",
- "PUK_REQUIRED":"PUK_REQUIRED",
- "NETWORK_LOCKED": "NETWORK_LOCKED",
- "SIM_LOCKED": "SIM_LOCKED",
- "UNKNOWN": "UNKNOWN"
- };
+ _self;
-function deviceStatusEventTrigger(setting) {
- event.trigger("DeviceStatusChanged", [setting]);
+function _initialize() {
+ var adapterName, devs;
+
+ _data.bluetoothClassDeviceMajor = new BluetoothClassDeviceMajor();
+ _data.bluetoothClassDeviceMinor = new BluetoothClassDeviceMinor();
+ _data.bluetoothClassDeviceService = new BluetoothClassDeviceService();
+ adapterName = db.retrieveObject(_data.DB_BLUETOOTH_KEY) ||
+ _data.DEFAULT_ADAPTER_NAME;
+ _data.adapter = new BluetoothAdapter(adapterName,
+ _data.DEFAULT_ADAPTER_ADDRESS);
+
+ // get defalt nearby devices
+ devs = db.retrieveObject("bt-simulated-devices");
+ utils.forEach(devs, function (item) {
+ if (!_data.availableDevs[item.address]) {
+ _data.availableDevs[item.address] = new BluetoothDevice({
+ name: item.name,
+ address: item.address,
+ deviceClass: item.deviceClass,
+ isBonded: false,
+ isTrusted: item.isTrusted,
+ isConnected: false,
+ services: item.services,
+ metaData: _security
+ });
+ }
+ });
}
-module.exports = {
- "Config": {
- "vibratingMode": {
- "name": "Vibrator",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("VibratingModeChanged", [setting]);
- }
- },
- "lockScreen": {
- "name": "Lock Screen",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "callback": function (setting) {
- event.trigger("LockScreenChanged", [setting]);
+BluetoothAdapter = function (devName, devAddress) {
+ var adapter,
+ timeoutVar,
+ _devName = devName,
+ _devAddress = devAddress,
+ _devPowered = false,
+ _devVisible = false,
+ _isDiscovering = false,
+ discoverInterval;
+
+ // private
+ function updateVisibleStatus(status, time) {
+ if (!_devPowered)
+ return;
+
+ _devVisible = status;
+ event.trigger("bt-adapter-visible-changed", [_devVisible]);
+ if (_devVisible) {
+ if (time > 0) {
+ timeoutVar = window.setTimeout(function () {
+ _devVisible = false;
+ event.trigger("bt-adapter-visible-changed", [_devVisible]);
+ }, time);
}
+ } else {
+ window.clearTimeout(timeoutVar);
}
- },
- "DEVICE_ORIENTATION": {
- "status": {
- "name": "Status",
- "control": {
- "type": "label",
- "innertext": "PORTRAIT_PRIMARY",
- "value": "PORTRAIT_PRIMARY"
- },
- "event": "LayoutChanged"
- },
- "isAutoRotation": {
- "name": "Is Auto Rotation",
- "control": {
- "type": "label",
- "value": false
- }
+ }
+
+ function updatePowerStatus(status) {
+ if (_devPowered === status) {
+ return;
}
- },
- "CPU": {
- "load": {
- "name": "Load",
- "control": {
- "type": "number",
- "value": 0.1
- },
- "event": "CpuLoadChanged",
- "callback": function (setting) {
- if (setting > 1) setting = 1;
- if (setting < 0) setting = 0;
- event.trigger("CpuLoadChanged", [setting]);
- }
+ if (!status) {
+ updateVisibleStatus(false);
+ utils.forEach(_data.historyDevs, function (dev) {
+ event.trigger("bt-service-state-update", [dev.address, false]);
+ event.trigger("bt-device-bonded-changed", [dev.address, false]);
+ jQuery("#service-transfer-textarea-" + dev.address.replace(/:/g, "")).val("");
+ jQuery("#service-receive-textarea-" + dev.address.replace(/:/g, "")).html("");
+ });
}
- },
- "STORAGE": {
- "type": {
- "name": "Type",
- "control": {
- "type": "select",
- "value": StorageTypeTable["INTERNAL"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(StorageTypeTable, function (key, value) {
- optionList[key] = StorageTypeTable[value];
- });
+ _devPowered = status;
+ event.trigger("bt-adapter-power-changed", [_devPowered]);
+ }
- return optionList;
- }())
- },
- "capacity": {
- "name": "Capacity(bytes)",
- "control": {
- "type": "label",
- "value": 16000000000
- },
- },
- "availableCapacity": {
- "name": "AvailableCapacity(bytes)",
- "control": {
- "type": "number",
- "value": 12000000000
- },
- "callback": function (setting) {
- event.trigger("AvailCapacityChanged", [setting]);
- }
- },
- "isRemovable": {
- "name": "IsRemovable",
- "control": {
- "type": "checkbox",
- "value": true
- }
+ // public
+ function setName(name, successCallback, errorCallback) {
+ if (!_security.setName) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- },
- "BUILD": {
- "model": {
- "name": "Model",
- "control": {
- "type": "label",
- "innertext": "tizen-2.2 build",
- "value": "tizen-2.2 build"
- }
- },
- "manufacturer": {
- "name": "Manufacturer",
- "control": {
- "type": "label",
- "innertext": "Tizen",
- "value": "Tizen"
+
+ t.BluetoothAdapter("setName", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "buildVersion": {
- "name": "Build Version",
- "control": {
- "type": "label",
- "innertext": "TIZEN_WEB_SIMULATOR_000001",
- "value": "TIZEN_WEB_SIMULATOR_000001"
+
+ _devName = name;
+ db.saveObject(_data.DB_BLUETOOTH_KEY, _devName);
+ event.trigger("bt-adapter-name-changed", [_devName]);
+ if (successCallback) {
+ successCallback();
}
+ }, 1);
+ }
+
+ function setPowered(state, successCallback, errorCallback) {
+ if (!_security.setPowered) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- },
- "LOCALE": {
- "language": {
- "name": "Language",
- "control": {
- "type": "select",
- "value": LocaleTable["eng_USA"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(LocaleTable, function (key, value) {
- optionList[key] = LocaleTable[value];
- });
- return optionList;
- }())
- },
- "country": {
- "name": "Country",
- "control": {
- "type": "select",
- "value": LocaleTable["eng_USA"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(LocaleTable, function (key, value) {
- optionList[key] = LocaleTable[value];
- });
+ t.BluetoothAdapter("setPowered", arguments);
- return optionList;
- }())
- }
- },
- "DISPLAY": {
- "resolutionWidth": {
- "name": "Resolution Width(pixels)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "resolutionHeight": {
- "name": "Resolution Height(pixels)",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "dotsPerInchWidth": {
- "name": "DPI-X",
- "control": {
- "type": "label",
- "value": 0
- }
- },
- "dotsPerInchHeight": {
- "name": "DPI-Y",
- "control": {
- "type": "label",
- "value": 0
+ window.setTimeout(function () {
+ updatePowerStatus(state);
+ if (successCallback) {
+ successCallback();
}
- },
- "physicalWidth": {
- "name": "Physical Width(millimeters)",
- "control": {
- "type": "label",
- "value": 0
+ }, 1);
+ }
+
+ function setVisible(mode, successCallback, errorCallback, timeout) {
+ if (!_security.setVisible) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothAdapter("setVisible", arguments);
+
+ window.setTimeout(function () {
+ var time;
+
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "physicalHeight": {
- "name": "Physical Height(millimeters)",
- "control": {
- "type": "label",
- "value": 0
+
+ if (typeof timeout === "number") {
+ if (timeout < 0) {
+ time = _data.DEFAULT_VISIBLE_TIME;
+ } else {
+ time = timeout * 1000;
+ }
+ } else {
+ time = _data.DEFAULT_VISIBLE_TIME;
}
- },
- "brightness": {
- "name": "Brightness",
- "control": {
- "type": "number",
- "value": 1
- },
- "event": "DisplayBrightnessChanged",
- "callback": function (setting) {
- if (setting > 1) setting = 1;
- if (setting < 0) setting = 0;
- event.trigger("DisplayBrightnessChanged", [setting]);
+ updateVisibleStatus(mode, time);
+
+ if (successCallback) {
+ successCallback();
}
- }
- },
- "NETWORK": {
- "networkType": {
- "name": "Network Type",
- "control" : {
- "type": "select",
- "value": NetworkTypeTable["NONE"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(NetworkTypeTable, function (key, value) {
- optionList[key] = NetworkTypeTable[value];
- });
+ }, 1);
+ }
- return optionList;
- }())
+ function discoverDevices(successCallback, errorCallback) {
+ if (!_security.discoverDevices) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- },
- "WIFI_NETWORK": {
- "status": {
- "name": "Status",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "event": "WiFiNetworkStatusChanged",
- "callback": function (setting) {
- event.trigger("WiFiNetworkStatusChanged", [setting]);
- }
- },
- "ssid": {
- "name": "SSID",
- "control": {
- "type": "text",
- "value": "Tizen WiFi"
- }
- },
- "ipAddress": {
- "name": "IP Address",
- "control": {
- "type": "text",
- "value": "192.168.0.1"
+
+ t.BluetoothAdapter("discoverDevices", arguments);
+
+ window.setTimeout(function () {
+ var interval;
+
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "ipv6Address": {
- "name": "IPv6 Address",
- "control": {
- "type": "text",
- "value": "2001:db8:85a3:0:0:0:70:7334"
+
+ // already discovering
+ if (_isDiscovering) {
+ return;
}
- },
- "signalStrength": {
- "name": "Signal Strength",
- "control": {
- "type": "select",
- "value": 0
- },
- "options": (function () {
- var i,
- optionList = {};
- for (i = 0; i <= 10; i++) {
- optionList[i] = i;
+ _isDiscovering = true;
+ _data.historyDevs = {};
+
+ successCallback.onstarted();
+
+ _data.availableDevsChanging = false;
+ utils.forEach(_data.availableDevs, function (item) {
+ _data.historyDevs[item.address] = item;
+ successCallback.ondevicefound(item);
+ });
+
+ discoverInterval = window.setTimeout(function () {
+ var devs = [];
+
+ window.clearInterval(interval);
+ utils.forEach(_data.historyDevs, function (item) {
+ devs.push(item);
+ });
+ successCallback.onfinished(devs);
+ _isDiscovering = false;
+ }, _data.DISCOVER_TIME);
+
+ interval = window.setInterval(function () {
+ var removeList = [], i;
+
+ if (!_isDiscovering) {
+ window.clearInterval(interval);
+ return;
}
- return optionList;
- }())
+ if (_data.availableDevsChanging) {
+ _data.availableDevsChanging = false;
+ utils.forEach(_data.historyDevs, function (item) {
+ if (!_data.availableDevs[item.address]) {
+ removeList.push(item.address);
+ }
+ });
+ for (i in removeList) {
+ successCallback.ondevicedisappeared(removeList[i]);
+ delete _data.historyDevs[removeList[i]];
+ }
+ utils.forEach(_data.availableDevs, function (item) {
+ if (!_data.historyDevs[item.address]) {
+ _data.historyDevs[item.address] = item;
+ successCallback.ondevicefound(item);
+ }
+ });
+ }
+ }, _data.DISCOVER_INTERVAL);
+ }, 1);
+ }
+
+ function stopDiscovery(successCallback, errorCallback) {
+ if (!_security.stopDiscovery) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- },
- "CELLULAR_NETWORK": {
- "status": {
- "name": "Status",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "CellularNetworkStatusChanged",
- "callback": function (setting) {
- event.trigger("CellularNetworkStatusChanged", [setting]);
- }
- },
- "apn": {
- "name": "APN",
- "control": {
- "type": "text",
- "value": "Tizen"
- }
- },
- "ipAddress": {
- "name": "IP Address",
- "control": {
- "type": "text",
- "value": "10.0.2.16"
- }
- },
- "ipv6Address": {
- "name": "IPv6 Address",
- "control": {
- "type": "text",
- "value": "2001:db8:85a3:0:0:0:70:7334"
+
+ t.BluetoothAdapter("stopDiscovery", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "mcc": {
- "name": "MCC",
- "control": {
- "type": "number",
- "value": 460
+
+ if (_isDiscovering) {
+ window.clearTimeout(discoverInterval);
}
- },
- "mnc": {
- "name": "MNC",
- "control": {
- "type": "number",
- "value": 0
+ _isDiscovering = false;
+ if (successCallback) {
+ successCallback();
}
- },
- "cellId": {
- "name": "Cell ID",
- "control": {
- "type": "number",
- "value": 0
+ }, 1);
+ }
+
+ function getKnownDevices(successCallback, errorCallback) {
+ if (!_security.getKnownDevices) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothAdapter("getKnownDevices", arguments);
+
+ window.setTimeout(function () {
+ var devs = [];
+
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "lac": {
- "name": "LAC",
- "control": {
- "type": "number",
- "value": 0
+ utils.forEach(_data.historyDevs, function (item) {
+ devs.push(new BluetoothDevice({
+ name: item.name,
+ address: item.address,
+ deviceClass: item.deviceClass,
+ isBonded: false,
+ isTrusted: item.isTrusted,
+ isConnected: false,
+ services: item.services,
+ metaData: _security
+ }));
+ });
+ successCallback(devs);
+ }, 1);
+ }
+
+ function getDevice(address, successCallback, errorCallback) {
+ if (!_security.getDevice) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothAdapter("getDevice", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "isRoaming": {
- "name": "Roaming",
- "control": {
- "type": "checkbox",
- "value": true
+
+ if (!_data.historyDevs[address]) {
+ if (!_data.availableDevs[address]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+
+ _data.historyDevs[address] = _data.availableDevs[address];
}
- },
- "isFlightMode": {
- "name": "Flight Mode",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "callback": function (setting) {
- event.trigger("FlightModeChanged", [setting]);
+
+ successCallback(_data.historyDevs[address]);
+ }, 1);
+ }
+
+ function createBonding(address, successCallback, errorCallback) {
+ if (!_security.createBonding) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothAdapter("createBonding", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "imei": {
- "name": "IMEI",
- "control": {
- "type": "text",
- "value": "012417005203000"
+
+ if (!_data.historyDevs[address]) {
+ if (!_data.availableDevs[address]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+
+ _data.historyDevs[address] = _data.availableDevs[address];
}
+
+ event.trigger("bt-device-bonded-changed", [address, true]);
+ successCallback(_data.historyDevs[address]);
+ }, 1);
+ }
+
+ function destroyBonding(address, successCallback, errorCallback) {
+ if (!_security.destroyBonding) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- },
- "SIM": {
- "state": {
- "name": "State",
- "control": {
- "type": "select",
- "value": SimStateTable["READY"]
- },
- "options": (function () {
- var optionList = {};
- utils.forEach(SimStateTable, function (key, value) {
- optionList[key] = SimStateTable[value];
- });
- return optionList;
- }())
- },
- "operatorName": {
- "name": "Operator Name",
- "control": {
- "type": "text",
- "value": "Tizen"
+ t.BluetoothAdapter("destroyBonding", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "msisdn": {
- "name": "MSISDN",
- "control": {
- "type": "text",
- "value": "088123456789"
+
+ if (!_data.historyDevs[address]) {
+ if (!_data.availableDevs[address]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+
+ _data.historyDevs[address] = _data.availableDevs[address];
}
- },
- "iccid": {
- "name": "ICCID",
- "control": {
- "type": "text",
- "value": "123000MFSSYYGXXXXXXP"
+
+ event.trigger("bt-service-state-update", [address, false]);
+ event.trigger("bt-device-bonded-changed", [address, false]);
+ if (successCallback) {
+ successCallback();
}
- },
- "mcc": {
- "name": "MCC",
- "control": {
- "type": "number",
- "value": 460
+ }, 1);
+ }
+
+ function registerRFCOMMServiceByUUID(uuid, name, successCallback,
+ errorCallback, securityLevel) {
+ if (!_security.registerRFCOMMServiceByUUID) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.BluetoothAdapter("registerRFCOMMServiceByUUID", arguments);
+
+ window.setTimeout(function () {
+ if (!_devPowered) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.SERVICE_NOT_AVAILABLE_ERR));
+ }
+ return;
}
- },
- "mnc": {
- "name": "MNC",
- "control": {
- "type": "number",
- "value": 0
+
+ _data.localServices[uuid] = new BluetoothServiceHandler({
+ uuid: uuid,
+ name: name,
+ isConnected: false,
+ metaData: _security
+ });
+ successCallback(_data.localServices[uuid]);
+ }, 1);
+ }
+
+ event.on("bt-simulated-devices-changed", function () {
+ var devs = db.retrieveObject("bt-simulated-devices");
+ utils.forEach(_data.availableDevs, function (item) {
+ if (!devs[item.address]) {
+ delete _data.availableDevs[item.address];
}
- },
- "msin": {
- "name": "MSIN",
- "control": {
- "type": "text",
- "value": "H1 H2 H3 S 12345"
+ });
+ utils.forEach(devs, function (item) {
+ if (!_data.availableDevs[item.address]) {
+ _data.availableDevs[item.address] = new BluetoothDevice({
+ name: item.name,
+ address: item.address,
+ deviceClass: item.deviceClass,
+ isBonded: false,
+ isTrusted: item.isTrusted,
+ isConnected: false,
+ services: item.services,
+ metaData: _security
+ });
}
- },
- "spn": {
- "name": "SPN",
- "control": {
- "type": "text",
- "value": "TizenSPN"
+ });
+ _data.availableDevsChanging = true;
+ });
+
+ event.on("bt-unregister-service", function (uuid, successCallback, errorCallback) {
+ if (!_data.localServices[uuid]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
}
+ return;
}
- },
- "PERIPHERAL": {
- "isVideoOutputOn": {
- "name": "Video Output",
- "control": {
- "type": "checkbox",
- "value": false
+ delete _data.localServices[uuid];
+ if (successCallback) {
+ successCallback();
+ }
+ });
+
+ event.on("bt-power-setting", function (status) {
+ updatePowerStatus(status);
+ });
+
+ adapter = {
+ setName: setName,
+ setPowered: setPowered,
+ setVisible: setVisible,
+ discoverDevices: discoverDevices,
+ stopDiscovery: stopDiscovery,
+ getKnownDevices: getKnownDevices,
+ getDevice: getDevice,
+ createBonding: createBonding,
+ destroyBonding: destroyBonding,
+ registerRFCOMMServiceByUUID: registerRFCOMMServiceByUUID
+ };
+
+ adapter.__defineGetter__("name", function () {
+ return _devName;
+ });
+
+ adapter.__defineGetter__("address", function () {
+ return _devAddress;
+ });
+
+ adapter.__defineGetter__("powered", function () {
+ return _devPowered;
+ });
+
+ adapter.__defineGetter__("visible", function () {
+ return _devVisible;
+ });
+
+ return adapter;
+};
+
+_self = function () {
+ var bluetooth;
+
+ function getDefaultAdapter() {
+ if (!_security.getDefaultAdapter) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ if (!_data.adapter) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+
+ return _data.adapter;
+ }
+
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
}
}
+
+ bluetooth = {
+ getDefaultAdapter: getDefaultAdapter,
+ handleSubFeatures: handleSubFeatures
+ };
+
+ bluetooth.__defineGetter__("deviceMajor", function () {
+ return _data.bluetoothClassDeviceMajor;
+ });
+
+ bluetooth.__defineGetter__("deviceMinor", function () {
+ return _data.bluetoothClassDeviceMinor;
+ });
+
+ bluetooth.__defineGetter__("deviceService", function () {
+ return _data.bluetoothClassDeviceService;
+ });
+
+ return bluetooth;
};
+_initialize();
+
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/spec/sensor', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/contact', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
-function sensorStatusEventTrigger(setting) {
- event.trigger("SensorStatusChanged", [setting]);
+var db = require('ripple/db'),
+ decorator = require('ripple/platform/tizen/2.0/decorator'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ utils = require('ripple/utils'),
+ ContactName = require('ripple/platform/tizen/2.0/ContactName'),
+ ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
+ ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
+ ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
+ ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
+ ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
+ ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ AddressBook,
+ AddressBookData,
+ AddressBookStorage,
+ Contact,
+ ContactData,
+ ContactInternal,
+ ContactGroup,
+ Person,
+ PersonBuilder,
+ _data = {
+ DB_CONTACT_KEY: "tizen1-contact",
+ addressBooks: [],
+ contacts: {},
+ persons: {},
+ contactData: {},
+ dbStorage: {}
+ },
+ _security = {
+ "http://tizen.org/privilege/contact.read": ["getAddressBooks",
+ "getUnifiedAddressBook", "getDefaultAddressBook",
+ "getAddressBook", "get", "find", "addChangeListener",
+ "removeChangeListener", "getGroup", "getGroups", "clone"],
+ "http://tizen.org/privilege/contact.write": ["add", "addBatch",
+ "update", "updateBatch", "remove", "removeBatch", "addGroup",
+ "updateGroup", "removeGroup", "link", "unlink"]
+ },
+ _self;
+
+function _get() {
+ _data.dbStorage = db.retrieveObject(_data.DB_CONTACT_KEY) ||
+ {addressBooks: [], persons: {}};
}
-module.exports = {
- "Accelerometer": {
- "resolution": 0.039239998906850815,
- "minDelay": 20,
- "range": 20.051639556884766,
- "name": "Accelerometer",
- "type": "Accelerometer"
- },
- "MagneticField": {
- "x": {
- "name": "X",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-xChanged", [setting]);
+function _save() {
+ db.saveObject(_data.DB_CONTACT_KEY, _data.dbStorage);
+}
+
+function _serialize(obj) {
+ var i, dbObj = {};
+
+ for (i in obj) {
+ if (typeof obj[i] !== "function")
+ dbObj[i] = utils.copy(obj[i]);
+ }
+
+ return dbObj;
+}
+
+/* check filter type (it's a recursive function)
+ 0: It is not a filter
+ 1: CompositeFilter
+ 2: AttributeFilter
+ 3: AttributeRangeFilter
+ */
+function _filterType(filter) {
+ var i = 0, ret;
+
+ if (Object.prototype.toString.call(filter) !== "[object Object]") {
+ return 0; // 0: it is not a filter
+ }
+
+ /* check if it is CompositFilter or not */
+ if (filter.type !== null && filter.type !== undefined) {
+ /* attribute 'type' of CompositeFilter must be "UNION" or "INTERSECTION" */
+ if (filter.type === "UNION" || filter.type === "INTERSECTION") {
+ /*attribute 'filters' of CompositeFilter must be AbstractFilter array */
+ if (tizen1_utils.isValidArray(filter.filters)) {
+ for (i = 0; i < filter.filters.length; i++) {
+ /* recursive call */
+ if (_filterType(filter.filters[i]) === 0) {
+ return 0; // 0: it is not a filter
+ }
+ }
+ } else {
+ return 0; // 0: it is not a filter
}
- },
+ } else {
+ return 0; // 0: it is not a filter
+ }
+ return 1; // CompositeFilter
+ }
- "y": {
- "name": "Y",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-yChanged", [setting]);
+ /* AttributeFilter or AttributeRangeFilter must have attributeName */
+ if (filter.attributeName === null || filter.attributeName === undefined) {
+ return 0; // 0: it is not a filter
+ } else {
+ ret = 2; // assume it is an AttributeFilter
+ if ((filter.initialValue !== null && filter.initialValue !== undefined) ||
+ (filter.endValue !== null && filter.endValue !== undefined)) {
+ ret = 3; // AttributeRangeFilter
+ }
+ return ret;
+ }
+}
+
+function _sort(objects, sortMode) {
+ function getValue(obj, key) {
+ var keys = key.split("."),
+ value = obj[keys[0]],
+ i;
+
+ for (i = 1; i < keys.length; i++) {
+ if (value[keys[i]]) {
+ value = value[keys[i]];
}
- },
+ }
- "z": {
- "name": "Z",
- "control": {
- "type": "range",
- "value": 100.0000000000000000,
- "min": 0.0000000000000000,
- "max": 200.0000000000000000,
- "step": 0.0000000000000001
- },
- "callback": function (setting) {
- event.trigger("MagneticField-zChanged", [setting]);
+ return value;
+ }
+
+ objects.sort(function (a, b) {
+ return (sortMode.order === "ASC") ?
+ (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
+ (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
+ });
+
+ return objects;
+}
+
+function _replacePerson(oldId, newId) {
+ var contact, dbAddressBook, idab, idc, i;
+
+ for (idab in _data.contacts) {
+ for (idc in _data.contacts[idab]) {
+ contact = _data.contacts[idab][idc];
+ if (contact.personId === oldId) {
+ if (newId === null) {
+ delete _data.contacts[idab][idc];
+ } else {
+ contact.personId = newId;
+ }
}
- },
+ }
+ }
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "MagneticField",
- "type": "MagneticField"
- },
- "Rotation": {
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "Rotation",
- "type": "Rotation"
- },
- "Orientation": {
- "resolution": 1,
- "minDelay": 20,
- "range": 359,
- "name": "Orientation",
- "type": "Orientation"
+ if (_data.persons[oldId]) {
+ delete _data.persons[oldId];
}
-};
-});
-define('ripple/platform/tizen/2.0/spec/ui', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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 = {
- plugins: [
- "sensors",
- "communication",
- "geoView",
- "widgetConfig",
- "deviceSettings",
- "application",
- "network",
- "power",
- "download",
- "notifications",
- "package"
- ]
-};
+ for (i in _data.dbStorage.addressBooks) {
+ dbAddressBook = _data.dbStorage.addressBooks[i];
+ for (idc in dbAddressBook.contacts) {
+ contact = dbAddressBook.contacts[idc];
+ if (contact.personId === oldId) {
+ if (newId === null) {
+ delete dbAddressBook.contacts[idc];
+ } else {
+ contact.personId = newId;
+ }
+ }
+ }
+ }
-});
-define('ripple/platform/tizen/2.0/spec', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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.
- */
+ if (_data.dbStorage.persons[oldId]) {
+ delete _data.dbStorage.persons[oldId];
+ }
+}
-module.exports = {
+_self = function () {
+ var contact;
- id: "tizen",
- version: "2.2",
- name: "TIZEN",
+ // private
+ function loadAddressBooks() {
+ var i;
- persistencePrefix: "tizen1-",
+ _get();
- config: require('ripple/platform/tizen/2.0/spec/config'),
- ui: require('ripple/platform/tizen/2.0/spec/ui'),
- device: require('ripple/platform/tizen/2.0/spec/device'),
- sensor: require('ripple/platform/tizen/2.0/spec/sensor'),
- DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
- DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),
+ if (_data.dbStorage.addressBooks.length === 0) {
+ // Initialize default address books if database is empty
+ _data.dbStorage.addressBooks = [
+ new AddressBookStorage(Math.uuid(null, 16), "Phone address book", false, {}, []),
+ new AddressBookStorage(Math.uuid(null, 16), "SIM address book", false, {}, [])
+ ];
+ }
- objects: {
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- SensorConnection: {
- path: "w3c/1.0/SensorConnection"
- },
- navigator: {
- path: "tizen/2.0/navigator",
- children: {
- geolocation: {
- path: "wac/2.0/geolocation"
- },
- battery: {
- path: "tizen/2.0/battery"
+ utils.forEach(_data.dbStorage.addressBooks, function (addressBook) {
+ _data.addressBooks.push(new AddressBook(addressBook.id, addressBook.name,
+ addressBook.readOnly, addressBook.contacts, addressBook.groups));
+ });
+
+ for (i in _data.dbStorage.persons) {
+ _data.persons[i] = new Person(_data.dbStorage.persons[i]);
+ }
+ }
+
+ // public
+ // Address Book Methods
+ function getAddressBooks(successCallback, errorCallback) {
+ if (!_security.getAddressBooks) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.ContactManager("getAddressBooks", arguments);
+
+ window.setTimeout(function () {
+ if (_data.addressBooks.length === 0) {
+ loadAddressBooks();
+ }
+ successCallback(_data.addressBooks);
+ }, 1);
+ }
+
+ function getUnifiedAddressBook() {
+ if (!_security.getUnifiedAddressBook) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (_data.addressBooks.length === 0) {
+ loadAddressBooks();
+ }
+ return _data.addressBooks[0];
+ }
+
+ function getDefaultAddressBook() {
+ if (!_security.getDefaultAddressBook) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (_data.addressBooks.length === 0) {
+ loadAddressBooks();
+ }
+ return _data.addressBooks[0];
+ }
+
+ function getAddressBook(addressBookId) {
+ var i;
+
+ if (!_security.getAddressBook) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.ContactManager("getAddressBook", arguments);
+
+ if (_data.addressBooks.length === 0) {
+ loadAddressBooks();
+ }
+ for (i in _data.addressBooks) {
+ if (_data.addressBooks[i].id === addressBookId) {
+ return _data.addressBooks[i];
+ }
+ }
+
+ /* Cannot found */
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ // Person Methods
+ function get(personId) {
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.ContactManager("get", arguments);
+
+ if (_data.persons[personId] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ return new Person(_data.persons[personId]);
+ }
+
+ function update(person) {
+ var updated;
+
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.ContactManager("update", arguments);
+
+ if (!person.id) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ if (_data.persons[person.id] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+
+ updated = new Person(person);
+
+ _data.persons[updated.id] = updated;
+ _data.dbStorage.persons[updated.id] = _serialize(updated);
+ _save();
+
+ window.setTimeout(function () {
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ listener.onpersonsupdated([new Person(updated)]);
+ });
+ }, 1);
+ }
+
+ function updateBatch(persons, successCallback, errorCallback) {
+ if (!_security.updateBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.ContactManager("updateBatch", arguments, true);
+
+ window.setTimeout(function () {
+ var i, updated;
+
+ if (persons.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
}
+ return;
}
- },
- tizen: {
- feature: "http://tizen.org/privilege/tizen",
- children: {
- AlarmAbsolute: {
- path: "tizen/2.0/AlarmAbsolute"
- },
- AlarmRelative: {
- path: "tizen/2.0/AlarmRelative"
- },
- ApplicationControl: {
- path: "tizen/2.0/ApplicationControl"
- },
- ApplicationControlData: {
- path: "tizen/2.0/ApplicationControlData"
- },
- AttributeFilter: {
- path: "tizen/2.0/AttributeFilter"
- },
- AttributeRangeFilter: {
- path: "tizen/2.0/AttributeRangeFilter"
- },
- BookmarkFolder: {
- path: "tizen/2.0/BookmarkFolder"
- },
- BookmarkItem: {
- path: "tizen/2.0/BookmarkItem"
- },
- CalendarAlarm: {
- path: "tizen/2.0/CalendarAlarm"
- },
- CalendarAttendee: {
- path: "tizen/2.0/CalendarAttendee"
- },
- CalendarEvent: {
- path: "tizen/2.0/CalendarEvent"
- },
- CalendarEventId: {
- path: "tizen/2.0/CalendarEventId"
- },
- CalendarRecurrenceRule: {
- path: "tizen/2.0/CalendarRecurrenceRule"
- },
- CalendarTask: {
- path: "tizen/2.0/CalendarTask"
- },
- CompositeFilter: {
- path: "tizen/2.0/CompositeFilter"
- },
- Contact: {
- path: "tizen/2.0/ContactBase"
- },
- ContactAddress: {
- path: "tizen/2.0/ContactAddress"
- },
- ContactAnniversary: {
- path: "tizen/2.0/ContactAnniversary"
- },
- ContactEmailAddress: {
- path: "tizen/2.0/ContactEmailAddress"
- },
- ContactGroup: {
- path: "tizen/2.0/ContactGroup"
- },
- ContactName: {
- path: "tizen/2.0/ContactName"
- },
- ContactOrganization: {
- path: "tizen/2.0/ContactOrganization"
- },
- ContactPhoneNumber: {
- path: "tizen/2.0/ContactPhoneNumber"
- },
- ContactRef: {
- path: "tizen/2.0/ContactRef"
- },
- ContactWebSite: {
- path: "tizen/2.0/ContactWebSite"
- },
- DownloadRequest: {
- path: "tizen/2.0/DownloadRequest"
- },
- Message: {
- path: "tizen/2.0/Message"
- },
- NDEFMessage: {
- path: "tizen/2.0/NDEFMessage"
- },
- NDEFRecord: {
- path: "tizen/2.0/NDEFRecord"
- },
- NDEFRecordMedia: {
- path: "tizen/2.0/NDEFRecordMedia"
- },
- NDEFRecordText: {
- path: "tizen/2.0/NDEFRecordText"
- },
- NDEFRecordURI: {
- path: "tizen/2.0/NDEFRecordURI"
- },
- NotificationDetailInfo: {
- path: "tizen/2.0/NotificationDetailInfo"
- },
- SimpleCoordinates: {
- path: "tizen/2.0/SimpleCoordinates"
- },
- SortMode: {
- path: "tizen/2.0/SortMode"
- },
- StatusNotification: {
- path: "tizen/2.0/StatusNotification"
- },
- SyncInfo: {
- path: "tizen/2.0/SyncInfo"
- },
- SyncServiceInfo: {
- path: "tizen/2.0/SyncServiceInfo"
- },
- SyncProfileInfo: {
- path: "tizen/2.0/SyncProfileInfo"
- },
- TZDate: {
- path: "tizen/2.0/TZDate"
- },
- TimeDuration: {
- path: "tizen/2.0/TimeDuration"
- },
- alarm: {
- path: "tizen/2.0/alarm",
- feature: "http://tizen.org/privilege/alarm",
- handleSubfeatures: true
- },
- application: {
- path: "tizen/2.0/application",
- feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
- handleSubfeatures: true
- },
- bluetooth: {
- path: "tizen/2.0/bluetooth",
- feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
- handleSubfeatures: true
- },
- bookmark: {
- path: "tizen/2.0/bookmark",
- feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
- handleSubfeatures: true
- },
- callhistory: {
- path: "tizen/2.0/callHistory",
- feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
- handleSubfeatures: true
- },
- calendar: {
- path: "tizen/2.0/calendar",
- feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
- handleSubfeatures: true
- },
- contact: {
- path: "tizen/2.0/contact",
- feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
- handleSubfeatures: true
- },
- content: {
- path: "tizen/2.0/content",
- feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
- handleSubfeatures: true
- },
- datacontrol: {
- path: "tizen/2.0/datacontrol",
- feature: "http://tizen.org/privilege/datacontrol.consumer",
- handleSubfeatures: true
- },
- datasync: {
- path: "tizen/2.0/datasync",
- feature: "http://tizen.org/privilege/datasync",
- handleSubfeatures: true
- },
- download: {
- path: "tizen/2.0/download",
- feature: "http://tizen.org/privilege/download",
- handleSubfeatures: true
- },
- filesystem: {
- path: "tizen/2.0/filesystem",
- feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
- },
- messaging: {
- path: "tizen/2.0/messaging",
- feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
- handleSubfeatures: true
- },
- networkbearerselection: {
- path: "tizen/2.0/networkbearerselection",
- feature: "http://tizen.org/privilege/networkbearerselection",
- handleSubfeatures: true
- },
- nfc: {
- path: "tizen/2.0/nfc",
- feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
- handleSubfeatures: true
- },
- notification: {
- path: "tizen/2.0/notification",
- feature: "http://tizen.org/privilege/notification",
- handleSubfeatures: true
- },
- package: {
- path: "tizen/2.0/package",
- feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
- handleSubfeatures: true
- },
- power: {
- path: "tizen/2.0/power",
- feature: "http://tizen.org/privilege/power",
- handleSubfeatures: true
- },
- push: {
- path: "tizen/2.0/push",
- feature: "http://tizen.org/privilege/push",
- handleSubfeatures: true
- },
- systeminfo: {
- path: "tizen/2.0/systeminfo",
- feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
- handleSubfeatures: true
- },
- systemsetting: {
- path: "tizen/2.0/systemsetting",
- feature: "http://tizen.org/privilege/setting",
- handleSubfeatures: true
- },
- time: {
- path: "tizen/2.0/time",
- feature: "http://tizen.org/privilege/time",
- handleSubfeatures: true
+
+ for (i in persons) {
+ if (!persons[i].id) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ if (_data.persons[persons[i].id] === undefined) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
}
}
- }
- }
-};
+ for (i in persons) {
+ updated = new Person(persons[i]);
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/adapter', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.adapter
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/10/22
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ _data.persons[updated.id] = updated;
+ _data.dbStorage.persons[updated.id] = _serialize(updated);
+ }
+ _save();
+ if (successCallback) {
+ successCallback();
+ }
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store');
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ var i, watched = [];
+ for (i in persons) {
+ watched.push(new Person(_data.persons[persons[i].id]));
+ }
+ listener.onpersonsupdated(watched);
+ });
+ }, 1);
+ }
-var _self = (function () {
+ function remove(personId) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- var exports = {};
+ t.ContactManager("remove", arguments);
- //---------------------------------------------------------------------------
- exports.Adapter = common.Base.extend({
+ if (_data.persons[personId] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ _replacePerson(personId, null);
+ _save();
- // //-------------------------------------------------------------------------
- // constructor: function(context, options, devInfo) {
+ window.setTimeout(function () {
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ listener.onpersonsremoved([personId]);
+ });
+ }, 1);
+ }
- //-------------------------------------------------------------------------
- normUri: function(uri) {
- return common.normpath(uri);
- },
+ function removeBatch(personIds, successCallback, errorCallback) {
+ if (!_security.removeBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- getStores: function() {
- return _.values(this._stores);
- },
+ t.ContactManager("removeBatch", arguments, true);
- //-------------------------------------------------------------------------
- getStore: function(uri) {
- return this._stores[this.normUri(uri)];
- },
+ window.setTimeout(function () {
+ var i;
- //-------------------------------------------------------------------------
- addStore: function(store, cb) {
- var self = this;
- if ( store instanceof storemod.Store )
- {
- store.uri = self.normUri(store.uri);
- store._a = self;
+ if (personIds.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
}
- else
- store = new storemod.Store(this, store);
- store._updateModel(function(err) {
- if ( err )
- return cb(err);
- self._stores[store.uri] = store;
- // TODO: remove this sensitivity...
- if ( ! self.isLocal )
- return cb();
+ for (i in personIds) {
+ if (!personIds[i]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ if (_data.persons[personIds[i]] === undefined) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+ }
+ for (i in personIds) {
+ _replacePerson(personIds[i], null);
+ }
+ _save();
+ if (successCallback) {
+ successCallback();
+ }
- self._save(self._c._txn(), function(err) {
- if ( err )
- return cb(err);
- cb(null, store);
- });
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ listener.onpersonsremoved(utils.copy(personIds));
});
- },
+ }, 1);
+ }
- //-------------------------------------------------------------------------
- removeStore: function(uri, cb) {
- var self = this;
- if ( ! self.isLocal )
- // todo: implement
- return cb(new common.LogicalError(
- 'cannot remove remote store "' + uri + '": remote peer responsibility'));
- if ( ! self._stores[uri] )
- return cb(new common.InternalError(
- 'cannot remove store "' + uri + '": no such store'));
- delete self._stores[uri];
- var model = self._getModel();
- model.stores = _.filter(model.stores, function(store) {
- return store.uri != uri;
- });
- _.each(model.peers, function(peer) {
- peer.routes = _.filter(peer.routes, function(route) {
- return route.localUri != uri;
- });
- _.each(peer.stores, function(store) {
- if ( store.binding && store.binding.uri == uri )
- store.binding = null;
- });
- });
- return cb();
- },
+ function find(successCallback, errorCallback, filter, sortMode) {
+ if (!_security.find) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- _isMapper: function() {
- // indicates whether or not this adapter is capable of mapping
- // items. in the standard SyncML peer model, only the server
- // ever does mapping, but in the dream-land of syncml-js, all
- // peers can be mappers, or even better, implements an extension
- // "is-uuid/adopted" that does not require mapping. so, since
- // that is just a dream-land for now, this will try to identify
- // if this adapter represents a server...
- // todo: enhance syncml-js so that it is not needed!...
- if ( ! this.isLocal )
- return this.url && this.url.length > 0;
- return this.devInfo && this.devInfo.devType == constant.DEVTYPE_SERVER;
- },
+ t.ContactManager("find", arguments, true);
- //-------------------------------------------------------------------------
- describe: function(stream, cb) {
- var self = this;
- if ( self.url )
- stream.writeln('URL: ' + self.url);
- stream.writeln('Device ID: ' + self.devID);
- var s1 = stream.indented();
- var s2 = s1.indented();
+ window.setTimeout(function () {
+ var i, matched = [], result = [];
- var describe_stores = function(cb) {
- var stores = self.getStores();
- if ( stores.length <= 0 )
- {
- stream.writeln('Data stores: (none)');
- return cb();
+ if (filter) {
+ switch (_filterType(filter)) {
+ case 0:
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+
+ case 1:
+ //TODO:
+ //"compositeFilter doesn't support"
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
+ }
+ return;
+
+ case 2:
+ case 3:
+ break;
}
- stream.writeln('Data stores:');
- common.cascade(stores, function(store, cb) {
- s1.writeln(( store.displayName || store.uri ) + ':');
- store.describe(s2, cb);
- }, cb);
- };
+ }
- var describe_peers = function(cb) {
- if ( ! self.getPeers )
- return cb();
- var peers = self.getPeers();
- if ( peers.length <= 0 )
- {
- stream.writeln('Known peers: (none)');
- return cb();
+ if (filter === null || filter === undefined) {
+ utils.forEach(_data.persons, function (person) {
+ matched.push(person);
+ });
+ } else {
+ switch (filter.attributeName) {
+ case "id":
+ case "displayName":
+ case "photoURI":
+ case "ringtoneURI":
+ case "displayContactId":
+ matched = tizen1_utils.matchAttributeFilter(_data.persons,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
+
+ case "contactCount":
+ if ((filter.matchFlag !== "EXACTLY") ||
+ (typeof filter.matchValue !== "number")) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ matched = tizen1_utils.matchAttributeFilter(_data.persons,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
+
+ case "hasPhoneNumber":
+ case "hasEmail":
+ case "isFavorite":
+ if ((filter.matchFlag !== "EXACTLY") ||
+ (typeof filter.matchValue !== "boolean")) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ matched = tizen1_utils.matchAttributeBooleanFilter(_data.persons,
+ filter.attributeName, filter.matchValue);
+ break;
+
+ default:
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
}
- stream.writeln('Known peers:');
- common.cascade(peers, function(peer, cb) {
- s1.writeln(( peer.displayName || peer.url ) + ':');
- peer.describe(s2, cb);
- }, cb);
}
- describe_stores(function(err) {
- if ( err )
- return cb(err);
- describe_peers(cb);
- });
+ if (sortMode) {
+ _sort(matched, sortMode);
+ }
+
+ for (i in matched) {
+ result.push(new Person(matched[i]));
+ }
+
+ successCallback(result);
+ }, 1);
+ }
+
+ function addChangeListener(successCallback) {
+ var id;
+
+ if (!_security.addChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
+ t.ContactManager("addChangeListener", arguments);
- return exports;
+ id = ++_data.contactData.nListener;
+ _data.contactData.listeners[id] = successCallback;
- })();
+ return id;
+ }
- module.exports = _self;
+ function removeChangeListener(watchId) {
+ if (!_security.removeChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/agent', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.agent
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/10/22
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ if (!_data.contactData.listeners[watchId])
+ return;
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');
+ delete _data.contactData.listeners[watchId];
+ }
-var _self = (function () {
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- var exports = {};
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
- //---------------------------------------------------------------------------
- exports.Agent = common.Base.extend({
+ _data.contactData = new ContactData();
- //-------------------------------------------------------------------------
- constructor: function(options) {
- options = _.defaults(options, {
- hierarchicalSync: false
+ contact = {
+ getAddressBooks: getAddressBooks,
+ getUnifiedAddressBook: getUnifiedAddressBook,
+ getDefaultAddressBook: getDefaultAddressBook,
+ getAddressBook: getAddressBook,
+
+ get: get,
+ update: update,
+ updateBatch: updateBatch,
+ remove: remove,
+ removeBatch: removeBatch,
+ find: find,
+ addChangeListener: addChangeListener,
+ removeChangeListener: removeChangeListener,
+ handleSubFeatures: handleSubFeatures
+ };
+
+ return contact;
+};
+
+AddressBook = function (id, name, readOnly, dbContacts, dbGroups) {
+ var addressBook,
+ privateData = new AddressBookData(dbContacts, dbGroups);
+
+ // private
+ function addNewContact(contact, external) {
+ var added, person;
+
+ added = new ContactInternal(contact);
+ privateData.contacts[added.id] = added;
+
+ person = new PersonBuilder(added);
+ _data.persons[person.id] = person;
+
+ added.personId = person.id;
+ added.addressBookId = id;
+
+ dbContacts[added.id] = _serialize(added);
+ _data.dbStorage.persons[person.id] = _serialize(_data.persons[person.id]);
+
+ decorator.Contact(external, added);
+ }
+
+ // public
+ function get(id) {
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.AddressBook("get", arguments);
+
+ if (privateData.contacts[id] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ return new Contact(privateData.contacts[id]);
+ }
+
+ function add(contact) {
+ var external = contact;
+
+ if (!_security.add) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.AddressBook("add", arguments, true);
+
+ addNewContact(contact, external);
+ _save();
+
+ window.setTimeout(function () {
+ utils.forEach(privateData.listeners, function (listener) {
+ listener.oncontactsadded([new Contact(external)]);
});
- this.hierarchicalSync = options.hierarchicalSync;
- },
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ listener.onpersonsadded([new Person(_data.persons[external.personId])]);
+ });
+ }, 1);
+ }
- //-------------------------------------------------------------------------
- dumpItem: function(item, stream, contentType, version, cb) {
- return this.dumpsItem(
- item, contentType, version,
- function(err, data, new_contentType, new_version) {
- if ( err ) {
- return cb(err);
- }
- stream.write(data, function(err) {
- if ( err ) {
- return cb(err);
- }
- cb(null, new_contentType, new_version);
- });
- });
- },
+ function addBatch(contacts, successCallback, errorCallback) {
+ var external = contacts;
+ if (!_security.addBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- loadItem: function(stream, contentType, version, cb) {
- var self = this;
- stream.read(function(err, data) {
- if ( err ) {
- cb(err);
+ t.AddressBook("addBatch", arguments, true);
+
+ window.setTimeout(function () {
+ var i, personIds = [];
+
+ if (contacts.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
}
- self.loadsItem(data, contentType, version, cb);
+ return;
+ }
+
+ for (i in contacts) {
+ addNewContact(contacts[i], external[i]);
+ personIds.push(external[i].personId);
+ }
+ _save();
+ if (successCallback) {
+ successCallback(external);
+ }
+
+ utils.forEach(privateData.listeners, function (listener) {
+ var i, watched = [];
+
+ for (i in contacts) {
+ watched.push(new Contact(external[i]));
+ }
+ listener.oncontactsadded(watched);
});
- },
+ utils.forEach(_data.contactData.listeners, function (listener) {
+ var i, watched = [];
- //-------------------------------------------------------------------------
- deleteAllItems: function(cb) {
- var self = this;
- self.getAllItems(function(err, items) {
- if ( err ) {
- return cb(err);
+ for (i in personIds) {
+ watched.push(new Person(_data.persons[personIds[i]]));
}
- common.cascade(items, function(e, cb) {
- self.deleteItem(e, cb);
- }, cb);
+ listener.onpersonsadded(watched);
});
- },
+ }, 1);
+ }
- // TODO: add documentation about all expected methods...
+ function update(contact) {
+ var updated;
- getAllItems: function(cb) {
- // cb(null, LIST)
- return cb(new common.NotImplementedError());
- },
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- dumpsItem: function(item, contentType, version, cb) {
- // cb(null, DATA [, NEW-CONTENTTYPE [, NEW-VERSION]])
- return cb(new common.NotImplementedError());
- },
+ t.AddressBook("update", arguments);
- loadsItem: function(data, contentType, version, cb) {
- // cb(null, ITEM)
- return cb(new common.NotImplementedError());
- },
+ if (!contact.id) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ if (privateData.contacts[contact.id] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- addItem: function(item, cb) {
- // cb(null, ITEM)
- return cb(new common.NotImplementedError());
- },
+ updated = new ContactInternal(contact);
- getItem: function(itemID, cb) {
- // cb(null, ITEM)
- return cb(new common.NotImplementedError());
- },
+ privateData.contacts[updated.id] = updated;
+ dbContacts[updated.id] = _serialize(updated);
+ _save();
- replaceItem: function(item, reportChanges, cb) {
- // cb(null [, CSPEC])
- return cb(new common.NotImplementedError());
- },
+ window.setTimeout(function () {
+ utils.forEach(privateData.listeners, function (listener) {
+ listener.oncontactsupdated([new Contact(updated)]);
+ });
+ }, 1);
+ }
- deleteItem: function(itemID, cb) {
- // cb(null)
- return cb(new common.NotImplementedError());
- },
+ function updateBatch(contacts, successCallback, errorCallback) {
+ if (!_security.updateBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- getContentTypes: function() {
- throw new common.NotImplementedError();
- },
+ t.AddressBook("updateBatch", arguments, true);
- matchItem: function(item, cb) {
- this.getAllItems(function(err, list) {
- if ( err ) {
- return cb(err);
+ window.setTimeout(function () {
+ var i, updated;
+
+ if (contacts.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
}
- var match = _.find(list, function(cur) {
- return cur.compare && cur.compare(item) == 0;
- });
- return cb(null, match);
- });
- }
+ return;
+ }
- // TODO: mergeItems()
+ for (i in contacts) {
+ if (!contacts[i].id) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ if (privateData.contacts[contacts[i].id] === undefined) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+ }
+ for (i in contacts) {
+ updated = new ContactInternal(contacts[i]);
- });
+ privateData.contacts[updated.id] = updated;
+ dbContacts[updated.id] = _serialize(updated);
+ }
+ _save();
+ if (successCallback) {
+ successCallback();
+ }
- return exports;
+ utils.forEach(privateData.listeners, function (listener) {
+ var i, watched = [];
-})();
+ for (i in contacts) {
+ watched.push(new Contact(
+ privateData.contacts[contacts[i].id]));
+ }
+ listener.oncontactsupdated(watched);
+ });
+ }, 1);
+ }
-module.exports = _self;
+ function remove(id) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/base64', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-//-----------------------------------------------------------------------------
+ t.AddressBook("remove", arguments);
-var _self = (function() {
+ if (privateData.contacts[id] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- // shamelessly scrubbed from:
- // http://www.webtoolkit.info/javascript-base64.html
+ delete privateData.contacts[id];
+ if (dbContacts[id]) {
+ delete dbContacts[id];
+ }
+ _save();
- /**
- *
- * Base64 encode / decode
- * http://www.webtoolkit.info/
- *
- **/
+ window.setTimeout(function () {
+ utils.forEach(privateData.listeners, function (listener) {
+ listener.oncontactsremoved([id]);
+ });
+ }, 1);
+ }
- var Base64 = {
+ function removeBatch(ids, successCallback, errorCallback) {
+ if (!_security.removeBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ if (addressBook.readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // private property
- _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
+ t.AddressBook("removeBatch", arguments, true);
- // public method for encoding
- encode : function (input) {
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
+ window.setTimeout(function () {
+ var i;
- input = Base64._utf8_encode(input);
+ if (ids.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
- while (i < input.length) {
+ for (i in ids) {
+ if (!ids[i]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ if (privateData.contacts[ids[i]] === undefined) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+ }
+ for (i in ids) {
+ delete privateData.contacts[ids[i]];
+ if (dbContacts[ids[i]]) {
+ delete dbContacts[ids[i]];
+ }
+ }
+ _save();
+ if (successCallback) {
+ successCallback();
+ }
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
+ utils.forEach(privateData.listeners, function (listener) {
+ listener.oncontactsremoved(utils.copy(ids));
+ });
+ }, 1);
+ }
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
+ function find(successCallback, errorCallback, filter, sortMode) {
+ if (!_security.find) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if (isNaN(chr3)) {
- enc4 = 64;
- }
+ t.AddressBook("find", arguments, true);
- output = output +
- this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
- this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+ window.setTimeout(function () {
+ var result = [], begin, end, i, atr, _re, errFlag = false,
+ _rangeMatch, low, high, matched, _existMatch, _arrayMatch;
- }
+ if (filter) {
+ switch (_filterType(filter)) {
+ case 0:
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
- return output;
- },
+ case 1:
+ //TODO:
+ //"compositeFilter doesn't support"
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
+ }
+ return;
- // public method for decoding
- decode : function (input) {
- var output = "";
- var chr1, chr2, chr3;
- var enc1, enc2, enc3, enc4;
- var i = 0;
+ case 2:
+ case 3:
+ break;
+ }
+ }
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
+ /* return all contacts if no filter argument */
+ if (filter === null || filter === undefined) {
+ utils.forEach(privateData.contacts, function (contact) {
+ result.push(new Contact(contact));
+ });
- while (i < input.length) {
+ successCallback(result);
+ return;
+ }
- enc1 = this._keyStr.indexOf(input.charAt(i++));
- enc2 = this._keyStr.indexOf(input.charAt(i++));
- enc3 = this._keyStr.indexOf(input.charAt(i++));
- enc4 = this._keyStr.indexOf(input.charAt(i++));
+ /* check composition of filter.attributeName */
+ switch (filter.attributeName) {
+ case "id" :
+ case "personId" :
+ case "addressBookId" :
+ case "name.prefix" :
+ case "name.suffix" :
+ case "name.firstName" :
+ case "name.middleName" :
+ case "name.lastName" :
+ case "name.phoneticFirstName" :
+ case "name.phoneticLastName" :
+ case "name.displayName" :
+ case "account.accountServiceId" :
+ case "account.contactURI" :
+ case "photoURI" :
+ case "ringtoneURI" :
+ matched = tizen1_utils.matchAttributeFilter(privateData.contacts,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
+ case "name.nicknames" :
+ case "notes" :
+ case "groupIds" :
+ matched = tizen1_utils.matchAttributeArrayFilter(privateData.contacts,
+ filter.attributeName, filter.matchFlag, filter.matchValue);
+ break;
- output = output + String.fromCharCode(chr1);
+ case "addresses.country" :
+ case "addresses.region" :
+ case "addresses.city" :
+ case "addresses.streetAddress" :
+ case "addresses.additionalInformation" :
+ case "addresses.postalCode" :
+ case "phoneNumbers.number" :
+ case "emails.email" :
+ case "anniversaries.label" :
+ case "organizations.name" :
+ case "organizations.department" :
+ case "organizations.title" :
+ case "organizations.role" :
+ case "organizations.logoURI" :
+ case "urls.url" :
+ case "urls.type" :
+ atr = filter.attributeName.split(".");
+ _existMatch = function (obj) {
+ return (obj[atr[0]] !== undefined);
+ };
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
+ if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
+ matched = utils.filter(privateData.contacts, _existMatch);
+ break;
+ }
- }
+ errFlag = false;
- output = Base64._utf8_decode(output);
+ switch (filter.matchFlag)
+ {
+ case "EXACTLY":
+ _re = new RegExp("^" + filter.matchValue + "$");
+ break;
+ case "FULLSTRING":
+ _re = new RegExp("^" + filter.matchValue + "$", "i");
+ break;
+ case "CONTAINS":
+ _re = new RegExp(filter.matchValue, "i");
+ break;
+ case "STARTSWITH":
+ _re = new RegExp("^" + filter.matchValue, "i");
+ break;
+ case "ENDSWITH":
+ _re = new RegExp(filter.matchValue + "$", "i");
+ break;
+ default:
+ errFlag = true;
+ }
- return output;
+ if (errFlag) {
+ matched = [];
+ break;
+ }
- },
+ _arrayMatch = function (obj) {
+ return (obj[atr[0]].some(function (o) {
+ if (typeof o[atr[1]] !== "string") {
+ return false;
+ } else {
+ return (o[atr[1]].search(_re) !== -1);
+ }
+ }));
+ };
- // private method for UTF-8 encoding
- _utf8_encode : function (string) {
- string = string.replace(/\r\n/g,"\n");
- var utftext = "";
+ matched = utils.filter(privateData.contacts, _arrayMatch);
+ break;
- for (var n = 0; n < string.length; n++) {
+ case "addresses.types" :
+ case "phoneNumbers.types" :
+ case "emails.types" :
+ atr = filter.attributeName.split(".");
+ _existMatch = function (obj) {
+ return (obj[atr[0]].some(function (o) {
+ return (o[atr[1]] !== undefined);
+ }));
+ };
- var c = string.charCodeAt(n);
+ if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
+ matched = utils.filter(privateData.contacts, _existMatch);
+ break;
+ }
- if (c < 128) {
- utftext += String.fromCharCode(c);
- }
- else if((c > 127) && (c < 2048)) {
- utftext += String.fromCharCode((c >> 6) | 192);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- else {
- utftext += String.fromCharCode((c >> 12) | 224);
- utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- utftext += String.fromCharCode((c & 63) | 128);
- }
+ errFlag = false;
- }
+ switch (filter.matchFlag) {
+ case "EXACTLY":
+ _re = new RegExp("^" + filter.matchValue + "$");
+ break;
+ case "FULLSTRING":
+ _re = new RegExp("^" + filter.matchValue + "$", "i");
+ break;
+ case "CONTAINS":
+ _re = new RegExp(filter.matchValue, "i");
+ break;
+ case "STARTSWITH":
+ _re = new RegExp("^" + filter.matchValue, "i");
+ break;
+ case "ENDSWITH":
+ _re = new RegExp(filter.matchValue + "$", "i");
+ break;
+ default:
+ errFlag = true;
+ }
- return utftext;
- },
+ if (errFlag) {
+ matched = [];
+ break;
+ }
- // private method for UTF-8 decoding
- _utf8_decode : function (utftext) {
- var string = "";
- var i = 0;
- var c = c1 = c2 = 0;
+ _arrayMatch = function (obj) {
+ return (obj[atr[0]].some(function (o) {
+ if (!tizen1_utils.isValidArray(o[atr[1]])) {
+ return false;
+ } else {
+ return (o[atr[1]].some(function (t) {
+ return (t.search(_re) !== -1);
+ }));
+ }
+ }));
+ };
- while ( i < utftext.length ) {
+ matched = utils.filter(privateData.contacts, _arrayMatch);
+ break;
- c = utftext.charCodeAt(i);
+ case "anniversaries.date" :
+ low = filter.initialValue;
+ high = filter.endValue;
+ atr = filter.attributeName.split(".");
- if (c < 128) {
- string += String.fromCharCode(c);
- i++;
- }
- else if((c > 191) && (c < 224)) {
- c2 = utftext.charCodeAt(i+1);
- string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
- i += 2;
- }
- else {
- c2 = utftext.charCodeAt(i+1);
- c3 = utftext.charCodeAt(i+2);
- string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
- i += 3;
- }
+ _rangeMatch = function (obj) {
+ var isMatched = true;
+ if (low !== null && low !== undefined) {
+ if (!tizen1_utils.isValidArray(obj[atr[0]])) {
+ isMatched = false;
+ } else {
+ isMatched = (obj[atr[0]].some(function (o) {
+ return (o[atr[1]] >= low);
+ }));
+ }
+ }
+ if (isMatched && (high !== null && high !== undefined)) {
+ if (!tizen1_utils.isValidArray(obj[atr[0]])) {
+ isMatched = false;
+ } else {
+ isMatched = (obj[atr[0]].some(function (o) {
+ return (o[atr[1]] <= high);
+ }));
+ }
+ }
+ return isMatched;
+ };
- }
+ matched = utils.filter(privateData.contacts, _rangeMatch);
+ break;
+
+ case "addresses.isDefault" :
+ case "phoneNumbers.isDefault" :
+ case "emails.isDefault" :
+ break;
+
+ case "isFavorite" :
+ if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ } else {
+ matched = tizen1_utils.matchAttributeBooleanFilter(privateData.contacts,
+ filter.attributeName, filter.matchValue);
+ }
+ break;
+
+ case "birthday" :
+ begin = filter.initialValue;
+ end = filter.endValue;
- return string;
- }
+ matched = tizen1_utils.matchAttributeRangeFilter(privateData.contacts,
+ filter.attributeName, begin, end);
+ break;
- };
+ default:
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
- return Base64;
+ if (sortMode) {
+ _sort(matched, sortMode);
+ }
-})();
+ for (i in matched) {
+ result.push(new Contact(matched[i]));
+ }
-module.exports = _self;
+ successCallback(result);
+ }, 1);
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/codec', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// auth: metagriffin <metagriffin@uberdev.org>
-// date: 2012/10/13
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ function addChangeListener(successCallback, errorCallback) {
+ var id;
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- _self;
+ if (!_security.addChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_self = (function () {
+ t.AddressBook("addChangeListener", arguments);
- var exports = {};
+ id = ++privateData.nListener;
+ privateData.listeners[id] = successCallback;
- //---------------------------------------------------------------------------
- exports.Codec = common.Base.extend({
+ return id;
+ }
- encode: function(xtree, cb) {
- throw new common.NotImplementedError();
- },
+ function removeChangeListener(watchId) {
+ if (!_security.removeChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- decode: function(contentType, data, cb) {
- throw new common.NotImplementedError();
- },
- }, {
+ if (!privateData.listeners[watchId])
+ return;
- factory: function(codec) {
- // todo: should this be converted to callback-based?...
- if ( codec == constant.CODEC_XML )
- return new exports.XmlCodec()
- // TODO
- // if ( codec == constant.CODEC_WBXML )
- // return exports.WbxmlCodec()
- throw new common.UnknownCodec('unknown or unimplemented codec "' + codec + '"')
- },
+ delete privateData.listeners[watchId];
+ }
- autoEncode: function(xtree, codecName, cb) {
- exports.Codec.factory(codecName).encode(xtree, cb);
- },
+ function getGroup(groupId) {
+ var i;
- autoDecode: function(contentType, data, cb) {
- if ( contentType.indexOf(constant.TYPE_SYNCML + '+') != 0 )
- return cb('unknown or unimplemented content type "' + contentType + '"');
- var ct = contentType.slice((constant.TYPE_SYNCML + '+').length).split(';')[0];
- exports.Codec.factory(ct).decode(contentType, data, function(err, tree) {
- if ( err )
- return cb(err);
- return cb(null, tree, ct);
- });
- },
- });
+ if (!_security.getGroup) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //---------------------------------------------------------------------------
- exports.XmlCodec = exports.Codec.extend({
+ t.AddressBook("getGroup", arguments);
- name: constant.CODEC_XML,
+ for (i in privateData.groups) {
+ if (privateData.groups[i].id === groupId)
+ break;
+ }
+ if (privateData.groups[i] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- encode: function(xtree, cb) {
- // todo: really enforce this charset...
- var ctype = constant.TYPE_SYNCML + '+' + this.name + '; charset=UTF-8';
- var ret = ET.tostring(xtree);
- if ( ret.charAt(0) == '<' && ret.charAt(1) == '?' )
- {
- var idx = ret.indexOf('?>');
- if ( idx >= 0 )
- ret = ret.substr(0, idx + 2).replace(/'/g, '"') + ret.substr(idx + 2);
+ return new ContactGroup(privateData.groups[i]);
}
- cb(null, ctype, ret);
- },
- decode: function(contentType, data, cb) {
- var expCT = constant.TYPE_SYNCML + '+' + this.name;
- if ( contentType.indexOf(expCT) != 0 )
- cb(new common.ProtocolError(
- 'received unexpected content-type "' + contentType + '" (expected "'
- + expCT + '")'));
- try
- {
- return cb(null, ET.parse(data).getroot());
- }
- catch(e)
- {
- return cb(new common.ProtocolError('could not parse XML: ' + e, e));
- }
+ function addGroup(group) {
+ var external = group;
+
+ if (!_security.addGroup) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- });
+ t.AddressBook("addGroup", arguments, true);
- //---------------------------------------------------------------------------
- // TODO: implement wbxml...
- // exports.WbXmlCodec = exports.Codec.extend({
- // encode: function(xtree, cb) {
- // },
- // decode: function(contentType, data, cb) {
- // }
- // });
+ group.id = Math.uuid(null, 16);
+ group.addressBookId = id;
- return exports;
+ external.__defineGetter__("id", function () {
+ return group.id;
+ });
-})();
+ external.__defineGetter__("addressBookId", function () {
+ return group.addressBookId;
+ });
-module.exports = _self;
+ privateData.groups.push(group);
+ _save();
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/common', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// auth: metagriffin <metagriffin@uberdev.org>
-// date: 2012/10/13
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ function updateGroup(group) {
+ var i;
-var constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- _self;
+ if (!_security.updateGroup) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_self = (function () {
- var exports = {};
+ t.AddressBook("updateGroup", arguments);
- //---------------------------------------------------------------------------
- // object inheritance helper routines shamelessly scrubbed from backbone.js
+ if (!group.id) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ for (i in privateData.groups) {
+ if (privateData.groups[i].id === group.id)
+ break;
+ }
+ if (privateData.groups[i].id === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ if (privateData.groups[i].readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ privateData.groups[i] = utils.copy(group);
+ _save();
+ }
- // The self-propagating extend function that Backbone classes use.
- var extend = exports.extend = function (protoProps, classProps) {
- var child = inherits(this, protoProps, classProps);
- child.extend = this.extend;
- return child;
- };
+ function removeGroup(groupId) {
+ var i;
- // Shared empty constructor function to aid in prototype-chain creation.
- var ctor = function(){};
+ if (!_security.removeGroup) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // Helper function to correctly set up the prototype chain, for subclasses.
- // Similar to `goog.inherits`, but uses a hash of prototype properties and
- // class properties to be extended.
- var inherits = function(parent, protoProps, staticProps) {
- var child;
+ t.AddressBook("removeGroup", arguments);
- // 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 && protoProps.hasOwnProperty('constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ parent.apply(this, arguments); };
+ for (i in privateData.groups) {
+ if (privateData.groups[i].id === groupId)
+ break;
+ }
+ if (privateData.groups[i].id === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ if (privateData.groups[i].readOnly) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- // Inherit class (static) properties from parent.
- _.extend(child, parent);
+ privateData.groups.splice(i, 1);
+ _save();
+ }
- // Set the prototype chain to inherit from `parent`, without calling
- // `parent`'s constructor function.
- ctor.prototype = parent.prototype;
- child.prototype = new ctor();
+ function getGroups() {
+ var groups = [], i;
- // Add prototype properties (instance properties) to the subclass,
- // if supplied.
- if (protoProps) _.extend(child.prototype, protoProps);
+ if (!_security.getGroups) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // Add static properties to the constructor function, if supplied.
- if (staticProps) _.extend(child, staticProps);
+ for (i in privateData.groups) {
+ groups.push(new ContactGroup(privateData.groups[i]));
+ }
+ return groups;
+ }
- // Correctly set child's `prototype.constructor`.
- child.prototype.constructor = child;
+ privateData.load();
+ // Make private contacts accessible for Person methods
+ _data.contacts[id] = privateData.contacts;
- // Set a convenience property in case the parent's prototype is needed later.
- child.__super__ = parent.prototype;
+ addressBook = {
+ get: get,
+ add: add,
+ addBatch: addBatch,
+ update: update,
+ updateBatch: updateBatch,
+ remove: remove,
+ removeBatch: removeBatch,
+ find: find,
+ addChangeListener: addChangeListener,
+ removeChangeListener: removeChangeListener,
- return child;
+ getGroup: getGroup,
+ addGroup: addGroup,
+ updateGroup: updateGroup,
+ removeGroup: removeGroup,
+ getGroups: getGroups
};
- //-----------------------------------------------------------------------------
- exports.Base = function() {};
- exports.Base.extend = extend;
+ addressBook.__defineGetter__("id", function () {
+ return id;
+ });
- //-----------------------------------------------------------------------------
- var SyncmlError = exports.Base.extend({
- constructor: function(msg, exception, attrs) {
- this.message = this.name;
- if ( msg != undefined )
- this.message += ': ' + msg;
- this.exception = exception;
- if ( attrs )
- _.extend(this, attrs);
- },
- toString: function() {
- return this.message;
- }
+ addressBook.__defineGetter__("name", function () {
+ return name;
});
- //---------------------------------------------------------------------------
- exports.Stream = exports.Base.extend({
+ addressBook.__defineGetter__("readOnly", function () {
+ return readOnly;
+ });
- writeln: function(data) {
- if ( data == undefined )
- return;
- return this.write(data + '\n');
- },
+ return addressBook;
+};
- indented: function(indent) {
- return new exports.IndentStream(this, indent || this._indent);
+AddressBookData = function (contacts, groups) {
+ var addressBookData;
+
+ // private
+ function loadContacts() {
+ for (var i in contacts) {
+ addressBookData.contacts[i] = new ContactInternal(contacts[i]);
}
+ }
- });
+ function loadGroups() {
+ addressBookData.groups = groups;
+ }
- _.extend(exports, {
+ // public
+ function load() {
+ loadContacts();
+ loadGroups();
+ }
- //---------------------------------------------------------------------------
- // exceptions
- SyncmlError: SyncmlError.extend({name: 'SyncmlError'}),
- TypeError: SyncmlError.extend({name: 'TypeError'}),
- NotImplementedError: SyncmlError.extend({name: 'NotImplementedError'}),
- ProtocolError: SyncmlError.extend({name: 'ProtocolError'}),
- InternalError: SyncmlError.extend({name: 'InternalError'}),
- ConflictError: SyncmlError.extend({name: 'ConflictError'}),
- FeatureNotSupported: SyncmlError.extend({name: 'FeatureNotSupported'}),
- LogicalError: SyncmlError.extend({name: 'LogicalError'}),
- CredentialsRequired: SyncmlError.extend({name: 'CredentialsRequired'}),
- InvalidCredentials: SyncmlError.extend({name: 'InvalidCredentials'}),
- InvalidContext: SyncmlError.extend({name: 'InvalidContext'}),
- InvalidAdapter: SyncmlError.extend({name: 'InvalidAdapter'}),
- InvalidStore: SyncmlError.extend({name: 'InvalidStore'}),
- InvalidContentType: SyncmlError.extend({name: 'InvalidContentType'}),
- InvalidAgent: SyncmlError.extend({name: 'InvalidAgent'}),
- InvalidContent: SyncmlError.extend({name: 'InvalidContent'}),
- InvalidItem: SyncmlError.extend({name: 'InvalidItem'}),
- UnknownCodec: SyncmlError.extend({name: 'UnknownCodec'}),
- NoSuchRoute: SyncmlError.extend({name: 'NoSuchRoute'}),
- UnknownAuthType: SyncmlError.extend({name: 'UnknownAuthType'}),
- UnknownFormatType: SyncmlError.extend({name: 'UnknownFormatType'}),
+ addressBookData = {
+ contacts: {},
+ groups: [],
+ listeners: {},
+ nListener: 0,
+ load: load
+ };
- //---------------------------------------------------------------------------
- // UUID generation
- makeID: function() {
- // shamelessly scrubbed from:
- // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
- // (adjusted to remove the dashes)
- // todo: see some of those links on how to make this more "robust"...
- return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
- var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
- return v.toString(16);
- });
- },
+ return addressBookData;
+};
- //-------------------------------------------------------------------------
- synctype2alert: function(type) {
- return constant.SyncTypeToAlert[type];
- },
+AddressBookStorage = function (id, name, readOnly, contacts, groups) {
+ this.id = id;
+ this.name = name;
+ this.readOnly = readOnly;
+ this.contacts = contacts;
+ this.groups = groups;
+};
- //-------------------------------------------------------------------------
- alert2synctype: function(alert) {
- for ( var key in constant.SyncTypeToAlert )
- {
- if ( constant.SyncTypeToAlert[key] == alert )
- return exports.int(key);
+Contact = function (contact) {
+ var i, attr, arr;
+
+ this.name = null;
+ this.addresses = [];
+ this.photoURI = null;
+ this.phoneNumbers = [];
+ this.emails = [];
+ this.birthday = null;
+ this.anniversaries = [];
+ this.organizations = [];
+ this.notes = [];
+ this.urls = [];
+ this.ringtoneURI = null;
+ this.groupIds = [];
+
+ for (attr in contact) {
+ switch (attr) {
+ case "name":
+ this[attr] = new ContactName(contact[attr]);
+ break;
+
+ case "addresses":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactAddress(arr[i]);
+ }
}
- return null;
- },
+ break;
- //-------------------------------------------------------------------------
- mode2string: function(code) {
- switch ( code )
- {
- case constant.ALERT_TWO_WAY: return 'two-way';
- case constant.ALERT_SLOW_SYNC: return 'slow-sync';
- case constant.ALERT_ONE_WAY_FROM_CLIENT: return 'one-way-from-client';
- case constant.ALERT_REFRESH_FROM_CLIENT: return 'refresh-from-client';
- case constant.ALERT_ONE_WAY_FROM_SERVER: return 'one-way-from-server';
- case constant.ALERT_REFRESH_FROM_SERVER: return 'refresh-from-server';
- case constant.ALERT_TWO_WAY_BY_SERVER: return 'two-way-by-server';
- case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER: return 'one-way-from-client-by-server';
- case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER: return 'refresh-from-client-by-server';
- case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER: return 'one-way-from-server-by-server';
- case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER: return 'refresh-from-server-by-server';
- default: return 'UNKNOWN';
+ case "phoneNumbers":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactPhoneNumber(arr[i].number,
+ arr[i].types || null, arr[i].isDefault || null);
+ }
}
- },
+ break;
- //-------------------------------------------------------------------------
- state2string: function(state) {
- switch ( state )
- {
- case constant.ITEM_OK: return 'ok';
- case constant.ITEM_ADDED: return 'added';
- case constant.ITEM_MODIFIED: return 'modified';
- case constant.ITEM_DELETED: return 'deleted';
- case constant.ITEM_SOFTDELETED: return 'soft-deleted';
- default: return 'UNKNOWN';
+ case "emails":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactEmailAddress(arr[i].email,
+ arr[i].types || null, arr[i].isDefault || null);
+ }
}
- },
+ break;
- //-------------------------------------------------------------------------
- oneWay: function(mode) {
- switch ( mode )
- {
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_SLOW_SYNC:
- return false;
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- case constant.ALERT_REFRESH_FROM_SERVER:
- return true;
- // case constant.ALERT_TWO_WAY_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
- default:
- throw new exports.InternalError('invalid mode "' + mode + '"');
+ case "birthday":
+ this[attr] = new Date(contact[attr]);
+ break;
+
+ case "anniversaries":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ if (!tizen1_utils.isValidDate(arr[i].date)) {
+ arr[i].date = new Date(arr[i].date);
+ }
+ this[attr][i] = new ContactAnniversary(arr[i].date,
+ arr[i].label || null);
+ }
}
- },
+ break;
- //-------------------------------------------------------------------------
- oneWayIn: function(session, mode) {
- switch ( mode )
- {
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_SLOW_SYNC:
- return false;
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- return !! session.isServer;
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- case constant.ALERT_REFRESH_FROM_SERVER:
- return ! session.isServer;
- // case constant.ALERT_TWO_WAY_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
- default:
- throw new exports.InternalError('invalid mode "' + mode + '"');
+ case "organizations":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactOrganization(arr[i]);
+ }
}
- },
+ break;
- //-------------------------------------------------------------------------
- oneWayOut: function(session, mode) {
- switch ( mode )
- {
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_SLOW_SYNC:
- return false;
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- return ! session.isServer;
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- case constant.ALERT_REFRESH_FROM_SERVER:
- return !! session.isServer;
- // case constant.ALERT_TWO_WAY_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
- default:
- throw new exports.InternalError('invalid mode "' + mode + '"');
+ case "notes":
+ case "groupIds":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = arr[i];
+ }
}
- },
+ break;
- //-------------------------------------------------------------------------
- cascade: function(list, iterator, cb) {
- if ( ! cb && iterator )
- {
- cb = iterator;
- iterator = null;
+ case "urls":
+ arr = contact[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactWebSite(arr[i].url,
+ arr[i].type || null);
+ }
}
- if ( ! list )
- return cb();
- var cur = 0;
- var next = function() {
- if ( cur >= list.length )
- return cb();
- var curcb = function(err) {
- if ( err )
- return cb(err);
- cur += 1;
- var args = [];
- for ( var idx=1 ; idx<arguments.length ; idx++ )
- args.push(arguments[idx]);
- return next.apply(null, args);
- };
- var func = iterator || list[cur];
- var args = [];
- if ( iterator )
- args.push(list[cur]);
- for ( var idx=0 ; idx<arguments.length ; idx++ )
- args.push(arguments[idx]);
- args.push(curcb);
- return func.apply(null, args);
- };
- return next();
- },
+ break;
- //-------------------------------------------------------------------------
- ts: function() {
- return Math.floor((new Date()).getTime() / 1000);
- },
+ default:
+ this[attr] = contact[attr];
+ break;
+ }
+ }
- //-------------------------------------------------------------------------
- j: function(obj) {
- return JSON.stringify(obj);
- },
+ decorator.Contact(this, contact);
+ this.__proto__ = tizen.Contact.prototype;
+};
- //-------------------------------------------------------------------------
- noop: function(cb) {
- return cb();
- },
+ContactInternal = function (contact) {
+ var attr;
- //-------------------------------------------------------------------------
- platformBits: function() {
+ for (attr in contact) {
+ this[attr] = contact[attr];
+ }
- // TODO: implement this!...
+ if (!contact.id) {
+ this.id = Math.uuid(null, 16);
+ this.lastUpdated = new Date();
+ } else {
+ this.lastUpdated = new Date(contact.lastUpdated);
+ }
- return 32;
- },
+ if (this.name) {
+ this.name.__defineGetter__("displayName", function () {
+ var displayName = "";
- //-------------------------------------------------------------------------
- getMaxMemorySize: function(context) {
+ if (!this)
+ return "";
- // Returns the maximum size of a memory object. By default this
- // is, set to ``sys.maxint``, however the `context` may override
- // this behavior.
+ if ((this.firstName !== null) &&
+ (this.lastName !== null)) {
+ displayName = [this.firstName, this.middleName, this.lastName];
+ displayName = displayName.join(" ").replace(/ +/g, " ").trim();
+ } else if (this.nicknames.length !== 0) {
+ this.nicknames.some(function (nickname) {
+ displayName = nickname;
+ return displayName;
+ });
+ }
- // NOTE: currently, this is being hardcoded to a maximum of 2GB for
- // compatibility with funambol servers, which croak above that
- // value.
+ return displayName;
+ });
+ }
+};
- // TODO: allow the context to control this, or implement auto-detect to
- // determine what the remote peer can support...
+ContactData = function () {
+ this.listeners = {};
+ this.nListener = 0;
+};
- return Math.min(Math.pow(2, exports.platformBits() - 1) - 1,
- Math.pow(2, 31) - 1);
- },
+ContactGroup = function (groupInitDict) {
+ var id, addressBookId, readOnly;
- //-------------------------------------------------------------------------
- normpath: function(path) {
- if ( path == undefined )
- return null;
- if ( path.length <= 0 )
- return '';
- if ( path.indexOf('/') < 0 )
- path = path.replace('\\', '/');
- var ret = [];
- var plist = path.split('/');
- for ( var idx=0 ; idx<plist.length ; idx++ )
- {
- var item = plist[idx];
- if ( item.length <= 0 || item == '.' )
- continue;
- if ( item != '..' || ret.length <= 0 || ret[ret.length - 1] == '..' )
- {
- ret.push(item);
- continue;
- }
- ret.pop();
- }
- ret = ret.join('/');
- if ( path.charAt(0) != '/' )
- return ret;
- return '/' + ret;
- },
+ this.__defineGetter__("id", function () {
+ return id;
+ });
- //-------------------------------------------------------------------------
- int: function(str, defval) {
- if ( ! str )
- return defval;
- return parseInt(str, 10);
- },
+ this.__defineGetter__("addressBookId", function () {
+ return addressBookId;
+ });
- //-------------------------------------------------------------------------
- cmp: function(a, b) {
- if ( a < b )
- return -1;
- if ( a > b )
- return 1;
- return 0;
- },
+ this.__defineGetter__("readOnly", function () {
+ return readOnly;
+ });
- //-------------------------------------------------------------------------
- // partially emulates python's string.split() method
- splitn: function(str, sep, limit) {
- var ret = str.split(sep);
- if ( ret.length <= ( limit + 1 ) )
- return ret;
- var tmp = ret.slice(0, limit);
- tmp.push(ret.slice(limit).join(sep));
- return tmp;
- },
+ id = groupInitDict.id || null;
+ addressBookId = groupInitDict.addressBookId || null;
+ readOnly = groupInitDict.readOnly || false;
- //-------------------------------------------------------------------------
- prettyJson: function(obj, indent) {
- indent = indent || '';
- var ret = '';
- if ( _.isArray(obj) )
- {
- if ( obj.length <= 0 )
- return '[]';
- ret = '[\n' + indent;
- _.each(obj, function(el, idx) {
- ret += ' ' + exports.prettyJson(el, indent + ' ');
- if ( idx + 1 < obj.length )
- ret += ',';
- ret += '\n' + indent;
- });
- return ret + ']';
- }
- if ( _.isObject(obj) )
- {
- var keys = _.keys(obj);
- if ( keys.length <= 0 )
- return '{}';
- keys.sort();
- ret = '{\n' + indent;
- _.each(keys, function(key, idx) {
- ret += ' ' + exports.prettyJson(key)
- + ': ' + exports.prettyJson(obj[key], indent + ' ');
- if ( idx + 1 < keys.length )
- ret += ',';
- ret += '\n' + indent;
- });
- return ret + ( indent.length <= 0 ? '}\n' : '}' );
- }
- return JSON.stringify(obj);
- },
+ this.name = groupInitDict.name || "";
+ this.ringtoneURI = groupInitDict.ringtoneURI || null;
+ this.photoURI = groupInitDict.photoURI || null;
- //-------------------------------------------------------------------------
- urlEncode: function(dat) {
- return ( dat == undefined ? dat : encodeURIComponent(dat) );
- },
+ this.__proto__ = tizen.ContactGroup.prototype;
+};
- //-------------------------------------------------------------------------
- /*
- rmfr: function(path, cb) {
- fs.stat(path, function(err, stats) {
- if ( err && err.code == 'ENOENT' )
- return cb();
- if ( err )
- return cb(err);
- if ( ! stats.isDirectory() )
- return fs.unlink(path, cb);
- fs.readdir(path, function(err, files) {
- exports.cascade(files, function(file, cb) {
- var curpath = pathmod.join(path, file);
- return exports.rmfr(curpath, cb);
- }, function(err) {
- if ( err )
- return cb(err);
- fs.rmdir(path, cb);
- });
- });
- });
- },
- */
- //-------------------------------------------------------------------------
- /*
- makedirs: function(path, cb) {
- // node sucks. i can't believe it doesn't provide a fs.makedirs(). wtf.
- // clean up the path
- path = pathmod.normalize(path.split(/[\\\/]/).join('/'));
- var paths = path.split('/');
- paths = _.map(paths, function(p, idx) {
- return paths.slice(0, idx + 1).join('/');
- });
- if ( path.charAt(0) == '/' )
- paths.shift();
- exports.cascade(paths, function(path, cb) {
- fs.stat(path, function(err, stats) {
- if ( err && err.code == 'ENOENT' )
- return fs.mkdir(path, cb);
- if ( err )
- return cb(err);
- if ( stats.isDirectory() )
- return cb();
- // this probably won't work, but let's get the error anyhow...
- return fs.mkdir(path, cb);
- });
- }, cb);
- },
- */
+Person = function (personInitDict) {
+ var person = {};
- //-------------------------------------------------------------------------
- StringStream: exports.Stream.extend({
+ function hasContactMethod(method) {
+ var idab, idc, contact, count = 0;
- constructor: function(initData) {
- this._data = initData || '';
- },
+ for (idab in _data.contacts) {
+ for (idc in _data.contacts[idab]) {
+ contact = _data.contacts[idab][idc];
+ if (contact.personId === person.id) {
+ count += contact[method].length;
+ }
+ }
+ }
- write: function(data) {
- if ( data == undefined )
- return;
- this._data += data;
- },
+ return (count !== 0);
+ }
- getData: function() {
- return this._data;
- }
+ person.id = personInitDict.id || Math.uuid(null, 16);
+ person.isFavorite = personInitDict.isFavorite || false;
+ person.photoURI = personInitDict.photoURI || null;
+ person.ringtoneURI = personInitDict.ringtoneURI || null;
+ person.displayContactId = personInitDict.displayContactId;
- }),
+ this.__defineGetter__("id", function () {
+ return person.id;
+ });
- //-------------------------------------------------------------------------
- IndentStream: exports.Stream.extend({
+ this.__defineGetter__("displayName", function () {
+ var idab, contact, displayName = "";
- //-----------------------------------------------------------------------
- constructor: function(stream, indent, options) {
- options = options || {};
- this._stream = stream;
- this._indent = indent || ' ';
- this._cleared = true;
- this._stayBlank = !! options.stayBlank;
- },
+ for (idab in _data.contacts) {
+ contact = _data.contacts[idab][this.displayContactId];
- //-----------------------------------------------------------------------
- write: function(data) {
- var self = this;
- if ( data == undefined )
- return;
- // if ( ! data || ! data.length || data.length <= 0 )
- // return;
- var lines = data.split('\n');
- if ( self._cleared )
- self._stream.write(self._indent);
- self._cleared = false;
- for ( var idx=0 ; idx<lines.length ; idx++ )
- {
- var line = lines[idx];
- if ( line == '' )
- {
- if ( idx + 1 >= lines.length )
- self._cleared = true;
- else
- {
- if ( idx != 0 && ! self._stayBlank )
- self._stream.write(self._indent);
+ if (contact !== undefined) {
+ if (contact.name && contact.name.displayName) {
+ displayName = contact.name.displayName;
}
+ break;
}
- else
- {
- if ( idx != 0 || self._cleared )
- self._stream.write(self._indent);
- self._stream.write(line);
- }
- if ( idx + 1 < lines.length )
- self._stream.write('\n');
}
+
+ return displayName;
+ });
+
+ this.__defineGetter__("contactCount", function () {
+ var idab, idc, contactCount = 0;
+
+ for (idab in _data.contacts) {
+ for (idc in _data.contacts[idab]) {
+ if (_data.contacts[idab][idc].personId === person.id) {
+ ++contactCount;
+ }
+ }
}
- })
+ return contactCount;
+ });
+ this.__defineGetter__("hasPhoneNumber", function () {
+ return hasContactMethod("phoneNumbers");
});
- return exports;
-})();
+ this.__defineGetter__("hasEmail", function () {
+ return hasContactMethod("emails");
+ });
-module.exports = _self;
+ this.__defineGetter__("isFavorite", function () {
+ return person.isFavorite;
+ });
+ this.__defineSetter__("isFavorite", function (val) {
+ try {
+ person.isFavorite = t.boolean(val);
+ } catch (e) {
+ }
+ });
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/constant', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// desc: SyncML constants
-// auth: metagriffin <metagriffin@uberdev.org>
-// date: 2012/10/13
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ this.__defineGetter__("photoURI", function () {
+ return person.photoURI;
+ });
+ this.__defineSetter__("photoURI", function (val) {
+ try {
+ person.photoURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-var _self = {
- // SyncML versions
- SYNCML_VERSION_1_0 : 'SyncML/1.0',
- SYNCML_VERSION_1_1 : 'SyncML/1.1',
- SYNCML_VERSION_1_2 : 'SyncML/1.2',
- SYNCML_DTD_VERSION_1_0 : '1.0',
- SYNCML_DTD_VERSION_1_1 : '1.1',
- SYNCML_DTD_VERSION_1_2 : '1.2',
+ this.__defineGetter__("ringtoneURI", function () {
+ return person.ringtoneURI;
+ });
+ this.__defineSetter__("ringtoneURI", function (val) {
+ try {
+ person.ringtoneURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- // SyncML alert/sync codes
- ALERT_DISPLAY : 100,
- ALERT_TWO_WAY : 200,
- ALERT_SLOW_SYNC : 201,
- ALERT_ONE_WAY_FROM_CLIENT : 202,
- ALERT_REFRESH_FROM_CLIENT : 203,
- ALERT_ONE_WAY_FROM_SERVER : 204,
- ALERT_REFRESH_FROM_SERVER : 205,
- ALERT_TWO_WAY_BY_SERVER : 206,
- ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER : 207,
- ALERT_REFRESH_FROM_CLIENT_BY_SERVER : 208,
- ALERT_ONE_WAY_FROM_SERVER_BY_SERVER : 209,
- ALERT_REFRESH_FROM_SERVER_BY_SERVER : 210,
- // alert codes 211-220 are reserved for future use
+ this.__defineGetter__("displayContactId", function () {
+ return person.displayContactId;
+ });
+ this.__defineSetter__("displayContactId", function (val) {
+ try {
+ person.displayContactId = t.ContactId(val);
+ } catch (e) {
+ }
+ });
- // SyncML SyncCap SyncTypes
- SYNCTYPE_AUTO : null,
- SYNCTYPE_TWO_WAY : 1,
- SYNCTYPE_SLOW_SYNC : 2,
- SYNCTYPE_ONE_WAY_FROM_CLIENT : 3,
- SYNCTYPE_REFRESH_FROM_CLIENT : 4,
- SYNCTYPE_ONE_WAY_FROM_SERVER : 5,
- SYNCTYPE_REFRESH_FROM_SERVER : 6,
- SYNCTYPE_SERVER_ALERTED : 7,
+ this.link = function (personId) {
+ if (!_security.link) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.Person("link", arguments);
+
+ if (_data.persons[personId] === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- // Special syncml-js SyncTypes
- SYNCTYPE_DISCOVER : 'discover',
+ _replacePerson(personId, person.id);
+ _save();
+ };
- // SyncML synctype-to-alertcode mapping
- // taking advantage of the fact that 1..7 maps to 200..206
- // (more or less... "7" is a bit "nebulous"...)
- SyncTypeToAlert: _.object(_.map(_.range(7), function(i) {
- return [ i + 1, i + 200 ];
- })),
+ this.unlink = function (contactId) {
+ var idab, contact, separated, i, dbAddressBook;
- // Conflict handling policies
- POLICY_ERROR : 1,
- POLICY_CLIENT_WINS : 2,
- POLICY_SERVER_WINS : 3,
+ if (!_security.unlink) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // SyncML XML namespaces
- NAMESPACE_SYNCML_1_0 : 'syncml:syncml1.0',
- NAMESPACE_SYNCML_1_1 : 'syncml:syncml1.1',
- NAMESPACE_SYNCML_1_2 : 'syncml:syncml1.2',
- NAMESPACE_METINF : 'syncml:metinf',
- NAMESPACE_DEVINF : 'syncml:devinf',
- NAMESPACE_AUTH_BASIC : 'syncml:auth-basic',
- NAMESPACE_AUTH_MD5 : 'syncml:auth-md5',
- NAMESPACE_FILTER_CGI : 'syncml:filtertype-cgi',
+ t.Person("unlink", arguments);
- // Commonly used content-types
- TYPE_TEXT_PLAIN : 'text/plain',
- TYPE_VCARD_V21 : 'text/x-vcard',
- TYPE_VCARD_V30 : 'text/vcard',
- TYPE_VCALENDAR : 'text/x-vcalendar',
- TYPE_ICALENDAR : 'text/calendar',
- TYPE_MESSAGE : 'text/message',
- TYPE_SYNCML : 'application/vnd.syncml',
- TYPE_SYNCML_DEVICE_INFO : 'application/vnd.syncml-devinf',
- TYPE_SYNCML_ICALENDAR : 'application/vnd.syncml-xcal',
- TYPE_SYNCML_EMAIL : 'application/vnd.syncml-xmsg',
- TYPE_SYNCML_BOOKMARK : 'application/vnd.syncml-xbookmark',
- TYPE_SYNCML_RELATIONAL_OBJECT : 'application/vnd.syncml-xrelational',
- TYPE_OMADS_FOLDER : 'application/vnd.omads-folder',
- TYPE_OMADS_FILE : 'application/vnd.omads-file',
- TYPE_OMADS_EMAIL : 'application/vnd.omads-email',
- TYPE_SQL : 'application/sql',
- TYPE_LDAP : 'text/directory',
- TYPE_EMAIL : 'message/rfc2822',
- TYPE_EMAIL_822 : 'message/rfc822',
- TYPE_SIF_CONTACT : 'text/x-s4j-sifc',
- TYPE_SIF_NOTE : 'text/x-s4j-sifn',
- TYPE_SIF_TASK : 'text/x-s4j-sift',
- TYPE_SIF_EVENT : 'text/x-s4j-sife',
+ for (idab in _data.contacts) {
+ if (_data.contacts[idab][contactId] !== undefined) {
+ contact = _data.contacts[idab][contactId];
+ break;
+ }
+ }
- // non-agent URI paths
- URI_DEVINFO_1_0 : 'devinf10',
- URI_DEVINFO_1_1 : 'devinf11',
- URI_DEVINFO_1_2 : 'devinf12',
+ if (contact === undefined) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ if (contact.personId !== person.id) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
- // Response codes - Generic
- STATUS_INVALID_CODE : 0,
- // Response codes - Informational 1xx
- STATUS_IN_PROGRESS : 101,
- // Response codes - Successful 2xx
- STATUS_OK : 200,
- STATUS_ITEM_ADDED : 201,
- STATUS_ACCEPTED_FOR_PROCESSING : 202,
- STATUS_NONAUTHORIATATIVE_RESPONSE : 203,
- STATUS_NO_CONTENT : 204,
- STATUS_RESET_CONTENT : 205,
- STATUS_PARTIAL_CONTENT : 206,
- STATUS_CONFLICT_RESOLVED_MERGE : 207,
- STATUS_CONFLICT_RESOLVED_CLIENT_DATA : 208,
- STATUS_CONFLICT_RESOLVED_DUPLICATE : 209,
- STATUS_DELETE_WITHOUT_ARCHIVE : 210,
- STATUS_ITEM_NOT_DELETED : 211,
- STATUS_AUTHENTICATION_ACCEPTED : 212,
- STATUS_CHUNKED_ITEM_ACCEPTED : 213,
- STATUS_OPERATION_CANCELLED_OK : 214,
- STATUS_NOT_EXECUTED : 215,
- STATUS_ATOMIC_ROLLBACK_OK : 216,
- STATUS_RESULT_ALERT : 221,
- STATUS_NEXT_MESSAGE : 222,
- STATUS_NO_END_OF_DATA : 223,
- STATUS_SUSPEND : 224,
- STATUS_RESUME : 225,
- STATUS_DATA_MANAGEMENT : 226,
- // status codes 227-250 are reserved for future use,
- // Response codes - Redirection 3xx
- STATUS_MULTIPLE_CHOICES : 300,
- STATUS_MOVED_PERMANENTLY : 301,
- STATUS_FOUND : 302,
- STATUS_SEE_ANOTHER_URI : 303,
- STATUS_NOT_MODIFIED : 304,
- STATUS_USE_PROXY : 305,
- // Response codes - Originator Exceptions 4xx
- STATUS_BAD_REQUEST : 400,
- STATUS_INVALID_CREDENTIALS : 401,
- STATUS_PAYMENT_REQUIRED : 402,
- STATUS_FORBIDDEN : 403,
- STATUS_NOT_FOUND : 404,
- STATUS_COMMAND_NOT_ALLOWED : 405,
- STATUS_OPTIONAL_FEATURE_NOT_SUPPORTED : 406,
- STATUS_MISSING_CREDENTIALS : 407,
- STATUS_REQUEST_TIMEOUT : 408,
- STATUS_UPDATE_CONFLICT : 409,
- STATUS_GONE : 410,
- STATUS_SIZE_REQUIRED : 411,
- STATUS_INCOMPLETE_COMMAND : 412,
- STATUS_REQUESTED_ENTITY_TOO_LARGE : 413,
- STATUS_URI_TOO_LONG : 414,
- STATUS_UNSUPPORTED_MEDIA_TYPE : 415,
- STATUS_REQUESTED_SIZE_TOO_BIG : 416,
- STATUS_RETRY_LATER : 417,
- STATUS_ALREADY_EXISTS : 418,
- STATUS_CONFLICT_RESOLVED_SERVER_DATA : 419,
- STATUS_DEVICE_FULL : 420,
- STATUS_UNKNOWN_SEARCH_GRAMMAR : 421,
- STATUS_BAD_CGI_SCRIPT : 422,
- STATUS_SOFT_DELETE_CONFLICT : 423,
- STATUS_OBJECT_SIZE_MISMATCH : 424,
- STATUS_PERMISSION_DENIED : 425,
- // Response codes - Recipient Exceptions 5xx
- STATUS_COMMAND_FAILED : 500,
- STATUS_NOT_IMPLEMENTED : 501,
- STATUS_BAD_GATEWAY : 502,
- STATUS_SERVICE_UNAVAILABLE : 503,
- STATUS_GATEWAY_TIMEOUT : 504,
- STATUS_VERSION_NOT_SUPPORTED : 505,
- STATUS_PROCESSING_ERROR : 506,
- STATUS_ATOMIC_FAILED : 507,
- STATUS_REFRESH_REQUIRED : 508,
- STATUS_RECIPIENT_EXCEPTION_RESERVED1 : 509,
- STATUS_DATASTORE_FAILURE : 510,
- STATUS_SERVER_FAILURE : 511,
- STATUS_SYNCHRONIZATION_FAILED : 512,
- STATUS_PROTOCOL_VERSION_NOT_SUPPORTED : 513,
- STATUS_OPERATION_CANCELLED : 514,
- STATUS_ATOMIC_ROLLBACK_FAILED : 516,
- STATUS_ATOMIC_RESPONSE_TOO_LARGE_TO_FIT : 517,
+ separated = new PersonBuilder(contact);
+ _data.persons[separated.id] = separated;
+ contact.personId = separated.id;
- // SyncML codecs
- CODEC_XML : 'xml',
- CODEC_WBXML : 'wbxml',
- FORMAT_B64 : 'b64',
- FORMAT_AUTO : 'auto',
+ _data.dbStorage.persons[separated.id] = _serialize(separated);
+ for (i in _data.dbStorage.addressBooks) {
+ dbAddressBook = _data.dbStorage.addressBooks[i];
+ if (dbAddressBook.id === idab) {
+ dbAddressBook.contacts[contact.id].personId = separated.id;
+ break;
+ }
+ }
+ _save();
- // SyncML nodes
- NODE_SYNCML : 'SyncML',
- NODE_SYNCBODY : 'SyncBody',
+ return separated;
+ };
+};
- // SyncML commands
- CMD_SYNCHDR : 'SyncHdr',
- CMD_SYNC : 'Sync',
- CMD_ALERT : 'Alert',
- CMD_STATUS : 'Status',
- CMD_GET : 'Get',
- CMD_PUT : 'Put',
- CMD_ADD : 'Add',
- CMD_REPLACE : 'Replace',
- CMD_DELETE : 'Delete',
- CMD_RESULTS : 'Results',
- CMD_ATOMIC : 'Atomic',
- CMD_COPY : 'Copy',
- CMD_EXEC : 'Exec',
- CMD_MAP : 'Map',
- CMD_MAPITEM : 'MapItem',
- CMD_SEARCH : 'Search',
- CMD_SEQUENCE : 'Sequence',
- CMD_FINAL : 'Final',
+PersonBuilder = function (contact) {
+ var person, personInitDict = {};
- // SyncML standard device types
- DEVTYPE_HANDHELD : 'handheld',
- DEVTYPE_PAGER : 'pager',
- DEVTYPE_PDA : 'pda',
- DEVTYPE_PHONE : 'phone',
- DEVTYPE_SERVER : 'server',
- DEVTYPE_SMARTPHONE : 'smartphone',
- DEVTYPE_WORKSTATION : 'workstation',
+ personInitDict.displayContactId = contact.id;
+ person = new Person(personInitDict);
- // Item status codes
- ITEM_OK : 0,
- ITEM_ADDED : 1,
- ITEM_MODIFIED : 2,
- ITEM_DELETED : 3,
- ITEM_SOFTDELETED : 4,
+ return person;
};
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/context', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.context
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/10/22
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+define('ripple/platform/tizen/2.0/NDEFRecordText', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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 common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
- router = require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
- synchronizer = require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
- protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
- localadapter = require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
- idxdb = {},
- _self;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
+ NDEFRecordText;
-// todo: is this the right place to put this?...
-// the reason that i did not put it in the `define` call is
-// because it needs access to `this.indexedDB`...
-var idxdb = {};
-if ( typeof(window) != 'undefined' && window.indexedDB )
-{
- idxdb.indexedDB = window.indexedDB;
- idxdb.IDBKeyRange = window.IDBKeyRange;
-}
-else
-{
- idxdb.indexedDB = this.indexedDB;
- idxdb.IDBKeyRange = this.IDBKeyRange;
-}
+NDEFRecordText = function (text, languageCode, encoding) {
+ var payload = [], i;
-_self = (function () {
- var exports = {};
+ t.NDEFRecordText(arguments, this);
- //---------------------------------------------------------------------------
- exports.Context = common.Base.extend({
+ encoding = encoding || "UTF8";
- //-------------------------------------------------------------------------
- constructor: function(options) {
- // options.storage expects the following properties:
- // - indexedDB
- // - IDBKeyRange
- options = options || {};
- this.storage = options.storage || idxdb;
- this.dbname = ( options.prefix || '' ) + 'syncml-js';
- this.autoCommit = options.autoCommit == undefined ? true : options.autoCommit;
- this.router = options.router || new router.SmartRouter();
- this.synchronizer = options.synchronizer || new synchronizer.Synchronizer();
- this.protocol = options.protocol || new protocol.Protocol();
- this.codec = options.codec || constant.CODEC_XML;
- this.listener = options.listener;
- this.ua = options.ua;
- this.config = _.defaults({}, options.config, {
- trustDevInfo : false,
- exposeErrorTrace : false
- });
- this._db = null;
- this._dbtxn = null;
- },
+ // Store languageCode in payload
+ payload.push(languageCode.length);
+ for (i = 0; i < languageCode.length; i++) {
+ payload.push(languageCode.charCodeAt(i));
+ }
- //-------------------------------------------------------------------------
- getAdapter: function(options, devInfo, cb) {
- options = options || {};
- var self = this;
- if ( this._db == undefined )
- {
- storage.openDatabase(this, function(err, db) {
- if ( err ) {
- return cb(err);
- }
- self._db = db;
- self._db.onerror = function(event) {
- // todo: remove this?...
- };
- self._dbtxn = storage.getTransaction(self._db, null, 'readwrite');
- self.getAdapter(options, devInfo, cb);
- });
- }
- else
- {
- var ret = new localadapter.LocalAdapter(this, options, devInfo);
- return ret._load(cb);
- }
- },
+ // Store text in payload
+ for (i = 0; i < text.length; i++) {
+ payload.push(text.charCodeAt(i));
+ }
- //-------------------------------------------------------------------------
- _txn: function() {
- try {
- // this is a work-around for XPC-based syncml... try to open
- // a store, if it fails, we need a new transaction.
- var store = this._dbtxn.objectStore('mapping');
- return this._dbtxn;
- } catch ( exc ) {
- this._dbtxn = storage.getTransaction(this._db, null, 'readwrite');
- return this._dbtxn;
- }
- },
+ NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
+ ["T".charCodeAt(0)], payload, []);
- //-------------------------------------------------------------------------
- getEasyClientAdapter: function(options, cb) {
- try{
- this._getEasyClientAdapter(options, cb);
- }catch(e){
- cb(e);
- }
- },
+ this.__defineGetter__("text", function () {
+ return text;
+ });
- //-------------------------------------------------------------------------
- _getEasyClientAdapter: function(options, cb) {
- // options should be:= {
- // // devID,
- // // displayName,
- // devInfo: {},
- // stores: [],
- // peer: {},
- // routes: [
- // [ source, target ],
- // ]
- // }
- // response: cb(err, adapter, stores, peer);
+ this.__defineGetter__("languageCode", function () {
+ return languageCode;
+ });
- var self = this;
+ this.__defineGetter__("encoding", function () {
+ return encoding;
+ });
+};
- var ret = {
- adapter: null,
- stores: [],
- peer: null
- };
+module.exports = NDEFRecordText;
- var setupAdapter = function(cb) {
- var adapterOptions = _.omit(options, 'devInfo', 'stores', 'peers', 'routes');
- self.getAdapter(adapterOptions, options.devInfo, function(err, adapter) {
- if ( err ) {
- return cb(err);
- }
- ret.adapter = adapter;
- if ( adapter.devInfo ) {
- return cb();
- }
- adapter.setDevInfo(options.devInfo, cb);
- });
- };
+});
+define('ripple/platform/tizen/2.0/ContactOrganization', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 setupStores = function(cb) {
- common.cascade(options.stores, function(storeInfo, cb) {
- var store = ret.adapter.getStore(storeInfo.uri);
- if ( store != undefined )
- {
- if ( storeInfo.agent ) {
- store.agent = storeInfo.agent;
- }
- ret.stores.push(store);
- return cb();
- }
- ret.adapter.addStore(storeInfo, function(err, store) {
- if ( err ) {
- return cb(err);
- }
- ret.stores.push(store);
- return cb();
- });
- }, cb);
- };
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactOrganization;
- var setupPeer = function(cb) {
- var peer = _.find(ret.adapter.getPeers(), function(p) {
- return p.url == options.peer.url;
- });
- if ( peer )
- {
- ret.peer = peer;
- return cb();
- }
- ret.adapter.addPeer(options.peer, function(err, peer) {
- if ( err ) {
- return cb(err);
- }
- ret.peer = peer;
- common.cascade(options.routes, function(route, cb) {
- ret.peer.setRoute(route[0], route[1], cb);
- }, cb);
- });
- };
- setupAdapter(function(err) {
- if ( err ) {
- return cb(err);
- }
- setupStores(function(err) {
- if ( err ) {
- return cb(err);
- }
- setupPeer(function(err) {
- if ( err ) {
- return cb(err);
- }
- cb(null, ret.adapter, ret.stores, ret.peer);
- });
- });
- });
- },
+ContactOrganization = function (orgInitDict) {
+ var contactOrganization = {}, attr;
- //-------------------------------------------------------------------------
- close: function(cb) {
- if ( this._db )
- this._db.close();
- this._db = null;
- cb(null);
- }
+ t.ContactOrganization(arguments, this);
+
+ contactOrganization.name = null;
+ contactOrganization.department = null;
+ contactOrganization.title = null;
+ contactOrganization.role = null;
+ contactOrganization.logoURI = null;
+ this.__defineGetter__("name", function () {
+ return contactOrganization.name;
+ });
+ this.__defineSetter__("name", function (val) {
+ try {
+ contactOrganization.name = t.DOMString(val, "?");
+ } catch (e) {
+ }
});
- return exports;
+ this.__defineGetter__("department", function () {
+ return contactOrganization.department;
+ });
+ this.__defineSetter__("department", function (val) {
+ try {
+ contactOrganization.department = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-})();
+ this.__defineGetter__("title", function () {
+ return contactOrganization.title;
+ });
+ this.__defineSetter__("title", function (val) {
+ try {
+ contactOrganization.title = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-module.exports = _self;
+ this.__defineGetter__("role", function () {
+ return contactOrganization.role;
+ });
+ this.__defineSetter__("role", function (val) {
+ try {
+ contactOrganization.role = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("logoURI", function () {
+ return contactOrganization.logoURI;
+ });
+ this.__defineSetter__("logoURI", function (val) {
+ try {
+ contactOrganization.logoURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+
+ if (orgInitDict) {
+ for (attr in orgInitDict) {
+ contactOrganization[attr] = orgInitDict[attr];
+ }
+ }
+};
+
+module.exports = ContactOrganization;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/ctype', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// auth: metagriffin <metagriffin@uberdev.org>
-// date: 2012/10/13
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
- _self;
+define('ripple/platform/tizen/2.0/MessageFolder', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
-_self = (function () {
+module.exports = function (opt) {
+ var folder = {}, _id = opt.id, _parentId = null, _serviceId = opt.serviceId,
+ _contentType = opt.contentType, _name = opt.id, _path = opt.path,
+ _type = opt.type, _synchronizable = opt.synchronizable;
- var exports = {};
+ folder.name = _name;
+ folder.synchronizable = _synchronizable;
+
+ folder.__defineGetter__("id", function () {
+ return _id;
+ });
+ folder.__defineGetter__("parentId", function () {
+ return _parentId;
+ });
+ folder.__defineGetter__("serviceId", function () {
+ return _serviceId;
+ });
+ folder.__defineGetter__("contentType", function () {
+ return _contentType;
+ });
+ folder.__defineGetter__("path", function () {
+ return _path;
+ });
+ folder.__defineGetter__("type", function () {
+ return _type;
+ });
+ return folder;
+};
- //---------------------------------------------------------------------------
- exports.ContentTypeInfo = common.Base.extend({
+});
+define('ripple/platform/tizen/2.0/touchEvent', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation
+ *
+ * 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.
+ */
- //-------------------------------------------------------------------------
- constructor: function(ctype, versions, options) {
- this.ctype = ctype;
- this.versions = _.isArray(versions) ? versions : [versions];
- _.defaults(this, options || {}, {
- preferred: false,
- transmit: true,
- receive: true,
- });
- },
+var emulatorBridge = require('ripple/emulatorBridge'),
+ event = require('ripple/event'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ Touch,
+ TouchList,
+ TouchEvent,
+ _touchCanvasElements = [],
+ _dataEnlargeRatio = 4,
+ _self;
- //-------------------------------------------------------------------------
- merge: function(other) {
- if ( this.ctype != other.ctype
- || ! _.isEqual(this.versions, other.versions)
- || this.preferred != other.preferred )
- return false;
- this.transmit = this.transmit || other.transmit;
- this.receive = this.receive || other.receive;
- return true
- },
+function _isValidTouch(touches) {
+ var touche, _touches = [], i;
+ if (!touches) {
+ return false;
+ }
+ if (!tizen1_utils.isValidArray(touches)) {
+ _touches = [touches];
+ }
- //-------------------------------------------------------------------------
- toStruct: function() {
- return {
- ctype: this.ctype,
- versions: this.versions,
- preferred: this.preferred,
- transmit: this.transmit,
- receive: this.receive
- };
- },
+ for (i = 0; i < _touches.length; i++) {
+ touche = _touches[i];
+ if ((touche !== undefined) &&
+ ((typeof touche !== "object") ||
+ (typeof touche.target !== "object") ||
+ (touche.identifier !== undefined) && (typeof touche.identifier !== "number") ||
+ (touche.screenX !== undefined) && (typeof touche.screenX !== "number") ||
+ (touche.screenY !== undefined) && (typeof touche.screenY !== "number") ||
+ (touche.clientX !== undefined) && (typeof touche.clientX !== "number") ||
+ (touche.clientY !== undefined) && (typeof touche.clientY !== "number") ||
+ (touche.pageX !== undefined) && (typeof touche.pageX !== "number") ||
+ (touche.pageY !== undefined) && (typeof touche.pageY !== "number")))
+ return false;
+ }
+ return true;
+}
- //-------------------------------------------------------------------------
- toSyncML: function(nodeName, uniqueVerCt) {
- if ( _.isFunction(nodeName) )
- {
- cb = nodeName;
- nodeName = null;
- }
- else if ( _.isFunction(uniqueVerCt) )
- {
- cb = uniqueVerCt;
- uniqueVerCt = null;
- }
- if ( ! nodeName )
- {
- nodeName = this.transmit ? 'Tx' : 'Rx';
- if ( this.preferred )
- nodeName += '-Pref';
- }
- if ( this.preferred )
- nodeName += '-Pref';
+function _dispatchAllEvents(event) {
+ _touchCanvasElements.forEach(function (value) {
+ if (value !== undefined) {
+ value.dispatchEvent(event);
+ }
+ });
+}
- if ( uniqueVerCt )
- {
- var ret = _.map(this.versions, function(v) {
- var tmp = ET.Element(nodeName);
- ET.SubElement(tmp, 'CTType').text = this.ctype;
- ET.SubElement(tmp, 'VerCT').text = v;
- return tmp;
- }, this);
- return ret;
- }
- var ret = ET.Element(nodeName);
- ET.SubElement(ret, 'CTType').text = this.ctype;
- _.each(this.versions, function(v) {
- ET.SubElement(ret, 'VerCT').text = v;
- });
- return ret;
- },
+function _touchMove(event) {
+ var data = event.data,
+ touches = [],
+ removedTouches = [],
+ touchList,
+ simulatedEvent,
+ dataId,
+ ids = [],
+ intervalId,
+ currentIndex,
+ item = {};
- describe: function(stream, cb) {
- stream.write(this.ctype);
- stream.write(this.versions.length == 1 ? ' version ' : ' versions ');
- stream.write(this.versions.join(', '));
- var flags = [];
- if ( this.preferred )
- flags.push('preferred');
- if ( this.transmit )
- flags.push('tx');
- if ( this.receive )
- flags.push('rx');
- if ( flags.length > 0 )
- {
- stream.write(' (');
- stream.write(flags.join(', '));
- stream.write(')');
- }
- stream.write('\n');
- }
+ if (_touchCanvasElements.length === 0)
+ return;
- }, {
+ for (dataId in data) {
+ if (!data[dataId].length || data[dataId].length === 0)
+ return;
- //-------------------------------------------------------------------------
- fromStruct: function(struct) {
- return new exports.ContentTypeInfo(struct.ctype, struct.versions, struct);
- },
+ ids.push(dataId);
+ item = data[dataId][0];
+ touches.push(new Touch(item.target, dataId, item.pageX * _dataEnlargeRatio, item.pageY * _dataEnlargeRatio, item.screenX * _dataEnlargeRatio,
+ item.screenY * _dataEnlargeRatio, item.offsetX * _dataEnlargeRatio, item.offsetY * _dataEnlargeRatio));
+ }
- //-------------------------------------------------------------------------
- fromSyncML: function(xnode) {
- return new exports.ContentTypeInfo(
- xnode.findtext('CTType'),
- _.map(xnode.findall('VerCT'), function(e) { return e.text; }),
- {
- preferred: xnode.tag.match('-Pref$') != undefined,
- transmit: xnode.tag.indexOf('Tx') >= 0,
- receive: xnode.tag.indexOf('Rx') >= 0
- }
- );
- }
+ // touch start
+ touchList = new TouchList(touches);
+ simulatedEvent = new TouchEvent("touchstart", true, true, touchList, touchList, touchList, event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
+ _dispatchAllEvents(simulatedEvent);
+ currentIndex = 0;
- });
+ // touch move and touch end
+ intervalId = setInterval(function () {
+ touches = [];
+ removedTouches = [];
- return exports;
+ ids.forEach(function (id) {
+ var points = data[id],
+ touchItem, removedItem;
-})();
+ if (currentIndex < points.length) {
+ touchItem = points[currentIndex];
+ } else {
+ removedItem = points[points.length - 1];
+ }
-module.exports = _self;
+ if (touchItem)
+ touches.push(new Touch(touchItem.target, id, touchItem.pageX * _dataEnlargeRatio, touchItem.pageY * _dataEnlargeRatio, touchItem.screenX * _dataEnlargeRatio,
+ touchItem.screenY * _dataEnlargeRatio, touchItem.offsetX * _dataEnlargeRatio, touchItem.offsetY * _dataEnlargeRatio));
+ if (removedItem)
+ removedTouches.push(new Touch(removedItem.target, id, removedItem.pageX * _dataEnlargeRatio, removedItem.pageY * _dataEnlargeRatio, removedItem.screenX * _dataEnlargeRatio,
+ removedItem.screenY * _dataEnlargeRatio, removedItem.offsetX * _dataEnlargeRatio, removedItem.offsetY * _dataEnlargeRatio));
+ });
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/devinfo', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.devinfo
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/06
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ if (touches.length > 0) {
+ simulatedEvent = new TouchEvent("touchmove", true, true, new TouchList(touches), new TouchList(touches), new TouchList(touches),
+ event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
+ _dispatchAllEvents(simulatedEvent);
+ } else {
+ clearInterval(intervalId);
+ }
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
- ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
- _self;
+ if (removedTouches.length > 0) {
+ simulatedEvent = new TouchEvent("touchend", true, true, new TouchList(removedTouches), new TouchList(removedTouches), new TouchList(removedTouches),
+ event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
+ _dispatchAllEvents(simulatedEvent);
+ }
+ currentIndex++;
+ }, 50);
+}
-_self = (function () {
+function _touchCancel(event) {
+ var mousedownEvent = event.touchEvent,
+ simulatedEvent;
- var exports = {};
+ simulatedEvent = new TouchEvent("touchcancel", true, true, new TouchList([]), new TouchList([]), new TouchList([]),
+ event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
+ _dispatchAllEvents(simulatedEvent);
+}
- var strAttributeMap = [
- ['manufacturerName', 'Man'],
- ['modelName', 'Mod'],
- ['oem', 'OEM'],
- ['firmwareVersion', 'FwV'],
- ['softwareVersion', 'SwV'],
- ['hardwareVersion', 'HwV'],
- ['devID', 'DevID'],
- ['devType', 'DevTyp']
- ];
+function _initialize() {
+ event.on("touchCancel", _touchCancel);
+ event.on("touchEvent", _touchMove);
+}
-var boolAttributeMap = [
- ['utc', 'UTC'],
- ['largeObjects', 'SupportLargeObjs'],
- ['hierarchicalSync', 'SupportHierarchicalSync'],
- ['numberOfChanges', 'SupportNumberOfChanges']
- ];
+Touch = function (target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
+ var _identifier = Number(identifier) || 0,
+ _screenX = Number(screenX) || 0,
+ _screenY = Number(screenY) || 0,
+ _clientX = Number(clientX) || 0,
+ _clientY = Number(clientY) || 0,
+ _pageX = Number(pageX) || 0,
+ _pageY = Number(pageY) || 0;
-//---------------------------------------------------------------------------
-exports.DevInfo = common.Base.extend({
+ this.__defineGetter__("identifier", function () {
+ return _identifier;
+ });
+ this.__defineGetter__("target", function () {
+ return target;
+ });
+ this.__defineGetter__("screenX", function () {
+ return _screenX;
+ });
+ this.__defineGetter__("screenY", function () {
+ return _screenY;
+ });
+ this.__defineGetter__("clientX", function () {
+ return _clientX;
+ });
+ this.__defineGetter__("clientY", function () {
+ return _clientY;
+ });
+ this.__defineGetter__("pageX", function () {
+ return _pageX;
+ });
+ this.__defineGetter__("pageY", function () {
+ return _pageY;
+ });
+};
- //-------------------------------------------------------------------------
- constructor: function(adapter, options) {
- var self = this;
- var options = _.defaults({}, options, {
- devType : constant.DEVTYPE_WORKSTATION,
- manufacturerName : '-',
- modelName : '-',
- oem : '-',
- hardwareVersion : '-',
- firmwareVersion : '-',
- softwareVersion : '-',
- utc : true,
- largeObjects : true,
- hierarchicalSync : true,
- numberOfChanges : true,
- extensions : {}
- });
+TouchList = function (touches) {
+ var _touches = _isValidTouch(touches) ? tizen1_utils.copy(touches) : [],
+ i, _self;
- // todo: is there anyway to mark attributes as read-only?...
+ _self = {
+ item : function (index) {
+ if (typeof index !== "number") {
+ return null;
+ }
+ if (index.toString().indexOf(".") !== -1) {
+ return null;
+ }
+ if (/^\\d+$/.test(index) || index >= _touches.length) {
+ return null;
+ }
+ if (!_touches) {
+ return null;
+ }
+ return _touches[index];
+ },
- //: [read-only] these are all read-only attributes
- this.devID = options.devID || common.makeID();
- this.devType = options.devType;
- this.manufacturerName = options.manufacturerName;
- this.modelName = options.modelName;
- this.oem = options.oem;
- this.hardwareVersion = options.hardwareVersion;
- this.firmwareVersion = options.firmwareVersion;
- this.softwareVersion = options.softwareVersion;
- this.utc = options.utc;
- this.largeObjects = options.largeObjects;
- this.hierarchicalSync = options.hierarchicalSync;
- this.numberOfChanges = options.numberOfChanges;
- this.extensions = {};
+ identifiedTouch : function (identifier) {
+ if (typeof identifier !== "number") {
+ return null;
+ }
+ if (!_touches) {
+ return null;
+ }
+ for (var i in _touches) {
+ if (_touches[i].identifier === identifier) {
+ return _touches[i];
+ }
+ }
+ return null;
+ }
+ };
- _.each(options.extensions, function(values, name) {
- self.setExtension(name, values);
- });
+ for (i = 0; i < _touches.length; i++) {
+ _self.__defineGetter__(i, (function (index) {
+ return function () {
+ return _touches[index];
+ };
+ }(i)));
+ }
- // --- private attributes
- this._a = adapter;
- },
+ _self.__defineGetter__("length", function () {
+ return _touches.length;
+ });
- //-------------------------------------------------------------------------
- setExtension: function(name, values) {
- this.extensions[name] = _.isArray(values) ? values : [values];
- },
+ return _self;
+};
- //-------------------------------------------------------------------------
- getExtensionKeys: function() {
- return _.keys(this.extensions);
- },
+TouchEvent = function (type, canBubble, cancelable, touches, targetTouches, changedTouches, altKey, metaKey, ctrlKey, shiftKey) {
+ var touchEvent = emulatorBridge.document().createEvent("UIEvents");
+ touchEvent.initUIEvent(type, canBubble, cancelable, emulatorBridge.window(), 1);
+
+ touchEvent.__defineGetter__("touches", function () {
+ return touches;
+ });
+ touchEvent.__defineGetter__("targetTouches", function () {
+ return targetTouches;
+ });
+ touchEvent.__defineGetter__("changedTouches", function () {
+ return changedTouches;
+ });
+ touchEvent.__defineGetter__("altKey", function () {
+ return altKey;
+ });
+ touchEvent.__defineGetter__("metaKey", function () {
+ return metaKey;
+ });
+ touchEvent.__defineGetter__("ctrlKey", function () {
+ return ctrlKey;
+ });
+ touchEvent.__defineGetter__("shiftKey", function () {
+ return shiftKey;
+ });
+ return touchEvent;
+};
+
+_self = {
+ mask: function (frame) {
+ frame.addEventListener("DOMContentLoaded", function () {
+ /*
+ var widgetDocument = frame.contentDocument,
+ getElementByIdOri = widgetDocument.getElementById;
- //-------------------------------------------------------------------------
- getExtension: function(name) {
- return this.extensions[name];
- },
+ widgetDocument.getElementById = function () {
+ var element, addEventListenerOri;
- //-------------------------------------------------------------------------
- _load: function(cb) {
- cb();
- },
+ element = getElementByIdOri.apply(widgetDocument, Array.prototype.slice.call(arguments));
- //-------------------------------------------------------------------------
- _updateModel: function(cb) {
- if ( ! this._a._model )
- return cb('devinfo created on un-initialized adapter');
- this._a._model.devInfo = {
- devID : this.devID,
- devType : this.devType,
- manufacturerName : this.manufacturerName,
- modelName : this.modelName,
- oem : this.oem,
- hardwareVersion : this.hardwareVersion,
- firmwareVersion : this.firmwareVersion,
- softwareVersion : this.softwareVersion,
- utc : this.utc,
- largeObjects : this.largeObjects,
- hierarchicalSync : this.hierarchicalSync,
- numberOfChanges : this.numberOfChanges,
- extensions : this.extensions
+ if (element) {
+ addEventListenerOri = element.addEventListener;
+ element.addEventListener = function (event, callback, useCapture) {
+ if (event === "touchstart") {
+ _touchCanvasElements.push(element);
+ }
+ addEventListenerOri.apply(element, arguments);
+ };
+ }
+ return element;
};
- cb();
- },
- //-------------------------------------------------------------------------
- toSyncML: function(dtdVersion, stores) {
- dtdVersion = dtdVersion || constant.SYNCML_DTD_VERSION_1_2;
- if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
- throw new Error('unsupported DTD version "' + dtdVersion + '"')
- var xret = ET.Element('DevInf', {'xmlns': constant.NAMESPACE_DEVINF})
- ET.SubElement(xret, 'VerDTD').text = dtdVersion;
- for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
- {
- var map = strAttributeMap[idx];
- // todo: should i enforce the fact that these are all *required*?...
- if ( this[map[0]] != undefined )
- ET.SubElement(xret, map[1]).text = this[map[0]];
- }
- for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
- {
- var map = boolAttributeMap[idx];
- if ( this[map[0]] )
- ET.SubElement(xret, map[1])
- }
- if ( stores && stores.length > 0 )
- for ( var idx=0 ; idx<stores.length ; idx++ )
- xret.append(stores[idx].toSyncML());
- var xext = null;
- for ( var name in this.extensions )
- {
- if ( ! xext )
- xext = ET.SubElement(xret, 'Ext');
- ET.SubElement(xext, 'XNam').text = name;
- var values = this.extensions[name];
- for ( var idx=0 ; idx<values.length ; idx++ )
- ET.SubElement(xext, 'XVal').text = '' + values[idx];
+ widgetDocument.createTouch = function (view, target, identifier, pageX, pageY, screenX, screenY) {
+ return new Touch(view, target, identifier, pageX, pageY, screenX, screenY);
};
- return xret;
- },
-}, {
-
- //-------------------------------------------------------------------------
- fromSyncML: function(xnode) {
- var options = {};
- var stores = []
- var dtdVersion = xnode.findtext('VerDTD')
- if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
- throw new common.ProtocolError('unsupported DTD version "' + dtdVersion + '"');
- for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
- {
- var map = strAttributeMap[idx];
- // todo: should i enforce the fact that these are all *required*?...
- options[map[0]] = xnode.findtext(map[1]);
- }
- for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
- {
- var map = boolAttributeMap[idx];
- options[map[0]] = xnode.find(map[1]) != undefined;
- }
- _.each(xnode.getchildren(), function(child) {
- if ( child.tag == 'DataStore' )
- return stores.push(storemod.Store.fromSyncML(child));
- if ( child.tag == 'Ext' )
- {
- options.extensions = {};
- var elist = child.getchildren();
- var ecur = null;
- for ( var idx=0 ; idx<elist.length ; idx++ )
- {
- var eitem = elist[idx];
- if ( eitem.tag == 'XNam' )
- {
- ecur = eitem.text;
- continue;
- }
- if ( ! ecur )
- // paranoia...
- continue;
- if ( ! options.extensions[ecur] )
- options.extensions[ecur] = [];
- options.extensions[ecur].push(eitem.text);
- }
- return;
- }
+ widgetDocument.createTouchList = function (pattern) {
+ if (arguments.length !== 1) {
+ return null;
+ }
+ return new TouchList(pattern);
+ };
+ */
});
- return [new exports.DevInfo(null, options), stores];
}
+};
-});
-
-return exports;
-
-})();
+_initialize();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/elementtree', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/AttributeFilter', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- _parser,
- _serializer,
- _self;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ AttributeFilter;
-function _find(query, element, type) {
- var querylist = query.split("/"),
- e = element._node,
- tag, i, ret;
+AttributeFilter = function (attributeName, matchFlag, matchValue) {
+ var attributeFilter = {};
- if (querylist.length === 0) {
- return undefined;
- }
+ t.AttributeFilter(arguments, this);
- for(i = 0; i < querylist.length; i++) {
- tag = querylist[i];
+ attributeFilter.attributeName = attributeName;
+ attributeFilter.matchFlag = matchFlag || "EXACTLY";
+ attributeFilter.matchValue = (matchFlag === "EXISTS") ? null :
+ matchValue || null;
+
+ this.__defineGetter__("attributeName", function () {
+ return attributeFilter.attributeName;
+ });
+ this.__defineSetter__("attributeName", function (val) {
try {
- e = e.getElementsByTagName(tag)[0];
- } catch (error) {
- e = undefined;
- break;
+ attributeFilter.attributeName = t.DOMString(val);
+ } catch (e) {
}
- }
+ });
- if (e) {
- if (type === "TEXT") {
- return e.textContent;
- } else if (type === "NODE") {
- ret = {
- _doc: element,
- _node: e,
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
- }
- };
- ret.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
- ret.__defineGetter__("text", function () {
- return this._node.textContent;
- });
- ret.__defineGetter__("tag", function () {
- return _tag(this);
- });
- return ret;
+ this.__defineGetter__("matchFlag", function () {
+ return attributeFilter.matchFlag;
+ });
+ this.__defineSetter__("matchFlag", function (val) {
+ try {
+ attributeFilter.matchFlag = t.FilterMatchFlag(val);
+ } catch (e) {
}
- } else {
- return undefined;
- }
-}
-
-function _findall(query, element) {
- var querylist = query.split("/"),
- e = element._node,
- tag,
- array,
- tmp,
- ret = [],
- i;
+ });
- for(i = 0; i < querylist.length - 1; i++) {
- tag = querylist[i];
+ this.__defineGetter__("matchValue", function () {
+ return attributeFilter.matchValue;
+ });
+ this.__defineSetter__("matchValue", function (val) {
try {
- e = e.getElementsByTagName(tag)[0];
- } catch (error) {
- return ret;
+ if (attributeFilter.matchFlag === "EXISTS") {
+ return;
+ }
+ attributeFilter.matchValue = t.any(val, "?");
+ } catch (e) {
}
- }
+ });
+};
- tag = querylist[querylist.length - 1];
- array = e.getElementsByTagName(tag);
- ///return ret;
- for(i = 0; i < array.length; i++) {
- tmp = {
- _doc: element,
- _node: array[i],
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
- }
- };
- tmp.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
- tmp.__defineGetter__("text", function () {
- return this._node.textContent;
- });
- tmp.__defineGetter__("tag", function () {
- return _tag(this);
- });
- ret.push(tmp);
- }
- return ret;
-}
+module.exports = AttributeFilter;
-function _tag(element) {
- var array;
- array = element._node.tagName.split(":");
- return array[array.length - 1];
-}
+});
+define('ripple/platform/tizen/2.0/AccountService', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 _getchildren(element) {
- var ret = [], e, i;
- for (i = 0; i < element._node.childNodes.length; i++) {
- e = {
- _doc: element,
- _node: element._node.childNodes[i],
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
- }
- };
- e.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
- e.__defineGetter__("text", function () {
- return this._node.textContent;
- });
- e.__defineGetter__("tag", function () {
- return _tag(this);
- });
- ret.push(e);
- }
+module.exports = function (serviceName, serviceType, tag, displayName, icon, settings) {
+ var _self,
+ _id = Math.uuid(null, 16);
- return ret;
-}
+ _self = {
+ serviceName : serviceName || "",
+ serviceType : serviceType || "",
+ displayName : displayName || null,
+ icon : icon || null,
+ settings : settings || null,
+ tag : tag || []
+ };
+ _self.__defineGetter__("id", function () {
+ return _id;
+ });
-_self = (function () {
- ET = {};
+ return _self;
+};
- ET.Element = function(name, attributes) {
- var element = {},
- doc,
- node;
+});
+define('ripple/platform/tizen/2.0/nfc', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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.
+ */
- doc = _parser.parseFromString("<" + name + "></" + name + ">", "text/xml");
- node = doc.childNodes[0];
- if (attributes) {
- utils.forEach(attributes, function (value, key) {
- node.setAttribute(key, value);
- });
- }
+var db = require('ripple/db'),
+ event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
+ NDEFMessage = require('ripple/platform/tizen/2.0/NDEFMessage'),
+ NFCAdapter,
+ NFCAdapterPrototype,
+ NFCTag,
+ NFCPeer,
+ _data = {
+ DB_NFC_TAG: "tizen1.0-nfc-tag",
+ DB_NFC_PEER: "tizen1.0-nfc-peer",
+ DB_NFC_OUTPUT_MESSAGE: "tizen1.0-nfc-output-message",
+ INTERVAL: 1000,
+ listener: {
+ onCardEmulationChanged: null,
+ onTagDetected: null,
+ onPeerDetected: null,
+ onNDEFReceived: null
+ },
+ pairedNFC: null,
+ nfcAdapter: {},
+ nfcCardEmulation: {},
+ nfcTags: [],
+ nfcTag: {},
+ nfcPeer: null,
+ isNear: false, // Identify the device is whether near
+ isDetectTag: false, // Identify NFC tag is detected
+ isPeerConnected: false,
+ connectedState: false
+ },
+ _security = {
+ "http://tizen.org/privilege/nfc.admin": ["setPowered"],
+ "http://tizen.org/privilege/nfc.common": ["getDefaultAdapter",
+ "setExclusiveMode", "getCachedMessage"],
+ "http://tizen.org/privilege/nfc.p2p": ["setPeerListener",
+ "unsetPeerListener", "setReceiveNDEFListener",
+ "unsetReceiveNDEFListener", "sendNDEF"],
+ "http://tizen.org/privilege/nfc.tag": ["setTagListener",
+ "unsetTagListener", "readNDEF", "writeNDEF", "transceive"]
+ },
+ _self;
- element = {
- _doc: doc,
- _node: node,
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
- }
- };
+_self = function () {
+ var nfc, _exclusiveMode = false;
- element.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
+ function getDefaultAdapter() {
+ if (!_security.getDefaultAdapter) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- element.__defineGetter__("text", function () {
- return this._node.textContent;
- });
+ t.NFCManager("getDefaultAdapter", arguments);
- element.__defineGetter__("tag", function () {
- return _tag(this);
- });
+ if (!_data.nfcAdapter) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
- return element;
- };
+ return _data.nfcAdapter;
+ }
- ET.SubElement = function(element, name, attributes) {
- var subElement = {},
- node;
- node = element._doc.createElement(name);
- if (attributes) {
- utils.forEach(attributes, function (value, key) {
- node.setAttribute(key, value);
- });
+ /* API Description:
+ * If it gets priority and it is in foreground, system doesn't
+ * send app controls that are usually sent when detecting NFC Tag
+ * or receiving NDEF Message from the connected NFC peer-to-peer target
+ *
+ * Implementation detail:
+ * due to simulator only support single running instance and doesn't have
+ * other app controls which be called by design. we just put some system
+ * exclusive mode info on the 'System Summary' panel
+ */
+ function setExclusiveMode(mode) {
+ if (!_security.setExclusiveMode) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- element._node.appendChild(node);
- subElement = {
- _doc: element._doc,
- _node: node,
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
- }
- };
- subElement.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
- subElement.__defineGetter__("text", function () {
- return this._node.textContent;
- });
- subElement.__defineGetter__("tag", function () {
- return _tag(this);
- });
- return subElement;
- };
+ t.NFCManager("setExclusiveMode", arguments);
- ET.tostring = function(element) {
- return _serializer.serializeToString(element._node);
- };
- ET.parse = function(doc) {
- var element = {};
+ _exclusiveMode = mode;
+ jQuery("#NFCExclusiveModeValue").text(_exclusiveMode);
+ }
- element = {
- _doc: doc,
- _node: doc.childNodes[0],
- find: function (query) {
- return _find(query, this, "NODE");
- },
- findtext: function (query) {
- return _find(query, this, "TEXT");
- },
- findall: function (query) {
- return _findall(query, this);
- },
- getchildren: function () {
- return _getchildren(this);
- },
- append: function (node) {
- this._node.appendChild(node._node);
- },
- getroot: function () {
- return this;
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
- };
- element.__defineSetter__("text", function (text) {
- this._node.textContent = text;
- });
- element.__defineGetter__("text", function () {
- return this._node.textContent;
- });
- element.__defineGetter__("tag", function () {
- return _tag(this);
- });
+ }
+ }
- return element;
+ nfc = {
+ getDefaultAdapter: getDefaultAdapter,
+ setExclusiveMode: setExclusiveMode,
+ handleSubFeatures: handleSubFeatures
};
- ET.CdataElement = function(str) {
- var doc, cdata;
- doc = _parser.parseFromString("<data></data>", "text/xml");
- cdata = doc.createCDATASection(str);
- return cdata;
- };
+ nfc.__defineGetter__("NFC_RECORD_TNF_EMPTY", function () {
+ return 0;
+ });
- return ET;
-})();
+ nfc.__defineGetter__("NFC_RECORD_TNF_WELL_KNOWN", function () {
+ return 1;
+ });
-_parser = new DOMParser();
-_serializer = new XMLSerializer();
+ nfc.__defineGetter__("NFC_RECORD_TNF_MIME_MEDIA", function () {
+ return 2;
+ });
-module.exports = _self;
+ nfc.__defineGetter__("NFC_RECORD_TNF_URI", function () {
+ return 3;
+ });
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/item', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.item
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/30
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ nfc.__defineGetter__("NFC_RECORD_TNF_EXTERNAL_RTD", function () {
+ return 4;
+ });
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');
+ nfc.__defineGetter__("NFC_RECORD_TNF_UNKNOWN", function () {
+ return 5;
+ });
-var _self = (function () {
- var exports = {};
+ nfc.__defineGetter__("NFC_RECORD_TNF_UNCHANGED", function () {
+ return 6;
+ });
- //---------------------------------------------------------------------------
- exports.Item = common.Base.extend({
+ return nfc;
+};
- //: the unique identifier (within the context of a SyncML datastore)
- //: of the current SyncML item.
- id: null,
+NFCAdapterPrototype = function () {
+ var nfcAdapterPrototype,
+ interval,
+ powered = false, // Identify the device on or off
+ polling = false; // Identify the device is polled
- compare: function(other) {
- return ( other === this ? 0 : 1 );
- }
+ event.trigger("nfc-power-changed", [powered]);
+ event.on("nfc-power-setting", function (status) {
+ updatePowerStatus(status);
+ });
+ event.on("nfc-attach-setting", function (type, isAttached) {
+ var isDetectTag;
+ isDetectTag = (type === "Tag");
+ updateIsNear(isDetectTag, isAttached);
});
+ event.on("nfc-tag-send", function (status) {
+ var tag;
- return exports;
+ if (status) {
+ tag = db.retrieveObject(_data.DB_NFC_TAG);
+ if (tag.isSupportedNDEF) {
+ _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
+ tag.ndefSize, null, true, tag.ndefs);
+ } else {
+ _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
+ tag.ndefSize, null, true, tag.rawData);
+ }
+ if (_data.listener.onTagDetected) {
+ _data.listener.onTagDetected.onattach(_data.nfcTag);
+ }
+ } else {
+ tag = {};
+ if (_data.listener.onTagDetected) {
+ _data.listener.onTagDetected.ondetach();
+ }
+ }
+ });
+ event.on("nfc-peer-send", function (status) {
+ if (status) {
+ if (!_data.nfcPeer) {
+ _data.nfcPeer = new NFCPeer(true);
+ }
+ _data.isPeerConnected = true;
+ if (_data.listener.onPeerDetected) {
+ _data.listener.onPeerDetected.onattach(_data.nfcPeer);
+ }
+ } else {
+ _data.isPeerConnected = false;
+ if (_data.listener.onPeerDetected) {
+ _data.listener.onPeerDetected.ondetach();
+ }
+ }
+ });
+ event.on("nfc-peer-sending-ndef", function () {
+ var peer, _records = [], rec, _ndef, i;
-})();
+ if (_data.isPeerConnected) {
+ peer = db.retrieveObject(_data.DB_NFC_PEER);
+ for (i in peer.ndef.records) {
+ rec = peer.ndef.records[i];
+ _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
+ rec.id));
+ }
+ _ndef = new NDEFMessage(_records);
+ if (_data.listener.onNDEFReceived) {
+ _data.listener.onNDEFReceived(_ndef);
+ }
+ }
+ });
-module.exports = _self;
+ // private
+ function updatePowerStatus(status) {
+ if (powered === status) {
+ return;
+ }
+ if (!status) {
+ updateIsNear(_data.isDetectTag, false);
+ _data.listener.onTagDetected = null;
+ _data.listener.onPeerDetected = null;
+ _data.listener.onNDEFReceived = null;
+ _data.listener.onCardEmulationChanged = null;
+ }
+ powered = status;
+ updatePollingStatus(status);
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/localadapter', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.localadapter
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/10/22
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ event.trigger("nfc-power-changed", [powered]);
+ }
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- codec = require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
- storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
- remote = require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
- storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
- devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
- adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
- state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
- useragent = require('ripple/platform/tizen/2.0/syncml-js-lib/useragent'),
- _self;
+ function updatePollingStatus(status) {
+ if (!powered)
+ return;
+ if (polling === status) {
+ return;
+ }
+ polling = status;
+ event.trigger("nfc-polling-changed", [polling]);
+ if (polling) {
+ interval = setInterval(poll, _data.INTERVAL);
+ } else {
+ clearInterval(interval);
+ }
+ }
-_self = (function () {
- var exports = {};
+ function updateIsNear(isDetectTag, isAttached) {
+ _data.isDetectTag = isDetectTag;
+ _data.isNear = isAttached;
+ if (!_data.isNear) {
+ _data.connectedState = false;
+ event.trigger("nfc-connectedState-changed", [false]);
+ }
+ }
- //---------------------------------------------------------------------------
- exports.LocalAdapter = adapter.Adapter.extend({
+ function poll() {
+ if (!_data.isNear) {
+ return;
+ }
+ if (!_data.connectedState) {
+ _data.connectedState = true;
+ event.trigger("nfc-connectedState-changed", [true]);
+ }
+ }
- //-------------------------------------------------------------------------
- constructor: function(context, options, devInfo) {
+ // public
+ // Turns NFC adapter on or off.
+ function setPowered(state, successCallback, errorCallback) {
+ if (!_security.setPowered) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // todo: is there anyway to mark attributes as read-only?...
+ t.NFCAdapter("setPowered", arguments);
- //: [read-only] devInfo describes this adapter's device info and
- //: capabilities.
- this.devInfo = null;
+ window.setTimeout(function () {
+ updatePowerStatus(state);
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ }
- //: [read-only] the device ID of this adapter.
- this.devID = options.devID || null;
+ // Registers a callback function to invoke when NFC tag is detected.
+ function setTagListener(detectCallback, tagFilter) {
+ if (!_security.setTagListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //: [read-only] specifies whether this Adapter represents a local
- //: or remote peer.
- this.isLocal = true;
+ t.NFCAdapter("setTagListener", arguments);
- //: [read-only] human-facing name of this adapter
- this.displayName = options.displayName || null;
+ //TODO: tagFilter support
+ if (!powered) {
+ return;
+ }
+ _data.listener.onTagDetected = detectCallback;
+ }
- //: [read-only] the adapter-wide default value of the maximum
- //: message size.
- this.maxMsgSize = options.maxMsgSize || null;
+ // Registers a callback function to be invoked when NFC peer-to-peer target is detected.
+ function setPeerListener(detectCallback) {
+ if (!_security.setPeerListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //: [read-only] the adapter-wide default value of the maximum
- //: object size.
- this.maxObjSize = options.maxObjSize || null;
+ t.NFCAdapter("setPeerListener", arguments);
- //: [read-only] specifies default conflict resolution policy for
- //: this adapter. if undefined, defaults to constant.POLICY_ERROR.
- this.conflictPolicy = options.conflictPolicy || constant.POLICY_ERROR;
+ if (!powered) {
+ return;
+ }
+ _data.listener.onPeerDetected = detectCallback;
+ }
- // --- private attributes
- this.id = options.id || common.makeID();
- this._c = context;
- // TODO: use _.pick() for these options...
- this._options = options;
- this._devInfo = devInfo;
- this._model = null;
- this._stores = {};
- this._peers = [];
- },
+ // Unregisters the listener for detecting an NFC tag.
+ function unsetTagListener() {
+ if (!_security.unsetTagListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- _getModel: function() {
- return this._model;
- },
+ if (!powered || !_data.listener.onTagDetected) {
+ return;
+ }
- //-------------------------------------------------------------------------
- setDevInfo: function(devInfo, cb) {
- if ( this._model == undefined )
- this._model = {
- id : this.id,
- displayName : this.displayName,
- maxMsgSize : this.maxMsgSize,
- maxObjSize : this.maxObjSize,
- conflictPolicy : this.conflictPolicy,
- devInfo : null,
- stores : [],
- peers : [],
- isLocal : 1
- };
+ _data.listener.onTagDetected = null;
+ }
- var di = new devinfomod.DevInfo(this, devInfo);
- di._updateModel(_.bind(function(err) {
- if ( err )
- return cb(err);
+ // Unregisters the listener for detecting an NFC peer-to-peer target.
+ function unsetPeerListener() {
+ if (!_security.unsetPeerListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- this._model.devID = this._model.devInfo.devID;
- this.devID = this._model.devInfo.devID;
- this.devInfo = di;
+ if (!powered || !_data.listener.onPeerDetected) {
+ return;
+ }
- // since the local devinfo has changed, we need to ensure that
- // we rebroadcast it (in case there are any affects...), thus
- // resetting all anchors.
- // TODO: this seems a little heavy-handed, since this will force
- // a slow-sync for each datastore. is that really the best
- // thing?...
- this._resetAllAnchors();
+ _data.listener.onPeerDetected = null;
+ }
- this._save(this._c._txn(), cb);
+ // Gets NDEF message cached when the tag is detected.
+ function getCachedMessage() {
+ if (!_security.getCachedMessage) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- }, this));
- },
+ t.NFCAdapter("getCachedMessage", arguments);
- //-------------------------------------------------------------------------
- _resetAllAnchors: function() {
- _.each(this._model.peers, function(peer) {
- _.each(peer.stores, function(store) {
- if ( ! store.binding )
- return;
- store.binding.localAnchor = null;
- store.binding.remoteAnchor = null;
- });
- });
- },
+ return _data.pairedNFC || new NDEFMessage([]);
+ }
- //-------------------------------------------------------------------------
- getPeers: function() {
- return this._peers;
- },
+ nfcAdapterPrototype = {
+ setPowered: setPowered,
+ setTagListener: setTagListener,
+ setPeerListener: setPeerListener,
+ unsetTagListener: unsetTagListener,
+ unsetPeerListener: unsetPeerListener,
+ getCachedMessage: getCachedMessage
+ };
- //-------------------------------------------------------------------------
- addPeer: function(peerInfo, cb) {
- var self = this;
+ nfcAdapterPrototype.__defineGetter__("powered", function () {
+ return powered;
+ });
- // TODO: if there is already a peer for the specified URL, then
- // we may have a problem!...
+ return nfcAdapterPrototype;
+};
- // todo: if we are adding a peer to an adapter that already has
- // non-client peers, then we may have a problem!...
- // (this is only true while syncml-js is not capable of truly
- // operating in peer-to-peer mode)
+NFCAdapter = function () {
+ this.__defineGetter__("powered", function () {
+ return this.__proto__.powered;
+ });
+};
- var peer = new remote.RemoteAdapter(this, peerInfo);
- peer._updateModel(function(err) {
- if ( err )
- return cb(err);
- self._peers.push(peer);
- cb(null, peer);
- });
- },
+NFCAdapter.prototype = new NFCAdapterPrototype();
- //-------------------------------------------------------------------------
- save: function(cb) {
- this._save(this._c._txn(), cb);
- },
+NFCTag = function (type, isSupportedNDEF, ndefSize, properties, isConnected, ndefs) {
+ var nfcTag, i, j, _ndefs, rec, _records, _ndefs_index = 0;
- //-------------------------------------------------------------------------
- _save: function(dbtxn, cb) {
- var self = this;
- self._updateModel(function(err) {
- if ( err )
- return cb(err);
- storage.put(dbtxn.objectStore('adapter'), self._model, cb);
- });
- },
+ type = type || null;
+ isSupportedNDEF = isSupportedNDEF || false;
+ ndefSize = ndefSize || 1;
+ properties = null;
+ isConnected = isConnected || false;
- //-------------------------------------------------------------------------
- _updateModel: function(cb) {
- var self = this;
- var model = self._model;
- model.displayName = self.displayName;
- model.devID = self.devID;
- model.maxMsgSize = self.maxMsgSize;
- model.maxObjSize = self.maxObjSize;
- model.conflictPolicy = self.conflictPolicy;
- model.isLocal = 1;
- common.cascade([
- // update the devInfo model
- function(cb) {
- if ( ! self.devInfo )
- return cb();
- return self.devInfo._updateModel(cb);
- },
- // update the stores model
- function(cb) {
- model.stores = [];
- common.cascade(_.values(self._stores), function(store, cb) {
- store._updateModel(cb);
- }, cb);
- },
+ _ndefs = [];
+ for (i in ndefs) {
+ _records = [];
+ for (j in ndefs[i].records) {
+ rec = ndefs[i].records[j];
+ _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
+ rec.id));
+ }
+ _ndefs.push(new NDEFMessage(_records));
+ }
- // update the peers model
- function(cb) {
- // NOTE: unlike stores, which can completely regenerate the
- // model based on the class, the peers store binding
- // and routing info is only in the model, so cannot be
- // completely deleted...
- common.cascade(self._peers, function(peer, cb) {
- peer._updateModel(cb);
- }, cb);
- }
+ // Reads NDEF data.
+ function readNDEF(readCallback, errorCallback) {
+ if (!_security.readNDEF) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- ], cb);
- },
+ t.NFCTag("readNDEF", arguments);
- //-------------------------------------------------------------------------
- _load: function(cb) {
- var self = this;
+ window.setTimeout(function () {
+ if (!_data.isNear || !isSupportedNDEF ||
+ (_ndefs_index >= ndefSize)) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
+ _data.pairedNFC = _ndefs[_ndefs_index];
+ readCallback(_ndefs[_ndefs_index]);
+ _ndefs_index++;
+ }, 1);
+ }
- // TODO: if options specifies a devID/name/etc, use that...
+ // Writes NDEF data.
+ function writeNDEF(ndefMessage, successCallback, errorCallback) {
+ if (!_security.writeNDEF) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- storage.getAll(
- this._c,
- this._c._txn().objectStore('adapter').index('isLocal'),
- {only: 1},
- function(err, adapters) {
- if ( err ) {
- return cb(err);
- }
- if ( adapters.length > 1 )
- return cb('multiple local adapters defined - specify which devID to load');
- if ( adapters.length <= 0 )
- return cb(null, self);
- self._loadModel(adapters[0], function(err) {
- if ( err )
- return cb(err);
- return cb(null, self);
- });
- }
- );
- },
+ t.NFCTag("writeNDEF", arguments, true);
- //-------------------------------------------------------------------------
- _loadModel: function(model, cb) {
- var self = this;
- self._model = model;
- self.displayName = model.displayName;
- self.devID = model.devID;
- self.maxMsgSize = model.maxMsgSize;
- self.maxObjSize = model.maxObjSize;
- self.conflictPolicy = model.conflictPolicy;
- common.cascade([
- // load device info
- function(cb) {
- var di = new devinfomod.DevInfo(self, self._model.devInfo);
- di._load(function(err) {
- if ( err )
- return cb(err);
- self.devInfo = di;
- cb();
- });
- },
- // load stores
- function(cb) {
- common.cascade(model.stores, function(e, cb) {
- var store = new storemod.Store(self, e);
- store._load(function(err) {
- if ( err )
- return cb(err);
- self._stores[store.uri] = store;
- return cb();
- });
- }, cb);
- },
- // load peers
- function(cb) {
- var remotes = _.filter(model.peers, function(e) {
- return ! e.isLocal;
- });
- self._peers = [];
- common.cascade(remotes, function(e, cb) {
- var peer = new remote.RemoteAdapter(self, e);
- peer._load(function(err) {
- if ( err )
- return cb(err);
- self._peers.push(peer);
- return cb();
- });
- }, cb);
- }
- ], cb);
- },
+ window.setTimeout(function () {
+ if (!_data.isNear || !isSupportedNDEF) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
+ db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
+ event.trigger("nfc-output-msg", []);
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ }
- //-------------------------------------------------------------------------
- sync: function(peer, mode, options, cb) {
- // `options` is optional and can have the following properties:
- // * `ua`
+ // Access the raw format card.
+ function transceive(data, dataCallback, errorCallback) {
+ if (!_security.transceive) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // TODO: initialize a new context transaction?...
- // todo: or perhaps add a new session.txn?...
+ t.NFCTag("transceive", arguments, true);
- if ( cb == undefined && _.isFunction(options) )
- {
- cb = options;
- options = {};
+ window.setTimeout(function () {
+ if (!_data.isNear || isSupportedNDEF) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
}
- options = options || {};
+ return;
+ }
+ db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, data);
+ event.trigger("nfc-output-msg", []);
+ dataCallback(ndefs);
+ }, 1);
+ }
- var self = this;
- var discover = ( mode == constant.SYNCTYPE_DISCOVER );
- if ( discover )
- mode = constant.SYNCTYPE_SLOW_SYNC;
+ // Formats the detected tag that can store NDEF messages.
+ /*
+ function formatNDEF(successCallback, errorCallback, key) {
- if ( ! _.find(self._peers, function(p) { return p === peer; }) )
- return cb(new common.InvalidAdapter('invalid peer for adapter'));
- if ( mode != constant.SYNCTYPE_AUTO )
- {
- mode = common.synctype2alert(mode);
- if ( ! mode )
- return cb(new common.TypeError('invalid synctype'));
- }
- if ( ! self.devInfo )
- return cb(new common.InvalidAdapter('cannot synchronize adapter as client: invalid devInfo'));
+ tizen1_utils.validateCallbackType(successCallback, errorCallback);
- var session = state.makeSession({
- context : self._c,
- ua : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
- txn : _.bind(self._c._txn, self._c),
- adapter : self,
- peer : peer,
- isServer : false,
- discover : discover,
- info : state.makeSessionInfo({
- id : ( peer.lastSessionID || 0 ) + 1,
- msgID : 1,
- codec : self._c.codec,
- mode : mode
- })
- });
+ if (key) {
+ tizen1_utils.validateArgumentType(key, "array",
+ new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
- session.send = function(contentType, data, cb) {
- session.peer.sendRequest(session, contentType, data, function(err, response) {
- if ( err )
- return cb(err);
- // todo: allow the client to force the server to authorize itself as well...
- self._receive(session, response, null, cb);
- });
- };
+ if (!isConnected || !isSupportedNDEF) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
- // TODO: should i do a router.calculate() at this point?
- // the reason is that if there was a sync, then a
- // .setRoute(), then things may have changed...
- // corner-case, yes... but still valid.
+ successCallback();
+ }
+ */
- var failed = 0;
+ nfcTag = {
+ readNDEF: readNDEF,
+ writeNDEF: writeNDEF,
+ transceive: transceive
+ //formatNDEF: formatNDEF
+ };
- var startSession = function() {
- session.context.protocol.initialize(session, null, function(err, commands) {
- if ( err )
- return cb(err);
- self._transmit(session, commands, function(err) {
- if ( err )
- {
- if ( ! ( err instanceof common.InvalidCredentials )
- && ! ( err instanceof common.CredentialsRequired ) )
- return cb(err);
- if ( err instanceof common.InvalidCredentials )
- failed += 1;
- if ( failed > 100 )
- {
- return cb(err);
- }
- var credErr = err;
- var uaEvent = {
- session : session,
- auth : err.auth,
- count : failed
- };
- return session.ua.fetchCredentials(uaEvent, function(err, auth) {
- if ( err )
- return cb(err);
- if ( ! auth )
- return cb(credErr);
- if ( auth.persist )
- {
- session.peer.auth = auth.type;
- session.peer.username = auth.username;
- session.peer.password = auth.password;
- }
- else
- session.auth = auth;
- // todo: should i just create a new session?...
- session.info.id += 1;
- session.info.msgID = 1;
- return startSession();
- });
- }
- self._save(session.txn(), function(err) {
- if ( err )
- return cb(err);
- return cb(null, self._session2stats(session));
- });
- });
- });
- };
+ nfcTag.__defineGetter__("type", function () {
+ return type;
+ });
- session.context.synchronizer.initStoreSync(session, function(err) {
- if ( err )
- return cb(err);
- startSession();
- });
+ nfcTag.__defineGetter__("isSupportedNDEF", function () {
+ return isSupportedNDEF;
+ });
- },
+ nfcTag.__defineGetter__("ndefSize", function () {
+ return ndefSize;
+ });
- //-------------------------------------------------------------------------
- _session2stats: function(session) {
- var ret = {};
- _.each(_.values(session.info.dsstates), function(ds) {
- var stats = _.clone(ds.stats);
- stats.mode = common.alert2synctype(ds.mode);
- if ( ds.action == 'error' && ds.error )
- stats.error = ds.error;
- ret[ds.uri] = stats;
- });
- return ret;
- },
+ nfcTag.__defineGetter__("properties", function () {
+ return properties;
+ });
- //-------------------------------------------------------------------------
- _transmit: function(session, commands, cb) {
- var self = this;
- if ( session.info.msgID > 20 )
- return cb('too many client/server messages');
- session.context.protocol.negotiate(session, commands, function(err, commands) {
- if ( err )
- return cb(err);
- if ( session.context.protocol.isComplete(session, commands) )
- {
- // we're done! store all the anchors and session IDs and exit...
- var pmodel = session.peer._getModel();
- if ( ! pmodel )
- return cb('unexpected error: could not locate this peer in local adapter');
- _.each(session.info.dsstates, function(ds, uri) {
- var pstore = _.find(pmodel.stores, function(s) { return s.uri == ds.peerUri; });
- if ( ! pstore )
- return cb('unexpected error: could not locate bound peer store in local adapter');
- pstore.binding.localAnchor = ds.nextAnchor;
- pstore.binding.remoteAnchor = ds.peerNextAnchor;
- });
- session.peer.lastSessionID = session.info.id;
- pmodel.lastSessionID = session.info.id;
- return cb();
- }
- session.context.protocol.produce(session, commands, function(err, tree) {
- if ( err )
- return cb(err);
- codec.Codec.autoEncode(tree, session.info.codec, function(err, contentType, data) {
- if ( err )
- return cb(err);
- // update the session with the last request commands so
- // that when we receive the response package, it can be
- // compared against that.
- // TODO: should that only be done on successful transmit?...
- session.info.lastCommands = commands;
- session.send(contentType, data, function(err) {
- if ( err )
- return cb(err);
- cb();
- });
- })
- });
- });
- },
+ nfcTag.__defineGetter__("isConnected", function () {
+ return _data.isNear;
+ });
- //-------------------------------------------------------------------------
- authorize: function(request, sessionInfo, authorize, cb) {
- var self = this;
- var ct = request.headers['Content-Type'];
- codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
- if ( err )
- return cb(err);
- self._c.protocol.authorize(xtree, null, authorize, cb);
- });
- },
+ return nfcTag;
+};
- //-------------------------------------------------------------------------
- getTargetID: function(request, sessionInfo, cb) {
- var self = this;
- var ct = request.headers['Content-Type'];
- codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
- if ( err )
- return cb(err);
- return cb(null, self._c.protocol.getTargetID(xtree));
- });
- },
+NFCPeer = function (isConnected) {
+ var nfcPeer;
- //-------------------------------------------------------------------------
- handleRequest: function(request, sessionInfo, authorize, response, options, cb) {
+ isConnected = isConnected || false;
- // TODO: initialize a new context transaction?...
- // todo: or perhaps add a new session.txn?...
+ // Registers a callback function to be invoked when NDEF message is received from NFC peer-to-peer target connected.
+ function setReceiveNDEFListener(successCallback) {
+ if (!_security.setReceiveNDEFListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( cb == undefined && _.isFunction(options) )
- {
- cb = options;
- options = {};
- }
- options = options || {};
+ t.NFCPeer("setReceiveNDEFListener", arguments);
- var self = this;
- var session = state.makeSession({
- context : self._c,
- ua : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
- txn : _.bind(self._c._txn, self._c),
- adapter : self,
- peer : null,
- isServer : true,
- info : sessionInfo
- });
- session.send = response;
- this._receive(session, request, authorize, function(err, stats) {
- if ( err )
- return cb(err);
- self._save(session.txn(), function(err) {
- if ( err )
- return cb(err);
- return cb(null, self._session2stats(session));
- });
- });
- },
+ if (!_data.isPeerConnected) {
+ return;
+ }
+ _data.listener.onNDEFReceived = successCallback;
+ }
- //-------------------------------------------------------------------------
- _receive: function(session, request, authorize, cb) {
- var self = this;
- if ( ! session.isServer )
- {
- session.info.lastMsgID = session.info.msgID;
- session.info.msgID += 1;
+ // Unregisters the listener for receiving NDEFMessage from NFC peer-to-peer target connected.
+ function unsetReceiveNDEFListener() {
+ if (!_security.unsetReceiveNDEFListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ _data.listener.onNDEFReceived = null;
+ }
+
+ // Sends data to NFC peer-to-peer target.
+ function sendNDEF(ndefMessage, successCallback, errorCallback) {
+ if (!_security.sendNDEF) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+
+ t.NFCPeer("sendNDEF", arguments, true);
+
+ window.setTimeout(function () {
+ if (!_data.isPeerConnected) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
}
- var ct = request.headers['Content-Type'];
- codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
- if ( err )
- return cb(err);
- session.info.codec = codecName;
- var do_authorize = ( ! authorize ) ? common.noop : function(cb) {
- session.context.protocol.authorize(xtree, null, authorize, function(err) {
- return cb(err);
- });
- };
- do_authorize(function(err) {
- if ( err )
- return cb(err);
- session.context.protocol.consume(
- session, session.info.lastCommands, xtree,
- function(err, commands) {
- if ( err ) {
- return cb(err);
- }
- if ( session.discover && session.peer.devInfo )
- return cb(null, self._session2stats(session));
- self._transmit(session, commands, function(err) {
- if ( err )
- return cb(err);
- if ( ! session.isServer )
- return cb();
- self._save(session.txn(), function(err) {
- if ( err )
- return cb(err);
- return cb(null, self._session2stats(session));
- });
- });
- }
- );
- });
- })
- },
+ return;
+ }
+
+ db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
+ event.trigger("nfc-output-msg", []);
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ }
+
+ nfcPeer = {
+ setReceiveNDEFListener: setReceiveNDEFListener,
+ unsetReceiveNDEFListener: unsetReceiveNDEFListener,
+ sendNDEF: sendNDEF
+ };
+ nfcPeer.__defineGetter__("isConnected", function () {
+ return _data.isPeerConnected;
});
- return exports;
+ return nfcPeer;
+};
-})();
+function _initialize() {
+ _data.nfcAdapter = new NFCAdapter();
+}
+
+_initialize();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/matcher', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.matcher
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/12/05
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
-
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
+define('ripple/platform/tizen/2.0/power', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 event = require('ripple/event'),
+ constants = require('ripple/constants'),
+ deviceSettings = require('ripple/deviceSettings'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ _POWER_RESOURCE = constants.POWER_RESOURCE,
+ _SCREEN_STATE = constants.POWER_RESOURCE.SCREEN.STATE,
+ ScreenState = {"previous" : null, "current" : null},
+ _listeners = [],
+ _isScreenResourceOccupied = false,
+ _originalBrightness,
+ _isCPUAwake = false,
+ _isScreenOn = true,
+ _normalBrightness,
+ _minimal_screen_state = null,
+ _security = {
+ "http://tizen.org/privilege/power": ["request", "setScreenBrightness", "turnScreenOn", "turnScreenOff"]
+ },
_self;
-_self = (function () {
-
- var exports = {};
-
- //---------------------------------------------------------------------------
- exports._cntpref = function(source, target) {
- return ( source.preferred ? 1 : 0 ) + ( target.preferred ? 1 : 0 );
- };
+/**initialize**/
+function initState() {
+ _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
+ updateResourceState();
+}
- //---------------------------------------------------------------------------
- exports._pickTransmitContentType = function(source, target, prefcnt, checkVersion) {
- for ( var sidx=0 ; sidx<source.length ; sidx++ )
-{
- var sct = source[sidx];
- for ( var tidx=0 ; tidx<target.length ; tidx++ )
-{
- var tct = target[tidx];
- if ( sct.ctype != tct.ctype )
- continue;
-if ( ! checkVersion )
-{
- if ( exports._cntpref(sct, tct) >= prefcnt )
- return [sct.ctype, sct.versions[sct.versions.length - 1]];
- continue;
+function getResourceState(value) {
+ var state;
+ value = Number(value);
+ if (value <= _SCREEN_STATE.SCREEN_OFF.MAX) {
+ state = _SCREEN_STATE.SCREEN_OFF.NAME;
+ } else if (value < _SCREEN_STATE.SCREEN_DIM.MAX) {
+ state = _SCREEN_STATE.SCREEN_DIM.NAME;
+ } else if (value < _SCREEN_STATE.SCREEN_NORMAL.MAX) {
+ state = _SCREEN_STATE.SCREEN_NORMAL.NAME;
+ } else {
+ state = _SCREEN_STATE.SCREEN_BRIGHT.NAME;
+ }
+ return state;
}
-for ( var svidx=sct.versions.length ; svidx>0 ; svidx-- )
-{
- var sv = sct.versions[svidx - 1]
- for ( var tvidx=tct.versions.length ; tvidx>0 ; tvidx-- )
- {
- var tv = tct.versions[tvidx - 1]
- if ( sv != tv )
- continue;
- if ( exports._cntpref(sct, tct) >= prefcnt )
- return [sct.ctype, sv];
- }
+
+function updateResourceState() {
+ var brightness, actualState;
+ brightness = deviceSettings.retrieve("DISPLAY.brightness");
+ actualState = getResourceState(brightness);
+ ScreenState.previous = ScreenState.current;
+ ScreenState.current = actualState;
}
+
+function callListeners(listeners, previousState, changedState) {
+ listeners.forEach(function (listener) {
+ setTimeout(function () {
+ listener(previousState, changedState);
+ }, 1);
+ });
}
+
+function triggerListenerCB(stateObj) {
+ if (stateObj.previous !== stateObj.current) {
+ callListeners(_listeners, stateObj.previous, stateObj.current);
+ }
}
-return null;
-};
-//---------------------------------------------------------------------------
-exports.pickTransmitContentType = function(source, target) {
+_self = function () {
+ function request(resource, state) {
+ if (!_security.request) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
+ if (typeof resource !== 'string' || typeof state !== 'string') {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ }
+ //Check resource
+ if (!_POWER_RESOURCE.hasOwnProperty(resource)) {
+ throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
+ }
+ //Check state
+ if (!_POWER_RESOURCE[resource].STATE.hasOwnProperty(state)) {
+ throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
+ }
+ // Exception check: SCREEN_OFF is a state cannot be requested
+ if (resource === "SCREEN" && state === "SCREEN_OFF") {
+ throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
+ }
+ switch (resource) {
+ case "SCREEN" :
+ if ((_minimal_screen_state === null) ||
+ (_minimal_screen_state === "SCREEN_DIM" && (state === "SCREEN_NORMAL" || state === "SCREEN_BRIGHT")) ||
+ (_minimal_screen_state === "SCREEN_NORMAL" && state === "SCREEN_BRIGHT")) {
+ _minimal_screen_state = state;
+ }
+ break;
+ case "CPU" :
+ _isCPUAwake = true;
+ break;
+ default:
+ break;
+ }
+ }
- // TODO: this is probably not the most efficient algorithm!...
- // (but it works... ;-)
+ function release(resource) {
+ switch (resource) {
+ case "SCREEN" :
+ if (_isScreenResourceOccupied) {
+ _isScreenResourceOccupied = false;
+ deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
+ event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
+ updateResourceState();
+ triggerListenerCB(ScreenState);
+ }
+ _minimal_screen_state = null;
+ break;
+ case "CPU" :
+ _isCPUAwake = false;
+ break;
+ default:
+ if (typeof resource === "string") {
+ throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ } else {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ }
+ }
- // order of preference:
- // - transmit => receive, BOTH preferred, VERSION match
- // - transmit => receive, ONE preferred, VERSION match
- // - transmit => receive, neither preferred, VERSION match
- // - transmit => receive, BOTH preferred, no version match
- // - transmit => receive, ONE preferred, no version match
- // - transmit => receive, neither preferred, no version match
- // - tx/rx => tx/rx, BOTH preferred, VERSION match
- // - tx/rx => tx/rx, ONE preferred, VERSION match
- // - tx/rx => tx/rx, neither preferred, VERSION match
- // - tx/rx => tx/rx, BOTH preferred, no version match
- // - tx/rx => tx/rx, ONE preferred, no version match
- // - tx/rx => tx/rx, neither preferred, no version match
+ function setScreenStateChangeListener(listener) {
+ tizen1_utils.validateArgumentType(listener, "function",
+ new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ _listeners.push(listener);
+ }
- // todo: make it explicit (or overrideable) that i am depending on the ordering
- // of the versions supported to give an indicator of preference...
+ function unsetScreenStateChangeListener() {
+ _listeners = [];
+ }
- var sct = source.getContentTypes();
- var tct = target.getContentTypes();
+ function getScreenBrightness() {
+ var brightness = deviceSettings.retrieve("DISPLAY.brightness");
+ return brightness;
+ }
- var fct = function(cts, transmit) {
- return _.filter(cts, function(ct) {
- return transmit ? ct.transmit : ct.receive;
- });
- };
+ function setScreenBrightness(brightness) {
+ if (!_security.setScreenBrightness) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
+ if (typeof brightness !== 'number') {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (brightness < 0 || brightness > 1) {
+ throw new WebAPIError(errorcode.INVALID_VALUES_ERR);
+ }
+ if (!_isScreenResourceOccupied) {
+ _originalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
+ _isScreenResourceOccupied = true;
+ }
+ deviceSettings.persist("DISPLAY.brightness", brightness);
+ event.trigger("DisplayBrightnessChangedByPower", [brightness]);
+ updateResourceState();
+ triggerListenerCB(ScreenState);
+ }
- return exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, true)
- || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, true)
- || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, true)
- || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, false)
- || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, false)
- || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, false)
- || exports._pickTransmitContentType(sct, tct, 2, true)
- || exports._pickTransmitContentType(sct, tct, 1, true)
- || exports._pickTransmitContentType(sct, tct, 0, true)
- || exports._pickTransmitContentType(sct, tct, 2, false)
- || exports._pickTransmitContentType(sct, tct, 1, false)
- || exports._pickTransmitContentType(sct, tct, 0, false)
- || null;
+ function isScreenOn() {
+ return _isScreenOn;
+ }
-};
+ function restoreScreenBrightness() {
+ if (_isScreenResourceOccupied) {
+ _isScreenResourceOccupied = false;
+ deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
+ event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
+ updateResourceState();
+ triggerListenerCB(ScreenState);
+ }
+ }
-// TODO: OH MY GOD.
-// this is insanely inefficient.
-// i'm embarrassed.
-// fortunately, it's hidden really low-level...
-// but now you know, doh! please don't blackmail me!... ;-)
+ function turnScreenOn() {
+ var brightness, value, flag = false;
+ if (!_security.turnScreenOn) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
+ brightness = deviceSettings.retrieve("DISPLAY.brightness");
+ switch (_minimal_screen_state) {
+ case "SCREEN_DIM":
+ if (brightness <= _SCREEN_STATE.SCREEN_OFF.VALUE) {
+ if (!_isScreenResourceOccupied) {
+ _originalBrightness = brightness;
+ _isScreenResourceOccupied = true;
+ }
+ value = _SCREEN_STATE.SCREEN_DIM.VALUE;
+ flag = true;
+ }
+ break;
+ case "SCREEN_NORMAL":
+ if (brightness < _SCREEN_STATE.SCREEN_NORMAL.MIN) {
+ if (!_isScreenResourceOccupied) {
+ _originalBrightness = brightness;
+ _isScreenResourceOccupied = true;
+ }
+ value = _normalBrightness;
+ flag = true;
+ }
+ break;
+ case "SCREEN_BRIGHT":
+ if (brightness < _SCREEN_STATE.SCREEN_BRIGHT.MIN) {
+ if (!_isScreenResourceOccupied) {
+ _originalBrightness = brightness;
+ _isScreenResourceOccupied = true;
+ }
+ value = _SCREEN_STATE.SCREEN_BRIGHT.VALUE;
+ flag = true;
+ }
+ break;
+ }
+ if (flag) {
+ deviceSettings.persist("DISPLAY.brightness", value);
+ event.trigger("DisplayBrightnessChangedByPower", [value]);
+ updateResourceState();
+ triggerListenerCB(ScreenState);
+ }
+ _isScreenOn = true;
+ }
-// TODO: this currently requires that both tx and rx match in both
-// directions with the same velocity... it should prioritize
-// that, but then fallback to giving simplex matches priority.
+ function turnScreenOff() {
+ if (!_security.turnScreenOff) {
+ throw new WebAPIError(errorcode.SECURITY_ERR);
+ }
+ _isScreenOn = false;
+ }
-//---------------------------------------------------------------------------
-var has_ct = function(a, b, checkVersion, transmit, wildcard) {
- a = _.filter(a, function(e) { return transmit ? e.transmit : e.receive });
- b = _.filter(b, function(e) { return transmit ? e.transmit : e.receive });
- for ( var aidx=0 ; aidx<a.length ; aidx++ )
- {
- var ct_a = a[aidx];
- for ( var bidx=0 ; bidx<b.length ; bidx++ )
- {
- var ct_b = b[bidx];
- if ( ct_a.ctype != ct_b.ctype )
- continue;
- if ( ! checkVersion )
- return true;
- for ( var vaidx=0 ; vaidx<ct_a.versions.length ; vaidx++ )
- {
- var va = ct_a.versions[vaidx];
- for ( var vbidx=0 ; vbidx<ct_b.length ; vbidx++ )
- {
- var vb = ct_b.versions[vbidx];
- if ( va == vb )
- return true;
- }
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
}
- }
- return false;
-};
+ }
-//---------------------------------------------------------------------------
-var has_ct_both = function(a, b, checkVersion, wildcard) {
- return has_ct(a, b, checkVersion, true, wildcard)
- && has_ct(a, b, checkVersion, false, wildcard);
-};
+ var power = {
+ request: request,
+ release: release,
+ setScreenStateChangeListener: setScreenStateChangeListener,
+ unsetScreenStateChangeListener: unsetScreenStateChangeListener,
+ getScreenBrightness: getScreenBrightness,
+ setScreenBrightness: setScreenBrightness,
+ isScreenOn: isScreenOn,
+ restoreScreenBrightness: restoreScreenBrightness,
+ turnScreenOn: turnScreenOn,
+ turnScreenOff: turnScreenOff,
+ handleSubFeatures : handleSubFeatures
+ };
-//---------------------------------------------------------------------------
-var cmpStore_ct_set_crit = function(base, ds1, ds2, checkVersion, wildcard) {
- var bds1 = has_ct_both(base, ds1, checkVersion, wildcard);
- var bds2 = has_ct_both(base, ds2, checkVersion, wildcard);
- if ( bds1 && bds2 )
- return 0;
- if ( bds1 )
- return -1;
- if ( bds2 )
- return 1;
- return 0;
+ return power;
};
-//---------------------------------------------------------------------------
-var cmpStore_ct_set = function(base, ds1, ds2) {
- var ret = cmpStore_ct_set_crit(base, ds1, ds2, true, false);
- if ( ret != 0 )
- return ret;
- ret = cmpStore_ct_set_crit(base, ds1, ds2, false, false);
- if ( ret != 0 )
- return ret;
- ret = cmpStore_ct_set_crit(base, ds1, ds2, true, true);
- if ( ret != 0 )
- return ret;
- ret = cmpStore_ct_set_crit(base, ds1, ds2, false, true);
- if ( ret != 0 )
- return ret;
- return 0;
-};
+initState();
+event.on("CpuLoadChanged", function (value) {
+ var load;
+ if (_isCPUAwake && Number(value) === 0) {
+ load = _POWER_RESOURCE.CPU.STATE.CPU_AWAKE.DEFAULT_VALUE;
+ deviceSettings.persist("CPU.load", load);
+ event.trigger("CpuLoadChangedByPower", [load]);
+ }
+});
+event.on("DisplayBrightnessChanged", function () {
+ _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
+ updateResourceState();
+ triggerListenerCB(ScreenState);
+});
-//---------------------------------------------------------------------------
-var getct = function(store) {
- return store.getContentTypes ? store.getContentTypes() : store.contentTypes;
-};
+module.exports = _self;
-//---------------------------------------------------------------------------
-var cmpStore_ct_pref = function(base, ds1, ds2) {
- var basect = _.filter(getct(base), function(ct) { return ct.preferred; });
- var ds1ct = _.filter(getct(ds1), function(ct) { return ct.preferred; });
- var ds2ct = _.filter(getct(ds2), function(ct) { return ct.preferred; });
- return cmpStore_ct_set(basect, ds1ct, ds2ct);
+});
+define('ripple/platform/tizen/2.0/SimpleCoordinates', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 t = require('ripple/platform/tizen/2.0/typecast'),
+ SimpleCoordinates;
+
+SimpleCoordinates = function (latitude, longitude) {
+ var simpleCoordinates = {};
+
+ t.SimpleCoordinates(arguments, this);
+
+ this.__defineGetter__("latitude", function () {
+ return simpleCoordinates.latitude;
+ });
+ this.__defineSetter__("latitude", function (val) {
+ try {
+ simpleCoordinates.latitude = t.double(val);
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("longitude", function () {
+ return simpleCoordinates.longitude;
+ });
+ this.__defineSetter__("longitude", function (val) {
+ try {
+ simpleCoordinates.longitude = t.double(val);
+ } catch (e) {
+ }
+ });
+
+ simpleCoordinates.latitude = latitude;
+ simpleCoordinates.longitude = longitude;
};
-//---------------------------------------------------------------------------
-var cmpStore_ct_all = function(base, ds1, ds2) {
- return cmpStore_ct_set(getct(base), getct(ds1), getct(ds2));
+module.exports = SimpleCoordinates;
+
+});
+define('ripple/platform/tizen/2.0/MessageBody', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 = function (id, isloaded, _plainbody, _htmlbody, inlineattachments) {
+ var msgbody, _id = id, _loaded = isloaded;
+ msgbody = {
+ plainBody: _plainbody,
+ htmlBody: _htmlbody,
+ inlineAttachments: [] // TODO: not support attachment yet
+ };
+ msgbody.__defineGetter__("messageId", function () {
+ return _id;
+ });
+ msgbody.__defineGetter__("loaded", function () {
+ return _loaded;
+ });
+ return msgbody;
};
-//---------------------------------------------------------------------------
-var cmpStore_ct = function(base, ds1, ds2) {
- var ret = cmpStore_ct_pref(base, ds1, ds2)
- if ( ret != 0 )
- return ret;
- return cmpStore_ct_all(base, ds1, ds2);
-};
+});
+define('ripple/platform/tizen/2.0/NotificationDetailInfo', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 t = require('ripple/platform/tizen/2.0/typecast'),
+ NotificationDetailInfo;
-//---------------------------------------------------------------------------
-var cmpStore_uri = function(base, ds1, ds2) {
- var ret = difflib.getCloseMatches(base.uri, [ds1.uri, ds2.uri], 1, 0.5);
- if ( ret.length <= 0 )
- return 0;
- if ( ret[0] == ds1.uri )
- return -1;
- return 1;
-};
+NotificationDetailInfo = function (mainText, subText) {
+ var notificationDetailInfo = {};
-//---------------------------------------------------------------------------
-exports.cmpStore = function(base, ds1, ds2) {
- var ret = cmpStore_ct(base, ds1, ds2);
- if ( ret != 0 )
- return ret;
- return cmpStore_uri(base, ds1, ds2);
-};
+ t.NotificationDetailInfo(arguments, this);
-return exports;
+ notificationDetailInfo.mainText = mainText;
+ notificationDetailInfo.subText = subText || null;
-})();
+ this.__defineGetter__("mainText", function () {
+ return notificationDetailInfo.mainText;
+ });
+ this.__defineSetter__("mainText", function (val) {
+ try {
+ notificationDetailInfo.mainText = t.DOMString(val);
+ } catch (e) {
+ }
+ });
-module.exports = _self;
+ this.__defineGetter__("subText", function () {
+ return notificationDetailInfo.subText;
+ });
+ this.__defineSetter__("subText", function (val) {
+ try {
+ notificationDetailInfo.subText = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+};
+module.exports = NotificationDetailInfo;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/protocol', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.protocol
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/04
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+define('ripple/platform/tizen/2.0/PrivMessage', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 utils = require('ripple/utils');
-var db = require('ripple/db'),
- common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- devinfo = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
- state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
- base64 = require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
- ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
- _firstflag = false,
- changednum, _counts;
+module.exports = function (m, opt) {
+ return {
+// readonly begin
+ priv: {id: opt.id,
+ serviceId: opt.serviceId,
+ conversationId: opt.conversationId,
+ folderId: opt.folderId,
+ type: opt.type,
+ timestamp: new Date(opt.timestamp),
+ from: opt.from,
+ hasAttachment: opt.hasAttachment,
+ messageStatus: opt.messageStatus
+ },
+// readonly end
+ to: m.to.slice(0),
+ cc: m.cc.slice(0),
+ bcc: m.bcc.slice(0),
+ body: utils.copy(m.body),
+ isRead: m.isRead,
+ isHighPriority: m.isHighPriority,
+ subject: m.subject,
+ inResponseTo: m.inResponseTo,
+ attachments: utils.copy(m.attachments)
+ };
+};
-var _self = (function () {
+});
+define('ripple/platform/tizen/2.0/GeoRectBounds', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 exports = {};
+module.exports = function (_southWest, _northEast) {
+ var southWest, northEast;
+ southWest = _southWest || null;
+ northEast = _northEast || null;
- //---------------------------------------------------------------------------
- var getError = function(xnode) {
- var ret = {
- message: xnode.findtext('Item/Data')
- };
- try{
- var xerr = xnode.find('Error');
- }catch(e){
- var xerr = null;
- }
- if ( ! xerr )
-{
- try{
- var xerr = xnode.find('Item/Error');
- }catch(e){
- var xerr = null;
- }
-}
-if ( ! xerr )
-{
- if ( ! ret.message )
- return null;
- return ret;
-}
-ret.code = xerr.findtext('Code');
-ret.message = xerr.findtext('Message');
-ret.trace = xerr.findtext('Trace');
-return ret;
-}
+ this.__defineGetter__("southWest", function () {
+ return southWest;
+ });
-//---------------------------------------------------------------------------
-var badStatus = function(xnode, kls, attrs) {
- if ( ! kls )
- kls = common.ProtocolError;
- var code = xnode.findtext('Data');
- var cname = xnode.findtext('Cmd');
- var msg = null;
- if ( kls == common.ProtocolError )
- msg = 'unexpected status code ' + code + ' for command "' + cname + '"';
- else
- msg = 'received status code ' + code + ' for command "' + cname + '"';
- var error = getError(xnode);
- if ( error )
- {
- if ( error.code )
- msg += ': [' + error.code + '] ' + error.message;
- else
- msg += ': ' + error.message;
- }
- return new kls(msg, undefined, attrs)
+ this.__defineGetter__("northEast", function () {
+ return northEast;
+ });
};
-//---------------------------------------------------------------------------
-exports.getError = getError;
-exports.badStatus = badStatus;
-
-//---------------------------------------------------------------------------
-exports.Protocol = common.Base.extend({
+});
+define('ripple/platform/tizen/2.0/calendar', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- //-------------------------------------------------------------------------
- constructor: function(options) {
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ TZDate = require('ripple/platform/tizen/2.0/TZDate'),
+ TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
+ CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
+ CalendarEvent = require('ripple/platform/tizen/2.0/CalendarEvent'),
+ CalendarEventId = require('ripple/platform/tizen/2.0/CalendarEventId'),
+ CalendarTask = require('ripple/platform/tizen/2.0/CalendarTask'),
+ Calendar,
+ CalendarStorage,
+ CalendarItemsStorage,
+ _DB_CALENDARS_KEY = "tizen1-db-calendars",
+ _watchers = [],
+ _calendars = {
+ EVENT: {},
+ TASK: {}
},
+ _calendarsStorage,
+ _security = {
+ "http://tizen.org/privilege/calendar.read": ["getCalendars",
+ "getUnifiedCalendar", "getDefaultCalendar", "getCalendar",
+ "get", "find", "addChangeListener", "removeChangeListener",
+ "expandRecurrence", "convertToString", "clone"],
+ "http://tizen.org/privilege/calendar.write": ["add", "addBatch",
+ "update", "updateBatch", "remove", "removeBatch"]
+ },
+ _self;
- //-------------------------------------------------------------------------
- authorize: function(xtree, uri, authorize, cb) {
-
- // TODO: if this session has been authorized before, don't call authorize
- // ie.:
- // if ( session.info.authAccepted )
- // return cb();
- // BUT this requires the session object... oops.
-
- if ( ! authorize )
- authorize = function(uri, data, cb) { return cb(null, data); };
-if ( xtree.tag != 'SyncML' )
- throw new common.ProtocolError('root element was not "SyncML"');
-var xcred = xtree.find('SyncHdr/Cred');
-if ( ! xcred )
- return authorize(uri, null, cb);
-var data = xcred.findtext('Data');
-var authtype = xcred.findtext('Meta/Type');
-var format = xcred.findtext('Meta/Format');
-if ( format == constant.FORMAT_B64 )
- data = base64.decode(data);
-else if ( format )
- throw new common.UnknownFormatType(format);
-switch ( authtype )
-{
- case constant.NAMESPACE_AUTH_BASIC:
- {
- data = common.splitn(data, ':', 1);
- return authorize(uri, {
- auth: constant.NAMESPACE_AUTH_BASIC,
- username: data[0],
- password: data[1]
- }, cb);
- }
- case constant.NAMESPACE_AUTH_MD5:
- {
- return authorize(uri, {
- auth: constant.NAMESPACE_AUTH_BASIC,
- digest: data
- }, cb);
- }
- default:
- {
- return cb(new common.UnknownAuthType(
- 'unknown/unimplemented auth type "' + authtype + '"'));
- }
+function _isValidId(id) {
+ return (/[a-z]|[A-Z]|[0-9]|[\-]/).test(id);
}
-},
-
- //-------------------------------------------------------------------------
- getTargetID: function(xtree) {
- if ( xtree.tag != 'SyncML' )
- throw new common.ProtocolError('root element was not "SyncML"');
- // todo: do more validity checks?...
- return xtree.findtext('SyncHdr/Target/LocURI');
- },
- //-------------------------------------------------------------------------
- isComplete: function(session, commands) {
- return (! session.isServer
- && commands.length == 3
- && commands[0].name == constant.CMD_SYNCHDR
- && commands[1].name == constant.CMD_STATUS
- && commands[1].statusOf == constant.CMD_SYNCHDR
- && commands[1].statusCode == constant.STATUS_OK
- && commands[2].name == constant.CMD_FINAL
- );
- },
+function retrieveCalendars() {
+ _calendarsStorage = db.retrieveObject(_DB_CALENDARS_KEY) || {EVENT: {}, TASK: {}};
+}
- //----------------------<---------------------------------------------------
- initialize: function(session, xtree, cb) {
- var cmd = state.makeCommand({
- name : constant.CMD_SYNCHDR,
- cmdID : 0,
- version : constant.SYNCML_VERSION_1_2,
- source : session.info.effectiveID || session.adapter.devID,
- sourceName : session.adapter.displayName,
- respUri : session.isServer ? session.info.returnUrl : null
- });
+function saveCalendars() {
+ db.saveObject(_DB_CALENDARS_KEY, _calendarsStorage);
+}
- var checkPeer = ( ! session.isServer ) ? function(cb) {
- if ( ! xtree )
- return cb();
- var xhdr = xtree.find('SyncHdr');
- // todo: check peer id...
- if ( session.info.id != common.int(xhdr.findtext('SessionID')) )
- {
- return cb(new common.ProtocolError('session ID mismatch "'
- + xhdr.findtext('SessionID')
- + '" (expected: ' + session.info.id + ')'));
- }
- // todo: check message id...
- cb();
- } : function(cb) {
- var xhdr = xtree.find('SyncHdr');
- var peerID = xhdr.findtext('Source/LocURI');
- if ( session.info.peerID && session.info.peerID != peerID )
- {
- return cb(new common.ProtocolError('unexpected peer ID "' + peerID + '"'));
- }
- if ( session.peer && session.peer.devID != peerID )
- {
- return cb(new common.ProtocolError('unacceptable peer ID "' + peerID + '"'));
- }
- session.info.peerID = peerID;
- // check that no session swapping occurred
- if ( session.info.id != undefined
- && session.info.id != common.int(xhdr.findtext('SessionID')) )
- {
- return cb(new common.ProtocolError('session ID mismatch "'
- + xhdr.findtext('SessionID')
- + '" (expected: ' + session.info.id + ')'));
- }
- session.info.id = common.int(xhdr.findtext('SessionID'));
- session.info.msgID = common.int(xhdr.findtext('MsgID'));
- if ( session.peer && session.peer.devID == peerID )
- return cb();
- // TODO: i should delete unused peers here... ie. anything that
- // hasn't been used in some configurable number of seconds,
- // which should probably default to something like a month...
- session.peer = _.find(session.adapter.getPeers(), function(peer) {
- return ( peer.devID == peerID );
- });
- if ( session.peer )
- {
- return cb();
- }
- var peerInfo = {
- devID: peerID,
- displayName: xhdr.findtext('Source/LocName'),
- maxMsgSize: common.int(xhdr.findtext('Meta/MaxMsgSize')),
- maxObjSize: common.int(xhdr.findtext('Meta/MaxObjSize'))
- };
- session.adapter.addPeer(peerInfo, function(err, peer) {
- if ( err )
- return cb(err);
- session.peer = peer;
- return cb();
- });
- };
+_self = function () {
+ var calendarManager;
- checkPeer(function(err) {
+ // private
+ function loadCalendars(type) {
+ var calsStorage, defCalendar, id, i, item;
- session.info.cmdID = 0;
- session.info.pendingMsgID = ( session.isServer
- ? session.info.msgID
- : session.info.lastMsgID );
- cmd.sessionID = session.info.id;
- cmd.msgID = session.info.msgID;
- cmd.target = session.peer ? session.peer.devID || null : null;
- cmd.targetName = session.peer ? session.peer.displayName || null : null;
- cmd.auth = session.auth
- ? session.auth.type
- : session.peer
- ? session.peer.auth
- : null;
+ retrieveCalendars();
+ calsStorage = _calendarsStorage[type];
- if ( err )
- return cb(err, [cmd]);
+ if (tizen1_utils.isEmptyObject(calsStorage)) {
+ defCalendar = new Calendar(type, "Default " + type.toLowerCase() + " calendar");
- if ( cmd.msgID == 1 )
- {
- // NOTE: normally, the "server" would not send this info. however, in
- // the syncml-js world where it is much more peer-oriented
- // instead of client/server, i send this as well... the
- // idea being, if two "client" peers are communicating in
- // the event of server unavailability, then they may need
- // to know each-others limitations...
- cmd.maxMsgSize = common.getMaxMemorySize(session.context);
- cmd.maxObjSize = common.getMaxMemorySize(session.context);
- ///cmd.maxMsgSize = 150000;
- ///cmd.maxObjSize = 4000000;
+ _calendars[type][defCalendar.id] = defCalendar;
+ calsStorage[defCalendar.id] = new CalendarStorage(defCalendar);
+ } else {
+ for (id in calsStorage) {
+ for (i in calsStorage[id].items) {
+ item = calsStorage[id].items[i];
+ }
+ _calendars[type][id] = new Calendar(type, calsStorage[id].name,
+ calsStorage[id].items, id);
+ }
}
- cb(null, [cmd]);
- });
- },
+ }
- //-------------------------------------------------------------------------
- negotiate: function(session, commands, cb) {
- // // todo: determine why i decided to clone the commands...
- // commands = _.clone(commands);
+ // public
+ function getCalendars(type, successCallback, errorCallback) {
+ if (!_security.getCalendars) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( commands.length > 0 && _.last(commands).name == constant.CMD_FINAL )
- return cb(null, commands);
+ t.CalendarManager("getCalendars", arguments);
- if ( commands.length > 0
- && _.last(commands).name == constant.CMD_ALERT
- && _.last(commands).data == constant.STATUS_NEXT_MESSAGE )
- // todo: should i add a "final" here?...
- // commands.push(state.makeCommand({name: constant.CMD_FINAL}));
- return cb(null, commands);
+ window.setTimeout(function () {
+ var i, result = [];
- var createDevInfoCommands = function(commands, cb) {
- // todo: this flag is crap. instead, the local devInfo should have
- // a record of which sessionID lead to the recording, and
- // base it on that. maybe timestamp too... (but it must be
- // in the minutes, just in case...)
- session.info.gotinfo = true;
- if ( ! session.discover )
- {
- commands.push(state.makeCommand({
- name : constant.CMD_PUT,
- cmdID : session.nextCmdID(),
- type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
- source : './' + constant.URI_DEVINFO_1_2,
- data : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
- _.values(session.adapter._stores))
- }));
+ if (tizen1_utils.isEmptyObject(_calendars[type])) {
+ loadCalendars(type);
}
- commands.push(state.makeCommand({
- name : constant.CMD_GET,
- cmdID : session.nextCmdID(),
- type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
- target : './' + constant.URI_DEVINFO_1_2
- }));
- return cb(null, commands);
- };
- var createCommands = function(commands, cb) {
- // request the remote device info if not currently available or
- // in discover mode or explicitly re-exchanging it (paranoid mode)
- var putget = false;
- if ( !! session.discover )
- {
- return createDevInfoCommands(commands, cb);
- }
- if ( ! session.peer.devInfo )
- {
- var uaEvent = {session: session};
- return session.ua.acceptDevInfoSwap(uaEvent, function(err) {
- if ( err )
- {
- return cb(err);
+ if (_calendars.length !== 0) {
+ for (i in _calendars[type]) {
+ result.push(_calendars[type][i]);
}
- return createDevInfoCommands(commands, cb);
- });
- }
- if ( ! session.context.config.trustDevInfo && ! session.info.gotinfo )
- {
- return createDevInfoCommands(commands, cb);
+ successCallback(result);
+ } else if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
}
- // NOTE: in the current handling of "trustDevInfo", i am doing a
- // potentially unnecessary extra request/response phase to
- // confirm that the devInfo has not changed... i *could*
- // issue the put/get as well as the alert, *assuming* that
- // no devInfo is going to change...
- return session.context.synchronizer.actions(session, commands, cb);
- };
+ }, 1);
+ }
- return createCommands(commands, function(err, commands) {
- if ( err )
- return cb(err);
- //Hack: Memotoo service need to send alert command at the beging
- var args, tmp;
- args = db.retrieveObject("syncml-alert-args");
- tmp = {
- name : constant.CMD_ALERT,
- cmdID : session.nextCmdID(),
- data : args.data,
- source : args.source,
- target : args.target,
- maxObjSize : "4000000"
- };
- if (args.lastAnchor) {
- tmp.lastAnchor = args.lastAnchor;
+ function getUnifiedCalendar(type) {
+ var id, calendar;
+
+ if (!_security.getUnifiedCalendar) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- if (args.nextAnchor) {
- tmp.nextAnchor = args.nextAnchor;
+ t.CalendarManager("getUnifiedCalendar", arguments);
+
+ if (tizen1_utils.isEmptyObject(_calendars[type])) {
+ loadCalendars(type);
}
- _firstflag = db.retrieveObject("syncml-first-flag");
- if( !_firstflag) {
- commands.push(state.makeCommand(tmp));
- db.saveObject("syncml-first-flag", true);
+
+ for (id in _calendars[type]) {
+ calendar = _calendars[type][id];
+ break;
}
- commands.push(state.makeCommand({name: constant.CMD_FINAL}));
- cb(null, commands);
- });
- },
- //-------------------------------------------------------------------------
- // NOTE: `produce` is equivalent to the `pysyncml.protocol.commands2tree`...
- // Consumes state.Command commands and converts them to an ET protocol tree
- produce: function(session, commands, cb) {
+ if (calendar === undefined)
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- if ( commands.length <= 0 )
- return cb('protocol.produce received empty commands');
+ return calendar;
+ }
- var hdrcmd = commands[0];
- commands = _.rest(commands, 1);
+ function getDefaultCalendar(type) {
+ var id, calendar;
- if ( hdrcmd.name != constant.CMD_SYNCHDR )
- return cb('unexpected first command "' + hdrcmd.name + '"');
+ if (!_security.getDefaultCalendar) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( hdrcmd.version != constant.SYNCML_VERSION_1_2 )
- return cb('unsupported SyncML version "' + hdrcmd.version + '"');
+ t.CalendarManager("getDefaultCalendar", arguments);
- var xsync = ET.Element(constant.NODE_SYNCML);
- var xhdr = ET.SubElement(xsync, hdrcmd.name);
- if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
- {
- ET.SubElement(xhdr, 'VerDTD').text = constant.SYNCML_DTD_VERSION_1_2;
- ET.SubElement(xhdr, 'VerProto').text = hdrcmd.version;
+ if (tizen1_utils.isEmptyObject(_calendars[type])) {
+ loadCalendars(type);
}
- ET.SubElement(xhdr, 'SessionID').text = hdrcmd.sessionID;
- ET.SubElement(xhdr, 'MsgID').text = hdrcmd.msgID;
- var xsrc = ET.SubElement(xhdr, 'Source');
- ET.SubElement(xsrc, 'LocURI').text = hdrcmd.source;
- if ( hdrcmd.sourceName )
- ET.SubElement(xsrc, 'LocName').text = hdrcmd.sourceName;
- var xtgt = ET.SubElement(xhdr, 'Target');
- ET.SubElement(xtgt, 'LocURI').text = hdrcmd.target;
- if ( hdrcmd.targetName )
- ET.SubElement(xtgt, 'LocName').text = hdrcmd.targetName;
- if ( hdrcmd.respUri )
- ET.SubElement(xhdr, 'RespURI').text = hdrcmd.respUri;
+ for (id in _calendars[type]) {
+ calendar = _calendars[type][id];
+ break;
+ }
- if ( hdrcmd.auth && ! session.info.authAccepted )
- {
- // TODO: implement other auth schemes...
- if ( hdrcmd.auth != constant.NAMESPACE_AUTH_BASIC )
- return cb('auth method "' + hdrcmd.auth + '" not implemented');
+ if (calendar === undefined)
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- if ( hdrcmd.auth == constant.NAMESPACE_AUTH_BASIC )
- {
- var xcred = ET.SubElement(xhdr, 'Cred');
- var xmeta = ET.SubElement(xcred, 'Meta');
- ET.SubElement(xmeta, 'Format', {'xmlns': constant.NAMESPACE_METINF}).text = 'b64';
- ET.SubElement(xmeta, 'Type', {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.auth;
- ET.SubElement(xcred, 'Data').text = base64.encode(
- ( session.auth ? session.auth.username : session.peer.username )
- + ':' + ( session.auth ? session.auth.password : session.peer.password ) );
- }
+ return calendar;
+ }
- }
- if ( hdrcmd.maxMsgSize || hdrcmd.maxObjSize )
- {
- var xmeta = ET.SubElement(xhdr, 'Meta');
- if ( hdrcmd.maxMsgSize )
- ET.SubElement(xmeta, 'MaxMsgSize',
- {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxMsgSize;
- if ( hdrcmd.maxObjSize )
- ET.SubElement(xmeta, 'MaxObjSize',
- {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxObjSize;
+ function getCalendar(type, id) {
+ var calendar;
+
+ if (!_security.getCalendar) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- var xbody = ET.SubElement(xsync, constant.NODE_SYNCBODY);
+ t.CalendarManager("getCalendar", arguments);
- for ( var idx=0 ; idx<commands.length ; idx++ )
- {
- var cmd = commands[idx];
- var xcmd = ET.SubElement(xbody, cmd.name);
- if ( cmd.cmdID != undefined )
- ET.SubElement(xcmd, 'CmdID').text = cmd.cmdID;
- var func = this['_produce_cmd_' + cmd.name.toLowerCase()];
- if ( ! func )
- return cb(new common.InternalError('unexpected command "' + cmd.name + '"'));
- try{
- func.call(this, session, cmd, xcmd);
- }catch(e){
- return cb(new common.InternalError(
- 'failed invoking protocol sub-production of "' + cmd.name + '": ' + e, e));
- }
- if ( cmd.name == constant.CMD_FINAL && idx + 1 != commands.length )
- return cb('command "' + cmd.name + '" not at end of commands');
+ if (tizen1_utils.isEmptyObject(_calendars[type])) {
+ loadCalendars(type);
}
- cb(null, xsync);
- },
+ calendar = _calendars[type][id];
+ if (calendar === undefined)
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- //-------------------------------------------------------------------------
- _produce_cmd_alert: function(session, cmd, xcmd) {
- ET.SubElement(xcmd, 'Data').text = cmd.data;
- var xitem = ET.SubElement(xcmd, 'Item');
- ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.source;
- ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.target;
- if ( cmd.lastAnchor || cmd.nextAnchor || cmd.maxObjSize )
- {
- var xmeta = ET.SubElement(xitem, 'Meta');
- var xanch = ET.SubElement(xmeta, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
- if ( cmd.lastAnchor )
- ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
- if ( cmd.nextAnchor )
- ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
- if ( cmd.maxObjSize )
- ET.SubElement(xmeta, 'MaxObjSize',
- {'xmlns': constant.NAMESPACE_METINF}).text = cmd.maxObjSize;
- }
- },
+ return calendar;
+ }
- //-------------------------------------------------------------------------
- _produce_cmd_status: function(session, cmd, xcmd) {
- ET.SubElement(xcmd, 'MsgRef').text = '' + cmd.msgRef;
- ET.SubElement(xcmd, 'CmdRef').text = '' + cmd.cmdRef;
- ET.SubElement(xcmd, 'Cmd').text = cmd.statusOf;
- if ( cmd.sourceRef )
- ET.SubElement(xcmd, 'SourceRef').text = cmd.sourceRef;
- if ( cmd.targetRef )
- ET.SubElement(xcmd, 'TargetRef').text = cmd.targetRef;
- ET.SubElement(xcmd, 'Data').text = cmd.statusCode;
- var xitem = null;
- var xdata = null;
- if ( cmd.nextAnchor || cmd.lastAnchor )
- {
- xitem = ET.SubElement(xcmd, 'Item');
- xdata = ET.SubElement(xitem, 'Data');
- var xanch = ET.SubElement(xdata, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
- if ( cmd.lastAnchor )
- ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
- if ( cmd.nextAnchor )
- ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
- }
- // NOTE: this is NOT standard SyncML...
- if ( cmd.errorCode || cmd.errorMsg )
- {
- xitem = xitem || ET.SubElement(xcmd, 'Item');
- xdata = xdata || ET.SubElement(xitem, 'Data');
- var xerr = ET.SubElement(xitem, 'Error');
- xdata.text = cmd.errorMsg;
- if ( cmd.errorCode )
- ET.SubElement(xerr, 'Code').text = cmd.errorCode;
- if ( cmd.errorMsg )
- ET.SubElement(xerr, 'Message').text = cmd.errorMsg;
- if ( session.context.config.exposeErrorTrace && cmd.errorTrace )
- ET.SubElement(xerr, 'Trace').text = cmd.errorTrace;
- }
- },
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- //-------------------------------------------------------------------------
- _produce_cmd_get: function(session, cmd, xcmd) {
- ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
- {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
- if ( cmd.source || cmd.target || cmd.data )
- {
- var xitem = ET.SubElement(xcmd, 'Item');
- if ( cmd.source )
- {
- var xsrc = ET.SubElement(xitem, 'Source');
- ET.SubElement(xsrc, 'LocURI').text = cmd.source;
- ET.SubElement(xsrc, 'LocName').text = cmd.source;
- }
- if ( cmd.target )
- {
- var xtgt = ET.SubElement(xitem, 'Target');
- ET.SubElement(xtgt, 'LocURI').text = cmd.target;
- ET.SubElement(xtgt, 'LocName').text = cmd.target;
- }
- if ( cmd.data )
- {
- if ( _.isString(cmd.data) )
- ET.SubElement(xitem, 'Data').text = cmd.data;
- else
- // assuming here that it is an ElementTree object...
- ET.SubElement(xitem, 'Data').append(cmd.data);
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
}
- },
+ }
- //-------------------------------------------------------------------------
- _produce_cmd_put: function(session, cmd, xcmd) {
- return this._produce_cmd_get(session, cmd, xcmd);
- },
+ calendarManager = {
+ getCalendars: getCalendars,
+ getUnifiedCalendar: getUnifiedCalendar,
+ getDefaultCalendar: getDefaultCalendar,
+ getCalendar: getCalendar,
+ handleSubFeatures: handleSubFeatures
+ };
- //-------------------------------------------------------------------------
- _produce_cmd_results: function(session, cmd, xcmd) {
- ET.SubElement(xcmd, 'MsgRef').text = cmd.msgRef;
- ET.SubElement(xcmd, 'CmdRef').text = cmd.cmdRef;
- ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
- {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
- var xitem = ET.SubElement(xcmd, 'Item');
- var xsrc = ET.SubElement(xitem, 'Source');
- ET.SubElement(xsrc, 'LocURI').text = cmd.source;
- ET.SubElement(xsrc, 'LocName').text = cmd.source;
- if ( cmd.data )
- {
- if ( _.isString(cmd.data) )
- ET.SubElement(xitem, 'Data').text = cmd.data;
- else
- // assuming here that it is an ElementTree object...
- ET.SubElement(xitem, 'Data').append(cmd.data);
- }
- },
+ return calendarManager;
+};
- //-------------------------------------------------------------------------
- _produce_cmd_sync: function(session, cmd, xcmd) {
- ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
- ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
- if ( cmd.noc != undefined )
- ET.SubElement(xcmd, 'NumberOfChanges').text = '' + cmd.noc;
- if ( ! cmd.data )
- return;
- for ( var idx=0 ; idx<cmd.data.length ; idx++ )
- {
- var scmd = cmd.data[idx];
- var xscmd = ET.SubElement(xcmd, scmd.name);
- if ( scmd.cmdID )
- ET.SubElement(xscmd, 'CmdID').text = scmd.cmdID;
- if ( scmd.type
- || ( scmd.format && scmd.format != constant.FORMAT_AUTO ) )
- {
- var xsmeta = ET.SubElement(xscmd, 'Meta')
- // todo: implement auto encoding determination...
- // (the current implementation just lets XML encoding
- // do it, which is for most things good enough, but
- // not so good for sequences that need a large amount
- // of escaping such as binary data...)
- if ( scmd.format && scmd.format != constant.FORMAT_AUTO )
- ET.SubElement(xsmeta, 'Format',
- {'xmlns': constant.NAMESPACE_METINF}).text = scmd.format;
- if ( scmd.type )
- ET.SubElement(xsmeta, 'Type',
- {'xmlns': constant.NAMESPACE_METINF}).text = scmd.type;
- }
- var xsitem = ET.SubElement(xscmd, 'Item');
- if ( scmd.source )
- ET.SubElement(ET.SubElement(xsitem, 'Source'),
- 'LocURI').text = scmd.source;
- if ( scmd.sourceParent )
- ET.SubElement(ET.SubElement(xsitem, 'SourceParent'),
- 'LocURI').text = scmd.sourceParent;
- if ( scmd.target )
- ET.SubElement(ET.SubElement(xsitem, 'Target'),
- 'LocURI').text = scmd.target;
- if ( scmd.targetParent )
- ET.SubElement(ET.SubElement(xsitem, 'TargetParent'),
- 'LocURI').text = scmd.targetParent;
- if ( scmd.data )
- {
- if ( _.isString(scmd.data) )
- ET.SubElement(xsitem, 'Data').text = scmd.data;
- else
- // assuming here that it is an ElementTree object...
- ET.SubElement(xsitem, 'Data')._node.appendChild(scmd.data);
- }
- }
- },
+Calendar = function (type, name, storageItems, calendarId) {
+ var privateItems = {},
+ defaultWatchId = 0;
+ calendarId = calendarId || Math.uuid(null, 16);
- //-------------------------------------------------------------------------
- _produce_cmd_map: function(session, cmd, xcmd) {
- ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
- ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
- if ( cmd.sourceItem || cmd.targetItem )
- {
- var xitem = ET.SubElement(xcmd, constant.CMD_MAPITEM);
- if ( cmd.sourceItem )
- ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.sourceItem;
- if ( cmd.targetItem )
- ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.targetItem;
+ // private
+ function createCalendarItem() {
+ var calendarItem = null;
+
+ switch (type) {
+ case "EVENT":
+ calendarItem = new CalendarEvent();
+ break;
+
+ case "TASK":
+ calendarItem = new CalendarTask();
+ break;
+
+ default:
+ break;
}
- },
- //-------------------------------------------------------------------------
- _produce_cmd_final: function(session, cmd, xcmd) {
- return;
- },
+ return calendarItem;
+ }
- //-------------------------------------------------------------------------
- // NOTE: `consume` is equivalent to the `pysyncml.protocol.tree2commands`...
- // consume: function...
- consume: function(session, lastcmds, xsync, cb) {
+ function isValidCalendarItemId(itemId) {
+ var i;
- // do some preliminary sanity checks...
- // todo: do i really want to be returning an error instead of
- // generating an error response?...
+ if (!_isValidId(itemId))
+ return false;
- if ( xsync.tag != constant.NODE_SYNCML
- || xsync.getchildren().length != 2
- || xsync.getchildren()[0].tag != constant.CMD_SYNCHDR
- || xsync.getchildren()[1].tag != constant.NODE_SYNCBODY
- )
- {
- return cb('unexpected SyncML document structure');
+ for (i in privateItems) {
+ if (i === itemId)
+ return true;
}
- var version = xsync.getchildren()[0].findtext('VerProto');
- if ( version != constant.SYNCML_VERSION_1_2 )
- return cb('unsupported SyncML version "' + version + '"');
+ return false;
+ }
- var verdtd = xsync.getchildren()[0].findtext('VerDTD');
- if ( verdtd != constant.SYNCML_DTD_VERSION_1_2 )
- return cb('unsupported SyncML DTD version "' + verdtd + '"');
+ function loadCalendarItemInit(calendarItem, storageItem) {
+ calendarItem.description = utils.copy(storageItem.description);
+ calendarItem.summary = utils.copy(storageItem.summary);
+ calendarItem.isAllDay = utils.copy(storageItem.isAllDay);
+ calendarItem.startDate = storageItem.startDate;
+ if (storageItem.startDate instanceof TZDate) {
+ calendarItem.startDate = storageItem.startDate.addDuration(new TDur(0, 'MSECS'));
+ }
+ if (typeof storageItem.startDate === 'string') {
+ calendarItem.startDate = new TZDate(new Date(storageItem.startDate));
+ }
- var self = this;
+ calendarItem.duration = utils.copy(storageItem.duration);
+ calendarItem.location = utils.copy(storageItem.location);
+ calendarItem.geolocation = utils.copy(storageItem.geolocation);
+ calendarItem.organizer = utils.copy(storageItem.organizer);
+ calendarItem.visibility = utils.copy(storageItem.visibility);
+ calendarItem.status = utils.copy(storageItem.status);
+ calendarItem.priority = utils.copy(storageItem.priority);
+ calendarItem.alarms = utils.copy(storageItem.alarms);
+ calendarItem.categories = utils.copy(storageItem.categories);
+ calendarItem.attendees = utils.copy(storageItem.attendees);
+ }
- self.initialize(session, xsync, function(err, cmds) {
- var hdrcmd = ( cmds && cmds.length > 0 ) ? cmds[0] : null;
- var makeErrorCommands = function(err, cb) {
+ function loadCalendarEventInit(calendarItem, storageItem) {
+ loadCalendarItemInit(calendarItem, storageItem);
- if ( err.exception )
+ calendarItem.endDate = storageItem.endDate;
+ if (storageItem.endDate instanceof TZDate) {
+ calendarItem.endDate = storageItem.endDate.addDuration(new TDur(0, 'MSECS'));
+ }
+ if (typeof storageItem.endDate === 'string') {
+ calendarItem.endDate = new TZDate(new Date(storageItem.endDate));
+ }
+ calendarItem.availability = utils.copy(storageItem.availability);
+ calendarItem.recurrenceRule = utils.copy(storageItem.recurrenceRule);
+ calendarItem.expandRecurrence = function (startDate, endDate, successCallback, errorCallback) {
+ if (!_security.expandRecurrence) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( ! session.isServer )
- return cb(err);
+ calendarItem.startDate = startDate;
+ calendarItem.endDate = endDate;
- var errcmd = state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : '1',
- msgRef : session.info.pendingMsgID,
- cmdRef : 0,
- sourceRef : xsync.getchildren()[0].findtext('Source/LocURI'),
- targetRef : xsync.getchildren()[0].findtext('Target/LocURI'),
- statusOf : constant.CMD_SYNCHDR,
- statusCode : constant.STATUS_COMMAND_FAILED,
- errorMsg : 'an error occurred during processing'
- });
+ if (errorCallback) {
+ window.setTimeout(function () {
+ errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
+ }, 1);
+ }
+ };
+ calendarItem.frequency = utils.copy(storageItem.frequency);
+ calendarItem.interval = utils.copy(storageItem.interval);
+ calendarItem.untilDate = storageItem.untilDate;
+ if (storageItem.untilDate instanceof TZDate) {
+ calendarItem.untilDate = storageItem.untilDate.addDuration(new TDur(0, 'MSECS'));
+ }
+ if (typeof storageItem.untilDate === 'string') {
+ calendarItem.untilDate = new TZDate(new Date(storageItem.untilDate));
+ }
+ calendarItem.occurrenceCount = utils.copy(storageItem.occurrenceCount);
+ calendarItem.daysOfTheWeek = utils.copy(storageItem.daysOfTheWeek);
+ calendarItem.setPositions = utils.copy(storageItem.setPositions);
+ calendarItem.exceptions = utils.copy(storageItem.exceptions);
+ }
- // TODO: make this configurable as to whether or not any error
- // is sent back to the peer as a SyncML "standardized" error
- // status...
+ function loadCalendarTaskInit(calendarItem, storageItem) {
+ loadCalendarItemInit(calendarItem, storageItem);
- // TODO: make sure this is doing what is expected/intended...
- if ( err.code || err.name )
- errcmd.errorCode = 'syncml-js.' + ( err.code || err.name );
- errcmd.errorMsg = err.message || common.j(err) || '' + err;
+ calendarItem.dueDate = storageItem.dueDate;
+ if (storageItem.dueDate instanceof TZDate) {
+ calendarItem.dueDate = storageItem.dueDate.addDuration(new TDur(0, 'MSECS'));
+ }
+ if (typeof storageItem.dueDate === 'string') {
+ calendarItem.dueDate = new TZDate(new Date(storageItem.dueDate));
+ }
+ calendarItem.completeDate = storageItem.completeDate;
+ if (storageItem.completeDate instanceof TZDate) {
+ calendarItem.completeDate = storageItem.completeDate.addDuration(new TDur(0, 'MSECS'));
+ }
+ if (typeof storageItem.completeDate === 'string') {
+ calendarItem.completeDate = new TZDate(new Date(storageItem.completeDate));
+ }
+ calendarItem.progress = utils.copy(storageItem.progress);
+ }
+
+ function loadCalendarItems() {
+ var i, calendarItem;
- return cb(null, [hdrcmd, errcmd,
- state.makeCommand({name: constant.CMD_FINAL})]);
- };
+ if (storageItems === undefined)
+ return;
- if ( err )
- return makeErrorCommands(err, cb);
+ for (i in storageItems) {
+ calendarItem = new CalendarItem(type, i, storageItems[i].lastModificationDate? new TZDate(new Date(storageItems[i].lastModificationDate)) : null, _security);
- try {
- self._consume(session, lastcmds, xsync, cmds, function(err, commands) {
- if ( err )
- return makeErrorCommands(err, cb);
- return cb(null, commands);
- });
- } catch ( exc ) {
- return makeErrorCommands(exc, cb);
+ if (type === "EVENT") {
+ loadCalendarEventInit(calendarItem, storageItems[i]);
+ } else {
+ loadCalendarTaskInit(calendarItem, storageItems[i]);
}
- });
- },
-
- //-------------------------------------------------------------------------
- _consume: function(session, lastcmds, xsync, commands, cb) {
+ privateItems[i] = calendarItem;
+ }
+ }
- var self = this;
- var hdrcmd = commands[0];
- var statusCode = constant.STATUS_OK;
+ function saveCalendarItems() {
+ _calendarsStorage[type][calendarId] || (_calendarsStorage[type][calendarId] = {});
+ _calendarsStorage[type][calendarId].items = new CalendarItemsStorage(privateItems);
+ saveCalendars();
+ }
- // analyze the SyncHdr
- var children = xsync.getchildren()[0].getchildren();
- for ( var idx=0 ; idx<children.length ; idx++ )
- {
- var child = children[idx];
+ // public
+ function get(id) {
+ var item, uid, CalendarItemType, external = {};
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( child.tag == 'VerDTD' )
- {
- if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
- {
- if ( child.text != constant.SYNCML_DTD_VERSION_1_2 )
- return cb(new common.ProtocolError('bad VerDTD "' + child.text + '"'));
- }
- else
- return cb(new common.FeatureNotSupported(
- 'unsupported internal SyncML version "' + hdrcmd.version + '"'));
- continue;
- }
+ t.Calendar("get", arguments);
- if ( child.tag == 'VerProto' )
- // this was checked earlier...
- continue;
+ if (type === "EVENT") {
+ t.CalendarEventId(id);
+ uid = id.uid;
+ CalendarItemType = CalendarEvent;
+ } else {
+ t.CalendarTaskId(id);
+ uid = id;
+ CalendarItemType = CalendarTask;
+ }
- if ( child.tag == 'SessionID' )
- {
- if ( child.text != hdrcmd.sessionID )
- return cb(new common.ProtocolError(
- 'session ID mismatch: "' + child.text + '" != "' + hdrcmd.sessionID + '"'));
- continue;
- }
+ if (!isValidCalendarItemId(uid))
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- if ( child.tag == 'MsgID' )
- {
- var chkmsg = ( session.isServer ? hdrcmd.msgID : lastcmds[0].msgID );
- if ( child.text != chkmsg )
- return cb(new common.ProtocolError(
- 'message ID mismatch: "' + child.text + '" != "' + chkmsg + '"'));
- continue;
- }
+ item = new CalendarItemType(privateItems[uid]);
+ external.id = privateItems[uid].id;
+ external.lastModificationDate = privateItems[uid].lastModificationDate;
- if ( child.tag == 'Target' )
- {
- var uri = child.findtext('LocURI');
+ item.__defineGetter__("calendarId", function () {
+ return calendarId;
+ });
- // TODO... server-side...
+ item.__defineGetter__("id", function () {
+ return external.id;
+ });
- if ( uri != hdrcmd.source )
- return cb(new common.ProtocolError(
- 'incoming target mismatch: "' + uri + '" != "' + hdrcmd.source + '"'));
- continue;
- }
+ item.__defineGetter__("lastModificationDate", function () {
+ return external.lastModificationDate;
+ });
- if ( child.tag == 'Source' )
- {
- var uri = child.findtext('LocURI');
- if ( uri != hdrcmd.target && uri != lastcmds[0].target )
- return cb(new common.ProtocolError(
- 'incoming source mismatch: "' + uri + '" != "' + hdrcmd.target + '"'));
- continue;
- }
+ return item;
+ }
- if ( child.tag == 'RespURI' )
- {
- // hdrcmd.target = child.text
- // session.info.respUri = child.text
- if ( ! session.isServer )
- session.info.respUri = child.text;
- continue;
- }
+ function add(item) {
+ var uid, external = {};
- if ( child.tag == 'Cred' )
- {
- // the responsibility is on the calling framework to ensure this is
- // checked long before we get here... ie. Adapter.authorize(...)
- // or via the Adapter.handleRequest() `authorize` parameter...
- statusCode = constant.STATUS_AUTHENTICATION_ACCEPTED;
- continue;
- }
+ if (!_security.add) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( child.tag == 'Meta' )
- {
- // this should already have been consumed during the protocol.initialize() call
- continue;
- }
+ t.Calendar("add", arguments);
- return cb(new common.ProtocolError('unexpected header node "' + child.tag + '"'));
- };
+ uid = Math.uuid(null, 16);
+ privateItems[uid] = t.CalendarItem(item, "+");
+ if (type === "EVENT") {
+ privateItems[uid].id = new CalendarEventId(uid);
+ } else {
+ privateItems[uid].id = uid;
+ }
+ privateItems[uid].lastModificationDate = new TZDate();
- commands.push(state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : session.info.pendingMsgID,
- cmdRef : 0,
- sourceRef : xsync.getchildren()[0].findtext('Source/LocURI'),
- targetRef : xsync.getchildren()[0].findtext('Target/LocURI'),
- statusOf : constant.CMD_SYNCHDR,
- statusCode : statusCode
- }));
+ external.id = privateItems[uid].id;
+ external.lastModificationDate = privateItems[uid].lastModificationDate;
- // and now evaluate the SyncBody
+ saveCalendarItems();
- var chkcmds = _.filter(lastcmds, function(e) {
- return e.name != constant.CMD_STATUS && e.name != constant.CMD_FINAL;
+ // set the calendarId of the item
+ item.__defineGetter__("calendarId", function () {
+ return calendarId;
});
- // for each "sync" command, search for sub-commands
- // todo: should this be generalized to search for any sub-commands?...
- _.each(chkcmds, function(e) {
- if ( e.name != constant.CMD_SYNC || ! e.data || e.data.length <= 0 )
- return;
- _.each(e.data, function(sub) { chkcmds.push(sub); });
+ item.__defineGetter__("id", function () {
+ return external.id;
});
- var children = xsync.getchildren()[1].getchildren();
+ item.__defineGetter__("lastModificationDate", function () {
+ return external.lastModificationDate;
+ });
- // first, check all the 'Status' commands
+ window.setTimeout(function () {
+ for (var i in _watchers) {
+ _watchers[i].onitemsadded([item]);
+ }
+ }, 1);
+ }
- var consumeStatus = function(cb) {
+ function addBatch(items, successCallback, errorCallback) {
+ if (!_security.addBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- common.cascade(children, function(child, cb) {
+ t.Calendar("addBatch", arguments, true);
- if ( child.tag != constant.CMD_STATUS )
- return cb();
+ window.setTimeout(function () {
+ var i, j, uid, external = [];
- cname = child.findtext('Cmd');
+ for (i in items) {
+ uid = Math.uuid(null, 16);
+ privateItems[uid] = utils.copy(items[i]);
- var blen = chkcmds.length;
- var chkcmd = null;
- var chkerr = null;
+ if (type === "EVENT") {
+ privateItems[uid].id = new CalendarEventId(uid);
+ } else {
+ privateItems[uid].id = uid;
+ }
- chkcmds = _.filter(chkcmds, function(cmd) {
- if ( chkerr )
- return;
- if ( cmd.cmdID != child.findtext('CmdRef')
- || cmd.name != cname
- || lastcmds[0].msgID != child.findtext('MsgRef') )
- return true;
- if ( chkcmd )
- chkerr = new Error('unexpected error: multiple check commands match status command');
- chkcmd = cmd;
- return false;
- });
+ external[i] = {};
+ external[i].id = privateItems[uid].id;
+ external[i].lastModificationDate = new TZDate();
- if ( chkerr )
- return cb(chkerr);
+ items[i].__defineGetter__("calendarId", function () {
+ return calendarId;
+ });
- if ( chkcmds.length >= blen )
- return cb(new common.ProtocolError(
- 'unexpected status node "s' + session.info.id + '.m' + child.findtext('MsgRef')
- + '.c' + child.findtext('CmdRef') + ' cmd=' + cname + '"'));
+ items[i].__defineGetter__("id", function () {
+ return external[i].id;
+ });
- // TODO: check for unknown elements (and complain?)...
+ items[i].__defineGetter__("lastModificationDate", function () {
+ return external[i].lastModificationDate;
+ });
+ }
- var code = common.int(child.findtext('Data'));
+ saveCalendarItems();
- if ( code == constant.STATUS_MISSING_CREDENTIALS )
- {
- var authtype = child.findtext('Chal/Meta/Type');
- var attrs = {auth: {type: authtype}};
- return cb(badStatus(child, common.CredentialsRequired, attrs));
+ if (successCallback) {
+ successCallback(items);
}
-
- if ( code == constant.STATUS_INVALID_CREDENTIALS )
- {
- // TODO: get the auth type... from where??...
- var authtype = child.findtext('Chal/Meta/Type');
- var attrs = {auth: {type: authtype}};
- return cb(badStatus(child, common.InvalidCredentials, attrs));
+ for (j in _watchers) {
+ _watchers[j].onitemsadded(items);
}
+ }, 1);
+ }
- var targetRef = child.findtext('TargetRef');
- if ( targetRef )
- {
- // note: doing a normUri on chkcmd.target because it could be "./devinf12"...
- if ( session.peer.normUri(targetRef) != session.peer.normUri(chkcmd.target) )
- return cb(new common.ProtocolError('unexpected target-ref "'
- + targetRef + '" != "' + chkcmd.target
- + '" for command "' + cname + '"'));
- }
+ function update(item, updateAllInstances) {
+ var calendarItem, attr, uid;
- var sourceRef = child.findtext('SourceRef');
- if ( sourceRef )
- {
- // note: doing a normUri on chkcmd.source because it could be "./devinf12"...
- if ( cname == constant.CMD_SYNCHDR )
- {
- // this is a little odd, but syncevolution strips the sessionid path
- // parameter off for some reason, so compensating here...
- if ( _.indexOf([session.adapter.normUri(chkcmd.source),
- session.info.effectiveID,
- session.info.returnUrl],
- session.adapter.normUri(sourceRef)) < 0
- && session.adapter.normUri(chkcmd.source).indexOf(session.adapter.normUri(sourceRef)) != 0 )
- return cb(new common.ProtocolError('unexpected source-ref "'
- + sourceRef + '" != "' + chkcmd.source
- + '" for command "' + cname + '"'));
- }
- else
- {
- if ( session.adapter.normUri(sourceRef) != session.adapter.normUri(chkcmd.source) )
- return cb(new common.ProtocolError('unexpected source-ref "'
- + sourceRef + '" != "' + chkcmd.source
- + '" for command "' + cname + '"'));
- }
- }
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // todo: any other common elements?...
+ t.Calendar("update", arguments);
- switch ( cname )
- {
+ uid = (type === "EVENT") ? item.id.uid : item.id;
+ if (!isValidCalendarItemId(uid))
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- case constant.CMD_SYNCHDR:
- {
- if ( code != constant.STATUS_OK && code != constant.STATUS_AUTHENTICATION_ACCEPTED )
- return cb(badStatus(child));
- if ( code == constant.STATUS_AUTHENTICATION_ACCEPTED )
- {
- // TODO: there is currently nothing that can "reset" the
- // authAccepted flag... there should be a trap such
- // that if an auth fails, then authAccepted gets set
- // to false.
- session.info.authAccepted = true;
- }
- return cb();
- }
+ if (updateAllInstances === undefined || updateAllInstances === null) {
+ updateAllInstances = true;
+ }
- case constant.CMD_ALERT:
- {
- if ( code == constant.STATUS_OK )
- // TODO: do something with the Item/Data/Anchor/Next?...
- return cb();
- if ( code == constant.STATUS_REFRESH_REQUIRED && ! session.isServer )
- {
- // TODO: support the ability for the UA to control which kind of
- // refresh to do (slow-sync, client-refresh, server-refresh)
- return cb();
- }
- return cb(badStatus(child));
- }
+ if ((type === "EVENT") && !updateAllInstances) {
+ calendarItem = createCalendarItem();
- case constant.CMD_GET:
- {
- if ( code != constant.STATUS_OK )
- return cb(badStatus(child));
- return cb();
- }
+ for (attr in privateItems[uid]) {
+ if (attr !== "id" && attr !== "lastModificationDate") {
+ if (item[attr] !== undefined)
+ calendarItem[attr] = utils.copy(item[attr]);
+ else
+ calendarItem[attr] = utils.copy(privateItems[uid][attr]);
+ }
+ }
- case constant.CMD_PUT:
- {
- if ( code != constant.STATUS_OK )
- return cb(badStatus(child));
- return cb();
- }
+ add(calendarItem);
+ } else {
+ for (attr in privateItems[uid]) {
+ if ((attr !== "id") && (attr !== "lastModificationDate") && (item[attr] !== undefined))
+ privateItems[uid][attr] = utils.copy(item[attr]);
+ }
+ window.setTimeout(function () {
+ var i;
- case constant.CMD_RESULTS:
- {
- if ( code != constant.STATUS_OK )
- return cb(badStatus(child));
- return cb();
- }
+ for (i in _watchers) {
+ _watchers[i].onitemsupdated([utils.copy(privateItems[uid])]);
+ }
+ }, 1);
+ }
+ saveCalendarItems();
+ }
- case constant.CMD_SYNC:
- {
- // todo: should this be moved into the synchronizer as a "settle" event?...
- var ds = session.info.dsstates[session.adapter.normUri(chkcmd.source)]
- if ( code != constant.STATUS_OK )
- {
- // check for server-side errors...
- if ( code >= 500 && code < 600 && child.findtext('Item/Data') )
- {
- ds.action = 'error';
- ds.error = getError(child);
- ds.stats.peerErr += 1;
- return cb();
- }
- return cb(badStatus(child));
- }
- if ( ds.action == 'send' )
- {
- if ( session.isServer )
- {
- ds.action = 'save';
- return cb();
- }
- ds.action = common.oneWayOut(session, ds.mode) ? 'done' : 'recv';
- return cb();
- }
- return cb(new common.ProtocolError('unexpected sync state for action=' + ds.action));
- }
+ function updateBatch(items, successCallback, errorCallback,
+ updateAllInstances) {
+ if (!_security.updateBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- case constant.CMD_ADD:
- case constant.CMD_REPLACE:
- case constant.CMD_DELETE:
- {
- var scmd = state.makeCommand({
- name : cname,
- msgID : hdrcmd.msgID,
- cmdID : child.findtext('CmdID'),
- sourceRef : sourceRef,
- targetRef : targetRef,
- data : code
- });
+ t.Calendar("updateBatch", arguments, true);
- session.context.synchronizer.settle(
- session, scmd, chkcmd, child,
- function(err, cmds) {
- if ( err )
- return cb(err);
- _.each(cmds, function(cmd) { commands.push(cmd); });
- return cb();
- });
- return;
+ window.setTimeout(function () {
+ var i, j, attr, calendarItem, updatedItems = [], uid;
+
+ for (i in items) {
+ uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
+ if (!uid || !privateItems[uid]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
}
+ return;
+ }
+ }
- case constant.CMD_MAP:
- {
- if ( session.isServer )
- return cb(new common.ProtocolError(
- 'unexpected server-side status for command "' + cname + '"'));
- if ( code != constant.STATUS_OK )
- return cb(badStatus(child));
- return cb();
+ if (updateAllInstances) {
+ for (i in privateItems) {
+ for (j in items) {
+ uid = (type === "EVENT") ? items[j].id.uid : items[j].id;
+ if (i === uid) {
+ for (attr in privateItems[i]) {
+ if (attr !== "id" && attr !== "lastModificationDate" && items[j][attr] !== undefined)
+ privateItems[i][attr] = utils.copy(items[j][attr]);
+ }
+ saveCalendarItems();
+ updatedItems.push(utils.copy(privateItems[i]));
+ }
}
+ }
+ } else {
+ for (i in items) {
+ calendarItem = createCalendarItem();
- default:
- {
- return cb(new common.ProtocolError('unexpected status for command "' + cname + '"'));
+ uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
+ for (attr in privateItems[uid]) {
+ if (attr !== "id" && attr !== "lastModificationDate") {
+ if (items[i][attr] !== undefined)
+ calendarItem[attr] = utils.copy(items[i][attr]);
+ else
+ calendarItem[attr] = utils.copy(privateItems[uid][attr]);
+ }
}
+ add(calendarItem);
+ updatedItems.push(utils.copy(calendarItem));
+ }
}
- }, cb);
-
- };
-
- // second, check all the non-'Status' commands
-
- var consumeCommands = function(cb) {
+ saveCalendarItems();
+ if (successCallback) {
+ successCallback();
+ }
+ for (i in _watchers) {
+ _watchers[i].onitemsupdated(utils.copy(updatedItems));
+ }
+ }, 1);
+ }
- var gotFinal = false;
+ function remove(id) {
+ var isFound = false, i, uid;
- common.cascade(children, function(child, cb) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ t.Calendar("remove", arguments);
- if ( child.tag == constant.CMD_STATUS )
- return cb();
+ if (type === "EVENT") {
+ t.CalendarEventId(id);
+ uid = id.uid;
+ } else {
+ t.CalendarTaskId(id);
+ uid = id;
+ }
- if ( child.tag == constant.CMD_FINAL )
- {
- gotFinal = true;
- return cb();
+ for (i in privateItems) {
+ if (i === uid) {
+ delete privateItems[i];
+ isFound = true;
+ break;
}
+ }
+ if (!isFound)
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
- // todo: restrict this to the following commands?...
- // CMD_ALERT, CMD_GET, CMD_PUT,
- // CMD_SYNC, CMD_RESULTS, CMD_MAP
-
- var func = self['_consume_node_' + child.tag.toLowerCase()];
+ saveCalendarItems();
- if ( ! func )
- return cb(new common.ProtocolError('unexpected command node "' + child.tag + '"'));
+ window.setTimeout(function () {
+ var i;
- try{
+ for (i in _watchers) {
+ _watchers[i].onitemsremoved([id]);
+ }
+ }, 1);
+ }
- func.call(self, session, lastcmds, xsync, child, function(err, cmds) {
- if ( err )
- return cb(err);
- _.each(cmds, function(cmd) { commands.push(cmd); });
- return cb();
- });
+ function removeBatch(ids, successCallback, errorCallback) {
+ if (!_security.removeBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- }catch(e){
- // log.error('failed invoking protocol sub-consumption of "%s": %s', child.tag, e);
- // log.error(' ' + stacktrace({e: e}).join('\n '));
- return cb(new common.InternalError(
- 'failed invoking protocol sub-consumption of "' + child.tag + '": ' + e, e));
- }
+ t.Calendar("removeBatch", arguments, true);
- }, function(err) {
+ window.setTimeout(function () {
+ var i, uid;
- if ( err )
- return cb(err);
+ for (i in ids) {
+ uid = (type === "EVENT") ? ids[i].uid : ids[i];
- if ( ! gotFinal )
- {
- commands.push(state.makeCommand({
- name : constant.CMD_ALERT,
- cmdID : session.nextCmdID(),
- data : constant.STATUS_NEXT_MESSAGE,
- source : session.adapter.devID,
- target : session.peer.devID,
- }));
+ if (!privateItems[uid]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
}
+ }
- return cb();
+ for (i in ids) {
+ uid = (type === "EVENT") ? ids[i].uid : ids[i];
+ delete privateItems[uid];
+ }
+ saveCalendarItems();
+ if (successCallback) {
+ successCallback();
+ }
- });
+ for (i in _watchers) {
+ _watchers[i].onitemsremoved(utils.copy(ids));
+ }
+ }, 1);
+ }
- };
+ function find(successCallback, errorCallback, filter, sortMode) {
+ if (!_security.find) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // do it!
+ t.Calendar("find", arguments, true);
- consumeStatus(function(err) {
+ window.setTimeout(function () {
+ var i, calendarItems = [], result = [];
- if ( err )
- return cb(err);
+ for (i in privateItems) {
+ calendarItems.push(privateItems[i]);
+ }
+ if (calendarItems.length > 0) {
+ result = tizen1_utils.query(calendarItems, filter, sortMode);
+ }
+ successCallback(result);
+ }, 1);
+ }
- // TODO: is this right?... or should i be getting pissed off and
- // raising hell that all my commands were not addressed?...
+ function addChangeListener(successCallback) {
+ var watchId;
- _.each(chkcmds, function(chkcmd) {
- commands.push(chkcmd);
- });
+ if (!_security.addChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- return consumeCommands(function(err) {
- if ( err )
- return cb(err);
- return cb(null, commands);
- });
+ t.Calendar("addChangeListener", arguments);
- });
+ watchId = ++defaultWatchId;
+ _watchers[watchId] = successCallback;
- },
+ return watchId;
+ }
- //-------------------------------------------------------------------------
- _consume_node_get: function(session, lastcmds, xsync, xnode, cb) {
- var cttype = xnode.findtext('Meta/Type');
- var target = xnode.findtext('Item/Target/LocURI');
- if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
- && session.adapter.normUri(target) == constant.URI_DEVINFO_1_2 )
- return this._consume_node_get_devinf12(session, lastcmds, xsync, xnode, cb);
- // todo: make error status node...
- cb(new common.ProtocolError(
- 'unexpected "' + constant.CMD_GET + '" command for local "' + target + '"'));
- },
+ function removeChangeListener(watchId) {
+ if (!_security.removeChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- _consume_node_get_devinf12: function(session, lastcmds, xsync, xnode, cb) {
- var ret = [];
- ret.push(state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : session.info.pendingMsgID,
- cmdRef : xnode.findtext('CmdID'),
- statusOf : xnode.tag,
- statusCode : constant.STATUS_OK,
- targetRef : xnode.findtext('Item/Target/LocURI')
- }));
- ret.push(state.makeCommand({
- name : constant.CMD_RESULTS,
- cmdID : session.nextCmdID(),
- msgRef : session.info.pendingMsgID,
- cmdRef : xnode.findtext('CmdID'),
- type : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
- source : './' + constant.URI_DEVINFO_1_2,
- data : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
- _.values(session.adapter._stores))
+ if (!_watchers[watchId])
+ return;
- }));
- cb(null, ret);
- },
+ delete _watchers[watchId];
+ }
- //-------------------------------------------------------------------------
- _consume_node_put: function(session, lastcmds, xsync, xnode, cb) {
- var cttype = xnode.findtext('Meta/Type');
- var source = xnode.findtext('Item/Source/LocURI');
- if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
- && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
- return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
- // todo: make error status node...
- cb(new common.ProtocolError(
- 'unexpected "' + constant.CMD_PUT + '" command for remote "' + source + '"'));
- },
+ loadCalendarItems(type, privateItems, storageItems);
- //-------------------------------------------------------------------------
- _consume_node_put_devinf12: function(session, lastcmds, xsync, xnode, cb) {
- var xdev = xnode.find('Item/Data/DevInf');
- var res = devinfo.DevInfo.fromSyncML(xdev);
- session.peer._setRemoteInfo(res[0], res[1], function(err) {
- if ( err )
- return cb(err);
+ this.__defineGetter__("id", function () {
+ return calendarId;
+ });
+ this.__defineGetter__("name", function () {
+ return name;
+ });
- var okcmd = state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : xsync.findtext('SyncHdr/MsgID'),
- cmdRef : xnode.findtext('CmdID'),
- sourceRef : xnode.findtext('Item/Source/LocURI'),
- statusOf : xnode.tag,
- statusCode : constant.STATUS_OK
- });
+ this.get = get;
+ this.add = add;
+ this.addBatch = addBatch;
+ this.update = update;
+ this.updateBatch = updateBatch;
+ this.remove = remove;
+ this.removeBatch = removeBatch;
+ this.find = find;
+ this.addChangeListener = addChangeListener;
+ this.removeChangeListener = removeChangeListener;
+};
- if ( session.isServer )
- return cb(null, [okcmd]);
+CalendarStorage = function (calendar) {
+ this.id = calendar.id;
+ this.name = calendar.name;
+};
- // TODO: this should only cause a `recalculate` if any
- // meta-information actually changed...
+CalendarItemsStorage = function (privateItems) {
+ var itemsStorage = {}, i, attr;
- session.context.router.recalculate(session.adapter, session.peer, function(err) {
- if ( err )
- return cb(err);
- session.context.synchronizer.initStoreSync(session, function(err) {
- if ( err )
- return cb(err);
+ for (i in privateItems) {
+ itemsStorage[i] = {};
+ for (attr in privateItems[i]) {
+ //TODO: should be
+ // if (privateItems[i][attr] instanceof TZDate) {
+ //But, we used "utils.copy" before store the item to privateItems list.
+ //So the constructor information all lost
+ if ((attr === "startDate" || attr === "endDate" || attr === "dueDate" || attr === "completedDate" || attr === "lastModificationDate") &&
+ (privateItems[i][attr])) {
- // TODO: the call to _setRemoteInfo makes the peer
- // "dirty" without saving changes to the model...
- // make sure the `save` executed in Adapter.sync()
- // or Adapter.handleRequest() appropriately causes
- // objects to save themselves to the model...
+ itemsStorage[i][attr] = privateItems[i][attr].toString();
+ } else if (typeof privateItems[i] !== "function") {
+ itemsStorage[i][attr] = privateItems[i][attr];
+ }
+ }
+ }
- // session.adapter._save(session.txn(), function(err) {
- // if ( err )
- // return cb(err);
+ return itemsStorage;
+};
- return cb(null, [okcmd]);
+module.exports = _self;
- // });
+});
+define('ripple/platform/tizen/2.0/DownloadRequest', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 t = require('ripple/platform/tizen/2.0/typecast'),
+ DownloadRequest;
- //-------------------------------------------------------------------------
- _consume_node_results: function(session, lastcmds, xsync, xnode, cb) {
- var cttype = xnode.findtext('Meta/Type');
- var source = xnode.findtext('Item/Source/LocURI');
- if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
- && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
- return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
- // todo: make error status node...
- return cb(new common.ProtocolError('unexpected "' + constant.CMD_RESULTS
- + '" command for remote "' + source + '"'))
- },
+DownloadRequest = function (url, destination, fileName, networkType,
+ httpHeader) {
+ var downloadRequest = {};
- //-------------------------------------------------------------------------
- _consume_node_alert: function(session, lastcmds, xsync, xnode, cb) {
- var code = common.int(xnode.findtext('Data'));
- var statusCode = constant.STATUS_OK
- switch ( code )
- {
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_SLOW_SYNC:
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- case constant.ALERT_REFRESH_FROM_SERVER:
- // todo: these should only be received out-of-band: right?...
- // case constant.ALERT_TWO_WAY_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
- {
- break;
- }
- default:
- {
- if ( session.isServer && code == constant.STATUS_RESUME )
- {
- code = constant.ALERT_SLOW_SYNC;
- }
- else
- {
- return cb(new common.FeatureNotSupported(
- 'unimplemented sync mode '
- + code + ' ("' + common.mode2string(code) + '")'));
- }
- }
- }
+ t.DownloadRequest(arguments, this);
- if ( session.isServer )
- {
- // TODO: if this is the server, we need to validate that the requested
- // sync mode is actually feasible... i.e. check:
- // - do the anchors match?
- // - have we bound the datastores together?
- // - is there a pending sync?
+ this.__defineGetter__("url", function () {
+ return downloadRequest.url;
+ });
+ this.__defineSetter__("url", function (val) {
+ try {
+ downloadRequest.url = t.DOMString(val);
+ } catch (e) {
}
+ });
- var uri = session.adapter.normUri(xnode.findtext('Item/Target/LocURI'));
- var ruri = session.peer.normUri(xnode.findtext('Item/Source/LocURI'));
-
- // TODO: this should really be done by the synchronizer... as it can
- // then also do a lot of checks - potentially responding with
- // an error...
-
- var getDS = function(cb) {
- if ( session.isServer )
- {
- var ds = session.info.dsstates[uri];
- if ( ds )
- {
- ds.action = 'alert';
- return cb(null, ds);
- }
-
- var peerStore = session.peer.getStore(ruri);
- if ( ! peerStore )
- return cb(new common.ProtocolError(
- 'request to synchronize unknown remote client URI "' + ruri
- + '" (to local server URI "' + uri + '")'));
-
- // todo: if already correctly bound, then we don't need to re-bind
- // if ( peerStore._getBinding() )
- // {
- // log.critical('(currently bound)');
- // }
- // else
- // log.critical('(currently unbound)');
+ this.__defineGetter__("networkType", function () {
+ return downloadRequest.networkType;
+ });
+ this.__defineSetter__("networkType", function (val) {
+ try {
+ downloadRequest.networkType = t.DownloadNetworkType(val, "?");
+ } catch (e) {
+ }
+ });
- session.peer.setRoute(uri, ruri, true, function(err) {
- if ( err )
- return cb(err);
- var peerStore = session.peer.getStore(ruri);
- var ds = state.makeStoreSyncState({
- uri : uri,
- peerUri : ruri,
- lastAnchor : peerStore._getBinding().localAnchor,
- mode : null,
- action : 'alert'
- });
- session.info.dsstates[uri] = ds;
- return cb(null, ds);
- });
- return;
- }
- else
- {
- var ds = session.info.dsstates[uri];
- if ( ! ds )
- return cb(new common.ProtocolError('request for unreflected local datastore "'
- + uri + '"'));
- ds.action = 'send';
- if ( code == ds.mode )
- return cb(null, ds);
+ this.destination = destination || "";
+ this.fileName = fileName || "";
+ this.httpHeader = httpHeader || {};
- var uaEvent = {
- session : session,
- uri : uri,
- peerUri : ruri,
- modeReq : ds.mode,
- modeRes : code
- };
- session.ua.acceptSyncModeSwitch(uaEvent, function(err) {
- if ( err )
- {
- return cb(err);
- }
- if ( session.context.listener )
- session.context.listener(uaEvent);
- return cb(null, ds);
- });
- }
- };
+ downloadRequest.url = url;
+ downloadRequest.networkType = networkType || "ALL";
+};
+module.exports = DownloadRequest;
- getDS(function(err, ds) {
+});
+define('ripple/platform/tizen/2.0/networkbearerselection', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if ( err )
- return cb(err);
+var event = require('ripple/event'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ _security = {
+ "http://tizen.org/privilege/networkbearerselection":
+ ["requestRouteToHost", "releaseRouteToHost"]
+ },
+ _self;
- ds.mode = code;
- ds.peerLastAnchor = xnode.findtext('Item/Meta/Anchor/Last', null);
- ds.peerNextAnchor = xnode.findtext('Item/Meta/Anchor/Next', null);
+_self = function () {
+ var networkBearerSelection;
- if ( ds.peerLastAnchor != session.peer.getStore(ruri)._getBinding().remoteAnchor )
- {
- ds.peerLastAnchor = null;
- switch ( ds.mode )
- {
- case constant.ALERT_SLOW_SYNC:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_SERVER:
- {
- break;
- }
- default:
- {
- if ( session.isServer )
- {
- ds.mode = constant.ALERT_SLOW_SYNC;
- statusCode = constant.STATUS_REFRESH_REQUIRED;
- }
- else
- {
- // todo: should i assume that the server knows something
- // that i don't and just go along with it?...
- return cb(new common.ProtocolError(
- 'server-side requested inappropriate ' + common.mode2string(ds.mode)
- + ' sync mode on unbound datastore "' + uri + '"'));
- }
- }
+ function requestRouteToHost(networkType, domainName, successCallback, errorCallback) {
+ var evNetworkOpened = "NO_" + networkType + "_" + domainName,
+ evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
+
+ if (!_security.requestRouteToHost) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
+
+ t.NetworkBearerSelection("requestRouteToHost", arguments);
+
+ if (!domainName) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
}
- return cb(null, [state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : xsync.findtext('SyncHdr/MsgID'),
- cmdRef : xnode.findtext('CmdID'),
- targetRef : xnode.findtext('Item/Target/LocURI'),
- sourceRef : xnode.findtext('Item/Source/LocURI'),
- statusOf : xnode.tag,
- statusCode : statusCode,
- // todo: syncevolution does not echo the remote last anchor... why not?
- lastAnchor : ds.peerLastAnchor,
- nextAnchor : ds.peerNextAnchor
- })]);
+ event.once(evNetworkOpened, function (isOpened) {
+ if (!isOpened)
+ return;
+ successCallback.onsuccess();
});
+ event.once(evNetworkDisconnected, successCallback.ondisconnected);
+ event.trigger("NetworkRequest", [networkType, domainName]);
+ }
- },
+ function releaseRouteToHost(networkType, domainName, successCallback, errorCallback) {
+ var evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
- //-------------------------------------------------------------------------
- _consume_node_sync: function(session, lastcmds, xsync, xnode, cb) {
- var self = this;
- var uri = xnode.findtext('Target/LocURI');
- var store = session.adapter.getStore(session.adapter.normUri(uri));
- var ds = session.info.dsstates[session.adapter.normUri(uri)];
- var commands = [state.makeCommand({
- name : constant.CMD_SYNC,
- msgID : xsync.findtext('SyncHdr/MsgID'),
- cmdID : xnode.findtext('CmdID'),
- source : xnode.findtext('Source/LocURI'),
- target : uri,
- data : [],
- })];
- var noc = common.int(xnode.findtext('NumberOfChanges'));
- if (noc !== undefined) {
- changednum = noc;
- _counts = 0;
- }
- common.cascade(xnode.getchildren(), function(child, cb) {
- switch ( child.tag )
- {
- case 'CmdID':
- case 'Target':
- case 'Source':
- case 'NumberOfChanges':
- {
- return cb();
- }
- case constant.CMD_ADD:
- case constant.CMD_REPLACE:
- case constant.CMD_DELETE:
- {
- var func = self['_consume_sync_' + child.tag.toLowerCase()];
- func.call(self, session, lastcmds, store, xsync, child, function(err, cmds) {
- if ( err )
- return cb(err);
- _.each(cmds, function(cmd) { commands[0].data.push(cmd); });
- return cb();
- });
- return;
- }
- default:
- {
- return cb(new common.ProtocolError('unexpected sync command "' + child.tag + '"'));
- }
+ if (!_security.releaseRouteToHost) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- }, function(err) {
- if ( err )
- return cb(err);
- // confirm that i received the right number of changes...
- /*
- if ( noc != undefined && noc != commands[0].data.length )
- return cb(new common.ProtocolError('number-of-changes mismatch (received '
- + commands[0].data.length + ', expected '
- + noc + ')'));
- */
- _counts = _counts + commands[0].data.length;
- if ( ds.action != 'error' )
- {
- if ( ! session.isServer )
- {
- if ( ds.action != 'recv' )
- return cb(new common.ProtocolError('unexpected sync state for URI "'
- + uri + '": action=' + ds.action));
- if (changednum != undefined && changednum <= _counts) {
- ds.action = 'done';
- changednum = undefined;
- _counts = 0;
- }
- }
- else
- {
- if ( ds.action != 'alert' )
- return cb(new common.ProtocolError(
- 'unexpected sync state for URI "' + uri + '": action=' + ds.action));
- ds.action = common.oneWayIn(session, ds.mode) ? 'save' : 'send';
- }
+
+ t.NetworkBearerSelection("releaseRouteToHost", arguments);
+
+ if (!domainName) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
}
- return session.context.synchronizer.reactions(session, commands, cb);
- });
- },
+ return;
+ }
- //-------------------------------------------------------------------------
- _consume_xnode2item: function(session, lastcmds, store, xsync, xnode, cb) {
- var ctype = xnode.findtext('Meta/Type');
- // todo: can the version be specified in the Meta tag?... maybe create an
- // extension to SyncML to communicate this?...
- var ctver = null;
- var format = xnode.findtext('Meta/Format');
- var xitem = xnode.findall('Item/Data');
- if ( xitem.length > 1 )
- return cb(new common.ProtocolError(
- '"' + xnode.tag + '" command with non-singular item data nodes'));
- if ( xitem.length < 1 )
- return cb(new common.ProtocolError(
- '"' + xnode.tag + '" command with missing data node'));
- var xitem = xitem[0];
- // todo: confirm that getchildren only returns element nodes...
- if ( xitem.getchildren().length == 1 )
- data = xitem.getchildren()[0];
- else
- {
- data = xitem.text;
- if ( format == constant.FORMAT_B64 )
- data = base64.decode(data);
+ event.once(evNetworkDisconnected, successCallback);
+ event.trigger("NetworkRelease", [networkType, domainName]);
+ }
+
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
}
- return store.agent.loadsItem(data, ctype, ctver, cb);
- },
+ }
- //-------------------------------------------------------------------------
- _consume_sync_add: function(session, lastcmds, store, xsync, xnode, cb) {
- this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
- if ( err )
- return cb(err);
- return cb(null, [state.makeCommand({
- name : constant.CMD_ADD,
- msgID : xsync.findtext('SyncHdr/MsgID'),
- cmdID : xnode.findtext('CmdID'),
- source : xnode.findtext('Item/Source/LocURI'),
- sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
- targetParent : xnode.findtext('Item/TargetParent/LocURI'),
- data : item
- })]);
- });
- },
+ networkBearerSelection = {
+ requestRouteToHost: requestRouteToHost,
+ releaseRouteToHost: releaseRouteToHost,
+ handleSubFeatures: handleSubFeatures
+ };
- //-------------------------------------------------------------------------
- _consume_sync_replace: function(session, lastcmds, store, xsync, xnode, cb) {
- this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
- if ( err )
- return cb(err);
- return cb(null, [state.makeCommand({
- name : constant.CMD_REPLACE,
- msgID : xsync.findtext('SyncHdr/MsgID'),
- cmdID : xnode.findtext('CmdID'),
- source : xnode.findtext('Item/Source/LocURI'),
- sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
- target : xnode.findtext('Item/Target/LocURI'),
- targetParent : xnode.findtext('Item/TargetParent/LocURI'),
- data : item
- })]);
- });
- },
+ return networkBearerSelection;
+};
- //-------------------------------------------------------------------------
- _consume_sync_delete: function(session, lastcmds, store, xsync, xnode, cb) {
- return cb(null, [state.makeCommand({
- name : constant.CMD_DELETE,
- msgID : xsync.findtext('SyncHdr/MsgID'),
- cmdID : xnode.findtext('CmdID'),
- source : xnode.findtext('Item/Source/LocURI'),
- sourceParent : xnode.findtext('Item/SourceParent/LocURI'),
- target : xnode.findtext('Item/Target/LocURI'),
- targetParent : xnode.findtext('Item/TargetParent/LocURI')
- })]);
- },
+module.exports = _self;
- // #----------------------------------------------------------------------------
- // def makeStatus(self, session, xsync, xnode, status=constant.STATUS_OK, **kw):
- // return state.Command(
- // name = constant.CMD_STATUS,
- // cmdID = session.nextCmdID(),
- // msgRef = xsync.findtext('SyncHdr/MsgID'),
- // cmdRef = xnode.findtext('CmdID'),
- // statusOf = xnode.tag,
- // statusCode = status,
- // **kw
- // )
+});
+define('ripple/platform/tizen/2.0/geoBackend_local', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- //-------------------------------------------------------------------------
- _consume_node_map: function(session, lastcmds, xsync, xnode, cb) {
- if ( ! session.isServer )
- return cb(new common.ProtocolError(
- 'unexpected "Map" command received by client-side SyncML peer'));
- // TODO: convert the sender-side to support command.items like
- // this as well...
- var cmd = state.makeCommand({
- name : constant.CMD_MAP,
- msgID : xsync.findtext('SyncHdr/MsgID'),
- cmdID : xnode.findtext('CmdID'),
- source : xnode.findtext('Source/LocURI'),
- target : xnode.findtext('Target/LocURI'),
- items : []
- });
- _.each(xnode.findall('MapItem'), function(xnode) {
- // todo: support hierarchical sync...
- cmd.items.push({
- source : xnode.findtext('Source/LocURI'),
- // sourceParent : xnode.findtext('SourceParent/LocURI'),
- target : xnode.findtext('Target/LocURI'),
- // targetParent : xnode.findtext('TargetParent/LocURI')
- });
- });
- return session.context.synchronizer.reactions(session, [cmd], cb);
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ PendingObject = require('ripple/platform/tizen/2.0/pendingObject'),
+ PendingOperation = require('ripple/platform/tizen/2.0/pendingoperation'),
+ GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult'),
+ _GEO_OBJECTS = "tizen1.0-geocode-objects",
+ _get, _save, _geoList_init, GeoEntry,
+ _checkAddressType, _transAddressStr,
+ _geocodeByString, _findCoordsByString, _geocodeByAddress,
+ _reverseGeocodeBySimple, _reverseGeocodeByGeo, _checkCoordsType,
+ _geoList = [],
+ _PENDING_TIME = 10;
+
+function _get() {
+ var geoList = [],
+ data = db.retrieveObject(_GEO_OBJECTS);
+
+ utils.forEach(data, function (geo) {
+ geoList.push(geo);
+ });
+ return geoList;
+}
+
+function _save() {
+ db.saveObject(_GEO_OBJECTS, _geoList);
+}
+
+function _geoList_init() {
+ var entry;
+ _geoList = _get();
+
+ /* Put some default data if database is empty */
+ if (_geoList.length === 0) {
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ country : "UK",
+ region : "London",
+ county : "Lambeth",
+ city : "London",
+ street : "Westminster Bridge Road",
+ streetNumber : "1",
+ premises : "Riverside Building",
+ additionalInformation : "London Eye",
+ postalCode : "SE1 7PB"
+ }),
+ new lbs.GeoCoordinates({
+ latitude : 51.510452,
+ longitude : -0.119820,
+ altitude : 0,
+ accuracy : 0,
+ altitudeAccuracy : 0,
+ heading : 0,
+ speed : 0
+ }));
+ _geoList.push(entry);
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ country : "UK",
+ city : "London",
+ street : "Baker Street",
+ streetNumber : "221B",
+ postalCode : "NW1 6XE"
+ }),
+ new lbs.GeoCoordinates({
+ latitude : 51.524552,
+ longitude : -0.158615,
+ altitude : 0,
+ accuracy : 0,
+ altitudeAccuracy : 0,
+ heading : 0,
+ speed : 0
+ }));
+ _geoList.push(entry);
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ country : "US",
+ region : "OR",
+ city : "Portland",
+ street : "SE Water Ave",
+ streetNumber : "1945",
+ additionalInformation : "OMSI",
+ }),
+ new lbs.GeoCoordinates({
+ latitude : 45.508490,
+ longitude : -122.665953,
+ altitude : 0,
+ accuracy : 0,
+ altitudeAccuracy : 0,
+ heading : 0,
+ speed : 0
+ }));
+ _geoList.push(entry);
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ country : "US",
+ region : "OR",
+ city : "Portland",
+ street : "NW Pittock Drive",
+ streetNumber : "3229",
+ additionalInformation : "Pittock Mansion",
+ }),
+ new lbs.GeoCoordinates({
+ latitude : 45.531365,
+ longitude : -122.716255,
+ altitude : 0,
+ accuracy : 0,
+ altitudeAccuracy : 0,
+ heading : 0,
+ speed : 0
+ }));
+ _geoList.push(entry);
+ entry = new GeoEntry(new lbs.StructuredAddress({
+ region : "OR",
+ city : "Hillsboro",
+ street : "NE 25th St",
+ streetNumber : "2111",
+ postalCode : "97124"
+ }),
+ new lbs.GeoCoordinates({
+ latitude : 45.543479,
+ longitude : -122.9621601,
+ altitude : 0,
+ accuracy : 0,
+ altitudeAccuracy : 0,
+ heading : 0,
+ speed : 0
+ }));
+ _geoList.push(entry);
+ _save();
}
+}
+function _pendingOperate(operate) {
+ var pendingObj, pendingOperation, i, argumentVector = [];
-});
+ for (i = 0; i < arguments.length - 1; i++)
+ argumentVector[i] = arguments[i + 1];
-return exports;
+ pendingObj = new PendingObject();
-})();
+ pendingObj.pendingID = window.setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ operate.apply(this, argumentVector);
+ }, _PENDING_TIME);
-module.exports = _self;
+ pendingOperation = new PendingOperation(pendingObj);
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.remoteadapter
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/04
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ return pendingOperation;
+}
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
- adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
- storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
- _self;
+function GeoEntry(addr, coord) {
+ var _self;
+ _self = {
+ address : addr || null,
+ coordinate : coord || null
+ };
+ return _self;
+}
-_self = (function () {
- var exports = {};
+function SortMode() {
+ var _self;
+ _self = {
+ attributeName : "",
+ order : "ASC"
+ };
+ return _self;
+}
- //---------------------------------------------------------------------------
- exports.RemoteAdapter = adapter.Adapter.extend({
+function _transAddressStr(addr) {
+ var str = "";
+ if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
+ str = str + addr.additionalInformation + ", ";
+ if (addr.premises !== null && addr.premises !== undefined)
+ str = str + addr.premises + ", ";
+ if (addr.streetNumber !== null && addr.streetNumber !== undefined)
+ str = str + addr.streetNumber + " ";
+ if (addr.street !== null && addr.street !== undefined)
+ str = str + addr.street + ", ";
+ if (addr.city !== null && addr.city !== undefined)
+ str = str + addr.city + ", ";
+ if (addr.county !== null && addr.county !== undefined)
+ str = str + addr.county + ", ";
+ if (addr.region !== null && addr.region !== undefined)
+ str = str + addr.region + ", ";
+ if (addr.country !== null && addr.country !== undefined)
+ str = str + addr.country + ", ";
+ if (addr.postalCode !== null && addr.postalCode !== undefined)
+ str = str + addr.postalCode;
- //-------------------------------------------------------------------------
- constructor: function(adapter, options) {
+ if (str.lastIndexOf(", ") === str.length - 2)
+ str = str.slice(0, -2);
+ return str;
+}
- //: [read-only] the URL of the remote syncml peer, acting as a server,
- //: to connect to.
- this.url = options.url || null;
+function _concatAddress(addr) {
+ var str = "";
+ if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
+ str = str + addr.additionalInformation + " ";
+ if (addr.premises !== null && addr.premises !== undefined)
+ str = str + addr.premises + " ";
+ if (addr.streetNumber !== null && addr.streetNumber !== undefined)
+ str = str + addr.streetNumber + " ";
+ if (addr.street !== null && addr.street !== undefined)
+ str = str + addr.street + " ";
+ if (addr.city !== null && addr.city !== undefined)
+ str = str + addr.city + " ";
+ if (addr.county !== null && addr.county !== undefined)
+ str = str + addr.county + " ";
+ if (addr.region !== null && addr.region !== undefined)
+ str = str + addr.region + " ";
+ if (addr.country !== null && addr.country !== undefined)
+ str = str + addr.country + " ";
+ if (addr.postalCode !== null && addr.postalCode !== undefined)
+ str = str + addr.postalCode;
- //: [read-only] specifies whether this Adapter represents a local
- //: or remote peer.
- this.isLocal = false;
+ return str;
+}
- //: [read-only] the DevID of the remote syncml peer (which usually
- //: defaults to the URL).
- this.devID = options.devID || options.url || null;
+function _findCoordsByString(address) {
+ var array = [], reg, str, searchAddr, pieces, i;
+ if (address.length === 0)
+ return array;
- //: [read-only] the authentication method to use to identify the local
- //: peer to the remote peer.
- ///TODO: this.auth = options.auth || null;
- this.auth = 'syncml:auth-basic';
+ pieces = address.split(",");
+ searchAddr = "";
+ for (i = 0; i < pieces.length; i++) {
+ searchAddr = searchAddr + pieces[i];
+ }
+ reg = new RegExp(searchAddr, "i");
- //: [read-only] the human-friendly display name of the remote peer.
- this.displayName = options.displayName || null;
+ utils.forEach(_geoList, function (item) {
+ str = _concatAddress(item.address);
+ if (str.search(reg) !== -1)
+ array.push(new GeocodeResult(item.coordinate.latitude, item.coordinate.longitude));
+ });
- //: [read-only] the username to use during credential-based authentication.
- this.username = options.username || null;
+ return array;
+}
- //: [read-only] the password to use during credential-based authentication.
- this.password = options.password || null;
+function _geocodeByString(address, successCB, errorCB, options) {
+ var array;
+ array = _findCoordsByString(address);
+ successCB(array);
+}
- //: [read-only] the peer-wide default value of the maximum
- //: message size.
- this.maxMsgSize = options.maxMsgSize || null;
+function _findCoordsByAddress(addr) {
+ var array = [], select = false, i;
+ for (i = 0; i < _geoList.length; i++) {
+ select = false;
+ if (addr.country !== null && addr.country !== undefined) {
+ if (addr.country === _geoList[i].address.country)
+ select = true;
+ else
+ continue;
+ }
- //: [read-only] the peer-wide default value of the maximum
- //: object size.
- this.maxObjSize = options.maxObjSize || null;
+ if (addr.region !== null && addr.region !== undefined) {
+ if (addr.region === _geoList[i].address.region)
+ select = true;
+ else
+ continue;
+ }
- //: [read-only] the DevInfo object for this remote peer.
- this.devInfo = null;
+ if (addr.county !== null && addr.county !== undefined) {
+ if (addr.county === _geoList[i].address.county)
+ select = true;
+ else
+ continue;
+ }
- this.lastSessionID = options.lastSessionID || null;
+ if (addr.city !== null && addr.city !== undefined) {
+ if (addr.city === _geoList[i].address.city)
+ select = true;
+ else
+ continue;
+ }
- // --- private attributes
- this.id = options.id || common.makeID();
- this._a = adapter;
- this._c = adapter._c;
- this._stores = {};
- this._proxy = null;
+ if (addr.street !== null && addr.street !== undefined) {
+ if (addr.street === _geoList[i].address.street)
+ select = true;
+ else
+ continue;
+ }
- // TODO: filter these options for db-valid only properties...
- this._options = options;
- },
+ if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
+ if (addr.streetNumber === _geoList[i].address.streetNumber)
+ select = true;
+ else
+ continue;
+ }
- //-------------------------------------------------------------------------
- _load: function(cb) {
+ if (addr.premises !== null && addr.premises !== undefined) {
+ if (addr.premises === _geoList[i].address.premises)
+ select = true;
+ else
+ continue;
+ }
- var self = this;
- var model = this._getModel();
+ if (addr.additionalInformation !== null &&
+ addr.additionalInformation !== undefined) {
+ if (addr.additionalInformation === _geoList[i].address.additionalInformation)
+ select = true;
+ else
+ continue;
+ }
- // todo: should this be loading these?...
- // self.displayName = model.displayName;
- // self.devID = model.devID;
+ if (addr.postalCode !== null && addr.postalCode !== undefined) {
+ if (addr.postalCode === _geoList[i].address.postalCode)
+ select = true;
+ else
+ continue;
+ }
- var loadDevInfo = function(cb) {
- var di = new devinfomod.DevInfo(self, model.devInfo);
- di._load(function(err) {
- if ( err )
- return cb(err);
- self.devInfo = di;
- cb();
- });
- };
+ if (select === true) {
+ array.push(new GeocodeResult(_geoList[i].coordinate.latitude, _geoList[i].coordinate.longitude));
+ }
+ }
- var loadStores = function(cb) {
- common.cascade(model.stores, function(e, cb) {
- var store = new storemod.Store(self, e);
- store._load(function(err) {
- if ( err )
- return cb(err);
- self._stores[store.uri] = store;
- return cb();
- });
- }, cb);
- };
+ return array;
+}
- loadDevInfo(function(err) {
- if ( err )
- return cb(err);
- loadStores(cb);
- });
- },
+function _geocodeByAddress(address, successCB, errorCB, options) {
+ var array;
+ array = _findCoordsByAddress(address);
+ successCB(array);
+}
- //-------------------------------------------------------------------------
- _updateModel: function(cb) {
- var self = this;
- if ( ! this._a._model || ! this._a._model.peers )
- return cb(new common.InternalError('peer created on un-initialized adapter'));
- var model = self._getModel();
- // todo: should this be in this._getModel()?...
- if ( ! model )
- {
- model = {
- id: self.id,
- devInfo: null,
- stores: [],
- routes: []
- };
- self._a._model.peers.push(model);
- }
+function _checkAddressType(address) {
+ var str;
+ if (typeof address === "string") {
+ str = "string";
+ } else if (typeof address === "object") {
+ str = "StructuredAddress";
+ } else {
+ str = "typeMismatch";
+ }
+ return str;
+}
- model.isLocal = 0;
- model.url = self.url;
- model.devID = self.devID;
- model.displayName = self.displayName;
- model.auth = self.auth;
- model.username = self.username;
- model.password = self.password;
- model.lastSessionID = self.lastSessionID
- model.maxMsgSize = self.maxMsgSize;
- model.maxObjSize = self.maxObjSize;
+function _checkCoordsType(coord) {
+ var str;
+ /* SimpleCoordinates is a subset of GeoCoordinates.
+ SimpleCoordinates includes latitude, longitude as mandatory fields only.
+ GeoCoordinates not only includes latitude, longitude as mandatory fields
+ but also at least includes one more other optional fields */
+ if (typeof coord !== "object") {
+ str = "typeMismatch";
+ } else if (typeof coord.latitude === "number" &&
+ typeof coord.longitude === "number") {
+ str = "simpleCoordinates";
+ if (typeof coord.altitude === "number" ||
+ typeof coord.accuracy === "number" ||
+ typeof coord.altitudeAccuracy === "number" ||
+ typeof coord.heading === "number" ||
+ typeof coord.speed === "number") {
+ str = "geoCoordinates";
+ }
+ } else {
+ str = "typeMismatch";
+ }
- common.cascade([
+ return str;
+}
- // update the devInfo model
- function(cb) {
- if ( ! self.devInfo )
- return cb();
- return self.devInfo._updateModel(cb);
- },
+function _findReverseGeocode(coords, options) {
+ var array = [], _isStructured = false, i;
+ if (options !== null && options !== undefined) {
+ if (options.resultType === "STRUCTURED") {
+ _isStructured = true;
+ }
+ }
+ for (i = 0; i < _geoList.length; i++) {
+ if (_geoList[i].coordinate.latitude === coords.latitude &&
+ _geoList[i].coordinate.longitude === coords.longitude) {
+ if (coords.altitude) {
+ if (_geoList[i].coordinate.altitude !== coords.altitude)
+ continue;
+ }
+ if (coords.accuracy) {
+ if (_geoList[i].coordinate.accuracy !== coords.accuracy)
+ continue;
+ }
+ if (coords.altitudeAccuracy) {
+ if (_geoList[i].coordinate.altitudeAccuracy !== coords.altitudeAccuracy)
+ continue;
+ }
+ if (coords.heading) {
+ if (_geoList[i].coordinate.heading !== coords.heading)
+ continue;
+ }
+ if (coords.speed) {
+ if (_geoList[i].coordinate.speed !== coords.speed)
+ continue;
+ }
- // update the stores model
- function(cb) {
- // TODO: this should really be the responsibility of the Store class...
- // NOTE: since bindings are not stored in Store, they need to be saved
- // and re-applied.
- // TODO: or, perhaps better, i should purge all unwanted stores
- // instead of doing this brute-force method...
- var bindings = _.object(_.map(model.stores, function(store) {
- return [store.uri, store.binding];
- }));
- model.stores = [];
- common.cascade(_.values(self._stores), function(store, cb) {
- store._updateModel(cb);
- }, function(err) {
- if ( err )
- return cb(err);
- _.each(bindings, function(binding, uri) {
- var store = _.find(model.stores, function(s) { return s.uri == uri; });
- if ( ! store )
- return;
- store.binding = binding;
- });
- return cb();
- });
- },
+ if (_isStructured === true) {
+ array.push(new lbs.StructuredAddress(_geoList[i].address));
+ } else {
+ array.push(_transAddressStr(_geoList[i].address));
+ }
+ }
+ }
+ return array;
+}
- ], cb);
+function _reverseGeocodeByGeo(coordinates, successCB, errorCB, options) {
+ var array, coord;
+ coord = new lbs.GeoCoordinates(coordinates);
+ array = _findReverseGeocode(coord, options);
+ return successCB(array);
+}
- },
+function _reverseGeocodeBySimple(coordinates, successCB, errorCB, options) {
+ var array, coord;
+ coord = new lbs.GeoCoordinates({
+ latitude : coordinates.latitude,
+ longitude : coordinates.longitude
+ });
+ array = _findReverseGeocode(coord, options);
+ return successCB(array);
+}
- //-------------------------------------------------------------------------
- _getModel: function() {
- return _.find(this._a._model.peers,
- function(e) { return e.id == this.id; }, this);
- },
+module.exports = function (prop) {
+ var _self = new lbs.LocationServiceProvider(prop);
+ _geoList_init();
- //-------------------------------------------------------------------------
- _setRemoteInfo: function(devInfo, stores, cb) {
- var self = this;
- self._model = self._getModel();
- devInfo._a = self;
- self.devInfo = devInfo;
- self.devInfo._updateModel(function(err) {
- if ( err )
- return cb(err);
- // merge the new datastore info with any pre-existing store bindings
- // step 1: prepare the new stores (clean up the URIs)
- var lut = _.object(_.map(stores, function(store) {
- store.uri = self.normUri(store.uri);
- return [store.uri, store];
- }));
- // step 2: remove all stores that are no longer mentioned
- self._stores = _.object(
- _.map(
- _.filter(_.keys(self._stores), function(oldUri) {
- return _.indexOf(_.keys(lut), oldUri) >= 0;
- }), function(uri) {
- return [uri, self._stores[uri]];
- }
- )
- );
- // step 3: merge the datastore info for existing stores
- var merge_stores = function(cb) {
- common.cascade(_.values(self._stores), function(store, cb) {
- store.merge(lut[store.uri], function(err) {
- if ( err )
- return cb(err);
- delete lut[store.uri];
- return cb();
- });
- }, cb);
- };
- // step 4: add new datastores
- var add_stores = function(cb) {
- common.cascade(_.values(lut), function(store, cb) {
- self.addStore(store, cb);
- }, cb);
- };
- merge_stores(function(err) {
- if ( err )
- return cb(err);
- add_stores(cb);
- });
- });
- },
+ _self.geocode = function (address, successCB, errorCB, options) {
+ function _geocode() {
+ var ret;
- //-------------------------------------------------------------------------
- setRoute: function(localUri, remoteUri, autoMapped, cb) {
- if ( _.isFunction(autoMapped) )
- // defaulting 'autoMapped' to false
- return this.setRoute(localUri, remoteUri, false, autoMapped);
- var pmodel = this._getModel();
- if ( ! pmodel )
- return cb(new common.InternalError('could not locate this peer in local adapter'));
- pmodel.routes = _.filter(pmodel.routes, function(r) {
- return r.localUri != localUri && r.remoteUri != remoteUri;
- });
- pmodel.routes.push({localUri : localUri,
- remoteUri : remoteUri,
- autoMapped : autoMapped
- });
- // now search through previous bindings, breaking incorrect ones...
- // NOTE: this requires that a router.recalculate() is called at
- // some point later since other valid bindings may now be
- // possible...
- _.each(pmodel.stores, function(store) {
- if ( store.uri != remoteUri
- && ( ! store.binding || store.binding.uri != localUri ) )
- {
- return;
- }
- if ( ! store.binding )
- {
- store.binding = {
- uri : localUri,
- autoMapped : autoMapped,
- localAnchor : null,
- remoteAnchor : null
- };
- return;
+ ret = _pendingOperate(function () {
+ /* address: its type is AbstractAddress.
+ It could be StructuredAddress or String */
+ if (_checkAddressType(address) === "string") {
+ _geocodeByString(address, successCB, errorCB, options);
+ } else if (_checkAddressType(address) === "StructuredAddress") {
+ _geocodeByAddress(address, successCB, errorCB, options);
+ } else {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- if ( store.uri == remoteUri && store.binding.uri == localUri )
- {
- store.binding.autoMapped = store.binding.autoMapped && autoMapped;
- return;
+ });
+ }
+
+ tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
+ };
+
+ _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
+ function _reverseGeocode() {
+ var ret;
+
+ ret = _pendingOperate(function () {
+ /* coordinates: Its type is AbstractCoordinates.
+ It could be SimpleCoordinates or GeoCoordinates */
+ if (_checkCoordsType(coordinates) === "simpleCoordinates") {
+ _reverseGeocodeBySimple(coordinates, successCB, errorCB, options);
+ } else if (_checkCoordsType(coordinates) === "geoCoordinates") {
+ _reverseGeocodeByGeo(coordinates, successCB, errorCB, options);
+ } else {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
}
- store.binding = null;
- return;
- });
- // TODO: this additional route may impact "smart routing" - recalculate?...
- // TODO: saving adapter from peer --- SHOULD IT BE DOING THIS?...
- // TODO: get transaction from a session!...
- this._a._save(this._c._txn(), cb);
- },
+ });
+ }
- //-------------------------------------------------------------------------
- sendRequest: function(session, contentType, data, cb) {
- var xmlhttp;
+ tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
+ };
- // TODO: shouldn't proxies just overwrite .sendRequest() ?...
- if ( this._proxy )
- return this._proxy.sendRequest(session, contentType, data, cb);
+ return _self;
+};
- var req = {
- url : session.info.respUri || this.url,
- method : 'POST',
- headers : {'Content-Type': contentType},
- body : data
- };
- xmlhttp = new XMLHttpRequest();
- xmlhttp.open(req.method, req.url, false);
+});
+define('ripple/platform/tizen/2.0/package', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 db = require('ripple/db'),
+ app = require('ripple/app'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
+ _security = {
+ "http://tizen.org/privilege/packagemanager.install": ["install", "uninstall"],
+ "http://tizen.org/privilege/package.info": ["getPackagesInfo", "getPackageInfo",
+ "setPackageInfoEventListener", "unsetPackageInfoEventListener"]
+ },
+ DB_PACKAGE_KEY = "tizen-db-package",
+ _listeners = [],
+ _data = {
+ packageList: {},
+ installedList: {}
+ },
+ INTERVAL = 1000, // INTERVAL = 1sec
+ INSTALL_AMOUNT = 3072, // installation speed amount = 3072 (KB/sec)
+ PSEUDO_PACKAGE_ID = "pseudopack00",
+ PSEUDO_APP_ID = "pseudoapp00",
+ _self;
+
+function _get() {
+ _data = db.retrieveObject(DB_PACKAGE_KEY);
+}
+
+function _save() {
+ db.saveObject(DB_PACKAGE_KEY, _data);
+}
+
+function _exec(callback, name, id, arg1) {
+ switch (name) {
+ case "onprogress":
+ callback[name](id, arg1);
+ break;
+ case "oncomplete":
+ callback[name](id);
+ break;
+ default:
+ break;
+ }
+}
- xmlhttp.setRequestHeader("Content-Type", contentType);
- xmlhttp.send(req.body);
+function _setupCurrentPackage() {
+ var info, id, item, tizenAppId;
+ info = app.getInfo();
+ tizenAppId = info.tizenAppId || PSEUDO_APP_ID;
+ id = info.tizenPackageId;
+ if (id !== undefined) {
+ if (_data.installedList[id]) {
+ // already installed
+ return;
+ }
- var response = {
- headers: {
- "Content-Type": xmlhttp.getResponseHeader("content-type")
- },
- body: xmlhttp.responseXML
- };
- return cb(null, response);
+ item = null;
+ utils.forEach(_data.packageList, function (p) {
+ if (p.id === id) {
+ item = p;
}
+ });
+
+ if (item) {
+ _data.installedList[item.id] = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, new Date(),
+ item.author, item.description, item.appIds
+ );
+ event.trigger("install-current-package", [_data.installedList[item.id]]);
+ } else {
+ _data.installedList[id] = new PackageInformation(
+ id, "Tizen pseudo package", "icon.png", "2.2",
+ 8264, 50, new Date(),
+ "TizenDev", "This is a description which is used in tests.", [tizenAppId]
+ );
+ event.trigger("install-current-package", [_data.installedList[id]]);
+ }
+ } else {
+ _data.installedList[PSEUDO_PACKAGE_ID] = new PackageInformation(
+ PSEUDO_PACKAGE_ID, "Tizen pseudo package", "icon.png", "2.2",
+ 8264, 50, new Date(),
+ "TizenDev", "This is a description which is used in tests.", [tizenAppId]
+ );
+ event.trigger("install-current-package", [_data.installedList[PSEUDO_PACKAGE_ID]]);
+ }
+}
+
+function _updatePackage(path, updateFlag) {
+ var item, p, info;
+ if (!_data.packageList[path]) {
+ return;
+ }
+ _get();
+ p = _data.packageList[path];
+ item = _data.installedList[p.id];
+ utils.forEach(_listeners, function (listener) {
+ info = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, item.lastModified,
+ item.author, item.description, item.appIds);
+ if (!updateFlag) {
+ listener.oninstalled(info);
+ } else {
+ listener.onupdated(info);
+ }
});
+}
- return exports;
+function _initialize() {
+ _get();
-})();
+ if (!_data)
+ return;
-module.exports = _self;
+ utils.forEach(_data.installedList, function (item) {
+ item.lastModified = new Date(item.lastModified);
+ });
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/router', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.router
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/04
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ _setupCurrentPackage();
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
- matcher = require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
- stablematch = require('ripple/platform/tizen/2.0/syncml-js-lib/stablematch'),
- _self;
+ event.on("install-packge", function (path) {
+ _updatePackage(path, false);
+ });
+ event.on("update-package", function (path) {
+ _updatePackage(path, true);
+ });
-_self = (function () {
+ event.on("uninstall-package", function (id) {
+ _get();
+ utils.forEach(_listeners, function (listener) {
+ listener.onuninstalled(id);
+ });
+ });
+}
- var exports = {};
+_self = function () {
+ var package;
- //---------------------------------------------------------------------------
- exports.Router = common.Base.extend({
+ // public
+ function install(path, progressCallback, errorCallback) {
+ if (!_security.install) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- constructor: function(options) {
- },
+ t.PackageManager("install", arguments);
- //-------------------------------------------------------------------------
- getTargetUri: function(adapter, peer, sourceUri) {
- var pmodel = peer._getModel();
- for ( var idx=0 ; idx<pmodel.routes.length ; idx++ )
- {
- var route = pmodel.routes[idx];
- if ( route.localUri == sourceUri )
- return route.remoteUri;
- }
- for ( var idx=0 ; idx<pmodel.stores.length ; idx++ )
- {
- var store = pmodel.stores[idx];
- if ( store.binding && store.binding.uri == sourceUri )
- return store.uri;
+ window.setTimeout(function () {
+ var intervalId, installedSize = 0, packageSize, updateFlag = false,
+ item, info, progress;
+
+ if (!_data.packageList[path]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+ item = _data.packageList[path];
+ if (_data.installedList[item.id]) {
+ updateFlag = true;
+ }
+ packageSize = item.totalSize;
+ intervalId = setInterval(function () {
+ if (installedSize >= packageSize) {
+ // Install complete
+ _data.installedList[item.id] = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, new Date(),
+ item.author, item.description, item.appIds
+ );
+ event.trigger("install-apps", [item.appIds]);
+ _save();
+ _exec(progressCallback, "oncomplete", item.id);
+ clearInterval(intervalId);
+ item = _data.installedList[item.id];
+ utils.forEach(_listeners, function (listener) {
+ info = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, item.lastModified,
+ item.author, item.description, item.appIds);
+ if (!updateFlag) {
+ listener.oninstalled(info);
+ } else {
+ listener.onupdated(info);
+ }
+ });
+ event.trigger("installedList-updated");
+ } else {
+ installedSize += INSTALL_AMOUNT;
+ progress = (installedSize > packageSize) ? 100 :
+ Math.floor(installedSize * 100 / packageSize);
+ _exec(progressCallback, "onprogress", item.id, progress);
+ }
+ }, INTERVAL);
+ }, 1);
}
- return null;
- },
- //-------------------------------------------------------------------------
- recalculate: function(adapter, peer, cb) {
- // the non-"SmartRouter" only connects manually-configured routes...
- var routes = _.filter(peer._getModel().routes,
- function(r) { return ! r.autoMapped; });
- return this._setupRoutes(adapter, peer, routes, cb);
- },
+ function uninstall(id, progressCallback, errorCallback) {
+ if (!_security.uninstall) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- _setupRoutes: function(adapter, peer, routes, cb) {
- // available local URIs
- var lset = _.map(adapter._getModel().stores,
- function(s) { return adapter.normUri(s.uri); });
- // available remote URIs
- var rset = _.map(peer._getModel().stores,
- function(s) { return peer.normUri(s.uri); });
+ t.PackageManager("uninstall", arguments);
- // break all routes not listed
- var ruris = _.map(routes, function(r) { return r.remoteUri; });
- var xrset = _.filter(rset, function(uri) {
- return _.indexOf(ruris, uri) < 0;
- });
- _.each(xrset, function(uri) {
- var smodel = peer.getStore(uri)._getModel();
- if ( ! smodel.binding )
- return;
- smodel.binding = null;
- });
+ window.setTimeout(function () {
+ var intervalId, removedSize = 0, packageSize, item, progress;
- var err = null;
- _.each(routes, function(route) {
- if ( err )
+ if (!_data.installedList[id]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
return;
-
- route.localUri = adapter.normUri(route.localUri);
- route.remoteUri = peer.normUri(route.remoteUri);
- if ( _.indexOf(rset, route.remoteUri) < 0
- || _.indexOf(lset, route.localUri) < 0 )
- {
- err = 'unable to route from "' + route.localUri
- + '" (here) to "' + route.remoteUri
- + '" (peer): no such stores or already routed elsewhere';
- return;
}
+ item = _data.installedList[id];
+ packageSize = item.totalSize;
+ intervalId = setInterval(function () {
+ if (removedSize >= packageSize) {
+ utils.forEach(_data.packageList, function (package) {
+ if (package.id === id) {
+ event.trigger("remove-apps", [package.appIds]);
+ }
+ });
+ delete _data.installedList[item.id];
+ _save();
+ _exec(progressCallback, "oncomplete", item.id);
+ clearInterval(intervalId);
+ item = _data.installedList[item.id];
+ utils.forEach(_listeners, function (listener) {
+ listener.onuninstalled(id);
+ });
+ event.trigger("installedList-updated");
+ } else {
+ removedSize += INSTALL_AMOUNT * 10;
+ progress = (removedSize > packageSize) ? 100 :
+ Math.floor(removedSize * 100 / packageSize);
+ _exec(progressCallback, "onprogress", item.id, progress);
+ }
+ }, INTERVAL);
+ }, 1);
+ }
- lset = _.filter(lset, function(uri) { return uri != route.localUri; });
- rset = _.filter(rset, function(uri) { return uri != route.remoteUri; });
+ function getPackagesInfo(successCallback, errorCallback) {
+ if (!_security.getPackagesInfo) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
+ t.PackageManager("getPackagesInfo", arguments);
- var smodel = peer.getStore(route.remoteUri)._getModel();
- if ( smodel.binding && smodel.binding.uri == route.localUri )
- return;
- smodel.binding = {
- uri : route.localUri,
- autoMapped : route.autoMapped,
- localAnchor : null,
- remoteAnchor : null
- };
+ window.setTimeout(function () {
+ var packageArray = [];
+
+ utils.forEach(_data.installedList, function (item) {
+ var i;
+ i = new PackageInformation(
+ item.id, item.name, item.iconPath, item.version,
+ item.totalSize, item.dataSize, item.lastModified,
+ item.author, item.description, item.appIds
+ );
+ packageArray.push(i);
});
+ successCallback(packageArray);
+ }, 1);
+ }
- if ( err )
- return cb(err);
+ function getPackageInfo(id) {
+ var p, item;
- return cb();
- },
+ if (!_security.getPackageInfo) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- getBestTransmitContentType: function(adapter, peer, uri) {
- var lstore = adapter.getStore(uri);
- var rstore = peer.getStore(this.getTargetUri(adapter, peer, uri));
- return matcher.pickTransmitContentType(lstore, rstore);
- },
+ t.PackageManager("getPackageInfo", arguments);
- });
+ id = id || "api1pack00";
- //---------------------------------------------------------------------------
- exports.SmartRouter = exports.Router.extend({
+ if (!_data.installedList[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ item = _data.installedList[id];
+ p = new PackageInformation(item.id, item.name, item.iconPath,
+ item.version, item.totalSize, item.dataSize, item.lastModified,
+ item.author, item.description, item.appIds);
- //-------------------------------------------------------------------------
- recalculate: function(adapter, peer, cb) {
+ return p;
+ }
- // note: if you don't want smart routing, assign the non-SmartRouter
- // router (i.e. syncml-js.Router) to the loaded context
+ function setPackageInfoEventListener(eventCallback) {
+ if (!_security.setPackageInfoEventListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // available local URIs
- var llut = _.object(
- _.map(adapter._getModel().stores,
- function(s) { return [adapter.normUri(s.uri), s]; }));
- var lset = _.keys(llut);
+ t.PackageManager("setPackageInfoEventListener", arguments);
- // available remote URIs
- var rlut = _.object(
- _.map(peer._getModel().stores,
- function(s) { return [adapter.normUri(s.uri), s]; }));
- var rset = _.keys(rlut);
+ _listeners.push(eventCallback);
+ }
- // TODO: i am directly touching the model here.
- // total i-rep violation.
- // i'm embarrassed.
- // fortunately, it's just between syncml-js classes...
- // but now you know, doh! please don't blackmail me!... ;-)
+ function unsetPackageInfoEventListener() {
+ if (!_security.unsetPackageInfoEventListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // manual routes
- var pmodel = peer._getModel();
- pmodel.routes = _.filter(pmodel.routes,
- function(r) { return ! r.autoMapped; });
+ t.PackageManager("unsetPackageInfoEventListener", arguments);
- // remove manual routes from available routes
- var uris = _.map(pmodel.routes, function(r) { return r.localUri; });
- lset = _.filter(lset, function(uri) {
- return _.indexOf(uris, uri) < 0;
- });
- uris = _.map(pmodel.routes, function(r) { return r.remoteUri; });
- rset = _.filter(rset, function(uri) {
- return _.indexOf(uris, uri) < 0;
- });
+ _listeners = [];
+ }
- // match remaining stores
- var rankL = function(luri) {
- var ret = _.rest(rset, 0);
- ret.sort(function(a, b) {
- return matcher.cmpStore(llut[luri], rlut[a], rlut[b]);
- });
- return ret;
- };
- var rankR = function(ruri) {
- var ret = _.rest(lset, 0);
- ret.sort(function(a, b) {
- return matcher.cmpStore(rlut[ruri], llut[a], llut[b]);
- });
- return ret;
- };
- var matches = stablematch.match(lset, rset, rankL, rankR);
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- // add them to the routes (as auto-routed)
- for ( var idx=0 ; idx<matches.length ; idx++ )
- {
- var pair = matches[idx];
- pmodel.routes.push({
- localUri : pair[0],
- remoteUri : pair[1],
- autoMapped : true
- });
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
+ }
+ }
- return this._setupRoutes(adapter, peer, pmodel.routes, cb);
- },
-
- });
+ package = {
+ install: install,
+ uninstall: uninstall,
+ getPackagesInfo: getPackagesInfo,
+ getPackageInfo: getPackageInfo,
+ setPackageInfoEventListener: setPackageInfoEventListener,
+ unsetPackageInfoEventListener: unsetPackageInfoEventListener,
+ handleSubFeatures: handleSubFeatures
+ };
- return exports;
+ return package;
+};
-})();
+_initialize();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/stablematch', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// desc: implements a solution to the stable matching problem using a
-// left-optimized algorithm. shamelessly adapted from:
-// https://github.com/paulgb/Python-Gale-Shapley/
-// auth: metagriffin <mg.npmjs@uberdev.org>
-// date: 2012/12/29
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
-
-var _self = (function () {
+define('ripple/platform/tizen/2.0/application', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 exports = {};
+var utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ app = require('ripple/app'),
+ db = require('ripple/db'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
+ Application,
+ ApplicationInformation,
+ ApplicationContext,
+ ApplicationCertificate,
+ RequestedApplicationControl,
+ _DB_APPLICATION_KEY = "tizen1-db-application",
+ PSEUDO_PACKAGE_ID = "pseudopack00",
+ PSEUDO_APP_ID = "pseudoapp00",
+ _security = {
+ "http://tizen.org/privilege/application.launch": ["launch", "launchAppControl"],
+ "http://tizen.org/privilege/appmanager.kill": ["kill"],
+ "http://tizen.org/privilege/appmanager.certificate": ["getAppCerts"]
+ },
+ _data = {
+ applications : {},
+ applicationContexts : {},
+ activeApp : null,
+ listeners : {}
+ },
+ _appDialogTemplate = jQuery("#app-dialog-template").html(),
+ _appDialogTemplate_short = jQuery("#app-dialog2-template").html(),
+ _appDialogTemplate_exit_hide = jQuery("#app-dialog3-template").html(),
+ reasonable_mimetype = {
+ "application" : true,
+ "text" : true,
+ "video" : true,
+ "audio" : true,
+ "image" : true
+ },
+ _self;
- // TODO: figure out how to pull this dynamically from package.json...
- exports.version = '0.0.4';
+function _setupCurrentApp() {
+ var info, contextId, packageId, appId;
+ info = app.getInfo();
+ packageId = info.tizenPackageId || PSEUDO_PACKAGE_ID;
+ appId = info.tizenAppId || PSEUDO_APP_ID;
+ contextId = Math.uuid(null, 16);
+ _data.applications[appId] = {
+ id: appId,
+ name: info.name,
+ iconPath: info.icon,
+ version: info.version,
+ show: true,
+ categories: [],
+ installDate: new Date(),
+ size: 1024,
+ packageId: packageId,
+ sharedURI: "/usr/local/share/",
+ operation: "",
+ appControl: {
+ uri: "",
+ mime: "",
+ category: "",
+ data: []
+ },
+ type: "AUTHOR_ROOT",
+ value: ""
+ };
+ event.trigger("install-current-app", [_data.applications[appId]]);
+ _data.applicationContexts[contextId] = {id: contextId, appId: appId};
+ _data.activeApp = _data.applicationContexts[contextId];
+}
- //---------------------------------------------------------------------------
- exports.match = function(A, B, rankA, rankB) {
- if ( ! A || ! B || ! A.length || ! B.length ) {
- return [];
- }
- if ( A.length == B.length ) {
- return exports._match(A, B, rankA, rankB);
+function _translate(apps) {
+ // translate string to Date after retrieving from DB,
+ // it is a temporary sulusion
+ var i;
+ for (i in apps) {
+ if (typeof apps[i].installDate === 'string') {
+ apps[i].installDate = new Date(apps[i].installDate);
}
+ }
+ return apps;
+}
- // TODO: this is a brute-force implementation of getting both
- // lists to be of symmetric length... make this "better".
- // for example, build this directly into _match() or use
- // deterministic exclusion of the longer data set.
-
- var sA = _.rest(A, 0);
- var sB = _.rest(B, 0);
- var mlen = Math.max(sA, sB);
- while ( sA.length < mlen )
- sA.push(null);
- while ( sB.length < mlen )
- sB.push(null);
- var sRA = function(a) {
- var ret = rankA(a);
- while ( ret.length < mlen )
- ret.push(null);
- return ret;
- };
- var sRB = function(b) {
- var ret = rankB(b);
- while ( ret.length < mlen )
- ret.push(null);
- return ret;
- };
- var ret = exports._match(sA, sB, sRA, sRB);
- return _.filter(ret, function(pair) {
- return pair[0] != null && pair[1] != null;
- });
+function _initialize() {
+ _data = {
+ applications : {},
+ applicationContexts : {},
+ activeApp : null,
+ listeners : {}
};
- //---------------------------------------------------------------------------
- exports._match = function(A, B, rankA, rankB) {
- // this translates sets A and B to indeces, since _imatch can only work
- // with sets of elements that can be used as the key in a hash (in this
- // implementation).
- var iA = _.range(A.length);
- var iB = _.range(B.length);
- var iRA = function(ia) {
- var ret = rankA(A[ia]);
- return _.map(ret, function(item) {
- return _.indexOf(B, item);
- });
- };
- var iRB = function(ib) {
- var ret = rankB(B[ib]);
- return _.map(ret, function(item) {
- return _.indexOf(A, item);
- });
- };
- var ret = exports._imatch(iA, iB, iRA, iRB);
- return _.map(ret, function(item) {
- return [A[item[0]], B[item[1]]];
- });
- };
+ if (!db.retrieveObject(_DB_APPLICATION_KEY))
+ return;
- //---------------------------------------------------------------------------
- exports._imatch = function(A, B, rankA, rankB) {
- // TODO: improve this... it was a brute-force porting of
- // https://github.com/paulgb/Python-Gale-Shapley
- // without any eye on optimal outcome or performance...
- //: `partners` is a paring hash of { a => [b, rank] }
- var partners = {};
- _.each(A, function(a) {
- partners[a] = [rankA(a)[0], 0];
- });
- //: `stable` indicates stability of the current pairing in `partners`
- var stable = false;
- while ( ! stable )
- {
- stable = true;
- _.each(B, function(b) {
- var paired = false;
- for ( var n=0 ; n<A.length ; n++ )
- {
- var a = rankB(b)[n];
- var pair = partners[a];
- if ( pair[0] == b )
- {
- if ( paired )
- {
- stable = false;
- partners[a] = [rankA(a)[pair[1] + 1], pair[1] + 1];
- }
- else
- paired = true;
- }
- }
- });
- }
- return _.map(_.keys(partners), function(a) {
- return [a, partners[a][0]];
- });
- };
+ _data.applications = _translate(db.retrieveObject(_DB_APPLICATION_KEY).installedAppList);
+ _setupCurrentApp();
+ $("#app-dialog").dialog({
+ resizable: false,
+ draggable: false,
+ modal: true,
+ autoOpen: false,
+ position: 'center',
+ minWidth: '500',
+ minHeight: '262',
+ open: function () { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); }
+ });
+}
- return exports;
-})();
+_self = function () {
+ // private
+ function getHandle() {
+ var handle;
+ do {
+ handle = Math.uuid(8, 10);
+ } while (handle.toString().indexOf('0') === 0);
-module.exports = _self;
+ return parseInt(handle, 10);
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/state', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// auth: metagriffin <metagriffin@uberdev.org>
-// date: 2012/10/27
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ // public
+ function getCurrentApplication() {
+ var application, innerApp;
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- _self;
+ t.ApplicationManager("getCurrentApplication", arguments);
-_self = (function () {
- var exports = {};
+ /* activeApp update (by WidgetInformationUpdate event) sometime will late after user calling getCurrentApplication()
+ for example: load other application by omnibar */
+ if (app.getInfo().id !== _data.activeApp.appId) {
+ _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
+ utils.forEach(_data.applications, function(item) {
+ item.installDate = new Date(item.installDate);
+ });
+ _setupCurrentApp();
+ }
+ innerApp = _data.applications[_data.activeApp.appId];
+ application = new Application(
+ new ApplicationInformation(
+ innerApp.id,
+ innerApp.name,
+ innerApp.iconPath,
+ innerApp.version,
+ innerApp.show,
+ innerApp.categories,
+ innerApp.installDate,
+ innerApp.size,
+ innerApp.packageId),
+ _data.activeApp.id, innerApp);
+ return application;
+ }
- //---------------------------------------------------------------------------
- exports.makeCommand = function(options) {
- return _.defaults({}, options, {
- // ?
- });
- };
+ function kill(contextId, successCallback, errorCallback) {
+ if (!_security.kill) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //---------------------------------------------------------------------------
- exports.makeStats = function(options) {
- return _.defaults({}, options, {
- mode : null,
- hereAdd : 0,
- hereMod : 0,
- hereDel : 0,
- hereErr : 0,
- peerAdd : 0,
- peerMod : 0,
- peerDel : 0,
- peerErr : 0,
- conflicts : 0,
- merged : 0,
- });
- };
+ t.ApplicationManager("kill", arguments);
- //---------------------------------------------------------------------------
- exports.makeSessionInfo = function(options) {
- return _.defaults({}, options, {
- id : null,
- msgID : null,
- cmdID : 0,
- dsstates : {},
- lastCommands : [],
- stats : exports.makeStats()
- });
- };
+ window.setTimeout(function () {
+ if (!_data.applicationContexts[contextId]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
- //---------------------------------------------------------------------------
- exports.makeStoreSyncState = function(options) {
- return _.defaults({}, options, {
- uri : null,
- peerUri : null,
- lastAnchor : null,
- nextAnchor : '' + common.ts(),
- mode : constant.ALERT_TWO_WAY,
- action : null,
- stats : exports.makeStats()
- });
- };
+ if (_data.activeApp && (_data.activeApp.id === contextId)) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
- //---------------------------------------------------------------------------
- exports.makeSession = function(options) {
- return new (function() {
- this.context = options.context || null;
- this.ua = options.ua || null;
- this.txn = options.txn || options.context.txn;
- this.adapter = options.adapter || null;
- this.peer = options.peer || null;
- this.info = options.info || null;
- this.discover = options.discover ? true : false;
- this.isServer = options.isServer ? true : false;
- this.nextCmdID = function() {
- this.info.cmdID += 1;
- return this.info.cmdID;
- };
- })();
+ delete _data.applicationContexts[contextId];
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ }
- // return _.defaults({}, options, {
- // context : null,
- // adapter : null,
- // peer : null,
- // info : null
- // });
- };
+ function launch(id, successCallback, errorCallback) {
+ if (!_security.launch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- var smult = function(s, count) {
- var ret = '';
- for ( var idx=0 ; idx<count ; idx++ )
- ret += s;
- return ret;
- };
+ t.ApplicationManager("launch", arguments);
- var num2str = function(num) {
- // TODO: i18n...
- // TODO: this is *UGLY*
- // TODO: OMG, i'm *so* embarrassed
- // TODO: but it works... sort of.
- if ( num == 0 )
- return '-';
- var ret = '';
- num = '' + num;
- for ( var idx=num.length ; idx>0 ; idx-=3 )
- {
- if ( ret.length > 0 )
- ret = ',' + ret;
- ret = num.charAt(idx - 1) + ret;
- if ( idx - 1 > 0 )
- ret = num.charAt(idx - 2) + ret;
- if ( idx - 2 > 0 )
- ret = num.charAt(idx - 3) + ret;
- }
- return ret;
- };
+ window.setTimeout(function () {
+ var htmlContent;
- var center = function(s, wid, pad) {
- // todo: is there no way to get sprintf to do this for me???...
- pad = pad || ' ';
- if ( wid <= s.length )
- return s;
- var diff = wid - s.length;
- return smult(pad, Math.floor(diff / 2)) + s + smult(pad, Math.ceil(diff / 2));
- };
+ if (!_data.applications[id]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
- var right = function(s, wid, pad) {
- // todo: is there no way to get sprintf to do this for me???...
- pad = pad || ' ';
- if ( wid <= s.length )
- return s;
- return smult(pad, wid - s.length) + s;
- };
+ htmlContent = _appDialogTemplate_short.replace(/#application-name/, _data.applications[id].name)
+ .replace(/#application-id/, id);
+ jQuery("#app-dialog-box").html(htmlContent);
+ $("#app-dialog").dialog("open");
- //---------------------------------------------------------------------------
- // TODO: this should probably be put into another package...
- exports.describeStats = function(stats, stream, options) {
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
+ }
- // ASCII OBJECTIVE:
- // +----------------------------------------------------------------------------------+
- // | TITLE |
- // +----------+------+-------------------------+--------------------------+-----------+
- // | | | Local | Remote | Conflicts |
- // | Source | Mode | Add | Mod | Del | Err | Add | Mod | Del | Err | Col | Mrg |
- // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
- // | contacts | <= | - | - | - | - | 10,387 | - | - | - | - | - |
- // | note | SS | 1,308 | - | 2 | - | - | - | - | - | - | - |
- // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
- // | 1,310 local changes and 10,387 remote changes. |
- // +----------------------------------------------------------------------------------+
+ function launchAppControl(appControl, id, successCallback, errorCallback, replyCallback) {
+ if (!_security.launchAppControl) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // UNICODE OBJECTIVE:
- // ┌──────────────────────────────────────────────────────────────────────────────────┐
- // │ TITLE │
- // ├──────────┬──────┬─────────────────────────┬──────────────────────────┬───────────┤
- // │ │ │ Local │ Remote │ Conflicts │
- // │ Source │ Mode │ Add Mod Del Err │ Add Mod Del Err │ Col Mrg │
- // ├──────────┼──────┼───────┼─────┼─────┼─────┼────────┼─────┼─────┼─────┼─────┼─────┤
- // │ contacts │ <= │ │ │ │ │ 10,387 │ │ │ │ │ │
- // │ note │ SS │ 1,308 │ │ 2 │ │ │ │ │ │ │ │
- // ├──────────┴──────┴───────┴─────┴─────┴─────┴────────┴─────┴─────┴─────┴─────┴─────┤
- // │ 1,310 local changes and 10,387 remote changes. │
- // └──────────────────────────────────────────────────────────────────────────────────┘
+ t.ApplicationManager("launchAppControl", arguments, true);
- // todo: perhaps the fancy version should have color-coding as well?...
+ window.setTimeout(function () {
+ var isFound = false, appId, htmlContent;
- options = _.defaults({}, options, {
- title : null,
- details : true,
- totals : true,
- ascii : false,
- gettext : function(text) { return text; }
- });
+ if (id) {
+ if (!_data.applications[id]) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+ htmlContent = _appDialogTemplate.replace(/#application-name/, _data.applications[appId].name)
+ .replace(/#appControl-operation/, _data.applications[appId].operation)
+ .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
+ .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
+ .replace(/#appControl-category/, _data.applications[appId].appControl.category)
+ .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
+ jQuery("#app-dialog-box").html(htmlContent);
+ $("#app-dialog").dialog("open");
- var modeStringLut = _.object([
- [constant.SYNCTYPE_TWO_WAY , '<>'],
- [constant.SYNCTYPE_SLOW_SYNC , 'SS'],
- [constant.SYNCTYPE_ONE_WAY_FROM_CLIENT , '->'],
- [constant.SYNCTYPE_REFRESH_FROM_CLIENT , '=>'],
- [constant.SYNCTYPE_ONE_WAY_FROM_SERVER , '<-'],
- [constant.SYNCTYPE_REFRESH_FROM_SERVER , '<=']
- ]);
+ _data.activeApp.replyCallback = replyCallback;
- if ( options.ascii )
- {
+ if (successCallback) {
+ successCallback();
+ }
+ } else {
+ utils.forEach(_data.applications, function (application) {
+ if (application.operation === appControl.operation) {
+ if (appControl.mime && (typeof appControl.mime === "string")) {
+ if (!reasonable_mimetype[appControl.mime.split("/")[0]]) {
+ return;
+ }
+ }
+ appId = application.id;
+ isFound = true;
+ }
+ });
- // unicode graphing characters: ('\xe2\x94\x80' - '\xe2\x94\xc0')
- // mapping table unicode ==> ascii
+ if (!isFound) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
- glyphs = {
- '─': '-',
- '━': '-',
- '│': '|',
- '┃': '|',
- '┄': '-',
- '┅': '-',
- '┆': '|',
- '┇': '|',
- '┈': '-',
- '┉': '-',
- '┊': '|',
- '┋': '|',
- '┌': '+',
- '┍': '+',
- '┎': '+',
- '┏': '+',
- '┐': '+',
- '┑': '+',
- '┒': '+',
- '┓': '+',
- '└': '+',
- '┕': '+',
- '┖': '+',
- '┗': '+',
- '┘': '+',
- '┙': '+',
- '┚': '+',
- '┛': '+',
- '├': '+',
- '┝': '+',
- '┞': '+',
- '┟': '+',
- '┠': '+',
- '┡': '+',
- '┢': '+',
- '┣': '+',
- '┤': '+',
- '┥': '+',
- '┦': '+',
- '┧': '+',
- '┨': '+',
- '┩': '+',
- '┪': '+',
- '┫': '+',
- '┬': '+',
- '┭': '+',
- '┮': '+',
- '┯': '+',
- '┰': '+',
- '┱': '+',
- '┲': '+',
- '┳': '+',
- '┴': '+',
- '┵': '+',
- '┶': '+',
- '┷': '+',
- '┸': '+',
- '┹': '+',
- '┺': '+',
- '┻': '+',
- '┼': '+',
- '┽': '+',
- '┾': '+',
- '┿': '+',
- };
+ htmlContent = _appDialogTemplate.replace(/#application-name/,
+ _data.applications[appId].name)
+ .replace(/#appControl-operation/, _data.applications[appId].operation)
+ .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
+ .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
+ .replace(/#appControl-category/, _data.applications[appId].appControl.category)
+ .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
+ jQuery("#app-dialog-box").html(htmlContent);
+ $("#app-dialog").dialog("open");
- var UnicodeToAsciiStream = common.Stream.extend({
- constructor: function(stream) {
- this.stream = stream;
- },
- write: function(data) {
- if ( data == undefined )
- return;
- var ascii = '';
- for ( var idx=0 ; idx<data.length ; idx++ )
- {
- var el = data[idx];
- if ( glyphs[el] != undefined )
- ascii += glyphs[el];
- else
- ascii += el;
- }
- this.stream.write(ascii);
+ _data.activeApp.replyCallback = replyCallback;
+
+ if (successCallback) {
+ successCallback();
}
- });
+ }
+ }, 1);
+ }
- stream = new UnicodeToAsciiStream(stream);
+ function findAppControl(appControl, successCallback, errorCallback) {
+ var appControlExternal = appControl;
- }
+ t.ApplicationManager("findAppControl", arguments, true);
- // todo: this does not handle the case where the title is wider than the table.
+ window.setTimeout(function () {
+ var informationArray = [];
- var wSrc = options.gettext('Source').length;
- var wMode = options.gettext('Mode').length;
- var wCon = options.gettext('Conflicts').length;
- var wCol = options.gettext('Col').length;
- var wMrg = options.gettext('Mrg').length;
- var wHereAdd = wPeerAdd = options.gettext('Add').length;
- var wHereMod = wPeerMod = options.gettext('Mod').length;
- var wHereDel = wPeerDel = options.gettext('Del').length;
- var wHereErr = wPeerErr = options.gettext('Err').length
+ utils.forEach(_data.applications, function (application) {
+ if (application.operation === appControl.operation) {
+ informationArray.push(new ApplicationInformation(
+ application.id,
+ application.name,
+ application.iconPath,
+ application.version,
+ application.show,
+ application.categories,
+ application.installDate,
+ application.size,
+ application.packageId));
+ }
+ });
- var totLoc = 0;
- var totRem = 0;
- var totErr = 0;
- var totCol = 0;
- var totMrg = 0;
+ successCallback(informationArray, appControlExternal);
+ }, 1);
+ }
- _.each(stats, function(value, key) {
- wSrc = Math.max(wSrc, key.length);
- wMode = Math.max(wMode, modeStringLut[value.mode].length);
- wCol = Math.max(wCol, num2str(value.conflicts).length);
- wMrg = Math.max(wMrg, num2str(value.merged).length);
- wHereAdd = Math.max(wHereAdd, num2str(value.hereAdd).length);
- wPeerAdd = Math.max(wPeerAdd, num2str(value.peerAdd).length);
- wHereMod = Math.max(wHereMod, num2str(value.hereMod).length);
- wPeerMod = Math.max(wPeerMod, num2str(value.peerMod).length);
- wHereDel = Math.max(wHereDel, num2str(value.hereDel).length);
- wPeerDel = Math.max(wPeerDel, num2str(value.peerDel).length);
- wHereErr = Math.max(wHereErr, num2str(value.hereErr).length);
- wPeerErr = Math.max(wPeerErr, num2str(value.peerErr).length);
- totLoc += value.hereAdd + value.hereMod + value.hereDel;
- totRem += value.peerAdd + value.peerMod + value.peerDel;
- totErr += value.hereErr + value.peerErr;
- totCol += value.conflicts;
- totMrg += value.merged;
- });
+ function getAppsContext(successCallback, errorCallback) {
+ t.ApplicationManager("getAppsContext", arguments);
- // TODO: i'm 100% sure there is a python library that can do this for me...
+ window.setTimeout(function () {
+ var contexts = [];
- if ( wCon > wCol + 3 + wMrg )
- {
- diff = wCon - ( wCol + 3 + wMrg );
- wCol += diff / 2;
- wMrg = wCon - 3 - wCol;
- }
- else
- wCon = wCol + 3 + wMrg;
+ utils.forEach(_data.applicationContexts, function (context) {
+ contexts.push(new ApplicationContext(context.id, context.appId));
+ });
- if ( options.details )
- tWid = ( wSrc + 3 + wMode + 3
- + wHereAdd + wHereMod + wHereDel + wHereErr + 9 + 3
- + wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 + 3
- + wCon );
- else
- tWid = options.title ? options.title.length : 0;
+ successCallback(contexts);
+ }, 1);
+ }
- if ( options.totals )
- {
- // TODO: oh dear. from an i18n POV, this is *horrible*!...
- sumlist = [];
- // for val, singular, plural in [
- _.each([
- [totLoc, options.gettext('local change'), options.gettext('local changes')],
- [totRem, options.gettext('remote change'), options.gettext('remote changes')],
- [totErr, options.gettext('error'), options.gettext('errors')]
- ], function(set) {
- if ( set[0] <= 0 )
- return;
- sumlist.push(num2str(set[0]) + ' ' + ( set[0] == 1 ? set[1] : set[2] ));
- });
- if ( sumlist.length <= 0 )
- sumlist = options.gettext('No changes');
- else if ( sumlist.length == 1 )
- sumlist = sumlist[0];
- else
- sumlist = ( sumlist.slice(0, -1).join(', ') + ' '
- + options.gettext('and') + ' ' + sumlist[sumlist.length - 1] );
- if ( totMrg > 0 || totCol > 0 )
- {
- sumlist += ': ';
- if ( totMrg == 1 )
- sumlist += num2str(totMrg) + ' ' + options.gettext('merge');
- else if ( totMrg > 1 )
- sumlist += num2str(totMrg) + ' ' + options.gettext('merges');
- if ( totMrg > 0 && totCol > 0 )
- sumlist += ' ' + options.gettext('and') + ' ';
- if ( totCol == 1 )
- sumlist += num2str(totCol) + ' ' + options.gettext('conflict');
- else if ( totCol > 1 )
- sumlist += num2str(totCol) + ' ' + options.gettext('conflicts');
- }
- sumlist += '.';
- if ( sumlist.length > tWid )
- {
- wSrc += sumlist.length - tWid;
- tWid = sumlist.length;
- }
+ function getAppContext(contextId) {
+ var appContext;
+
+ if (contextId === null || contextId === undefined) {
+ appContext = new ApplicationContext(_data.activeApp.id, _data.activeApp.appId);
+ return (appContext);
}
- if ( options.title )
- {
- stream.write('┏━' + smult('━', tWid) + '━┓\n');
- stream.write('┃ ' + center(options.title, tWid) + ' ┃\n');
+ t.ApplicationManager("getAppContext", arguments);
+
+ if (_data.applicationContexts[contextId]) {
+ appContext = new ApplicationContext(contextId, _data.applicationContexts[contextId].appId);
+ return (appContext);
}
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- if ( options.details )
- {
- if ( options.title )
- stream.write('┡━'
- + smult('━', wSrc)
- + '━┯━'
- + smult('━', wMode)
- + '━┯━'
- + smult('━', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
- + '━┯━'
- + smult('━', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
- + '━┯━'
- + smult('━', wCon)
- + '━┩\n'
- );
- else
- stream.write('┌─'
- + smult('─', wSrc)
- + '─┬─'
- + smult('─', wMode)
- + '─┬─'
- + smult('─', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
- + '─┬─'
- + smult('─', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
- + '─┬─'
- + smult('─', wCon)
- + '─┐\n'
- );
+ function getAppsInfo(successCallback, errorCallback) {
+ t.ApplicationManager("getAppsInfo", arguments);
- stream.write('│ ' + smult(' ', wSrc));
- stream.write(' │ ' + smult(' ', wMode));
- stream.write(' │ ' + center(options.gettext('Local'), wHereAdd + wHereMod + wHereDel + wHereErr + 9 ));
- stream.write(' │ ' + center(options.gettext('Remote'), wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ));
- stream.write(' │ ' + center(options.gettext('Conflicts'), wCon));
- stream.write(' │\n');
+ window.setTimeout(function () {
+ var applications = [];
- stream.write('│ ' + right(options.gettext('Source'), wSrc));
- stream.write(' │ ' + center(options.gettext('Mode'), wMode));
- stream.write(' │ ' + center(options.gettext('Add'), wHereAdd));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mod'), wHereMod));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Del'), wHereDel));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Err'), wHereErr));
- stream.write(' │ ' + center(options.gettext('Add'), wPeerAdd));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mod'), wPeerMod));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Del'), wPeerDel));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Err'), wPeerErr));
- stream.write(' │ ' + center(options.gettext('Col'), wCol));
- stream.write(( options.ascii ? ' │ ' : ' ' ) + center(options.gettext('Mrg'), wMrg));
- stream.write(' │\n');
+ utils.forEach(_data.applications, function (application) {
+ applications.push(new ApplicationInformation(
+ application.id,
+ application.name,
+ application.iconPath,
+ application.version,
+ application.show,
+ application.categories,
+ application.installDate,
+ application.size,
+ application.packageId));
+ });
- stream.write('├─' + smult('─', wSrc)
- + '─┼─' + smult('─', wMode)
- + '─┼─' + smult('─', wHereAdd)
- + '─┼─' + smult('─', wHereMod)
- + '─┼─' + smult('─', wHereDel)
- + '─┼─' + smult('─', wHereErr)
- + '─┼─' + smult('─', wPeerAdd)
- + '─┼─' + smult('─', wPeerMod)
- + '─┼─' + smult('─', wPeerDel)
- + '─┼─' + smult('─', wPeerErr)
- + '─┼─' + smult('─', wCol)
- + '─┼─' + smult('─', wMrg)
- + '─┤\n'
- );
+ successCallback(applications);
+ }, 1);
+ }
- var numcol = function(val, wid) {
- if ( val == 0 )
- return ' │ ' + center(options.ascii ? '-' : ' ', wid);
- return ' │ ' + right(num2str(val), wid);
- };
+ function getAppInfo(id) {
+ var appId, appInfo, theApp;
- var keys = _.keys(stats);
- // todo: sort case insensitively...
- keys.sort();
- _.each(keys, function(key) {
- var stat = stats[key];
- stream.write('│ ' + right(key, wSrc));
- stream.write(' │ ' + center(modeStringLut[stat.mode], wMode));
- stream.write(numcol(stat.hereAdd, wHereAdd));
- stream.write(numcol(stat.hereMod, wHereMod));
- stream.write(numcol(stat.hereDel, wHereDel));
- stream.write(numcol(stat.hereErr, wHereErr));
- stream.write(numcol(stat.peerAdd, wPeerAdd));
- stream.write(numcol(stat.peerMod, wPeerMod));
- stream.write(numcol(stat.peerDel, wPeerDel));
- stream.write(numcol(stat.peerErr, wPeerErr));
- stream.write(numcol(stat.conflicts, wCol));
- stream.write(numcol(stat.merged, wMrg));
- stream.write(' │\n');
- });
+ t.ApplicationManager("getAppInfo", arguments);
- if ( options.totals )
- stream.write('├─');
- else
- stream.write('└─');
+ if (arguments.length === 0) {
+ appId = _data.activeApp.appId;
+ theApp = _data.applications[appId];
- stream.write(smult('─', wSrc)
- + '─┴─' + smult('─', wMode)
- + '─┴─' + smult('─', wHereAdd)
- + '─┴─' + smult('─', wHereMod)
- + '─┴─' + smult('─', wHereDel)
- + '─┴─' + smult('─', wHereErr)
- + '─┴─' + smult('─', wPeerAdd)
- + '─┴─' + smult('─', wPeerMod)
- + '─┴─' + smult('─', wPeerDel)
- + '─┴─' + smult('─', wPeerErr)
- + '─┴─' + smult('─', wCol)
- + '─┴─' + smult('─', wMrg)
- );
+ appInfo = new ApplicationInformation(
+ theApp.id,
+ theApp.name,
+ theApp.iconPath,
+ theApp.version,
+ theApp.show,
+ theApp.categories,
+ theApp.installDate,
+ theApp.size,
+ theApp.packageId);
+ return appInfo;
+ }
- if ( options.totals )
- stream.write('─┤\n');
- else
- stream.write('─┘\n');
+ if (!_data.applications[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
}
- // ─━│┃┄┅┆┇┈┉┊┋┼┽┾┿
- // ┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛
- // ├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫
- // ┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻
+ theApp = _data.applications[id];
+ appInfo = new ApplicationInformation(
+ theApp.id,
+ theApp.name,
+ theApp.iconPath,
+ theApp.version,
+ theApp.show,
+ theApp.categories,
+ theApp.installDate,
+ theApp.size,
+ theApp.packageId);
+ return appInfo;
+ }
- if ( options.totals )
- {
- if ( !! options.title && ! options.details )
- stream.write('┌─' + smult('─', tWid) + '─┐\n');
- stream.write('│ ' + center(sumlist, tWid));
- stream.write(' │\n');
- stream.write('└─' + smult('─', tWid) + '─┘\n');
+ function getAppCerts(id) {
+ var certs = [];
+
+ if (!_security.getAppCerts) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- return;
+ t.ApplicationManager("getAppCerts", arguments);
- };
+ if (arguments.length === 0) {
+ id = _data.activeApp.appId;
+ certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
+ return certs;
+ }
- return exports;
+ if (!_data.applications[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
+ return certs;
+ }
-})();
+ function getAppSharedURI(id) {
+ var appId;
-module.exports = _self;
+ t.ApplicationManager("getAppSharedURI", arguments);
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/storage', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.storage
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/10/31
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ if (id === null || id === undefined) {
+ appId = _data.activeApp.appId;
+ return _data.applications[appId].sharedURI;
+ }
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant');
+ if (!_data.applications[id]) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
-var _self = (function () {
+ return _data.applications[id].sharedURI;
+ }
- var exports = {};
+ function addAppInfoEventListener(eventCallback) {
+ var handle;
- //---------------------------------------------------------------------------
- _.extend(exports, {
+ t.ApplicationManager("addAppInfoEventListener", arguments);
- //-------------------------------------------------------------------------
- errstr: function(target) {
- if ( target.error && typeof(target.error.toString) == 'function' )
- return target.error.toString();
- var ret = '';
- var count = 0;
- for ( var key in target.error )
- count += 1;
- if ( count == 1 && target.error.name )
- ret = '' + target.error.name;
- else
- {
- ret = '{';
- for ( var key in target.error )
- {
- ret += key + ': ' + target.error[key];
- count -= 1;
- if ( count > 0 )
- ret += ', ';
+ handle = getHandle();
+ _data.listeners[handle] = eventCallback;
+
+ return handle;
}
+
+ function removeAppInfoEventListener(listenerID) {
+ if (!_data.listeners[listenerID])
+ return;
+
+ delete _data.listeners[listenerID];
}
- if ( target.errorCode )
- {
- if ( ret.length <= 0 || ret == '{}' )
- ret = '' + target.errorCode;
- else
- ret = '[' + target.errorCode + '] ' + ret;
+
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
}
- if ( ret.length <= 0 || ret == '{}' )
- // last ditch effort...
- ret = common.prettyJson(target);
- return ret;
- },
- //-------------------------------------------------------------------------
- openDatabase: function(context, cb) {
- var dbreq = context.storage.indexedDB.open(context.dbname, 1);
- dbreq.onblocked = function(event) {
- cb({code: 'syncml-js.storage.OD.10',
- message: 'database blocked by other process/tab/window'});
- };
- dbreq.onerror = function(event) {
- var errmsg = exports.errstr(event.target);
- cb({code: 'syncml-js.storage.OD.20',
- message: 'failed to open syncml-js database: ' + errmsg});
- };
- dbreq.onupgradeneeded = function(event) {
+ var application = {
+ getCurrentApplication : getCurrentApplication,
+ kill : kill,
+ launch : launch,
+ launchAppControl : launchAppControl,
+ findAppControl : findAppControl,
+ getAppsContext : getAppsContext,
+ getAppContext : getAppContext,
+ getAppsInfo : getAppsInfo,
+ getAppInfo : getAppInfo,
+ getAppCerts : getAppCerts,
+ getAppSharedURI: getAppSharedURI,
+ addAppInfoEventListener : addAppInfoEventListener,
+ removeAppInfoEventListener : removeAppInfoEventListener,
+ handleSubFeatures : handleSubFeatures
+ };
+ return application;
+};
- var db = event.target.result;
+Application = function (appInfo, contextId, metaData) {
+ var application = {}, requestedAppControl;
- var adapterTable = db.createObjectStore('adapter', {keyPath: 'id'});
- adapterTable.createIndex('isLocal', 'isLocal', {unique: false});
- adapterTable.createIndex('devID', 'devID', {unique: true});
+ application.appInfo = appInfo;
+ application.contextId = contextId;
- var mappingTable = db.createObjectStore(
- 'mapping',
- {keyPath: ['store_id', 'guid']});
- mappingTable.createIndex('store_id', 'store_id', {unique: false});
- // mappingTable.createIndex('guid', 'guid', {unique: false});
- // mappingTable.createIndex('luid', 'luid', {unique: false});
+ requestedAppControl = new RequestedApplicationControl(
+ new ApplicationControl(metaData.operation, metaData.appControl.uri,
+ metaData.appControl.mime, metaData.appControl.category,
+ metaData.appControl.data), application.appInfo.id);
- var changeTable = db.createObjectStore(
- 'change',
- {keyPath: ['store_id', 'item_id']});
- changeTable.createIndex('store_id', 'store_id', {unique: false});
- // changeTable.createIndex('item_id', 'item_id', {unique: false});
+ this.__defineGetter__("appInfo", function () {
+ return application.appInfo;
+ });
- };
- dbreq.onsuccess = function(event) {
- cb(null, event.target.result);
- };
- },
+ this.__defineGetter__("contextId", function () {
+ return application.contextId;
+ });
- //-------------------------------------------------------------------------
- getTransaction: function(db, tables, mode) {
- // NOTE: the spec says passing in null should be valid... but
- // mozilla's indexedDB seems to barf with:
- // [Exception... "The operation failed because the
- // requested database object could not be found. For
- // example, an object store did not exist but was
- // being opened." code: "8" nsresult: "0x80660003
- // (NotFoundError)"
- if ( ! tables )
- tables = ['adapter','mapping','change'];
- if ( ! mode )
- mode = 'readwrite';
- return db.transaction(tables, mode);
- },
+ this.exit = function () {
+ event.trigger("tizen-application-exit", [contextId]);
+ };
- //-------------------------------------------------------------------------
- dumpDatabase: function(context, cb) {
+ this.hide = function () {
+ event.trigger("tizen-application-hide", [contextId]);
+ };
- var ret = {};
- var txn = context._txn();
+ this.getRequestedAppControl = function () {
+ return requestedAppControl;
+ };
+};
- var steps = [
- function(cb) {
- exports.getAll(context, txn.objectStore('adapter'), {}, function(err, adapters) {
- ret.adapter = adapters;
- return cb(err);
- });
- },
- function(cb) {
- exports.getAll(context, txn.objectStore('mapping'), {}, function(err, mappings) {
- ret.mapping = mappings;
- return cb(err);
- });
- },
- function(cb) {
- exports.getAll(context, txn.objectStore('change'), {}, function(err, changes) {
- ret.change = changes;
- return cb(err);
- });
- }
- ];
+ApplicationInformation = function (id, name, iconPath, version, show,
+ categories, installDate, size, packageId) {
+ this.__defineGetter__("id", function () {
+ return id;
+ });
- common.cascade(steps, function(step, cb) {
- return step(cb);
- }, function(err) {
- return cb(err, ret);
- });
- },
+ this.__defineGetter__("name", function () {
+ return name;
+ });
- //-------------------------------------------------------------------------
- clearDatabase: function(context, cb) {
- var dbreq = context.storage.indexedDB.open(context.dbname, 1);
- dbreq.onblocked = function(event) {
- cb({code: 'syncml-js.storage.CD.10',
- message: 'database blocked by other process/tab/window'});
- };
- dbreq.onerror = function(event) {
- var errmsg = exports.errstr(event.target);
- cb({code: 'syncml-js.storage.CD.20',
- message: 'failed to open syncml-js database: ' + errmsg});
- };
- dbreq.onsuccess = function(event) {
- var db = event.target.result;
- db.onerror = dbreq.onerror;
- async.map(['adapter', 'mapping', 'change'], function(name, cb) {
- cb();
- }, function(err) {
- if ( err )
- return cb(err);
- db.close();
- });
- };
- },
+ this.__defineGetter__("iconPath", function () {
+ return iconPath;
+ });
- //-------------------------------------------------------------------------
- getAll: function(context, source, options, cb) {
- // supported options:
- // - range
- // - only
- options = options || {};
- var range = options.range;
- if ( ! range && options.only )
- range = context.storage.IDBKeyRange.only(options.only);
- var req = source.openCursor(range);
- var ret = [];
- req.onsuccess = function(event) {
- var cursor = event.target.result;
- if ( cursor )
- {
- ret.push(cursor.value);
- // ret.push({key: cursor.key, value: cursor.value});
- return cursor.continue();
- }
- cb(null, ret);
- };
- req.onerror = function(event) {
- cb(exports.errstr(event.target));
- };
- },
+ this.__defineGetter__("version", function () {
+ return version;
+ });
- //-------------------------------------------------------------------------
- put: function(store, object, cb) {
- var req = store.put(object);
- req.onsuccess = function(event) { cb(); };
- req.onerror = function(event) {
- cb(exports.errstr(event.target));
- };
- },
+ this.__defineGetter__("show", function () {
+ return show;
+ });
- //-------------------------------------------------------------------------
- delete: function(store, objectID, cb) {
- var req = store.delete(objectID);
- req.onsuccess = function(event) { cb(); };
- req.onerror = function(event) {
- cb(exports.errstr(event.target));
- };
- },
+ this.__defineGetter__("categories", function () {
+ return categories;
+ });
- //-------------------------------------------------------------------------
- deleteAll: function(source, matches, cb) {
- var req = source.openCursor();
- req.onsuccess = function(event) {
- var cursor = event.target.result;
- if ( cursor )
- {
- for (key in matches)
- if ( matches[key] != cursor.value[key] )
- return cursor.continue();
- exports.delete(source, cursor.key, function(err) {
- if ( err )
- return cb(err);
- return cursor.continue();
- });
- return;
- }
- cb(null);
- };
- req.onerror = function(event) {
- cb(exports.errstr(event.target));
- };
- },
+ this.__defineGetter__("installDate", function () {
+ return installDate;
+ });
- //-------------------------------------------------------------------------
- iterateCursor: function(openCursor, iterator, cb) {
- openCursor.onsuccess = function(event) {
- var cursor = event.target.result;
- if ( ! cursor )
- return cb();
- iterator(cursor.value.value, cursor.value.id, function(err) {
- if ( err )
- return cb(err);
- return cursor.continue();
- });
- };
- openCursor.onerror = function(event) {
- cb(exports.errstr(event.target));
- };
- }
+ this.__defineGetter__("size", function () {
+ return size;
+ });
+ this.__defineGetter__("packageId", function () {
+ return packageId;
});
+};
- return exports;
+ApplicationContext = function (id, appId) {
+ this.__defineGetter__("id", function () {
+ return id;
+ });
-})();
+ this.__defineGetter__("appId", function () {
+ return appId;
+ });
+};
-module.exports = _self;
+RequestedApplicationControl = function (appControl, callerAppId) {
+ this.__defineGetter__("appControl", function () {
+ return appControl;
+ });
+
+ this.__defineGetter__("callerAppId", function () {
+ return callerAppId;
+ });
+
+ this.replyResult = function (data) {
+ t.RequestedApplicationControl("replyResult", arguments);
+
+ event.trigger("appServiceReplied", "Result: " + data);
+ };
+ this.replyFailure = function () {
+ event.trigger("appServiceReplied", "Failure");
+ };
+};
+
+ApplicationCertificate = function (type, value) {
+ this.__defineGetter__("type", function () {
+ return type;
+ });
+
+ this.__defineGetter__("value", function () {
+ return value;
+ });
+};
+
+jQuery("#app-dialog-return-btn").live("click", function () {
+ $("#app-dialog").dialog("close");
});
-define('ripple/platform/tizen/2.0/syncml-js-lib/store', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.store
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/04
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+jQuery("#app-dialog-reload-btn").live("click", function () {
+ $("#app-dialog").dialog("close");
+ window.tinyHipposReload = true;
+ location.reload();
+});
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
- storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
- ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree');
+jQuery("#app-dialog-generate-reply").live("click", function () {
+ var type, data, ret = [];
+ type = jQuery('input:radio[name="app-dialog-reply-type"]:checked').val();
+ data = jQuery("#app-dialog-reply-json").val();
+ $("#app-dialog").dialog("close");
+ if (_data.activeApp.replyCallback) {
+ switch (type) {
+ case "replyResult":
+ if (_data.activeApp.replyCallback.onsuccess) {
+ if (data === "") {
+ _data.activeApp.replyCallback.onsuccess();
+ } else {
+ try {
+ ret = JSON.parse(data);
+ _data.activeApp.replyCallback.onsuccess(ret);
+ } catch (e) {
+ console.log("replyResult: JSON parsing error: " + e.message);
+ _data.activeApp.replyCallback.onsuccess();
+ }
+ }
+ }
+ break;
+ case "replyFailure":
+ if (_data.activeApp.replyCallback.onfailure) {
+ _data.activeApp.replyCallback.onfailure();
+ }
+ break;
+ }
+ }
+});
+event.on("ApplicationLoad", function () {
+ _initialize();
+});
-var _self = (function () {
- var exports = {};
+event.on("tizen-application-exit", function () {
+ var htmlContent;
+ htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
+ .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
+ .replace(/#application-operation/g, "exit")
+ .replace(/#application-verb/, "launch")
+ .replace(/#next-command/g, "Launch")
+ .replace(/#application-btn/, "app-dialog-reload-btn");
+ jQuery("#app-dialog-box").html(htmlContent);
+ $("#app-dialog").dialog("open");
+});
- //---------------------------------------------------------------------------
- exports.Store = common.Base.extend({
+event.on("tizen-application-hide", function () {
+ var htmlContent;
+ htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
+ .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
+ .replace(/#application-operation/g, "hide")
+ .replace(/#application-verb/, "show")
+ .replace(/#next-command/g, "Show")
+ .replace(/#application-btn/, "app-dialog-return-btn");
+ jQuery("#app-dialog-box").html(htmlContent);
+ $("#app-dialog").dialog("open");
+});
- //-------------------------------------------------------------------------
- constructor: function(adapter, options) {
+event.on("programChanged", function (status, id) {
+ var callback, data, innerApp;
+ _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
+ utils.forEach(_data.applications, function(item) {
+ item.installDate = new Date(item.installDate);
+ });
+ _setupCurrentApp();
+ switch (status) {
+ case "installed":
+ case "updated":
+ innerApp = _data.applications[id];
+ data = new ApplicationInformation(
+ innerApp.id,
+ innerApp.name,
+ innerApp.iconPath,
+ innerApp.version,
+ innerApp.show,
+ innerApp.categories,
+ innerApp.installDate,
+ innerApp.size,
+ innerApp.packageId);
+ break;
+ case "uninstalled":
+ data = id;
+ break;
- // todo: some of these attributes should be modifiable...
+ default:
+ return;
+ }
+ callback = "on" + status;
+ utils.forEach(_data.listeners, function (listener) {
+ listener[callback](data);
+ });
+});
- //: for local stores, specifies the agent that will implement
- //: the actual item operations -- it must implement the
- //: syncml-js.Agent API.
- this.agent = options.agent || null;
+_initialize();
- //: [read-only] specifies the SyncML URI that this store is bound to.
- this.uri = ( adapter ? adapter.normUri(options.uri) : options.uri ) || null;
+module.exports = _self;
- //: [read-only] specifies the human-readable name for this store.
- //: if undefined, defaults to URI.
- this.displayName = options.displayName || this.uri || null;
+});
+define('ripple/platform/tizen/2.0/ContactRef', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- //: [read-only] specifies the maximum GUID size for items in this store.
- //: if undefined, defaults to adapter setting.
- this.maxGuidSize = options.maxGuidSize || null;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactRef;
- //: [read-only] specifies the maximum object size for items in this store.
- //: if undefined, defaults to adapter setting.
- this.maxObjSize = options.maxObjSize || null;
+ContactRef = function (addressBookId, contactId) {
+ var contactRef = {};
- //: [read-only] specifies conflict resolution policy for this store.
- //: if undefined, defaults to adapter setting.
- this.conflictPolicy = options.conflictPolicy || null;
+ t.ContactRef(arguments, this);
- //: [read-only] specifies which syncTypes this store supports.
- //: (defaults to all.)
- this.syncTypes = options.syncTypes;
- if ( this.syncTypes == undefined || this.syncTypes.length <= 0 )
- {
- this.syncTypes = [
- constant.SYNCTYPE_TWO_WAY,
- constant.SYNCTYPE_SLOW_SYNC,
- constant.SYNCTYPE_ONE_WAY_FROM_CLIENT,
- constant.SYNCTYPE_REFRESH_FROM_CLIENT,
- constant.SYNCTYPE_ONE_WAY_FROM_SERVER,
- constant.SYNCTYPE_REFRESH_FROM_SERVER,
- constant.SYNCTYPE_SERVER_ALERTED
- ];
- }
+ contactRef.addressBookId = addressBookId;
+ contactRef.contactId = contactId;
- ctypes = options.contentTypes;
- if ( ! ctypes && options.agent )
- ctypes = options.agent.getContentTypes();
+ this.__defineGetter__("addressBookId", function () {
+ return contactRef.addressBookId;
+ });
+ this.__defineSetter__("addressBookId", function (val) {
+ try {
+ contactRef.addressBookId = t.AddressBookId(val);
+ } catch (e) {
+ }
+ });
- this.contentTypes = _.map(ctypes, function(e) {
- if ( e instanceof ctype.ContentTypeInfo ) {
- return e;
- }
- return ctype.ContentTypeInfo.fromStruct(e);
- });
+ this.__defineGetter__("contactId", function () {
+ return contactRef.contactId;
+ });
+ this.__defineSetter__("contactId", function (val) {
+ try {
+ contactRef.contactId = t.ContactId(val);
+ } catch (e) {
+ }
+ });
+};
- // --- private attributes
- this.id = options.id || common.makeID();
- this._a = adapter;
- },
+module.exports = ContactRef;
- //-------------------------------------------------------------------------
- _load: function(cb) {
- cb();
- },
+});
+define('ripple/platform/tizen/2.0/CalendarEventId', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- //-------------------------------------------------------------------------
- _getModel: function() {
- var self = this;
- var uri = self._a.normUri(self.uri);
- return _.find(this._a._getModel().stores,
- function(s) { return self._a.normUri(s.uri) == uri; });
- },
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ CalendarEventId;
- //-------------------------------------------------------------------------
- _updateModel: function(cb) {
- if ( ! this._a._model || ! this._a._model.stores )
- return cb('store created on un-initialized adapter');
- // TODO: this squashes any data that may already be there, such
- // as *BINDING* info!...
- this._a._model.stores = _.filter(this._a._model.stores, function(e) {
- return e.uri != this.uri;
- }, this);
- this._a._model.stores.push({
- id : this.id,
- uri : this.uri,
- displayName : this.displayName,
- syncTypes : this.syncTypes,
- maxGuidSize : this.maxGuidSize,
- maxObjSize : this.maxObjSize,
- conflictPolicy : this.conflictPolicy,
- contentTypes : _.map(this.contentTypes, function(e) { return e.toStruct(); })
- });
- cb();
- },
+CalendarEventId = function (uid, rid) {
+ var calendarEventId = {};
- //-------------------------------------------------------------------------
- _getBinding: function() {
- return this._getModel().binding;
- },
+ t.CalendarEventId(arguments, this);
+
+ calendarEventId.uid = uid;
+ calendarEventId.rid = rid || null;
+
+ this.__defineGetter__("uid", function () {
+ return calendarEventId.uid;
+ });
+ this.__defineSetter__("uid", function (val) {
+ try {
+ calendarEventId.uid = t.DOMString(val);
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("rid", function () {
+ return calendarEventId.rid;
+ });
+ this.__defineSetter__("rid", function (val) {
+ try {
+ calendarEventId.rid = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+};
- //-------------------------------------------------------------------------
- _setBinding: function(binding) {
- this._getModel().binding = binding;
- },
+module.exports = CalendarEventId;
- //-------------------------------------------------------------------------
- getContentTypes: function() {
- if ( this.agent != undefined ) {
- return this.agent.getContentTypes();
- }
- return this.contentTypes;
- },
+});
+define('ripple/platform/tizen/2.0/content', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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.
+ */
- //-------------------------------------------------------------------------
- getPeerStore: function(peer) {
- var peerUri = null;
- if ( this._a.isLocal ) {
- peerUri = this._a._c.router.getTargetUri(this._a, peer, this.uri);
- }
- else {
- var binding = this.getBinding();
- peerUri = binding ? binding.uri : null;
- }
- if ( ! peerUri ) {
- return null;
- }
- return peer.getStore(peerUri);
- },
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ dbfs = require('ripple/platform/tizen/2.0/dbfs'),
+ dbinit = require('ripple/platform/tizen/2.0/dbinit'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ Content,
+ ContentDirectory,
+ ContentFactory,
+ ContentStorage,
+ AudioContent,
+ ImageContent,
+ VideoContent,
+ ContentInternal,
+ ContentDirectoryInternal,
+ AudioContentInternal,
+ ImageContentInternal,
+ VideoContentInternal,
+ AudioContentLyrics,
+ _data = {
+ DB_CONTENT_KEY: "tizen1-db-content",
+ content: {},
+ listener: null,
+ dbStorage: null
+ },
+ _security = {
+ "http://tizen.org/privilege/content.read": ["find",
+ "setChangeListener", "unsetChangeListener"],
+ "http://tizen.org/privilege/content.write": ["update", "updateBatch",
+ "scanFile"]
+ },
+ _self;
- //-------------------------------------------------------------------------
- merge: function(store, cb) {
- if ( this.uri != store.uri )
- return cb(new common.InternalError(
- 'unexpected merging of stores with different URIs ("' + this.uri
- + '" != "' + store.uri + '")'));
- if ( ! _.isEqual(this.contentTypes, store.contentTypes) )
- {
- // todo: this is a bit drastic... perhaps have an operational setting
- // which controls how paranoid to be?...
- this._setBinding(null);
- }
- this.displayName = store.displayName;
- this.contentTypes = _.rest(store.contentTypes, 0);
- this.syncTypes = _.rest(store.syncTypes, 0);
- this.maxGuidSize = store.maxGuidSize;
- this.maxObjSize = store.maxObjSize;
- this.agent = store.agent;
- this.conflictPolicy = store.conflictPolicy;
- return cb();
- },
+function _get() {
+ _data.dbStorage = db.retrieveObject(_data.DB_CONTENT_KEY) || dbinit.Content;
+}
- //-------------------------------------------------------------------------
- _clearAllMappings: function(cb) {
- if ( this._a.isLocal )
- return cb(new common.InternalError(
- 'unexpected mapping request for local store'));
- var mapping = this._a._c._txn().objectStore('mapping');
- storage.deleteAll(mapping, {store_id: this.id}, cb);
- },
+function _save() {
+ db.saveObject(_data.DB_CONTENT_KEY, _data.dbStorage);
+}
- //-------------------------------------------------------------------------
- _setMapping: function(guid, luid, cb) {
- var self = this;
- if ( this._a.isLocal )
- return cb(new common.InternalError(
- 'unexpected mapping request for local store'));
- // delete all previous mappings for this guid/store (there should
- // be at most one)... but paranoia rules.
- var mapping = this._a._c._txn().objectStore('mapping');
- storage.deleteAll(mapping, {store_id: this.id, guid: guid}, function(err) {
- if ( err ) {
- return cb(err);
- }
- storage.put(mapping, {store_id: self.id, guid: guid, luid: luid}, function(err) {
- if ( err ) {
- return cb(err);
- }
- cb();
- });
- });
- },
+function _initialize() {
+ _get();
- //-------------------------------------------------------------------------
- _getMapping: function(guid, cb) {
- if ( this._a.isLocal )
- return cb(new common.InternalError(
- 'unexpected mapping request for local store'));
- // todo: there must be a way to use IndexedDB since i have everything
- // needed to generate the keyPath!... eg:
- // objectStore.get({store_id:X,guid:Y})?...
- var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
- storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
- if ( err ) {
- return cb(err);
- }
- var item = _.find(list, function(item) {
- return item.guid == guid;
- });
- return cb(null, item ? item.luid : null);
- });
- },
+ if (!_data.dbStorage)
+ return;
- //-------------------------------------------------------------------------
- _getMappings: function(cb) {
- if ( this._a.isLocal )
- return cb(new common.InternalError(
- 'unexpected mapping request for local store'));
- var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
- storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
- if ( err )
- return cb(err);
- return cb(null, _.map(list, function(item) {
- return [item.guid, item.luid];
- }));
- });
- },
+ utils.forEach(_data.dbStorage, function (content) {
+ _data.content[content.directoryURI] = new ContentStorage(content);
+ });
- //-------------------------------------------------------------------------
- _getReverseMapping: function(luid, cb) {
- if ( this._a.isLocal )
- return cb(new common.InternalError(
- 'unexpected mapping request for local store'));
- // todo: there must be a way to use IndexedDB since i have everything
- // needed to generate the keyPath!... eg:
- // objectStore.get({store_id:X,guid:Y})?...
- var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
- storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
- if ( err )
- return cb(err);
- var item = _.find(list, function(item) {
- return item.luid == luid;
- });
- return cb(null, item ? item.guid : null);
- });
- },
+ _data.dbStorage = _data.content;
+ _save();
+}
- //-------------------------------------------------------------------------
- registerChange: function(itemID, state, options, cb) {
- // options can include:
- // - changeSpec (string)
- // - excludePeerID (string)
+_self = function () {
+ var content;
- if ( ! _.contains([constant.ITEM_ADDED, constant.ITEM_MODIFIED,
- constant.ITEM_DELETED], state) )
- return cb(new common.TypeError(
- 'registerChange: invalid state "' + state + '"'));
+ // private
+ function getType(file) {
+ var extName, type;
- options = options || {};
- var self = this;
- if ( self._a.isLocal )
- {
- // TODO: THIS NEEDS TO BE SIGNIFICANTLY OPTIMIZED!... either:
- // a) optimize this reverse lookup, or
- // b) use a query that targets exactly the set of stores needed
- // note that a pre-emptive model.session.flush() may be necessary.
- common.cascade(self._a.getPeers(), function(peer, cb) {
- if ( options.excludePeerID && options.excludePeerID == peer.id )
- return cb();
- common.cascade(peer.getStores(), function(store, cb) {
- var binding = store._getBinding()
- if ( ! binding || binding.uri != self.uri )
- return cb();
- store.registerChange(itemID, state, options, cb);
- }, cb);
- }, cb);
- return;
- }
+ extName = file.substr(file.lastIndexOf(".") + 1).toLowerCase();
- // todo: a non-ADD change event for an ID that has never been
- // seen does not create an error... should it??? that would mean
- // that syncml-js needs to track that. not a good idea.
+ switch (extName) {
+ case "bmp":
+ case "gif":
+ case "jpeg":
+ case "jpg":
+ case "png":
+ type = "IMAGE";
+ break;
- itemID = '' + itemID;
- var handled = false;
+ case "avi":
+ case "mpeg":
+ case "mpg":
+ case "wmv":
+ case "mp4":
+ type = "VIDEO";
+ break;
- // paranoia
- if ( options.changeSpec && state != constant.ITEM_MODIFIED )
- {
- options.changeSpec = null;
- }
+ case "wav":
+ case "mp3":
+ type = "AUDIO";
+ break;
- var check_update = function(cb) {
- self._getChange(itemID, function(err, change) {
- if ( err )
- return cb(err);
- if ( ! change)
- return cb();
- var badstate = function(action) {
- };
- // note: many of the following change.state / state combinations
- // should never occur. the following tries to recover gracefully.
- // todo: should i raise an error for "illogical" conditions?
- switch ( change.state )
- {
- case constant.ITEM_ADDED:
- {
- if ( state != constant.ITEM_DELETED )
- {
- // ADD + anything except DELETE stays ADD
- handled = true;
- return cb();
- }
- // ADD + DELETE cancels out
- handled = true;
- var changeTab = self._a._c._txn().objectStore('change');
- storage.deleteAll(changeTab, change, function(err) {
- if ( err )
- return cb(err);
- return cb();
- });
- return;
- }
- case constant.ITEM_MODIFIED:
- {
- if ( state == constant.ITEM_ADDED )
- {
- badstate('squelching changeSpec');
- delete change.changeSpec;
- break;
- }
- if ( state == constant.ITEM_DELETED )
- {
- change.state = state;
- delete change.changeSpec;
- break;
- }
- if ( change.changeSpec )
- {
- if ( options.changeSpec )
- change.changeSpec += ';' + options.changeSpec;
- else
- delete change.changeSpec;
- }
- break;
- }
- case constant.ITEM_DELETED:
- {
- if ( state == constant.ITEM_DELETED )
- {
- badstate('ignoring');
- handled = true;
- return cb();
- }
- badstate('reverting to modified');
- change.state = constant.ITEM_MODIFIED;
- delete change.changeSpec;
- break;
- }
- default:
- {
- return cb(new common.InternalError(
- 'unexpected recorded change state "' + change.state
- + '" for item ID "' + itemID + '"'));
- }
- }
- // update the change
- // todo: do i need to delete it first?
- handled = true;
- return storage.put(
- self._a._c._txn().objectStore('change'),
- change,
- cb);
- });
- };
+ default:
+ type = "OTHER";
+ break;
+ }
- var check_mapping = ( self._a._isMapper() || state == constant.ITEM_ADDED )
- ? common.noop
- : function(cb) {
- // doing a `_getMapping` for non-add events to make sure that
- // the remote peer actually has this object before we tell it
- // to modify or delete an item...
- self._getMapping(itemID, function(err, luid) {
- if ( err )
- return cb(err);
- if ( luid )
- return cb();
- // this item does not exist as (or has not been mapped to) an
- // item on the remote peer and is not an `ADD` event, so can
- // therefore be ignored - mark it as "handled".
- handled = true;
- return cb();
- });
- };
+ return type;
+ }
- // todo: there is a weirdness here wrt `handled` in the case
- // of check_mapping and deletes... ie. there is a bit of
- // a responsibility violation (handled does not actually
- // mean handled...)
+ function getMimeType(file) {
+ var mimeTypeTab = {
+ IMAGE: "image/x-msimage",
+ VIDEO: "video/x-msvideo",
+ AUDIO: "audio/x-msaudio",
+ OTHER: "other/unknown"
+ };
- check_update(function(err) {
- if ( err )
- return cb(err);
- if ( handled )
- return cb();
- check_mapping(function(err) {
- if ( err )
- return cb(err);
- if ( handled && state != constant.ITEM_DELETED )
- return cb();
- // note: if it is a delete event, and it has not been mapped
- // yet, so does not yet exist on the peer, therefore
- // propagate nothing -- continuing just to execute the
- // deleteAll().
- var changeTab = self._a._c._txn().objectStore('change');
- change = {store_id: self.id, item_id: itemID};
- // todo: is this deleteAll really necessary?... paranoia rules!
- storage.deleteAll(changeTab, change, function(err) {
- if ( err )
- return cb(err);
- if ( handled )
- return cb();
- change.state = state;
- change.changeSpec = options.changeSpec;
- storage.put(changeTab, change, cb);
- });
- });
- });
- },
+ return mimeTypeTab[getType(file)];
+ }
- //-------------------------------------------------------------------------
- _getChange: function(itemID, cb) {
- // returns cb(null, CHANGE)
- // change ::= { store_id: ID, item_id: GUID, state: STATE, changeSpec: SPEC }
- itemID = '' + itemID;
- var self = this;
- // todo: there must be a way to use IndexedDB since i have everything
- // needed to generate the keyPath!... eg:
- // objectStore.get({store_id:X,guid:Y})?...
- var changedb = self._a._c._txn().objectStore('change').index('store_id');
- storage.getAll(self._a._c, changedb, {only: self.id}, function(err, changes) {
- if ( err )
- return cb(err);
- var change = _.find(changes, function(change) {
- return change.item_id == itemID;
- });
- return cb(null, change);
- });
- },
+ function getTitle(file) {
+ var title;
- //-------------------------------------------------------------------------
- _delChange: function(options, cb) {
- // - if options is null/empty, delete all changes recorded
- // for this store
+ title = file.substr(0, file.lastIndexOf("."));
+ title = title.charAt(0).toUpperCase() + title.substr(1).toLowerCase();
- // // todo: this is *technically* subject to a race condition... but the
- // // same peer should really not be synchronizing at the same time...
- // // todo: also potentially check Change.registered...
- // // TODO: this could be solved by:
- // // a) never updating a Change record (only deleting and replacing)
- // // b) deleting Change records by ID instead of by store/item/state...
+ return title;
+ }
- // var objstore = session.context._txn().objectStore('change');
- // storage.iterateCursor(
- // objstore.index('store_id').openCursor(peerStore.id),
- // function(value, key, cb) {
- // if ( value.itemID != chkcmd.source || value.state != constant.ITEM_ADDED )
- // return;
- // storage.delete(objstore, key, cb);
- // }, cb);
+ function getDirectoryURI(contentURI) {
+ return contentURI.slice(0, contentURI.lastIndexOf("/") + 1)
+ .replace(/file:\/\//, "");
+ }
- var dbstore = this._a._c._txn().objectStore('change');
- var matches = {store_id: this.id};
- if ( options.itemID )
- matches.item_id = options.itemID;
- if ( options.state )
- matches.state = options.state;
- storage.deleteAll(dbstore, matches, cb);
- },
+ function extractProperties(entry) {
+ var contentInitDict = {};
- //-------------------------------------------------------------------------
- toSyncML: function() {
- var xstore = ET.Element('DataStore');
- if ( this.uri )
- ET.SubElement(xstore, 'SourceRef').text = this.uri;
- if ( this.displayName )
- ET.SubElement(xstore, 'DisplayName').text = this.displayName;
- if ( this.maxGuidSize )
- {
- // todo: this should ONLY be sent by the client... (according to the
- // spec, but not according to funambol behavior...)
- ET.SubElement(xstore, 'MaxGUIDSize').text = this.maxGuidSize;
- }
- if ( this.maxObjSize )
- ET.SubElement(xstore, 'MaxObjSize').text = this.maxObjSize;
+ contentInitDict.editableAttributes = ["name", "title", "description",
+ "rating"];
+ contentInitDict.name = entry.name;
+ contentInitDict.type = getType(entry.name);
+ contentInitDict.mimeType = getMimeType(entry.name);
+ contentInitDict.title = getTitle(entry.name);
+ contentInitDict.contentURI = entry.fullPath ?
+ "file://" + entry.fullPath : entry.fullPath;
+ contentInitDict.thumbnailURIs = [entry.fullPath];
+ contentInitDict.releaseDate = entry.lastModifiedDate;
+ contentInitDict.modifiedDate = entry.lastModifiedDate;
+ contentInitDict.size = 1048576;
- var ctypes = this.getContentTypes();
+ return contentInitDict;
+ }
- if ( ctypes && ctypes.length > 0 )
- {
- var pref = _.filter(ctypes, function(ct) { return ct.receive && ct.preferred; });
+ function updateContents(contents, successCallback, errorCallback) {
+ var i, isFound = false, dir, matched = [];
- // todo: should i just take the first one?...
- if ( pref.length > 1 )
- throw new Error('agents can prefer at most one receive content-type');
+ for (i in contents) {
+ dir = getDirectoryURI(contents[i].contentURI);
- if ( pref.length == 1 )
- {
- pref = pref[0].toSyncML('Rx', true);
- pref[0].tag = 'Rx-Pref';
- _.each(pref, function(xnode) { xstore.append(xnode); });
- }
+ isFound = ((dir in _data.content) && (contents[i].contentURI in
+ _data.content[dir].contents));
- _.each(
- _.filter(ctypes, function(ct) { return ct.receive && ! ct.preferred; }),
- function(ct) {
- _.each(ct.toSyncML('Rx', true), function(xnode) {
- xstore.append(xnode);
- });
- });
+ if (!isFound)
+ break;
- var pref = _.filter(ctypes, function(ct) { return ct.transmit && ct.preferred; });
+ matched.push(dir);
+ }
- // todo: should i just take the first one?...
- if ( pref.length > 1 )
- throw new Error('agents can prefer at most one transmit content-type');
+ if (!isFound) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
- if ( pref.length == 1 )
- {
- pref = pref[0].toSyncML('Tx', true);
- pref[0].tag = 'Tx-Pref';
- _.each(pref, function(xnode) { xstore.append(xnode); });
- }
+ for (i in matched) {
+ _data.content[matched[i]].contents[contents[i].contentURI] =
+ new ContentFactory(contents[i], true);
+ }
- _.each(
- _.filter(ctypes, function(ct) { return ct.transmit && ! ct.preferred; }),
- function(ct) {
- _.each(ct.toSyncML('Tx', true), function(xnode) {
- xstore.append(xnode);
- });
- });
+ _save();
- }
+ if (successCallback) {
+ successCallback();
+ }
- if ( this.syncTypes && this.syncTypes.length > 0 )
- {
- var xcap = ET.SubElement(xstore, 'SyncCap');
- for ( var idx=0 ; idx<this.syncTypes.length ; idx++ )
- ET.SubElement(xcap, 'SyncType').text = this.syncTypes[idx];
+ if (_data.listener !== null) {
+ for (i in matched) {
+ _data.listener.oncontentupdated(new ContentFactory(_data
+ .content[matched[i]].contents[contents[i].contentURI],
+ false));
}
- return xstore;
+ }
+ }
- },
+ // public
+ function update(content) {
+ if (!_security.update) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- describe: function(stream, cb) {
- stream.writeln('URI: ' + this.uri);
- stream.writeln('Max ID size: ' + ( this.maxGuidSize || '(none)' ));
- stream.writeln('Max object size: ' + ( this.maxObjSize || '(none)' ));
- stream.writeln('Sync types: ' + this.syncTypes.join(', '));
- var cts = this.getContentTypes();
- if ( cts.length <= 0 )
- {
- stream.writeln('Capabilities: (none)');
- return cb();
- }
- stream.writeln('Capabilities:');
- var s1 = new common.IndentStream(stream);
- common.cascade(cts, function(ct, cb) {
- s1.write('- ');
- ct.describe(s1);
- return cb();
- }, cb);
+ t.ContentManager("update", arguments);
+
+ updateContents([content]);
+ }
+
+ function updateBatch(contents, successCallback, errorCallback) {
+ if (!_security.updateBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
}
- }, {
- //-------------------------------------------------------------------------
- fromSyncML: function(xnode) {
- var options = {
- uri : xnode.findtext('SourceRef'),
- displayName : xnode.findtext('DisplayName'),
- maxGuidSize : common.int(xnode.findtext('MaxGUIDSize')),
- maxObjSize : common.int(xnode.findtext('MaxObjSize')),
- contentTypes : [],
- syncTypes : _.map(xnode.findall('SyncCap/SyncType'), function(e) {
- return common.int(e.text);
- })
- };
- _.each(xnode.getchildren(), function(child) {
- if ( _.indexOf(['Rx-Pref', 'Rx', 'Tx-Pref', 'Tx'], child.tag) < 0 )
- return;
- var cti = ctype.ContentTypeInfo.fromSyncML(child);
- var merged = false;
- _.each(options.contentTypes, function(ct) {
- if ( merged )
- return;
- if ( ct.merge(cti) )
- merged = true;
- });
- if ( ! merged )
- options.contentTypes.push(cti);
- });
- return new exports.Store(null, options);
- },
- });
+ t.ContentManager("updateBatch", arguments, true);
- return exports;
+ window.setTimeout(function () {
+ updateContents(contents, successCallback, errorCallback);
+ }, 1);
+ }
-})();
+ function getDirectories(successCallback, errorCallback) {
+ t.ContentManager("getDirectories", arguments);
-module.exports = _self;
+ window.setTimeout(function () {
+ var i, directories = [];
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.synchronizer
-// auth: griffin <griffin@uberdev.org>
-// date: 2012/11/05
-// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ for (i in _data.content) {
+ directories.push(new ContentDirectory(_data.content[i]));
+ }
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
- state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
- protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
- storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
- _self;
+ if (directories.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
-_self = (function () {
+ successCallback(directories);
+ }, 1);
+ }
- var exports = {};
- var badStatus = protocol.badStatus;
+ function find(successCallback, errorCallback, directoryId, filter, sortMode,
+ count, offset) {
+ if (!_security.find) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //---------------------------------------------------------------------------
- exports.Synchronizer = common.Base.extend({
+ t.ContentManager("find", arguments, true);
- //-------------------------------------------------------------------------
- constructor: function(options) {
- },
+ window.setTimeout(function () {
+ var i, dir, contents = [], results = [], matchedDir;
- //-------------------------------------------------------------------------
- initStoreSync: function(session, cb) {
- async.eachSeries(session.peer._getModel().stores, function(rstore, cb) {
- // TODO: should the server-side be doing this? probably not
- // since store mapping is a client-side decision...
- var ruri = session.peer.normUri(rstore.uri);
- if ( session.info.dsstates[ruri] || ! rstore.binding )
- return cb();
- var lstore = session.adapter.getStore(rstore.binding.uri);
- if ( ! lstore || ! lstore.agent )
- return cb();
- var ds = state.makeStoreSyncState({
- uri : lstore.uri,
- peerUri : ruri,
- lastAnchor : rstore.binding.localAnchor,
- mode : session.info.mode || constant.ALERT_TWO_WAY,
- action : 'alert'
- });
- if ( ! ds.lastAnchor )
- {
- switch ( ds.mode )
- {
- case constant.ALERT_SLOW_SYNC:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_SERVER:
- {
- break;
- }
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- {
- if ( session.info.mode == constant.SYNCTYPE_AUTO )
- {
- ds.mode = constant.ALERT_SLOW_SYNC;
- break;
- }
- var uaEvent = {
- session : session,
- store : lstore,
- peerStore : rstore,
- modeReq : ds.mode
- };
- return session.ua.chooseRefreshRequired(uaEvent, function(err, mode) {
- if ( err )
- return cb(err);
- if ( ! _.contains([constant.ALERT_SLOW_SYNC,
- constant.ALERT_REFRESH_FROM_CLIENT,
- constant.ALERT_REFRESH_FROM_SERVER], mode) )
- return cb(new common.TypeError(
- 'invalid mode chosen for refresh: ' + common.j(mode)));
- ds.mode = mode;
- session.info.dsstates[ds.uri] = ds;
- return cb();
- });
+ if (!directoryId) {
+ for (dir in _data.content) {
+ for (i in _data.content[dir].contents) {
+ contents.push(_data.content[dir].contents[i]);
}
- default:
- {
- return cb(new common.InternalError(
- 'unexpected sync mode "' + ds.mode + '" requested'));
+ }
+ } else {
+ for (dir in _data.content) {
+ if (_data.content[dir].id === directoryId) {
+ matchedDir = dir;
+ break;
}
- }
- }
- session.info.dsstates[ds.uri] = ds;
- return cb();
- }, cb);
- },
+ }
- //-------------------------------------------------------------------------
- // SYNCHRONIZATION PHASE: ACTION
- //-------------------------------------------------------------------------
+ if (!matchedDir) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
- //-------------------------------------------------------------------------
- actions: function(session, commands, cb) {
- var self = this;
- common.cascade(_.keys(session.info.dsstates), function(uri, cb) {
- var ds = session.info.dsstates[uri];
- if ( ds.action == 'done' )
- return cb();
- // TODO: is this the right handling of an "error" dsstate?...
- if ( ds.action == 'error' )
- return cb();
- var func = self['_action_' + ds.action.toLowerCase()];
- if ( ! func )
- return cb(new common.InternalError(
- 'unexpected store action "' + ds.action + '"'));
- try{
- func.call(self, session, ds, function(err, cmds) {
- if ( err )
- return cb(err);
- _.each(cmds, function(cmd) { commands.push(cmd); });
- return cb();
- });
- }catch(e){
- return cb(new common.InternalError(
- 'failed invoking synchronizer action: ' + e, e));
+ for (i in _data.content[matchedDir].contents) {
+ contents.push(_data.content[matchedDir].contents[i]);
+ }
}
- }, function(err) {
- if ( err )
- return cb(err);
- return cb(null, commands);
- });
- },
- //-------------------------------------------------------------------------
- _action_alert: function(session, dsstate, cb) {
+ if (contents.length === 0) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
- var src = session.adapter.getStore(dsstate.uri);
- var tgt = session.peer.getStore(dsstate.peerUri);
+ contents = tizen1_utils.query(contents, filter, sortMode, count,
+ offset);
- // TODO: ensure that mode is acceptable...
+ contents.forEach(function (content) {
+ results.push(new ContentFactory(content, false));
+ });
- // todo: perhaps i should only specify maxObjSize if it differs from
- // adapter.maxObjSize?...
+ successCallback(results);
+ }, 1);
+ }
- return cb(null, [state.makeCommand({
- name : constant.CMD_ALERT,
- cmdID : session.nextCmdID(),
- data : dsstate.mode,
- source : src.uri,
- target : tgt.uri,
- lastAnchor : dsstate.lastAnchor,
- nextAnchor : dsstate.nextAnchor,
- maxObjSize : src.maxObjSize,
- })]);
+ function scanFile(contentURI, successCallback, errorCallback) {
+ var dir, isFound;
- },
+ function onStatSuccess(entry) {
+ var contentInitDict, content;
- //-------------------------------------------------------------------------
- _action_send: function(session, dsstate, cb) {
- var store = session.adapter.getStore(dsstate.uri);
- var agent = store.agent;
- var peerStore = session.peer.getStore(dsstate.peerUri);
+ if (isFound) {
+ content = new ContentFactory(_data.content[dir]
+ .contents[contentURI], true);
+ } else {
+ contentInitDict = extractProperties(entry);
+ content = new ContentFactory(contentInitDict, true);
+ _data.content[dir].contents[contentURI] = content;
+ }
- var cmd = state.makeCommand({
- name : constant.CMD_SYNC,
- cmdID : session.nextCmdID(),
- source : dsstate.uri,
- // target : adapter.router.getTargetUri(uri),
- target : dsstate.peerUri
- });
+ _save();
- switch ( dsstate.mode )
- {
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_SLOW_SYNC:
- case constant.ALERT_ONE_WAY_FROM_CLIENT:
- case constant.ALERT_REFRESH_FROM_CLIENT:
- case constant.ALERT_ONE_WAY_FROM_SERVER:
- case constant.ALERT_REFRESH_FROM_SERVER:
- // todo: these should only be received out-of-band, right?...
- // case constant.ALERT_TWO_WAY_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
- // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
- // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
- {
- break;
- }
- default:
- {
- return cb(new common.InternalError(
- 'unexpected sync mode "' + common.mode2string(dsstate.mode) + '"'));
- }
+ if (successCallback) {
+ successCallback(contentURI);
}
- if ( session.isServer )
- {
- if ( dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT
- || dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT )
- {
- cmd.noc = 0;
- return cb(null, [cmd]);
+ if (_data.listener !== null) {
+ if (isFound) {
+ _data.listener.oncontentupdated(
+ new ContentFactory(content, false));
+ } else {
+ _data.listener.oncontentadded(
+ new ContentFactory(content, false));
}
}
+ }
- if ( ! session.isServer )
- {
- if ( dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER
- || dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER )
- {
- cmd.noc = 0;
- return cb(null, [cmd]);
+ function onStatError() {
+ if (isFound) {
+ delete _data.content[dir].contents[contentURI];
+ _save();
+
+ if (successCallback) {
+ successCallback(contentURI);
+ }
+
+ if (_data.listener !== null) {
+ _data.listener.oncontentremoved(_data.content[dir]
+ .contents[contentURI].id);
}
+ } else if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
}
+ }
- switch ( dsstate.mode )
- {
+ if (!_security.scanFile) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- case constant.ALERT_TWO_WAY:
- case constant.ALERT_ONE_WAY_FROM_CLIENT: // when ! session.isServer
- case constant.ALERT_ONE_WAY_FROM_SERVER: // when session.isServer
- {
- // send local changes
+ t.ContentManager("scanFile", arguments);
- storage.getAll(
- session.context,
- session.txn().objectStore('change').index('store_id'),
- {only: peerStore.id},
- function(err, changes) {
- if ( err )
- return cb(err);
- var ctype = session.context.router.getBestTransmitContentType(
- session.adapter, session.peer, dsstate.uri);
- cmd.data = [];
+ window.setTimeout(function () {
+ dir = getDirectoryURI(contentURI);
- // TODO: add support for hierarchical operations...
- // including MOVE, COPY, etc.
+ isFound = ((dir in _data.content) &&
+ (contentURI in _data.content[dir].contents));
- // TODO: this assumes that the entire object set can fit in memory...
- // perhaps, as a work-around, just keep a reference to the object
- // and then stream-based serialize it actually gets converted to
- // XML.
+ dbfs.stat(contentURI.replace(/file:\/\//, ""), onStatSuccess,
+ onStatError);
+ }, 1);
+ }
- common.cascade(changes, function(change, cb) {
+ function setChangeListener(changeCallback) {
+ if (!_security.setChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- if ( dsstate.conflicts && _.indexOf(dsstate.conflicts, change.item_id) >= 0 )
- return cb();
+ t.ContentManager("setChangeListener", arguments);
- var scmdtype = null;
- switch ( change.state )
- {
- case constant.ITEM_ADDED: scmdtype = constant.CMD_ADD; break;
- case constant.ITEM_MODIFIED: scmdtype = constant.CMD_REPLACE; break;
- case constant.ITEM_DELETED: scmdtype = constant.CMD_DELETE; break;
- default:
- {
- return cb();
- }
- }
+ _data.listener = changeCallback;
+ }
- // todo: do something with the ctype version (ie. ctype[1])?...
- var scmd = state.makeCommand({
- name : scmdtype,
- cmdID : session.nextCmdID(),
- format : constant.FORMAT_AUTO,
- type : change.state != constant.ITEM_DELETED ? ctype[0] : null,
- uri : dsstate.uri
- });
+ function unsetChangeListener() {
+ if (!_security.unsetChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- // TODO: need to add hierarchical addition support here...
+ _data.listener = null;
+ }
- var set_data = scmdtype == constant.CMD_DELETE ? common.noop : function(cb) {
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
- agent.getItem(change.item_id, function(err, item) {
- if ( err )
- return cb(err);
- agent.dumpsItem(item, ctype[0], ctype[1], function(err, data, nct, nv) {
- if ( err )
- return cb(err);
- scmd.data = data;
- scmd.type = nct || scmd.type;
- // todo: what to do with the content-type version?... eg.
- // scmd.version = nv || scmd.version;
- // TODO: support hierarchical sync
- // if ( agent.hierarchicalSync && item.parent )
- // scmd.sourceParent = '' + item.parent
- return cb();
- });
- });
- };
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
+
+ content = {
+ update: update,
+ updateBatch: updateBatch,
+ getDirectories: getDirectories,
+ find: find,
+ scanFile: scanFile,
+ setChangeListener: setChangeListener,
+ unsetChangeListener: unsetChangeListener,
+ handleSubFeatures: handleSubFeatures
+ };
- var set_target = scmdtype == constant.CMD_ADD ? function(cb) {
- scmd.source = change.item_id;
- cb();
- } : function(cb) {
- if ( ! session.isServer )
- {
- scmd.source = change.item_id;
- return cb();
- }
- peerStore._getMapping(change.item_id, function(err, luid) {
- if ( err )
- return cb(err);
- if ( luid )
- scmd.target = luid;
- else
- scmd.source = change.item_id;
- cb();
- });
- };
+ return content;
+};
- set_data(function(err) {
- if ( err )
- return cb(err);
- set_target(function(err) {
- if ( err )
- return cb(err);
- cmd.data.push(scmd);
- return cb();
- });
- });
- }, function(err) {
- if ( err )
- return cb(err);
- cmd.noc = cmd.data.length;
- return cb(null, [cmd]);
- });
- }
- );
- return;
- }
- case constant.ALERT_SLOW_SYNC:
- case constant.ALERT_REFRESH_FROM_SERVER: // when session.isServer
- case constant.ALERT_REFRESH_FROM_CLIENT: // when ! session.isServer
- {
- // todo: this approach assumes that the entire object set can fit
- // in memory... perhaps move to an iterator-based approach?...
- cmd.data = [];
+ContentDirectoryInternal = function (contentDirectoryInitDict) {
+ this.id = contentDirectoryInitDict.id || null;
+ this.directoryURI = contentDirectoryInitDict.directoryURI || null;
+ this.title = contentDirectoryInitDict.title || "";
+ this.storageType = contentDirectoryInitDict.storageType || "INTERNAL";
+ this.modifiedDate = contentDirectoryInitDict.modifiedDate ?
+ new Date(contentDirectoryInitDict.modifiedDate) : null;
+};
- agent.getAllItems(function(err, items) {
+ContentDirectory = function (contentDirectoryInitDict) {
+ var contentDirectory = {};
- if ( err )
- return cb(err);
+ contentDirectory.id = contentDirectoryInitDict.id || null;
+ contentDirectory.directoryURI = contentDirectoryInitDict.directoryURI || null;
+ contentDirectory.title = contentDirectoryInitDict.title || "";
+ contentDirectory.storageType = contentDirectoryInitDict.storageType || "INTERNAL";
+ contentDirectory.modifiedDate = contentDirectoryInitDict.modifiedDate ?
+ new Date(contentDirectoryInitDict.modifiedDate) : null;
- // TODO: support hierarchical sync...
+ this.__defineGetter__("id", function () {
+ return contentDirectory.id;
+ });
- if ( agent.hierarchicalSync )
- {
- return cb(new common.NotImplementedError('hierarchical-sync'));
- // orditems = [] # the ordered items
- // dunitems = dict() # lut of the ordered items
- // curitems = dict() # lut of current items (for loop detection)
- // lutitems = dict([(item.id, item) for item in items])
- // def appenditem(item):
- // if item.id in dunitems:
- // return
- // if item.id in curitems:
- // raise common.LogicalError('recursive item hierarchy detected at item %r' % (item,))
- // curitems[item.id] = True
- // if item.parent is not None:
- // appenditem(lutitems[item.parent])
- // orditems.append(item)
- // dunitems[item.id] = item
- // for item in items:
- // curitems = dict()
- // appenditem(item)
- }
+ this.__defineGetter__("directoryURI", function () {
+ return contentDirectory.directoryURI;
+ });
- var ctype = session.context.router.getBestTransmitContentType(
- session.adapter, session.peer, dsstate.uri);
+ this.__defineGetter__("title", function () {
+ return contentDirectory.title;
+ });
- common.cascade(items, function(item, cb) {
+ this.__defineGetter__("storageType", function () {
+ return contentDirectory.storageType;
+ });
- // TODO: these should all be non-deleted items, right?...
+ this.__defineGetter__("modifiedDate", function () {
+ return contentDirectory.modifiedDate;
+ });
+};
- if ( _.indexOf(dsstate.conflicts, '' + item.id) >= 0 )
- return cb();
+ContentInternal = function (contentInitDict) {
+ this.editableAttributes = contentInitDict.editableAttributes || [];
+ this.id = contentInitDict.id || Math.uuid(null, 16);
+ this.type = contentInitDict.type || "IMAGE";
+ this.mimeType = contentInitDict.mimeType || "";
+ this.title = contentInitDict.title || "";
+ this.contentURI = contentInitDict.contentURI || "";
+ this.thumbnailURIs = contentInitDict.thumbnailURIs || null;
+ this.releaseDate = contentInitDict.releaseDate ?
+ new Date(contentInitDict.releaseDate) : null;
+ this.modifiedDate = contentInitDict.modifiedDate ?
+ new Date(contentInitDict.modifiedDate) : null;
+ this.size = contentInitDict.size || 0;
+ this.name = contentInitDict.name || "";
+ this.description = contentInitDict.description || null;
+ this.rating = contentInitDict.rating || 0;
+};
- // note: need to check for mappings since on slow-sync, the
- // server will already have received the client's "add" commands
- // at this point (and therefore should not send them back...)
- var check_sync = function(cb) {
- if ( ! session.isServer )
- return cb(null, true);
- peerStore._getMapping(item.id, function(err, luid) {
- return cb(err, luid ? false : true);
- });
- };
+Content = function (contentInitDict) {
+ var content = {};
- check_sync(function(err, dosync) {
- if ( err )
- return cb(err);
+ content.editableAttributes = contentInitDict.editableAttributes || [];
+ content.id = contentInitDict.id || Math.uuid(null, 16);
+ content.name = contentInitDict.name || "";
+ content.type = contentInitDict.type || "IMAGE";
+ content.mimeType = contentInitDict.mimeType || "";
+ content.title = contentInitDict.title || "";
+ content.contentURI = contentInitDict.contentURI || "";
+ content.thumbnailURIs = contentInitDict.thumbnailURIs || null;
+ content.releaseDate = contentInitDict.releaseDate ?
+ new Date(contentInitDict.releaseDate) : null;
+ content.modifiedDate = contentInitDict.modifiedDate ?
+ new Date(contentInitDict.modifiedDate) : null;
+ content.size = contentInitDict.size || 0;
+ content.description = contentInitDict.description || null;
+ content.rating = contentInitDict.rating || 0;
- if ( ! dosync )
- return cb();
+ this.__defineGetter__("editableAttributes", function () {
+ return content.editableAttributes;
+ });
- agent.dumpsItem(
- item, ctype[0], ctype[1],
- function(err, data, new_ct, new_v) {
+ this.__defineGetter__("id", function () {
+ return content.id;
+ });
- if ( err )
- return cb(err);
+ this.__defineGetter__("name", function () {
+ return content.name;
+ });
+ this.__defineSetter__("name", function (val) {
+ try {
+ content.name = t.DOMString(val);
+ } catch (e) {
+ }
+ });
- // todo: do something with the content-type version...
- var scmd = state.makeCommand({
- name : constant.CMD_ADD,
- cmdID : session.nextCmdID(),
- format : constant.FORMAT_AUTO,
- type : new_ct || ctype[0],
- uri : dsstate.uri,
- source : '' + item.id,
- data : data
- });
+ this.__defineGetter__("type", function () {
+ return content.type;
+ });
- if ( agent.hierarchicalSync )
- {
- // TODO: support hierarchical sync...
- // if agent.hierarchicalSync and item.parent is not None:
- // scmd.sourceParent = str(item.parent)
- return cb(new common.NotImplementedError('hierarchical-sync'));
- }
+ this.__defineGetter__("mimeType", function () {
+ return content.mimeType;
+ });
- cmd.data.push(scmd);
- return cb();
- });
+ this.__defineGetter__("title", function () {
+ return content.title;
+ });
- });
+ this.__defineGetter__("contentURI", function () {
+ return content.contentURI;
+ });
- }, function(err) {
- if ( err )
- return cb(err);
- cmd.noc = cmd.data.length;
- return cb(null, [cmd]);
- });
+ this.__defineGetter__("thumbnailURIs", function () {
+ return content.thumbnailURIs;
+ });
- });
- return;
- }
- }
+ this.__defineGetter__("releaseDate", function () {
+ return content.releaseDate;
+ });
- return cb(new common.InternalError(
- 'unexpected sync situation (action=' + dsstate.action
- + ', mode=' + common.mode2string(dsstate.mode)
- + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));
- },
+ this.__defineGetter__("modifiedDate", function () {
+ return content.modifiedDate;
+ });
- //-------------------------------------------------------------------------
- _action_save: function(session, dsstate, cb) {
- if ( ! session.isServer )
- // TODO: for now, only servers should take the "save" action - the client
- // will explicitly do this at the end of the .sync() method.
- // ... mostly because clients don't call synchronizer.actions()
- // one final time ...
- // *BUT* perhaps that should be changed?... for example, .sync()
- // could call synchronizer.actions() to cause action_save's to occur
- // *AND* verify that synchronizer.actions() does not return anything...
- return cb(new common.InternalError(
- 'unexpected sync save situation (action=' + dsstate.action
- + ', mode=' + common.mode2string(dsstate.mode)
- + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));
+ this.__defineGetter__("size", function () {
+ return content.size;
+ });
- var peerStore = session.peer.getStore(dsstate.peerUri);
- var binding = peerStore._getBinding();
- binding.localAnchor = dsstate.nextAnchor;
- binding.remoteAnchor = dsstate.peerNextAnchor;
- return cb(null);
- },
+ this.__defineGetter__("description", function () {
+ return content.description;
+ });
+ this.__defineSetter__("description", function (val) {
+ try {
+ content.description = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- //-------------------------------------------------------------------------
- // SYNCHRONIZATION PHASE: REACTION
- //-------------------------------------------------------------------------
+ this.__defineGetter__("rating", function () {
+ return content.rating;
+ });
+ this.__defineSetter__("rating", function (val) {
+ try {
+ val = t.unsigned_long(val);
+ if ((val < 0) || (val > 10))
+ return;
+ content.rating = val;
+ } catch (e) {
+ }
+ });
+};
- //-------------------------------------------------------------------------
- reactions: function(session, commands, cb) {
- var self = this;
- var ret = [];
- session.hierlut = null;
- common.cascade(commands, function(cmd, cb) {
- var func = self['_reaction_' + cmd.name.toLowerCase()];
- if ( ! func )
- return cb(new common.InternalError(
- 'unexpected store reaction "' + cmd.name + '"'));
- try{
- func.call(self, session, cmd, function(err, cmds) {
- if ( err ) {
- return cb(err);
- }
- _.each(cmds, function(cmd) { ret.push(cmd); });
- return cb();
- });
- }catch(e){
- return cb(new common.InternalError(
- 'failed invoking synchronizer reaction: ' + e, e));
- }
- }, function(err) {
- session.hierlut = null;
- if ( err )
- return cb(err);
- return cb(null, ret);
- });
- },
+VideoContentInternal = function (videoContentInitDict) {
+ ContentInternal.call(this, videoContentInitDict);
- //-------------------------------------------------------------------------
- _reaction_sync: function(session, command, cb) {
- var self = this;
- var ret = [state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : command.msgID,
- cmdRef : command.cmdID,
- targetRef : command.target,
- sourceRef : command.source,
- statusOf : command.name,
- statusCode : constant.STATUS_OK
- })];
- var store = session.adapter.getStore(session.adapter.normUri(command.target));
- var dsstate = session.info.dsstates[store.uri];
- if ( ! store.agent )
- {
- // todo: this is a bit different handling than anywhere else...
- // should everywhere else be like here, or the other way
- // round?...
- // the "REAL BIG ISSUE" is that atomicity of the changes
- // is a little vague at this point...
- dsstate.stats.hereErr += 1;
- dsstate.action = 'error';
- dsstate.error = {
- message: 'Sync agent for store "' + store.uri + '" not available',
- code: 'syncml-js.TypeError'
- };
- ret[0].statusCode = constant.STATUS_SERVICE_UNAVAILABLE;
- ret[0].errorMsg = dsstate.error.message;
- ret[0].errorCode = dsstate.error.code;
- return cb(null, ret);
- }
+ this.album = videoContentInitDict.album || null;
+ this.artists = videoContentInitDict.artists || null;
+ this.duration = videoContentInitDict.duration || 0;
+ this.width = videoContentInitDict.width || 0;
+ this.height = videoContentInitDict.height || 0;
+ this.geolocation = null;
- if ( store.agent.hierarchicalSync )
- session.hierlut = {};
+ if (videoContentInitDict.geolocation) {
+ this.geolocation = new SimpleCoordinates(
+ videoContentInitDict.geolocation.latitude || null,
+ videoContentInitDict.geolocation.longitude || null);
+ }
+};
- var preprocess = common.noop;
+VideoContent = function (videoContentInitDict) {
+ var videoContent = {};
- if ( ( ! session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER )
- || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) )
- {
- // delete all local items
- preprocess = function(cb) {
- store.agent.getAllItems(function(err, items) {
- if ( err )
- return cb(err);
- common.cascade(items, function(item, cb) {
- store.agent.deleteItem(item.id, function(err) {
- if ( err )
- return cb(err);
- dsstate.stats.hereDel += 1;
- if ( ! session.isServer )
- return cb();
- store.registerChange(item.id, constant.ITEM_DELETED,
- {excludePeerID: session.peer.id}, cb);
- });
- }, function(err) {
- if ( err )
- return cb(err);
- return store.getPeerStore(session.peer)._delChange({}, cb);
- });
- });
- };
- }
+ Content.call(this, videoContentInitDict);
- if ( dsstate.mode == constant.ALERT_SLOW_SYNC
- || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
- {
- // delete all mappings and pending changes
- var peerStore = store.getPeerStore(session.peer);
- var prepreprocess = preprocess;
- preprocess = function(cb) {
- prepreprocess(function(err) {
- if ( err )
- return cb(err);
- peerStore._delChange({}, function(err) {
- if ( err )
- return cb(err);
- peerStore._clearAllMappings(cb);
- });
- });
- };
- }
+ videoContent.album = videoContentInitDict.album || null;
+ videoContent.artists = videoContentInitDict.artists || null;
+ videoContent.duration = videoContentInitDict.duration || 0;
+ videoContent.width = videoContentInitDict.width || 0;
+ videoContent.height = videoContentInitDict.height || 0;
+ videoContent.geolocation = null;
- preprocess(function(err) {
- if ( err )
- return cb(err);
+ if (videoContentInitDict.geolocation) {
+ videoContent.geolocation = new SimpleCoordinates(
+ videoContentInitDict.geolocation.latitude,
+ videoContentInitDict.geolocation.longitude);
+ }
- if ( command.data.length <= 0 )
- return cb(null, ret);
+ this.__defineGetter__("geolocation", function () {
+ return videoContent.geolocation;
+ });
+ this.__defineSetter__("geolocation", function (val) {
+ try {
+ videoContent.geolocation = t.SimpleCoordinates(val, "?");
+ } catch (e) {
+ }
+ });
- // paranoia: verify that i should be receiving data...
- if ( ! ( dsstate.mode == constant.ALERT_TWO_WAY
- || dsstate.mode == constant.ALERT_SLOW_SYNC
- || ( ! session.isServer
- && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER
- || dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
- || ( session.isServer
- && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT
- || dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) ) ) )
- return cb(new common.ProtocolError(
- 'unexpected sync data (role="'
- + ( session.isServer ? 'server' : 'client' )
- + '", mode="' + common.mode2string(dsstate.mode)
- + '")'));
+ this.__defineGetter__("album", function () {
+ return videoContent.album;
+ });
- common.cascade(command.data, function(cmd, cb) {
+ this.__defineGetter__("artists", function () {
+ return videoContent.artists;
+ });
- // NOTE: commented this paranoia setting out, since the server
- // *may* decide to update/delete a client item...
- // e.g. conflict-resolved-merge (207)
- // TODO: perhaps i should only allow non-ADDs for those items
- // that i received a conflict-resolved-merge (207) for?...
+ this.__defineGetter__("duration", function () {
+ return videoContent.duration;
+ });
- // // paranoia: non-'add' sync commands should only be received in non-refresh modes
- // if ( cmd.name != constant.CMD_ADD
- // && _.indexOf([constant.ALERT_TWO_WAY,
- // constant.ALERT_ONE_WAY_FROM_SERVER,
- // constant.ALERT_ONE_WAY_FROM_CLIENT], dsstate.mode) < 0 )
- // return cb(new common.ProtocolError(
- // 'unexpected non-add sync command (role="'
- // + ( session.isServer ? 'server' : 'client' )
- // + '", mode="' + common.mode2string(dsstate.mode)
- // + '", command="' + cmd.name
- // + '")'));
+ this.__defineGetter__("width", function () {
+ return videoContent.width;
+ });
- self._reaction_syncdispatch(session, cmd, store, dsstate, function(err, cmds) {
- if ( err )
- return cb(err);
- _.each(cmds, function(cmd) { ret.push(cmd); });
- return cb();
- });
+ this.__defineGetter__("height", function () {
+ return videoContent.height;
+ });
+};
- }, function(err) {
- if ( err )
- return cb(err);
- return cb(null, ret);
- });
- });
- },
+AudioContentInternal = function (audioContentInitDict) {
+ ContentInternal.call(this, audioContentInitDict);
- //-------------------------------------------------------------------------
- _reaction_syncdispatch: function(session, cmd, store, dsstate, cb) {
+ this.album = audioContentInitDict.album || null;
+ this.genres = audioContentInitDict.genres || null;
+ this.artists = audioContentInitDict.artists || null;
+ this.composers = audioContentInitDict.composers || null;
+ this.lyrics = audioContentInitDict.lyrics ?
+ new AudioContentLyrics(audioContentInitDict.lyrics) : null;
+ this.copyright = audioContentInitDict.copyright || null;
+ this.bitrate = audioContentInitDict.bitrate || 0;
+ this.trackNumber = audioContentInitDict.trackNumber || null;
+ this.duration = audioContentInitDict.duration || 0;
+};
- var self = this;
- var func = self['_reaction_sync_' + cmd.name.toLowerCase()];
- if ( ! func )
- return cb(new common.ProtocolError(
- 'unexpected reaction requested for sync command "' + cmd.name + '"'));
+AudioContentLyrics = function (lyrics) {
+ var audioContentLyrics = {};
- var check_for_conflicts = common.noop;
+ audioContentLyrics.type = lyrics.type;
+ audioContentLyrics.texts = lyrics.texts;
+ audioContentLyrics.timestamps = (lyrics.type === "SYNCHRONIZED") ?
+ lyrics.timestamps : undefined;
- if ( session.isServer
- && cmd.name != constant.CMD_ADD
- && dsstate.mode != constant.ALERT_REFRESH_FROM_CLIENT )
- {
- // server, non-add, non-slowsync, non-refresh commands: check for conflicts.
- // note that certain types of content could be a conflict even if it is an
- // "Add" command; for example, two files with the same name cannot be added
- // from separate clients.
+ this.__defineGetter__("type", function () {
+ return audioContentLyrics.type;
+ });
- check_for_conflicts = function(cb) {
+ this.__defineGetter__("texts", function () {
+ return audioContentLyrics.texts;
+ });
- // todo: allow agents to raise a ConflictError...
- // ==> perhaps this is already covered by the .matchItem() API?...
+ this.__defineGetter__("timestamps", function () {
+ return audioContentLyrics.timestamps;
+ });
+};
- var policy = store.conflictPolicy || session.adapter.conflictPolicy;
- var peerStore = session.peer.getStore(dsstate.peerUri);
- self.getSourceMapping(
- session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
- function(err, itemID) {
+AudioContent = function (audioContentInitDict) {
+ var audioContent = {};
- if ( err )
- return cb(err);
- if ( ! itemID )
- // this shouldn't happen...
- return cb();
+ Content.call(this, audioContentInitDict);
- peerStore._getChange(itemID, function(err, change) {
- if ( err )
- return cb(err);
- if ( ! change )
- return cb();
+ audioContent.album = audioContentInitDict.album || null;
+ audioContent.genres = audioContentInitDict.genres || null;
+ audioContent.artists = audioContentInitDict.artists || null;
+ audioContent.composers = audioContentInitDict.composers || null;
+ audioContent.lyrics = audioContentInitDict.lyrics ?
+ new AudioContentLyrics(audioContentInitDict.lyrics) : null;
+ audioContent.copyright = audioContentInitDict.copyright || null;
+ audioContent.bitrate = audioContentInitDict.bitrate || 0;
+ audioContent.trackNumber = audioContentInitDict.trackNumber || null;
+ audioContent.duration = audioContentInitDict.duration || 0;
- var retcmd = state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : cmd.msgID,
- cmdRef : cmd.cmdID,
- sourceRef : cmd.source,
- targetRef : cmd.target,
- statusOf : cmd.name,
- // todo: make this error message a bit more descriptive...
- errorMsg : 'command "' + cmd.name + '" conflict for item ID "'
- + itemID + '" (state: ' + common.state2string(change.state) + ')'
- });
+ this.__defineGetter__("album", function () {
+ return audioContent.album;
+ });
+ this.__defineGetter__("genres", function () {
+ return audioContent.genres;
+ });
- // four possible states: mod-mod, mod-del, del-mod, del-del
- if ( ! dsstate.conflicts )
- dsstate.conflicts = [];
+ this.__defineGetter__("artists", function () {
+ return audioContent.artists;
+ });
- // handle mod-mod (but only if change-tracking is enabled)
- if ( change.state == constant.ITEM_MODIFIED
- && cmd.name == constant.CMD_REPLACE )
- {
- cmd._conflict = retcmd;
- cmd._change = change;
- return cb();
- }
+ this.__defineGetter__("composers", function () {
+ return audioContent.composers;
+ });
- // handle del-del
- if ( change.state == constant.ITEM_DELETED
- && cmd.name == constant.CMD_DELETE )
- {
- // both changes are deletes... that's not a conflict.
- // TODO: should i really be doing all this here?... it does not
- // follow the pattern..
- peerStore._delChange({
- itemID: change.item_id,
- state: change.state
- }, function(err) {
- if ( err )
- return cb(err);
- dsstate.stats.peerDel += 1;
- dsstate.stats.hereDel += 1;
- dsstate.stats.merged += 1;
- retcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE;
- retcmd.errorCode = null;
- retcmd.errorMsg = null;
- return cb(null, [retcmd]);
- });
- return;
- }
+ this.__defineGetter__("lyrics", function () {
+ return audioContent.lyrics;
+ });
- // handle del-mod or mod-del
- if ( ( change.state == constant.ITEM_DELETED
- || cmd.name == constant.CMD_DELETE )
- && policy != constant.POLICY_ERROR )
- {
- // one of them is a delete and a conflict that can be solved
- // by the framework
- cmd._conflict = retcmd;
- cmd._change = change;
- return cb();
- }
+ this.__defineGetter__("copyright", function () {
+ return audioContent.copyright;
+ });
- dsstate.conflicts.push(itemID);
- dsstate.stats.peerErr += 1;
- dsstate.stats.conflicts += 1;
- retcmd.statusCode = constant.STATUS_UPDATE_CONFLICT;
- retcmd.errorCode = 'syncml-js.synchronizer.RSd.10';
- return cb(null, [retcmd]);
- });
- }
- );
- };
- }
+ this.__defineGetter__("bitrate", function () {
+ return audioContent.bitrate;
+ });
- check_for_conflicts(function(err, cmds) {
- if ( err || cmds )
- return cb(err, cmds);
- try{
- func.call(self, session, cmd, store, dsstate, cb);
- }catch(e){
- return cb(new common.InternalError(
- 'failed invoking synchronizer sync reaction: ' + e, e));
- }
- });
+ this.__defineGetter__("trackNumber", function () {
+ return audioContent.trackNumber;
+ });
- },
+ this.__defineGetter__("duration", function () {
+ return audioContent.duration;
+ });
+};
- //-------------------------------------------------------------------------
- _reaction_sync_add: function(session, cmd, store, dsstate, cb) {
- var curitem = null;
- var item = null;
- if ( store.agent.hierarchicalSync )
- {
- if ( cmd.targetParent )
- cmd.data.parent = cmd.targetParent;
- else if ( cmd.sourceParent )
- cmd.data.parent = session.hierlut[cmd.sourceParent];
- }
+ImageContentInternal = function (imageContentInitDict) {
+ ContentInternal.call(this, imageContentInitDict);
- var matcher = common.noop;
- if ( session.isServer && dsstate.mode == constant.ALERT_SLOW_SYNC )
- {
- // TODO: if the matched item is already mapped to another client-side
- // object, then this should cancel the matching...
- matcher = function(cb) {
- store.agent.matchItem(cmd.data, function(err, match) {
- if ( err )
- return cb(err);
- if ( ! match || ! match.compare )
- return cb();
- curitem = match;
- if ( match.compare(cmd.data) == 0 )
- return cb();
- store.agent.mergeItems(curitem, cmd.data, null, function(err) {
- // TODO: if there is a common.ConflictError, set
- // curitem to null and continue without error...
- if ( err )
- return cb(err);
- store.registerChange(curitem.id, constant.ITEM_MODIFIED,
- {changeSpec: cspec, excludePeerID: session.peer.id},
- cb);
- });
- });
- };
- }
+ this.geolocation = null;
+ this.width = imageContentInitDict.width || 0;
+ this.height = imageContentInitDict.height || 0;
+ this.orientation = imageContentInitDict.orientation || "NORMAL";
- matcher(function(err) {
- if ( err )
- return cb(err);
- var adder = common.noop;
- if ( ! curitem )
- adder = function(cb) {
- store.agent.addItem(cmd.data, function(err, newitem) {
- if ( err )
- return cb(err);
- item = newitem;
- dsstate.stats.hereAdd += 1;
- store.registerChange(item.id, constant.ITEM_ADDED,
- {excludePeerID: session.peer.id}, cb);
- });
- };
- else
- item = curitem;
- return adder(function(err) {
- if ( err )
- return cb(err);
+ if (imageContentInitDict.geolocation) {
+ this.geolocation = new SimpleCoordinates(
+ imageContentInitDict.geolocation.latitude,
+ imageContentInitDict.geolocation.longitude);
+ }
+};
- if ( store.agent.hierarchicalSync )
- session.hierlut[cmd.source] = item.id;
+ImageContent = function (imageContentInitDict) {
+ var imageContent = {};
- var ret = [state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : cmd.msgID,
- cmdRef : cmd.cmdID,
- sourceRef : cmd.source,
- statusOf : cmd.name,
- statusCode : ( curitem
- ? constant.STATUS_ALREADY_EXISTS
- : constant.STATUS_ITEM_ADDED )
- })];
+ Content.call(this, imageContentInitDict);
- if ( ! session.isServer )
- {
- ret.push(state.makeCommand({
- name : constant.CMD_MAP,
- cmdID : session.nextCmdID(),
- source : store.uri,
- target : dsstate.peerUri,
- sourceItem : item.id,
- targetItem : cmd.source
- }));
- return cb(null, ret);
- }
+ imageContent.width = imageContentInitDict.width || 0;
+ imageContent.height = imageContentInitDict.height || 0;
+ imageContent.geolocation = null;
+ imageContent.orientation = imageContentInitDict.orientation || "NORMAL";
- var peerStore = session.peer.getStore(dsstate.peerUri);
- peerStore._setMapping(item.id, cmd.source, function(err) {
- if ( err )
- return cb(err);
- return cb(null, ret);
- });
+ if (imageContentInitDict.geolocation) {
+ imageContent.geolocation = new SimpleCoordinates(
+ imageContentInitDict.geolocation.latitude,
+ imageContentInitDict.geolocation.longitude);
+ }
- });
- });
+ this.__defineGetter__("geolocation", function () {
+ return imageContent.geolocation;
+ });
+ this.__defineSetter__("geolocation", function (val) {
+ try {
+ imageContent.geolocation = t.SimpleCoordinates(val, "?");
+ } catch (e) {
+ }
+ });
- },
+ this.__defineGetter__("width", function () {
+ return imageContent.width;
+ });
- //-------------------------------------------------------------------------
- getSourceMapping: function(session, cmdctxt, cmd, peerStore, luid, cb) {
- peerStore._getReverseMapping(luid, function(err, guid) {
+ this.__defineGetter__("height", function () {
+ return imageContent.height;
+ });
- if ( err )
- return cb(err);
+ this.__defineGetter__("orientation", function () {
+ return imageContent.orientation;
+ });
+ this.__defineSetter__("orientation", function (val) {
+ try {
+ imageContent.orientation = t.ImageContentOrientation(val);
+ } catch (e) {
+ }
+ });
+};
- if ( guid )
- return cb(null, guid);
+ContentFactory = function (contentInitDict, isInternal) {
+ var ContentType;
- return cb(new common.InvalidItem(
- 'unexpected "' + cmdctxt + '/' + cmd.name
- + '" request for unmapped item ID "' + luid + '"'));
+ switch (contentInitDict.type) {
+ case "IMAGE":
+ ContentType = isInternal ? ImageContentInternal : ImageContent;
+ break;
- // todo: pysyncml generates a nice cmd-specific error node:
- // (which is probably over-kill)
+ case "VIDEO":
+ ContentType = isInternal ? VideoContentInternal : VideoContent;
+ break;
- // curmap = adapter._context._model.Mapping.q(store_id=peerStore.id, luid=luid).one()
- // return str(curmap.guid)
- // except NoResultFound:
- // msg = 'unexpected "%s/%s" request for unmapped item ID: %r' % (cmdctxt, cmd.name, luid)
- // # todo: this is a bit of a hack when cmdctxt == 'Status'...
- // return state.Command(
- // name = constant.CMD_STATUS,
- // cmdID = session.nextCmdID(),
- // msgRef = cmd.msgID,
- // cmdRef = cmd.cmdID,
- // sourceRef = cmd.source,
- // targetRef = cmd.target,
- // statusOf = cmd.name if cmdctxt != constant.CMD_STATUS else cmdctxt,
- // statusCode = constant.STATUS_COMMAND_FAILED,
- // errorCode = __name__ + '.' + self.__class__.__name__ + '.GSM.10',
- // errorMsg = msg,
- // )
+ case "AUDIO":
+ ContentType = isInternal ? AudioContentInternal : AudioContent;
+ break;
- });
- },
+ default:
+ ContentType = isInternal ? ContentInternal : Content;
+ break;
+ }
- //-------------------------------------------------------------------------
- _reaction_sync_replace: function(session, cmd, store, dsstate, cb) {
+ return new ContentType(contentInitDict);
+};
- // TODO: handle hierarchical-sync...
- var self = this;
- var item = cmd.data;
- var get_item_id = ( ! session.isServer ) ? function(cb) {
- item.id = cmd.target;
- return cb();
- } : function(cb) {
- var peerStore = session.peer.getStore(dsstate.peerUri);
- self.getSourceMapping(
- session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
- function(err, guid) {
+ContentStorage = function (content) {
+ var i;
- if ( err )
- return cb(err);
+ ContentDirectoryInternal.call(this, content);
+ this.contents = {};
- // todo: what if guid is null?...
+ for (i in content.contents) {
+ this.contents[i] = new ContentFactory(content.contents[i], true);
+ }
+};
- item.id = guid;
- return cb();
- }
- );
- };
+_initialize();
- var okcmd = state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : cmd.msgID,
- cmdRef : cmd.cmdID,
- targetRef : cmd.target,
- sourceRef : cmd.source,
- statusOf : cmd.name,
- statusCode : constant.STATUS_OK
- });
+module.exports = _self;
- var handle_conflict = ( ! cmd._conflict ) ? common.noop : function(cb) {
+});
+define('ripple/platform/tizen/2.0/GeoCircleBounds', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- // if cmd._conflict is not None:
- // try:
- // if cmd._change.state == constant.ITEM_DELETED:
- // raise common.ConflictError('item deleted')
- // if cmd._change.changeSpec is None:
- // raise common.ConflictError('no change tracking enabled - falling back to policy')
- // cspec = store.agent.mergeItems(store.agent.getItem(item.id), item, cmd._change.changeSpec)
- // dsstate.stats.hereMod += 1
- // store.registerChange(item.id, constant.ITEM_MODIFIED,
- // changeSpec=cspec, excludePeerID=adapter.peer.id)
- // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE
- // # NOTE: *not* suppressing the change that is registered from server
- // # to client, since the merge may have resulted in an item that
- // # is not identical to the one on the client.
- // return [okcmd]
- // except common.ConflictError, e:
- // # conflict types: client=mod/server=mod or client=mod/server=del
- // if store.conflictPolicy == constant.POLICY_CLIENT_WINS:
- // adapter._context._model.session.delete(cmd._change)
- // dsstate.stats.merged += 1
- // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
- // if cmd._change.state == constant.ITEM_DELETED:
- // # todo: this "re-creation" of a new item is detrimental to
- // # clients that are tracking changes to an item (for
- // # example, a SyncML svn client bridge...). but then, to
- // # them, this item may already have been deleted. ugh.
- // dsstate.stats.hereMod += 1
- // item = store.agent.addItem(item)
- // peerStore = store.peer
- // adapter._context._model.Mapping.q(store_id=peerStore.id, guid=item.id).delete()
- // newmap = adapter._context._model.Mapping(store_id=peerStore.id,
- // guid=item.id,
- // luid=cmd.source)
- // adapter._context._model.session.add(newmap)
- // store.registerChange(item.id, constant.ITEM_ADDED,
- // excludePeerID=adapter.peer.id)
- // return [okcmd]
- // # falling back to standard handling...
- // elif store.conflictPolicy == constant.POLICY_SERVER_WINS:
- // dsstate.stats.merged += 1
- // okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
- // return [okcmd]
- // else:
- // # store.conflictPolicy == constant.POLICY_ERROR or other...
- // dsstate.stats.peerErr += 1
- // dsstate.stats.conflicts += 1
- // cmd._conflict.errorMsg += ', agent failed merge: ' + str(e)
- // cmd._conflict.statusCode = constant.STATUS_UPDATE_CONFLICT
- // cmd._conflict.errorCode = common.fullClassname(self) + '.RSR.10'
- // dsstate.conflicts.append(str(item.id))
- // return [cmd._conflict]
+module.exports = function (_center, _radius) {
+ var center, radius;
+ center = _center || null;
+ radius = _radius || 0;
- cb();
+ this.__defineGetter__("center", function () {
+ return center;
+ });
- };
+ this.__defineGetter__("radius", function () {
+ return radius;
+ });
+};
- // TODO: support hierarchical-sync...
- // if ( store.agent.hierarchicalSync )
- // session.hierlut[cmd.source] = item.id;
+});
+define('ripple/platform/tizen/2.0/BluetoothServiceHandler', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation
+ *
+ * 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 event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BluetoothServiceHandler,
+ _security;
- get_item_id(function(err) {
- if ( err )
- return cb(err);
- handle_conflict(function(err) {
- if ( err )
- return cb(err);
- store.agent.replaceItem(item, session.isServer, function(err, cspec) {
- if ( err )
- return cb(err);
- dsstate.stats.hereMod += 1;
- store.registerChange(
- item.id, constant.ITEM_MODIFIED,
- {changeSpec: cspec, excludePeerID: session.peer.id},
- function(err) {
- if ( err )
- return cb(err);
- return cb(null, [okcmd]);
- }
- );
- });
- });
- });
+BluetoothServiceHandler = function (prop) {
+ var bluetoothServiceHandler = {};
- },
+ _security = prop.metaData;
- //-------------------------------------------------------------------------
- _reaction_sync_delete: function(session, cmd, store, dsstate, cb) {
+ bluetoothServiceHandler.uuid = prop.uuid || "";
+ bluetoothServiceHandler.name = prop.name || "";
+ bluetoothServiceHandler.isConnected = prop.isConnected || false;
+ bluetoothServiceHandler.onconnect = null;
- var self = this;
- var status = constant.STATUS_OK;
- var itemID = null;
+ this.__defineGetter__("uuid", function () {
+ return bluetoothServiceHandler.uuid;
+ });
- var get_item_id = ( ! session.isServer ) ? function(cb) {
- itemID = cmd.target;
- return cb();
- } : function(cb) {
- var peerStore = session.peer.getStore(dsstate.peerUri);
- self.getSourceMapping(
- session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
- function(err, guid) {
+ this.__defineGetter__("name", function () {
+ return bluetoothServiceHandler.name;
+ });
- // if not isinstance(itemID, basestring):
- // return [itemID]
+ this.__defineGetter__("isConnected", function () {
+ return bluetoothServiceHandler.isConnected;
+ });
- if ( err )
- return cb(err);
+ this.__defineGetter__("onconnect", function () {
+ return bluetoothServiceHandler.onconnect;
+ });
+ this.__defineSetter__("onconnect", function (val) {
+ try {
+ bluetoothServiceHandler.onconnect =
+ t.BluetoothSocketSuccessCallback(val, "?");
+ } catch (e) {
+ }
+ });
- // todo: what if guid is null?...
+ this.unregister = function (successCallback, errorCallback) {
+ if (!_security.unregister) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- itemID = guid;
- if ( ! cmd._conflict )
- return cb();
- var policy = store.conflictPolicy || session.adapter.conflictPolicy;
- switch ( policy )
- {
+ t.BluetoothServiceHandler("unregister", arguments);
- case constant.POLICY_CLIENT_WINS:
- {
+ event.trigger("bt-unregister-service", [bluetoothServiceHandler.uuid,
+ successCallback, errorCallback]);
+ };
+};
+module.exports = BluetoothServiceHandler;
- // TODO ::: implement these...
+});
+define('ripple/platform/tizen/2.0/GeometryFilter', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- // // adapter._context._model.session.delete(cmd._change)
- // // status = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
- // // session.dsstates[store.uri].stats.merged += 1
- // // # falling back to standard handling...
+module.exports = function (criteria, geometry) {
+ var _self;
- // break;
+ _self = {
+ criteria: criteria,
+ geometry: geometry
+ };
- }
- case constant.POLICY_SERVER_WINS:
- {
+ return _self;
+};
+});
+define('ripple/platform/tizen/2.0/bookmark', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- // // adapter._context._model.session.delete(cmd._change)
- // // store.peer.registerChange(itemID, constant.ITEM_ADDED)
- // // session.dsstates[store.uri].stats.merged += 1
- // // cmd._conflict.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
- // // cmd._conflict.errorCode = None
- // // cmd._conflict.errorMsg = None
- // // return [cmd._conflict]
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ BookmarkFolder = require('ripple/platform/tizen/2.0/BookmarkFolder'),
+ BookmarkItem = require('ripple/platform/tizen/2.0/BookmarkItem'),
+ BookmarkExternal,
+ BookmarkInternal,
+ BookmarkStorage,
+ _data = {
+ DB_BOOKMARK_KEY: "tizen1-bookmark",
+ bookmarks: [],
+ dbStorage: []
+ },
+ _security = {
+ "http://tizen.org/privilege/bookmark.read": ["get"],
+ "http://tizen.org/privilege/bookmark.write": ["add", "remove"]
+ },
+ _self;
- // break;
+function _get() {
+ _data.dbStorage = db.retrieveObject(_data.DB_BOOKMARK_KEY) || [];
+}
- }
+function _save() {
+ db.saveObject(_data.DB_BOOKMARK_KEY, _data.dbStorage);
+}
- default:
- {
- // a constant.POLICY_ERROR policy should have been handled by the dispatch
- return cb(new common.InternalError(
- 'unexpected conflictPolicy: %s', '' + policy));
- }
- }
- }
- );
+function _initialize() {
+ _get();
- };
+ utils.forEach(_data.dbStorage, function (bookmark) {
+ _data.bookmarks.push(new BookmarkInternal(bookmark, null));
+ });
+}
- get_item_id(function(err) {
- if ( err )
- return cb(err);
- store.agent.deleteItem(itemID, function(err) {
- if ( err )
- return cb(err);
- dsstate.stats.hereDel += 1;
- store.registerChange(
- itemID, constant.ITEM_DELETED, {excludePeerID: session.peer.id},
- function(err) {
- if ( err )
- return cb(err);
- return cb(null, [state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : cmd.msgID,
- cmdRef : cmd.cmdID,
- targetRef : cmd.target,
- sourceRef : cmd.source,
- statusOf : cmd.name,
- // todo: should this return DELETE_WITHOUT_ARCHIVE instead of OK?...
- // statusCode = constant.STATUS_DELETE_WITHOUT_ARCHIVE,
- statusCode : status
- })]);
- }
- );
- });
- });
+function _persist() {
+ _data.dbStorage = [];
- },
+ utils.forEach(_data.bookmarks, function (bookmark) {
+ _data.dbStorage.push(new BookmarkStorage(bookmark));
+ });
- //-------------------------------------------------------------------------
- _reaction_map: function(session, command, cb) {
- var peerStore = session.peer.getStore(command.source);
- if ( command.target != peerStore._getBinding().uri )
- return cb(new common.NoSuchRoute(
- 'unexpected "Map" event for unbound stores (local: "'
- + command.target + ', remote: "' + command.source + '")'));
- common.cascade(command.items, function(item, cb) {
- // todo: support hierarchical sync...
- peerStore._setMapping(item.target, item.source, cb);
- }, function(err) {
- if ( err )
- return cb(err);
- return cb(null, [state.makeCommand({
- name : constant.CMD_STATUS,
- cmdID : session.nextCmdID(),
- msgRef : command.msgID,
- cmdRef : command.cmdID,
- targetRef : command.target,
- sourceRef : command.source,
- statusOf : command.name,
- statusCode : constant.STATUS_OK
- })]);
- });
- },
+ _save();
+}
- //-------------------------------------------------------------------------
- // SYNCHRONIZATION PHASE: SETTLE
- //-------------------------------------------------------------------------
+function _isFolder(bookmark) {
+ return !bookmark.url;
+}
- //-------------------------------------------------------------------------
- settle: function(session, cmd, chkcmd, xnode, cb) {
+function _isExternal(bookmark) {
+ return !("children" in bookmark);
+}
- // TODO: remove the "xnode" parameter... it is a hack so that i can
- // call badStatus() the same way as in protocol.js
- // todo: there is a bit of a disconnect between how action and reaction
- // phases are called (for a list of commands), whereas the settle
- // phase is called on a per-item basis... not ideal, but the protocol
- // is really set up that way :(
- // TODO: check all valid values of ``data``...
- // todo: anything else in common?...
- // todo: trap errors...
+function _getChildren(bookmark, BookmarkType, parent) {
+ var i, children = [];
- var func = this['_settle_' + cmd.name.toLowerCase()];
- if ( ! func )
- return cb(new common.ProtocolError('unexpected settle command "' + cmd.name + '"'));
- return func.call(this, session, cmd, chkcmd, xnode, cb);
- },
+ if (!_isExternal(bookmark)) {
+ for (i in bookmark.children) {
+ children.push(new BookmarkType(bookmark.children[i], parent));
+ }
+ }
- //-------------------------------------------------------------------------
- _settle_add: function(session, cmd, chkcmd, xnode, cb) {
- switch ( cmd.data )
- {
- default:
- {
- return cb(badStatus(xnode));
- }
- case constant.STATUS_OK:
- case constant.STATUS_ITEM_ADDED:
- case constant.STATUS_CONFLICT_RESOLVED_DUPLICATE:
- {
- session.info.dsstates[chkcmd.uri].stats.peerAdd += 1;
- break;
- }
- case constant.STATUS_ALREADY_EXISTS:
- case constant.STATUS_CONFLICT_RESOLVED_MERGE:
- // todo: should this conflict-resolved-merge status be stored so
- // that only this item can have a non-"ADD" during initial
- // sync?...
- case constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA:
- {
- session.info.dsstates[chkcmd.uri].stats.merged += 1;
- break;
- }
- }
+ return children;
+}
- var peerStore = session.peer.getStore(
- session.context.router.getTargetUri(
- session.adapter, session.peer, chkcmd.uri));
+_self = function () {
+ var bookmark;
- peerStore._delChange({
- itemID: chkcmd.source,
- state: constant.ITEM_ADDED
- }, cb);
- },
+ // private
+ /*
+ * map
+ * Map the external bookmark to the internal one in the tree
+ *
+ * bookmarkExternal
+ * External bookmark Object
+ *
+ * callback
+ * callback(index, peers). Optional.
+ *
+ * Root Bookmark Not Found
+ * ------------------------------------------
+ * index 0 index -1
+ * peers null peers null
+ *
+ * Return null peers[index] undefined
+ */
- //-------------------------------------------------------------------------
- _settle_replace: function(session, cmd, chkcmd, xnode, cb) {
+ function map(bookmarkExternal, callback) {
+ var trace = [], it, i, peers = null;
- var self = this;
- var dsstate = session.info.dsstates[chkcmd.uri];
+ if (!bookmarkExternal) {
+ if (callback) {
+ callback(0, null);
+ }
+ return null;
+ }
- if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
- {
- dsstate.stats.hereErr += 1;
- dsstate.stats.conflicts += 1;
- return cb();
- }
- if ( cmd.data != constant.STATUS_OK
- && cmd.data != constant.STATUS_CONFLICT_RESOLVED_MERGE
- && cmd.data != constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
- && cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
- return cb(badStatus(xnode));
- if ( cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE
- || cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
- || cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
- dsstate.stats.merged += 1;
- if ( cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
- dsstate.stats.peerMod += 1;
+ for (it = bookmarkExternal; it; it = it.parent) {
+ trace.push(it);
+ }
- var peerStore = session.peer.getStore(
- session.context.router.getTargetUri(
- session.adapter, session.peer, chkcmd.uri));
+ for (it = _data.bookmarks; trace.length !== 0; it = it[i].children) {
+ bookmarkExternal = trace.pop();
+ peers = null;
- var get_item_id = ( ! session.isServer ) ? function(cb) {
- return cb(null, chkcmd.source);
- } : function(cb) {
- // if not isinstance(locItemID, basestring):
- // return locItemID
+ if (it.length === 0)
+ break;
- self.getSourceMapping(
- session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
- function(err, guid) { return cb(err, guid); }
- );
- };
+ for (i in it) {
+ if (it[i].external === bookmarkExternal) {
+ peers = it;
+ break;
+ }
+ }
+ }
- get_item_id(function(err, locItemID) {
+ if (callback) {
+ return callback((peers !== null) ? i : -1, peers);
+ }
- if ( err )
- return cb(err);
+ return (peers !== null) ? peers[i] : undefined;
+ }
- // todo: this is *technically* subject to a race condition... but the
- // same peer should really not be synchronizing at the same time...
- // todo: also potentially check Change.registered...
- // TODO: this could be solved by:
- // a) never updating a Change record (only deleting and replacing)
- // b) deleting Change records by ID instead of by store/item/state...
+ function traverse(bookmarks, trace, level) {
+ for (var i in bookmarks) {
+ trace.push(bookmarks[i].external);
+ if ((level !== 0) && bookmarks[i].children) {
+ traverse(bookmarks[i].children, trace, --level);
+ }
+ }
+ }
- peerStore._delChange({
- itemID : locItemID,
- state : constant.ITEM_MODIFIED,
- }, cb);
+ function findUrl(bookmarks, url) {
+ var i, isFound = false;
- });
+ for (i in bookmarks) {
+ if (_isFolder(bookmarks[i])) {
+ isFound = findUrl(bookmarks[i].children, url);
+ } else {
+ isFound = (bookmarks[i].url === url);
+ }
- },
+ if (isFound)
+ break;
+ }
- //-------------------------------------------------------------------------
- _settle_delete: function(session, cmd, chkcmd, xnode, cb) {
- var self = this;
- var dsstate = session.info.dsstates[chkcmd.uri];
- if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
- {
- dsstate.stats.hereErr += 1;
- dsstate.stats.conflicts += 1;
- return cb();
- }
- if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE )
- {
- dsstate.stats.hereDel += 1;
- dsstate.stats.peerDel += 1;
- dsstate.stats.merged += 1;
- }
- else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA )
- {
- dsstate.stats.peerDel += 1;
- dsstate.stats.merged += 1;
- }
- else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
- dsstate.stats.merged += 1;
- else if ( cmd.data == constant.STATUS_ITEM_NOT_DELETED )
- {
- // note: the reason that this *may* be ok is that some servers (funambol)
- // will report ITEM_NOT_DELETED when the item did not exist, thus this
- // is "alright"...
- // todo: perhaps this should be raised as an error if the
- // remote peer != funambol?...
- }
- else if ( cmd.data == constant.STATUS_OK )
- dsstate.stats.peerDel += 1;
- else
- return cb(badStatus(xnode));
+ return isFound;
+ }
- var peerStore = session.peer.getStore(
- session.context.router.getTargetUri(
- session.adapter, session.peer, chkcmd.uri));
+ function isExisting(bookmark, peers) {
+ var i;
- // todo: handle hierarchical sync...
- var get_locItemID = ( ! chkcmd.target ) ? function(cb) {
- cb(null, chkcmd.source);
- } : function(cb) {
- self.getSourceMapping(
- session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
- function(err, guid) { return cb(err, guid); }
- );
- };
+ if (!_isFolder(bookmark)) {
+ return findUrl(_data.bookmarks, bookmark.url);
+ }
- // todo: this is *technically* subject to a race condition... but the
- // same peer should really not be synchronizing at the same time...
- // todo: also potentially check Change.registered...
- // TODO: this could be solved by:
- // a) never updating a Change record (only deleting and replacing)
- // b) deleting Change records by ID instead of by store/item/state...
+ for (i in peers) {
+ if (_isFolder(peers[i]) && (peers[i].title === bookmark.title)) {
+ return true;
+ }
+ }
- get_locItemID(function(err, locItemID) {
- if ( err )
- return cb(err);
- peerStore._delChange({
- itemID : locItemID,
- state : constant.ITEM_DELETED,
- }, cb);
- });
+ return false;
+ }
- }
+ // public
+ function get(parentFolder, recursive) {
+ var bookmarks = [], parent, peers;
- });
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- return exports;
+ t.BookmarkManager("get", arguments);
-})();
+ parent = map(parentFolder);
+ if ((parent === undefined) || (parent && !_isFolder(parent))) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ peers = parent ? parent.children : _data.bookmarks;
+ traverse(peers, bookmarks, recursive ? -1 : 0);
-module.exports = _self;
+ return bookmarks;
+ }
-});
-define('ripple/platform/tizen/2.0/syncml-js-lib/useragent', function (require, exports, module) {
-// -*- coding: utf-8 -*-
-//-----------------------------------------------------------------------------
-// file: $Id$
-// lib: syncml-js.useragent
-// auth: griffin <griffin@uberdev.org>
-// date: 2013/06/07
-// copy: (C) CopyLoose 2013 UberDev <hardcore@uberdev.org>, No Rights Reserved.
-//-----------------------------------------------------------------------------
+ function add(bookmark, parentFolder) {
+ var parent, peers;
-var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
- constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
- _self;
+ if (!_security.add) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_self = (function () {
- var exports = {};
+ t.BookmarkManager("add", arguments);
- //---------------------------------------------------------------------------
- exports.UserAgent = common.Base.extend({
- // primary handlers:
- acceptSyncModeSwitch: null, // function(EVENT, CALLBACK(ERR))
- acceptDevInfoSwap: null, // function(EVENT, CALLBACK(ERR))
- chooseRefreshRequired: null, // function(EVENT, CALLBACK(ERR, TYPE))
- fetchCredentials: null, // function(EVENT, CALLBACK(ERR, AUTH))
- // fallback handlers:
- accept: null, // function(TYPE, EVENT, CALLBACK(ERR))
- choose: null, // function(TYPE, EVENT, CALLBACK(ERR, CHOICE))
- fetch: null, // function(TYPE, EVENT, CALLBACK(ERR, STRUCT))
- // catchall handler:
- handle: null // function(ACTION, TYPE, EVENT, CALLBACK(ERR, RESULT...))
- });
+ parent = map(parentFolder);
+ if ((parent === undefined) || (parent && !_isFolder(parent))) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ peers = parent ? parent.children : _data.bookmarks;
+ if (isExisting(bookmark, peers)) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
- //---------------------------------------------------------------------------
- exports.UserAgentMultiplexer = common.Base.extend({
+ peers.push(new BookmarkInternal(bookmark));
- //-------------------------------------------------------------------------
- constructor: function(uaList) {
- this.ualist = uaList;
- },
+ _persist();
- //-------------------------------------------------------------------------
- _getHandler: function(name) {
- for ( var idx=0 ; idx<this.ualist.length ; idx++ )
- {
- var ua = this.ualist[idx];
- if ( ua && _.isFunction(ua[name]) )
- return ua[name];
+ bookmark.__defineGetter__("parent", function () {
+ return parent ? parent.external : null;
+ });
}
- return null;
- },
- //-------------------------------------------------------------------------
- hasHandler: function(name) {
- return !! this._getHandler(name);
- },
+ function remove(bookmark) {
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- //-------------------------------------------------------------------------
- acceptSyncModeSwitch: function(event, cb) {
- return this._handle({
- handler: 'acceptSyncModeSwitch',
- action: 'accept',
- type: 'sync.mode.switch'
- }, event, cb);
- },
+ t.BookmarkManager("remove", arguments);
- //-------------------------------------------------------------------------
- acceptDevInfoSwap: function(event, cb) {
- return this._handle({
- handler: 'acceptDevInfoSwap',
- action: 'accept',
- type: 'dev.info.swap'
- }, event, cb);
- },
+ if (!bookmark) {
+ _data.bookmarks = [];
+ } else {
+ map(bookmark, function (index, peers) {
+ if (index === -1) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ peers.splice(index, 1);
+ });
- //-------------------------------------------------------------------------
- chooseRefreshRequired: function(event, cb) {
- return this._handle({
- handler: 'chooseRefreshRequired',
- action: 'choose',
- type: 'refresh.required',
- choices: [
- {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
- {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
- {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
- ]
- }, event, function(err, choice) {
- if ( err )
- return cb(err);
- // todo: catch the condition where `choice` is not a valid synctype
- return cb(err, common.synctype2alert(choice));
+ bookmark.__defineGetter__("parent", function () {
+ return undefined;
});
- },
+ }
- //-------------------------------------------------------------------------
- fetchCredentials: function(event, cb) {
- return this._handle({
- handler: 'fetchCredentials',
- action: 'fetch',
- type: 'auth.challenge',
- choices: [
- {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
- {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
- {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
- ]
- }, event, cb);
- },
+ _persist();
+ }
- //-------------------------------------------------------------------------
- _handle: function(spec, event, cb) {
- event = _.extend({}, spec, event, {
- type : spec.type,
- context : event.session.context,
- adapter : event.session.adapter,
- peer : event.session.peer,
- ua_handler : spec.handler,
- ua_action : spec.action
- });
- var handler = this._getHandler(spec.handler);
- if ( handler )
- return handler(event, cb);
- handler = this._getHandler(spec.action);
- if ( handler )
- return handler(spec.type, event, cb);
- handler = this._getHandler('handle');
- if ( handler )
- return handler(spec.action, spec.type, event, cb);
- if ( spec.action == 'accept' )
- {
- return cb();
- }
- if ( spec.action == 'choose'
- && event.choices && event.choices.length > 0 )
- {
- var choice = _.find(event.choices, function(c) { return c.default; });
- if ( ! choice )
- choice = event.choices[0];
- if ( choice.value )
- choice = choice.value;
- return cb(null, choice);
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
}
- if ( spec.type == 'auth.challenge' )
- return cb();
- return cb(new common.NotImplementedError(
- 'user-agent handler for event type "' + spec.type + '" (action: "'
- + spec.action + '") not found or defined'));
}
+ }
+
+ bookmark = {
+ get: get,
+ add: add,
+ remove: remove,
+ handleSubFeatures: handleSubFeatures
+ };
+
+ return bookmark;
+};
+
+/*
+ * BookmarkInternal BookmarkStorage BookmarkExternal
+ * ---------------------------------------------------------
+ * title title title
+ * url url url/-
+ * children children -
+ * external - -
+ * - - parent
+ */
+
+BookmarkInternal = function (bookmark, parent) {
+ this.title = bookmark.title;
+ this.url = _isFolder(bookmark) ? null : bookmark.url;
+ this.children = _isFolder(bookmark) ?
+ _getChildren(bookmark, BookmarkInternal, this) : null;
+ this.external = _isExternal(bookmark) ? bookmark :
+ new BookmarkExternal(bookmark, parent);
+};
+BookmarkStorage = function (bookmark) {
+ this.title = bookmark.title;
+ this.url = _isFolder(bookmark) ? null : bookmark.url;
+ this.children = _isFolder(bookmark) ?
+ _getChildren(bookmark, BookmarkStorage) : null;
+};
+
+BookmarkExternal = function (bookmark, parent) {
+ var self;
+
+ if (_isFolder(bookmark)) {
+ self = new BookmarkFolder(bookmark.title);
+ } else {
+ self = new BookmarkItem(bookmark.title, bookmark.url);
+ }
+
+ self.__defineGetter__("parent", function () {
+ return parent ? parent.external : null;
});
- return exports;
+ return self;
+};
-})();
+_initialize();
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/systeminfo', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/CalendarItem', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var deviceSettings = require('ripple/deviceSettings'),
- db = require('ripple/db'),
- t = require('ripple/platform/tizen/2.0/typecast'),
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
typedef = require('ripple/platform/tizen/2.0/typedef'),
- constants = require('ripple/constants'),
- event = require('ripple/event'),
- tizen_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- SystemInfoDeviceCapability,
- _systemInfoProperties = typedef.SystemInfoPropertyId,
- _propertyMap = {}, // Object like: {"BATTERY": ["level", "isCharging"], ...}
- _batteryEvent = ["BatteryLevelChanged", "BatteryChargingChanged"],
- _watches = {},
- _firstCall_watches = {},
- _powerData = {},
- _systemInfoDeviceCapability = null,
- _security = {
- "http://tizen.org/privilege/system": ["SystemInfoSIM", "webApiVersion",
- "nativeApiVersion", "platformVersion"],
- "http://tizen.org/privilege/systemmanager": ["NetworkImei"]
- },
- _self;
-
-function _prepareObj(obj, aspect, property, value) {
- if ((aspect === "CELLULAR_NETWORK") && (property === "imei")) {
- obj.__defineGetter__("imei", function () {
- if (!_security.NetworkImei) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
- return deviceSettings.retrieve("CELLULAR_NETWORK.imei");
- });
- } else {
- if (aspect === "WIFI_NETWORK" || aspect === "CELLULAR_NETWORK") {
- if (property === 'status') {
- if (value === true) {
- value = "ON";
- } else {
- value = "OFF";
- }
- }
- }
- obj.__defineGetter__(property, function () {
- return value;
- });
- }
-}
-
-function _getValue(aspect, successCallback) {
- var properties = [], value, index = 0, property, obj = {};
-
- if ((aspect === "SIM") && !_security.SystemInfoSIM) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
-
- if (aspect === "BATTERY") {
- successCallback(_powerData);
- return;
- }
+ CalendarItem;
- properties = _propertyMap[aspect];
- for (; index < properties.length; index++) {
- property = properties[index];
- value = deviceSettings.retrieve(aspect + "." + property);
- _prepareObj(obj, aspect, property, value);
- }
+CalendarItem = function (itemInitDict) {
+ var calendarItem = {}, attr;
- if (aspect === "STORAGE") {
- obj.__defineGetter__("units", function () {
- return [obj];
- });
+ // private
+ function toDigit(number) {
+ return ((number >= 10) ? "" : "0") + number;
}
- successCallback(obj);
-}
+ // public
+ function convertToString(format) {
+ var header = "BEGIN:VCALENDAR\r\nPRODID:-//Tizen.org//Tizen Calendar//EN\r\nVERSION:2.0\r\n",
+ end = "END:VCALENDAR\r\n", str = "", pri, i, date, before, y, m, d,
+ hh, mm, ss, dateStart = "", dateEnd = "";
-function _initialize() {
- var aspectName, index, i, vol;
+ t.CalendarItem("convertToString", arguments);
- for (index = 0; index < _systemInfoProperties.length; index++) {
- aspectName = _systemInfoProperties[index];
- _propertyMap[aspectName] = [];
- for (i in deviceSettings.retrieve(aspectName)) {
- _propertyMap[aspectName].push(i);
+ //TODO: vcalendar 1.0 doesn't support yet
+ if (format === "VCALENDAR_10") {
+ return;
}
- }
-
- _propertyMap.BATTERY.push("level");
- _propertyMap.BATTERY.push("isCharging");
-
- _powerData.__defineGetter__("isCharging", function () {
- return false;
- });
-
- vol = db.retrieve(constants.BATTERY.VOLUME) || 100.0;
- _powerData.__defineGetter__("level", function () {
- return Number((vol / 100.0).toFixed(4));
- });
-
- event.on("BatteryEvent", function (status) {
- _powerData.__defineGetter__("isCharging", function () {
- return status.charging;
- });
- _powerData.__defineGetter__("level", function () {
- return Number(status.level.toFixed(4));
- });
- });
-}
-
-function _isPropertyFound(property) {
- if (tizen_utils.isEmptyObject(_propertyMap)) {
- _initialize();
- }
-
- if (_propertyMap[property]) {
- return true;
- }
- return false;
-}
+ str = header + "BEGIN:#TYPE#\r\n";
-function _delayGetValue(timeout, property, successCallback, errorCallback) {
- return window.setInterval(function () {
- _getValue(property, successCallback, errorCallback);
- }, timeout);
-}
+ if (this.isAllDay) {
+ if (this.startDate) {
+ date = this.startDate;
+ y = date.getFullYear();
+ m = toDigit(date.getMonth() + 1);
+ d = toDigit(date.getDate());
+ str += "DTSTART;VALUE=DATE:" + y + m + d + "\r\n";
+ dateStart = "" + y + m + d + "T000000Z";
+ if (this.duration) {
+ date = date.addDuration(this.duration);
+ y = date.getFullYear();
+ m = toDigit(date.getMonth() + 1);
+ d = toDigit(date.getDate());
+ str += "DTEND;VALUE=DATE:" + y + m + d + "\r\n";
+ dateEnd = "" + y + m + d + "T000000Z";
+ }
+ }
+ } else {
+ if (this.startDate) {
+ date = this.startDate;
+ y = date.getFullYear();
+ m = toDigit(date.getMonth() + 1);
+ d = toDigit(date.getDate());
+ hh = toDigit(date.getHours());
+ mm = toDigit(date.getMinutes());
+ ss = toDigit(date.getSeconds());
+ str += "DTSTART:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
+ dateStart = "" + y + m + d + "T" + hh + mm + ss + "Z";
+ if (this.duration && this.duration.length && this.duration.unit) {
+ date = date.addDuration(this.duration);
+ y = date.getFullYear();
+ m = toDigit(date.getMonth() + 1);
+ d = toDigit(date.getDate());
+ hh = toDigit(date.getHours());
+ mm = toDigit(date.getMinutes());
+ ss = toDigit(date.getSeconds());
+ str += "DTEND:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
+ dateEnd = "" + y + m + d + "T" + hh + mm + ss + "Z";
+ }
+ }
+ }
-_self = function () {
- function getCapabilities() {
- if (_systemInfoDeviceCapability === null) {
- _systemInfoDeviceCapability = new SystemInfoDeviceCapability();
+ if (this.description) {
+ str += "DESCRIPTION:" + this.description + "\r\n";
+ }
+ if (this.summary) {
+ str += "SUMMARY:" + this.summary + "\r\n";
+ }
+ if (this.location) {
+ str += "LOCATION:" + this.location + "\r\n";
+ }
+ if (this.geolocation) {
+ // Don't need to check latitude and longitude due to they are mandatory attributes
+ str += "GEO:" + this.geolocation.latitude + "," + this.geolocation.longitude + "\r\n";
+ }
+ if (this.organizer) {
+ str += "ORGANIZER:" + this.organizer + "\r\n";
+ }
+ if (this.visibility) {
+ str += "CLASS:" + this.visibility + "\r\n";
+ }
+ if (this.status) {
+ str += "STATUS:" + this.status + "\r\n";
+ }
+ if (this.priority) {
+ switch (this.priority) {
+ case "HIGH":
+ pri = 2;
+ break;
+ case "MEDIUM":
+ pri = 5;
+ break;
+ case "LOW":
+ pri = 7;
+ break;
+ }
+ str += "PRIORITY:" + pri + "\r\n";
+ }
+ if (tizen1_utils.isValidArray(this.alarms)) {
+ for (i = 0; i < this.alarms.length; i++) {
+ str += "BEGIN:VALARM\r\n";
+ // Don't need to check this.alarms[i].method due to it is a mandatory attribute
+ str += "ACTION:" + this.alarms[i].method + "\r\n";
+ if (this.alarms[i].description) {
+ str += "DESCRIPTION:" + this.alarms[i].description + "\r\n";
+ } else {
+ // description property MUST included if action is DISPLAY (RFC5545 3.6.6)
+ str += "DESCRIPTION:This is a reminder\r\n";
+ }
+ if (this.alarms[i].absoluteDate) {
+ date = this.alarms[i].absoluteDate;
+ y = date.getFullYear();
+ m = toDigit(date.getMonth() + 1);
+ d = toDigit(date.getDate());
+ hh = toDigit(date.getHours());
+ mm = toDigit(date.getMinutes());
+ ss = toDigit(date.getSeconds());
+ str += "TRIGGER;VALUE=DATE-TIME:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
+ } else {
+ //it must be included before attribute
+ before = this.alarms[i].before;
+ switch (before.unit) {
+ case "DAYS":
+ str += "TRIGGER:-P" + before.length + "D" + "\r\n";
+ break;
+ case "HOURS":
+ str += "TRIGGER:-P0DT" + before.length + "H0M0S" + "\r\n";
+ break;
+ case "MINS":
+ str += "TRIGGER:-P0DT0H" + before.length + "M0S" + "\r\n";
+ break;
+ case "SECS":
+ str += "TRIGGER:-P0DT0H0M" + before.length + "S" + "\r\n";
+ break;
+ }
+ }
+ str += "END:VALARM\r\n";
+ }
+ }
+ if (tizen1_utils.isValidArray(this.categories)) {
+ str += "CATEGORIES:";
+ for (i = 0; i < this.categories.length; i++) {
+ str += this.categories[i] + ",";
+ }
+ str = str.slice(0, -1);
+ str += "\r\n";
}
- return _systemInfoDeviceCapability;
- }
-
- function getPropertyValue(property, successCallback, errorCallback) {
- t.SystemInfo("getPropertyValue", arguments);
-
- if (!_isPropertyFound(property)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ if (tizen1_utils.isValidArray(this.attendees)) {
+ for (i = 0; i < this.attendees.length; i++) {
+ //TODO: basic implementation
+ str += "ATTENDEE:mailto:" + this.attendees[i].uri + "\r\n";
+ }
}
- window.setTimeout(function () {
- _getValue(property, successCallback, errorCallback);
- }, 1);
- }
-
- function addPropertyValueChangeListener(property, successCallback, options) {
- var WatchOBJ, watchId = Number(Math.uuid(8, 10)),
- _options = new Object(options), properties, prop, index = 0,
- deviceEventType, watchObj, firstCallWatchObj;
-
- t.SystemInfo("addPropertyValueChangeListener", arguments);
-
- if (!_isPropertyFound(property)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ if ((dateStart !== "") && (dateEnd !== "")) {
+ str += "#AVAILABILITY#:" + dateStart + "/" + dateEnd + "\r\n";
}
- WatchOBJ = function (deviceEventType, property, successCallback) {
- var obj = this;
-
- this.eventType = deviceEventType;
- this.onEvent = function (newValue) {
- if (obj.timeout) {
- window.clearInterval(obj.intervalId);
- obj.intervalId = window.setInterval(function () {
- _getValue(property, successCallback, null);
- }, obj.timeout);
- }
-
- if ((obj.highThreshold && (newValue < obj.highThreshold)) ||
- (obj.lowThreshold && (newValue > obj.lowThreshold))) {
- return;
- }
-
- _getValue(property, successCallback, null);
- };
- };
-
- // A listener will listen all the properties of one aspect, each of the property
- // will have an internal watchObj to record the information.
- _watches[watchId] = [];
+ str += "#ENDDATE##RECURRENCERULE#";
+ str += "#DUEDATE##COMPLETEDDATE##PROGRESS#";
+ str += "END:#TYPE#\r\n" + end;
- if (property === "BATTERY") {
- properties = _batteryEvent;
- } else {
- properties = _propertyMap[property];
- }
+ return str;
+ }
- for (; index < properties.length; index++) {
- prop = properties[index];
- if (property === "BATTERY") {
- deviceEventType = prop;
- } else {
- deviceEventType = deviceSettings.retrieve(property)[prop].event;
- }
+ calendarItem.description = "";
+ calendarItem.summary = "";
+ calendarItem.isAllDay = false;
+ calendarItem.startDate = null;
+ calendarItem.duration = null;
+ calendarItem.location = "";
+ calendarItem.geolocation = null;
+ calendarItem.organizer = "";
+ calendarItem.visibility = "PUBLIC";
+ calendarItem.status = "TENTATIVE";
+ calendarItem.priority = "LOW";
+ calendarItem.alarms = [];
+ calendarItem.categories = [];
+ calendarItem.attendees = [];
- if (deviceEventType === undefined) continue;
- // These two items are needed when delete an event listener.
- watchObj = new WatchOBJ(deviceEventType, property, successCallback);
+ if (itemInitDict) {
+ for (attr in itemInitDict) {
+ if (!(attr in typedef.CalendarItemInit))
+ continue;
- if (options && _options.timeout) {
- watchObj.intervalId = _delayGetValue(_options.timeout, property,
- successCallback, null);
- }
+ switch (attr) {
+ case "alarms":
+ calendarItem.alarms = t.CalendarAlarm(itemInitDict.alarms,
+ "[]+");
+ break;
- if ((watchObj.eventType === "CpuLoadChanged") ||
- (watchObj.eventType === "DisplayBrightnessChanged") ||
- (watchObj.eventType === "BatteryLevelChanged")) {
- if (options && _options.highThreshold) {
- watchObj.highThreshold = _options.highThreshold;
- }
+ case "categories":
+ calendarItem.categories = t.DOMString(itemInitDict.categories,
+ "[]+");
+ break;
- if (options && _options.lowThreshold) {
- watchObj.lowThreshold = _options.lowThreshold;
- }
- }
+ case "attendees":
+ calendarItem.attendees = t.CalendarAttendee(
+ itemInitDict.attendees, "[]+");
+ break;
- _watches[watchId].push(watchObj);
- if (watchObj.eventType) {
- event.on(watchObj.eventType, watchObj.onEvent);
+ default:
+ calendarItem[attr] = itemInitDict[attr];
+ break;
}
}
-
- firstCallWatchObj = window.setTimeout(function () {
- _getValue(property, successCallback, null);
- delete _firstCall_watches[watchId];
- }, 1);
-
- _firstCall_watches[watchId] = firstCallWatchObj;
-
- return watchId;
}
- function removePropertyValueChangeListener(listenerID) {
- var _handler = listenerID, index = 0, watchObjs = [], watchObj;
+ this.__defineGetter__("id", function () {
+ return null;
+ });
- if (!_watches[_handler])
- return;
+ this.__defineGetter__("calendarId", function () {
+ return null;
+ });
- watchObjs = _watches[_handler];
- if (watchObjs) {
- for (; index < watchObjs.length; index++) {
- watchObj = watchObjs[index];
- event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);
- if (watchObj.intervalId) {
- window.clearInterval(watchObj.intervalId);
- }
- }
- delete _watches[_handler];
- }
+ this.__defineGetter__("lastModificationDate", function () {
+ return null;
+ });
- if (_firstCall_watches[_handler]) {
- window.clearTimeout(_firstCall_watches[_handler]);
- delete _firstCall_watches[_handler];
+ this.__defineGetter__("description", function () {
+ return calendarItem.description;
+ });
+ this.__defineSetter__("description", function (val) {
+ try {
+ calendarItem.description = t.DOMString(val, "?");
+ } catch (e) {
}
- }
+ });
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ this.__defineGetter__("summary", function () {
+ return calendarItem.summary;
+ });
+ this.__defineSetter__("summary", function (val) {
+ try {
+ calendarItem.summary = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
+ this.__defineGetter__("isAllDay", function () {
+ return calendarItem.isAllDay;
+ });
+ this.__defineSetter__("isAllDay", function (val) {
+ try {
+ calendarItem.isAllDay = t.boolean(val);
+ } catch (e) {
}
- }
+ });
- var systeminfo = {
- getCapabilities: getCapabilities,
- getPropertyValue: getPropertyValue,
- addPropertyValueChangeListener: addPropertyValueChangeListener,
- removePropertyValueChangeListener: removePropertyValueChangeListener,
- handleSubFeatures: handleSubFeatures
- };
+ this.__defineGetter__("startDate", function () {
+ return calendarItem.startDate;
+ });
+ this.__defineSetter__("startDate", function (val) {
+ try {
+ calendarItem.startDate = t.TZDate(val, "?");
+ } catch (e) {
+ }
+ });
- return systeminfo;
-};
+ this.__defineGetter__("duration", function () {
+ return calendarItem.duration;
+ });
+ this.__defineSetter__("duration", function (val) {
+ try {
+ calendarItem.duration = t.TimeDuration(val, "?");
+ } catch (e) {
+ }
+ });
-SystemInfoDeviceCapability = function () {
- this.__defineGetter__("bluetooth", function () {
- return true;
+ this.__defineGetter__("location", function () {
+ return calendarItem.location;
});
- this.__defineGetter__("nfc", function () {
- return true;
+ this.__defineSetter__("location", function (val) {
+ try {
+ calendarItem.location = t.DOMString(val, "?");
+ } catch (e) {
+ }
});
- this.__defineGetter__("nfcReservedPush", function () {
- return false;
+
+ this.__defineGetter__("geolocation", function () {
+ return calendarItem.geolocation;
});
- this.__defineGetter__("multiTouchCount", function () {
- return 5;
+ this.__defineSetter__("geolocation", function (val) {
+ try {
+ calendarItem.geolocation = t.SimpleCoordinates(val, "?");
+ } catch (e) {
+ }
});
- this.__defineGetter__("inputKeyboard", function () {
- return false;
+
+ this.__defineGetter__("organizer", function () {
+ return calendarItem.organizer;
});
- this.__defineGetter__("inputKeyboardLayout", function () {
- return false;
+ this.__defineSetter__("organizer", function (val) {
+ try {
+ calendarItem.organizer = t.DOMString(val, "?");
+ } catch (e) {
+ }
});
- this.__defineGetter__("wifi", function () {
- return true;
+
+ this.__defineGetter__("visibility", function () {
+ return calendarItem.visibility;
});
- this.__defineGetter__("wifiDirect", function () {
- return true;
+ this.__defineSetter__("visibility", function (val) {
+ try {
+ calendarItem.visibility = t.CalendarItemVisibility(val);
+ } catch (e) {
+ }
});
- this.__defineGetter__("opengles", function () {
- return false;
+
+ this.__defineGetter__("status", function () {
+ return calendarItem.status;
});
- this.__defineGetter__("openglestextureFormat", function () {
- return "";
+ this.__defineSetter__("status", function (val) {
+ try {
+ calendarItem.status = t.CalendarItemStatus(val);
+ } catch (e) {
+ }
});
- this.__defineGetter__("openglesVersion1_1", function () {
- return false;
+
+ this.__defineGetter__("priority", function () {
+ return calendarItem.priority;
});
- this.__defineGetter__("openglesVersion2_0", function () {
- return false;
+ this.__defineSetter__("priority", function (val) {
+ try {
+ calendarItem.priority = t.CalendarItemPriority(val);
+ } catch (e) {
+ }
});
- this.__defineGetter__("fmRadio", function () {
- return false;
+
+ this.__defineGetter__("alarms", function () {
+ return calendarItem.alarms;
});
- this.__defineGetter__("platformVersion", function () {
- if (!_security.platformVersion) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+ this.__defineSetter__("alarms", function (val) {
+ try {
+ calendarItem.alarms = t.CalendarAlarm(val, "[]");
+ } catch (e) {
}
- return "2.2.0";
});
- this.__defineGetter__("webApiVersion", function () {
- if (!_security.webApiVersion) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+
+ this.__defineGetter__("categories", function () {
+ return calendarItem.categories;
+ });
+ this.__defineSetter__("categories", function (val) {
+ try {
+ calendarItem.categories = t.DOMString(val, "[]");
+ } catch (e) {
}
- return "2.2";
});
- this.__defineGetter__("nativeApiVersion", function () {
- if (!_security.nativeApiVersion) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
+
+ this.__defineGetter__("attendees", function () {
+ return calendarItem.attendees;
+ });
+ this.__defineSetter__("attendees", function (val) {
+ try {
+ calendarItem.attendees = t.CalendarAttendee(val, "[]");
+ } catch (e) {
}
- return "2.2";
});
- this.__defineGetter__("platformName", function () {
- return "Tizen";
+
+ this.convertToString = convertToString;
+};
+
+module.exports = CalendarItem;
+
+});
+define('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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 BluetoothClassDeviceMinor = function () {
+ // COMPUTER
+ this.__defineGetter__("COMPUTER_UNCATEGORIZED", function () {
+ return 0x00;
});
- this.__defineGetter__("camera", function () {
- return false;
+
+ this.__defineGetter__("COMPUTER_DESKTOP", function () {
+ return 0x01;
});
- this.__defineGetter__("cameraFront", function () {
- return false;
+
+ this.__defineGetter__("COMPUTER_SERVER", function () {
+ return 0x02;
});
- this.__defineGetter__("cameraFrontFlash", function () {
- return false;
+
+ this.__defineGetter__("COMPUTER_LAPTOP", function () {
+ return 0x03;
});
- this.__defineGetter__("cameraBack", function () {
- return false;
+
+ this.__defineGetter__("COMPUTER_HANDHELD_PC_OR_PDA", function () {
+ return 0x04;
});
- this.__defineGetter__("cameraBackFlash", function () {
- return false;
+
+ this.__defineGetter__("COMPUTER_PALM_PC_OR_PDA", function () {
+ return 0x05;
});
- this.__defineGetter__("location", function () {
- return true;
+
+ this.__defineGetter__("COMPUTER_WEARABLE", function () {
+ return 0x06;
});
- this.__defineGetter__("locationGps", function () {
- return true;
+
+ // PHONE
+ this.__defineGetter__("PHONE_UNCATEGORIZED", function () {
+ return 0x00;
});
- this.__defineGetter__("locationWps", function () {
- return false;
+
+ this.__defineGetter__("PHONE_CELLULAR", function () {
+ return 0x01;
});
- this.__defineGetter__("microphone", function () {
- return false;
+
+ this.__defineGetter__("PHONE_CORDLESS", function () {
+ return 0x02;
});
- this.__defineGetter__("usbHost", function () {
- return true;
+
+ this.__defineGetter__("PHONE_SMARTPHONE", function () {
+ return 0x03;
});
- this.__defineGetter__("usbAccessory", function () {
- return false;
+
+ this.__defineGetter__("PHONE_MODEM_OR_GATEWAY", function () {
+ return 0x04;
});
- this.__defineGetter__("screenOutputRca", function () {
- return false;
+
+ this.__defineGetter__("PHONE_ISDN", function () {
+ return 0x05;
});
- this.__defineGetter__("screenOutputHdmi", function () {
- return false;
+
+ // AUDIO_VIDEO
+ this.__defineGetter__("AV_UNRECOGNIZED", function () {
+ return 0x00;
});
- this.__defineGetter__("platformCoreCpuArch", function () {
- return "x86";
+
+ this.__defineGetter__("AV_WEARABLE_HEADSET", function () {
+ return 0x01;
});
- this.__defineGetter__("platformCoreFpuArch", function () {
- return "ssse3";
+
+ this.__defineGetter__("AV_HANDSFREE", function () {
+ return 0x02;
});
- this.__defineGetter__("sipVoip", function () {
- return false;
+
+ this.__defineGetter__("AV_MICROPHONE", function () {
+ return 0x04;
});
- this.__defineGetter__("duid", function () {
- return "device unique ID";
+
+ this.__defineGetter__("AV_LOUDSPEAKER", function () {
+ return 0x05;
});
- this.__defineGetter__("speechRecognition", function () {
- return false;
+
+ this.__defineGetter__("AV_HEADPHONES", function () {
+ return 0x06;
});
- this.__defineGetter__("speechSynthesis", function () {
- return false;
+
+ this.__defineGetter__("AV_PORTABLE_AUDIO", function () {
+ return 0x07;
});
- this.__defineGetter__("accelerometer", function () {
- return true;
+
+ this.__defineGetter__("AV_CAR_AUDIO", function () {
+ return 0x08;
});
- this.__defineGetter__("accelerometerWakeup", function () {
- return false;
+
+ this.__defineGetter__("AV_SETTOP_BOX", function () {
+ return 0x09;
});
- this.__defineGetter__("barometer", function () {
- return false;
+
+ this.__defineGetter__("AV_HIFI", function () {
+ return 0x0a;
});
- this.__defineGetter__("barometerWakeup", function () {
- return false;
+
+ this.__defineGetter__("AV_VCR", function () {
+ return 0x0b;
});
- this.__defineGetter__("gyroscope", function () {
- return true;
+
+ this.__defineGetter__("AV_VIDEO_CAMERA", function () {
+ return 0x0c;
});
- this.__defineGetter__("gyroscopeWakeup", function () {
- return false;
+
+ this.__defineGetter__("AV_CAMCORDER", function () {
+ return 0x0d;
});
- this.__defineGetter__("magnetometer", function () {
- return false;
+
+ this.__defineGetter__("AV_MONITOR", function () {
+ return 0x0e;
});
- this.__defineGetter__("magnetometerWakeup", function () {
- return false;
+
+ this.__defineGetter__("AV_DISPLAY_AND_LOUDSPEAKER", function () {
+ return 0x0f;
});
- this.__defineGetter__("photometer", function () {
- return false;
+
+ this.__defineGetter__("AV_VIDEO_CONFERENCING", function () {
+ return 0x10;
});
- this.__defineGetter__("photometerWakeup", function () {
- return false;
+
+ this.__defineGetter__("AV_GAMING_TOY", function () {
+ return 0x12;
});
- this.__defineGetter__("proximity", function () {
- return false;
+
+ // PERIPHERAL
+ this.__defineGetter__("PERIPHERAL_UNCATEGORIZED", function () {
+ return 0;
});
- this.__defineGetter__("proximityWakeup", function () {
- return false;
+
+ this.__defineGetter__("PERIPHERAL_KEYBOARD", function () {
+ return 0x10;
});
- this.__defineGetter__("tiltmeter", function () {
- return false;
+
+ this.__defineGetter__("PERIPHERAL_POINTING_DEVICE", function () {
+ return 0x20;
});
- this.__defineGetter__("tiltmeterWakeup", function () {
- return false;
+
+ this.__defineGetter__("PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE", function () {
+ return 0x30;
});
- this.__defineGetter__("dataEncryption", function () {
- return false;
+
+ this.__defineGetter__("PERIPHERAL_JOYSTICK", function () {
+ return 0x01;
});
- this.__defineGetter__("graphicsAcceleration", function () {
- return false;
+
+ this.__defineGetter__("PERIPHERAL_GAMEPAD", function () {
+ return 0x02;
});
- this.__defineGetter__("push", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_REMOTE_CONTROL", function () {
+ return 0x03;
});
- this.__defineGetter__("telephony", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_SENSING_DEVICE", function () {
+ return 0x04;
});
- this.__defineGetter__("telephonyMms", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_DEGITIZER_TABLET", function () {
+ return 0x05;
});
- this.__defineGetter__("telephonySms", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_CARD_READER", function () {
+ return 0x06;
});
- this.__defineGetter__("screenSizeNormal", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_DIGITAL_PEN", function () {
+ return 0x07;
});
- this.__defineGetter__("screenSize480_800", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_HANDHELD_SCANNER", function () {
+ return 0x08;
});
- this.__defineGetter__("screenSize720_1280", function () {
- return true;
+
+ this.__defineGetter__("PERIPHERAL_HANDHELD_INPUT_DEVICE", function () {
+ return 0x09;
});
- this.__defineGetter__("autoRotation", function () {
- return true;
+
+ // IMAGING
+ this.__defineGetter__("IMAGING_UNCATEGORIZED", function () {
+ return 0x00;
});
- this.__defineGetter__("shellAppWidget", function () {
- return false;
+
+ this.__defineGetter__("IMAGING_DISPLAY", function () {
+ return 0x04;
});
- this.__defineGetter__("visionImageRecognition", function () {
- return false;
+
+ this.__defineGetter__("IMAGING_CAMERA", function () {
+ return 0x08;
});
- this.__defineGetter__("visionQrcodeGeneration", function () {
- return false;
+
+ this.__defineGetter__("IMAGING_SCANNER", function () {
+ return 0x10;
});
- this.__defineGetter__("visionQrcodeRecognition", function () {
- return false;
+
+ this.__defineGetter__("IMAGING_PRINTER", function () {
+ return 0x20;
});
- this.__defineGetter__("visionFaceRecognition", function () {
- return false;
+
+ // WEARABLE
+ this.__defineGetter__("WEARABLE_WRITST_WATCH", function () {
+ return 0x01;
});
- this.__defineGetter__("secureElement", function () {
- return false;
+
+ this.__defineGetter__("WEARABLE_PAGER", function () {
+ return 0x02;
});
- this.__defineGetter__("nativeOspCompatible", function () {
- return false;
+
+ this.__defineGetter__("WEARABLE_JACKET", function () {
+ return 0x03;
});
- this.__defineGetter__("profile", function () {
- return "MOBILE_WEB";
+
+ this.__defineGetter__("WEARABLE_HELMET", function () {
+ return 0x04;
});
-};
-module.exports = _self;
+ this.__defineGetter__("WEARABLE_GLASSES", function () {
+ return 0x05;
+ });
-});
-define('ripple/platform/tizen/2.0/systemsetting', function (require, exports, module) {
-/*
- * Copyright 2013 Intel Corporation.
- *
- * 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.
- */
+ // TOY
+ this.__defineGetter__("TOY_ROBOT", function () {
+ return 0x01;
+ });
-var db = require('ripple/db'),
- event = require('ripple/event'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- t = require('ripple/platform/tizen/2.0/typecast'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- _systemSettings = null,
- DBSYSTEMSETTING_KEY = "tizen2-systemsetting",
- _security = {
- "http://tizen.org/privilege/setting": ["setProperty"]
- },
- _self;
+ this.__defineGetter__("TOY_VEHICLE", function () {
+ return 0x02;
+ });
-function _initialize() {
- _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
- if (!_systemSettings) {
- _systemSettings = {"HOME_SCREEN": "images/home_screen.jpg", "LOCK_SCREEN": "images/lock_screen.jpg", "INCOMING_CALL": "sounds/incoming.wav", "NOTIFICATION_EMAIL": "sounds/notification.wav"};
- db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
- event.trigger("SystemSettingChanged");
- }
-}
+ this.__defineGetter__("TOY_DOLL", function () {
+ return 0x03;
+ });
-_self = function () {
- var systemSetting;
+ this.__defineGetter__("TOY_CONTROLLER", function () {
+ return 0x04;
+ });
- function setProperty(type, value, successCallback, errorCallback) {
- if (!_security.setProperty) {
- throw new WebAPIException(errorcode.SECURITY_ERR);
- }
+ this.__defineGetter__("TOY_GAME", function () {
+ return 0x05;
+ });
- t.SystemSettingManager("setProperty", arguments);
+ // HEALTH
+ this.__defineGetter__("HEALTH_UNDEFINED", function () {
+ return 0x00;
+ });
- _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
- _systemSettings[type] = value;
- db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
- event.trigger("SystemSettingChanged");
- window.setTimeout(function () {
- successCallback();
- }, 1);
- }
+ this.__defineGetter__("HEALTH_BLOOD_PRESSURE_MONITOR", function () {
+ return 0x01;
+ });
- function getProperty(type, successCallback, errorCallback) {
- t.SystemSettingManager("getProperty", arguments);
+ this.__defineGetter__("HEALTH_THERMOMETER", function () {
+ return 0x02;
+ });
- _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
- window.setTimeout(function () {
- successCallback(_systemSettings[type]);
- }, 1);
- }
+ this.__defineGetter__("HEALTH_WEIGHING_SCALE", function () {
+ return 0x03;
+ });
- function handleSubFeatures(subFeatures) {
- var i, subFeature;
+ this.__defineGetter__("HEALTH_GLUCOSE_METER", function () {
+ return 0x04;
+ });
- for (subFeature in subFeatures) {
- for (i in _security[subFeature]) {
- _security[_security[subFeature][i]] = true;
- }
- }
- }
+ this.__defineGetter__("HEALTH_PULSE_OXIMETER", function () {
+ return 0x05;
+ });
- systemSetting = {
- setProperty: setProperty,
- getProperty: getProperty,
- handleSubFeatures: handleSubFeatures
- };
+ this.__defineGetter__("HEALTH_PULSE_RATE_MONITOR", function () {
+ return 0x06;
+ });
- return systemSetting;
-};
+ this.__defineGetter__("HEALTH_DATA_DISPLAY", function () {
+ return 0x07;
+ });
-_initialize();
+ this.__defineGetter__("HEALTH_STEP_COUNTER", function () {
+ return 0x08;
+ });
-module.exports = _self;
+ this.__defineGetter__("HEALTH_BODY_COMPOSITION_ANALYZER", function () {
+ return 0x09;
+ });
+
+ this.__defineGetter__("HEALTH_PEAK_FLOW_MONITOR", function () {
+ return 0x0a;
+ });
+
+ this.__defineGetter__("HEALTH_MEDICATION_MONITOR", function () {
+ return 0x0b;
+ });
+
+ this.__defineGetter__("HEALTH_KNEE_PROSTHESIS", function () {
+ return 0x0c;
+ });
+
+ this.__defineGetter__("HEALTH_ANKLE_PROSTHESIS", function () {
+ return 0x0d;
+ });
+};
+
+module.exports = BluetoothClassDeviceMinor;
});
-define('ripple/platform/tizen/2.0/time', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/geocoder', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typecast'),
- TZDate = require('ripple/platform/tizen/2.0/TZDate'),
- db = require('ripple/db'),
- tz = require('ripple/platform/tizen/2.0/timezone_info'),
- _timeFormat = "h:m:s ap", _shortDateFormat = "d/m/y",
- _longDateFormat = "D, M d, y", _self;
+var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ ProviderLocal = require('ripple/platform/tizen/2.0/geoBackend_local'),
+ ProviderNominatim = require('ripple/platform/tizen/2.0/geoBackend_nominatim'), // Nominatim geocode service
+ _getProviders,
+ _providers,
+ _self;
-_self = {
- getCurrentDateTime: function () {
- t.TimeUtil("getCurrentDateTime", arguments);
- return new TZDate();
- },
- getLocalTimezone: function () {
- t.TimeUtil("getLocalTimezone", arguments);
- var localtz = db.retrieve("tizen-timezone") || "UTC";
- return localtz;
- },
- getAvailableTimezones: function () {
- t.TimeUtil("getAvailableTimezones", arguments);
- var ret = tz.getAllTimezone();
- return ret;
- },
- getDateFormat: function (shortformat) {
- t.TimeUtil("getDateFormat", arguments);
+function _initialize() {
+ _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})
+ /* ,new ProviderLocal({name : "Tizen Database", connectivity : "OFFLINE"}) */];
+}
- if (shortformat) {
- return _shortDateFormat;
- } else {
- return _longDateFormat;
- }
- },
- getTimeFormat: function () {
- t.TimeUtil("getTimeFormat", arguments);
- return _timeFormat;
+_initialize();
+
+_self = {
+ getDefaultProvider : function () {
+ return _providers[0];
},
- isLeapYear: function (year) {
- t.TimeUtil("isLeapYear", arguments);
- return ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0));
+ getProviders : function () {
+ return _providers;
}
};
"Etc/GMT-14": {diff: 14, abbr: "Etc/GMT-14"},
"Etc/GMT-2": {diff: 2, abbr: "Etc/GMT-2"},
"Etc/GMT-3": {diff: 3, abbr: "Etc/GMT-3"},
- "Etc/GMT-4": {diff: 4, abbr: "Etc/GMT-4"},
- "Etc/GMT-5": {diff: 5, abbr: "Etc/GMT-5"},
- "Etc/GMT-6": {diff: 6, abbr: "Etc/GMT-6"},
- "Etc/GMT-7": {diff: 7, abbr: "Etc/GMT-7"},
- "Etc/GMT-8": {diff: 8, abbr: "Etc/GMT-8"},
- "Etc/GMT-9": {diff: 9, abbr: "Etc/GMT-9"},
- "Etc/GMT0": {diff: 0, abbr: "Etc/GMT0"},
- "Etc/Greenwich": {diff: 0, abbr: "GMT"}
-};
-
-module.exports = {
- getAllTimezone: function () {
- var i, ret = [];
- for (i in _timezone_data)
- ret.push(i);
- return ret;
- },
- getTimezoneDiff: function (zone) {
- return _timezone_data[zone].diff;
- },
- getTimezoneAbbr: function (zone) {
- return _timezone_data[zone].abbr;
- },
- getTimezoneDesc: function (zone) {
- if (_timezone_data[zone].desc) {
- return _timezone_data[zone].desc;
- } else {
- return null;
- }
- },
- isValidTimezone: function (zone) {
- return (_timezone_data[zone] === undefined) ? false : true;
- }
-};
-
-
-});
-define('ripple/platform/tizen/2.0/tizen1_utils', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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 self,
- utils = require('ripple/utils'),
- errorcode = require('ripple/platform/tizen/2.0/errorcode'),
- WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');
-
-self = module.exports = {
- _wac2_regexSanitize: function (regexString) {
- var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
- return regexString.replace("^", "\\^")
- .replace("$", "\\$")
- .replace("(", "\\(")
- .replace(")", "\\)")
- .replace("<", "\\<")
- .replace("[", "\\[")
- .replace("{", "\\{")
- .replace(/\\([^%])/, "\\\\$1") /* don't replace \\% */
- .replace("|", "\\|")
- .replace(">", "\\>")
- .replace(".", "\\.")
- .replace("*", "\\*")
- .replace("+", "\\+")
- .replace("?", "\\?")
- .replace(escapePattern, "$1.*") /* replace % with .* */
- .replace(percentPattern, "%"); /* strip excape of % */
- },
-
- isValidDate: function (d) {
- if (Object.prototype.toString.call(d) !== "[object Date]")
- return false;
- return !isNaN(d.getTime());
- },
- isValidTZDate: function (d) {
- if (d && (d instanceof tizen.TZDate)) {
- return true;
- }
- return false;
- },
- isValidArray: function (a) {
- return (Object.prototype.toString.call(a) === "[object Array]");
- },
-
- matchOptionArrayString: function (src, attr, pattern) {
- /* src.obj[attr] is a StringArray */
- var _pattern, re, _stringMatch;
- _pattern = this._wac2_regexSanitize(pattern);
- re = new RegExp("^" + _pattern + "$", "i");
-
- _stringMatch = function (obj, index) {
- if (pattern.search(/^%*$/i) === 0)
- return true;
- if (obj[attr] === undefined || obj[attr] === null)
- return false;
- return obj[attr].some(function (f) {
- return f.search(re) !== -1;
- });
- };
- return utils.filter(src, _stringMatch);
- },
-
- matchAttributeBooleanFilter: function (src, attr, value) {
- // only support EXACTLY matchFlag
- var _booleanMatch, atr = attr.split(".");
-
- if (atr.length === 2) {
- _booleanMatch = function (obj, index) {
- if (!obj[atr[0]])
- return false;
-
- return (obj[atr[0]][atr[1]] === value);
- };
- } else {
- _booleanMatch = function (obj, index) {
- return (obj[attr] === value);
- };
- }
-
- return utils.filter(src, _booleanMatch);
- },
-
- matchAttributeArrayFilter: function (src, attr, matchFlag, value) {
- var _re, _arrayMatch, atr = attr.split("."), _existMatch;
-
- if (atr.length === 2) {
- _existMatch = function (obj, index) {
- if (!obj[atr[0]])
- return false;
-
- return (obj[atr[0]][atr[1]] !== undefined);
- };
- } else {
- _existMatch = function (obj, index) {
- return (obj[attr] !== undefined);
- };
- }
-
- if (value === undefined || value === null) {
- return utils.filter(src, _existMatch);
- }
-
- switch (matchFlag)
- {
- case "EXACTLY":
- _re = new RegExp("^" + value + "$");
- break;
- case "FULLSTRING":
- _re = new RegExp("^" + value + "$", "i");
- break;
- case "CONTAINS":
- _re = new RegExp(value, "i");
- break;
- case "STARTSWITH":
- _re = new RegExp("^" + value, "i");
- break;
- case "ENDSWITH":
- _re = new RegExp(value + "$", "i");
- break;
- case "EXISTS":
- return utils.filter(src, _existMatch);
- default:
- return [];
- }
-
- if (atr.length === 2) {
- _arrayMatch = function (obj, index) {
- if (!obj[atr[0]])
- return false;
-
- return (obj[atr[0]][atr[1]] && obj[atr[0]][atr[1]].some(function (o) {
- return (o.search(_re) !== -1);
- }));
- };
- } else {
- _arrayMatch = function (obj, index) {
- return (obj[attr] && obj[attr].some(function (o) {
- return (o.search(_re) !== -1);
- }));
- };
- }
-
- return utils.filter(src, _arrayMatch);
- },
-
- matchAttributeRangeFilter: function (src, attr, low, high) {
- var _rangeMatch, atr = attr.split(".");
-
- if (atr.length === 2) {
- _rangeMatch = function (obj, index) {
- var matched = true;
-
- if (!obj[atr[0]])
- return false;
+ "Etc/GMT-4": {diff: 4, abbr: "Etc/GMT-4"},
+ "Etc/GMT-5": {diff: 5, abbr: "Etc/GMT-5"},
+ "Etc/GMT-6": {diff: 6, abbr: "Etc/GMT-6"},
+ "Etc/GMT-7": {diff: 7, abbr: "Etc/GMT-7"},
+ "Etc/GMT-8": {diff: 8, abbr: "Etc/GMT-8"},
+ "Etc/GMT-9": {diff: 9, abbr: "Etc/GMT-9"},
+ "Etc/GMT0": {diff: 0, abbr: "Etc/GMT0"},
+ "Etc/Greenwich": {diff: 0, abbr: "GMT"}
+};
- if (low !== null && low !== undefined) {
- matched = (obj[atr[0]][atr[1]] >= low);
- }
- if (matched && (high !== null && high !== undefined)) {
- matched = (obj[atr[0]][atr[1]] <= high);
- }
- return matched;
- };
+module.exports = {
+ getAllTimezone: function () {
+ var i, ret = [];
+ for (i in _timezone_data)
+ ret.push(i);
+ return ret;
+ },
+ getTimezoneDiff: function (zone) {
+ return _timezone_data[zone].diff;
+ },
+ getTimezoneAbbr: function (zone) {
+ return _timezone_data[zone].abbr;
+ },
+ getTimezoneDesc: function (zone) {
+ if (_timezone_data[zone].desc) {
+ return _timezone_data[zone].desc;
} else {
- _rangeMatch = function (obj, index) {
- var matched = true;
-
- if (low !== null && low !== undefined) {
- matched = (obj[attr] >= low);
- }
- if (matched && (high !== null && high !== undefined)) {
- matched = (obj[attr] <= high);
- }
- return matched;
- };
+ return null;
}
- return utils.filter(src, _rangeMatch);
},
+ isValidTimezone: function (zone) {
+ return (_timezone_data[zone] === undefined) ? false : true;
+ }
+};
- matchAttributeFilter: function (src, attr, matchFlag, value) {
- var _re, _stringMatch, atr = attr.split("."),
- _existMatch;
- if (atr.length === 2) {
- _existMatch = function (obj, index) {
- if (!obj[atr[0]])
- return false;
+});
+define('ripple/platform/tizen/2.0/lbs_utils', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- return (obj[atr[0]][atr[1]] !== undefined);
- };
- } else {
- _existMatch = function (obj, index) {
- return (obj[attr] !== undefined);
- };
- }
+var tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ _self;
- if (value === undefined || value === null) {
- return utils.filter(src, _existMatch);
- }
+function CoordinateProperties(prop) {
+ var _self;
+ _self = {
+ latitude : prop.latitude || 0,
+ longitude : prop.longitude || 0,
+ altitude : prop.altitude || 0,
+ accuracy : prop.accuracy || 0,
+ altitudeAccuracy : prop.altitudeAccuracy || 0,
+ heading : prop.heading || 0,
+ speed : prop.speed || 0
+ };
+ return _self;
+}
- switch (matchFlag)
- {
- case "EXACTLY":
- _re = new RegExp("^" + value + "$");
- break;
- case "FULLSTRING":
- _re = new RegExp("^" + value + "$", "i");
- break;
- case "CONTAINS":
- _re = new RegExp(value, "i");
- break;
- case "STARTSWITH":
- _re = new RegExp("^" + value, "i");
- break;
- case "ENDSWITH":
- _re = new RegExp(value + "$", "i");
- break;
- case "EXISTS":
- return utils.filter(src, _existMatch);
- default:
- return [];
- }
- if (atr.length === 2) {
- _stringMatch = function (obj, index) {
- if (!obj[atr[0]])
- return false;
+function _checkAddressProperties(p, dst) {
+ if (p.country !== null && p.country !== undefined)
+ dst.country = String(p.country);
+ if (p.region !== null && p.region !== undefined)
+ dst.region = String(p.region);
+ if (p.county !== null && p.county !== undefined)
+ dst.county = String(p.county);
+ if (p.city !== null && p.city !== undefined)
+ dst.city = String(p.city);
+ if (p.street !== null && p.street !== undefined)
+ dst.street = String(p.street);
+ if (p.streetNumber !== null && p.streetNumber !== undefined)
+ dst.streetNumber = String(p.streetNumber);
+ if (p.premises !== null && p.premises !== undefined)
+ dst.premises = String(p.premises);
+ if (p.additionalInformation !== null &&
+ p.additionalInformation !== undefined)
+ dst.additionalInformation = String(p.additionalInformation);
+ if (p.postalCode !== null && p.postalCode !== undefined)
+ dst.postalCode = String(p.postalCode);
+}
- if (matchFlag === "EXACTLY") {
- return (obj[atr[0]][atr[1]] === value);
- } else if (typeof obj[atr[0]][atr[1]] !== 'string') {
- return false;
- }
+function AddressProperties(prop) {
+ var _self;
+ _self = {
+ country : null,
+ region : null,
+ county : null,
+ city : null,
+ street : null,
+ streetNumber : null,
+ premises : null,
+ additionalInformation : null,
+ postalCode : null
+ };
+ if (prop) {
+ if (_checkAddressProperties(prop, _self) === false)
+ return undefined;
+ }
+ return _self;
+}
- return (obj[atr[0]][atr[1]].search(_re) !== -1);
- };
- } else {
- _stringMatch = function (obj, index) {
- if (matchFlag === "EXACTLY") {
- return (obj[attr] === value);
- } else if (typeof obj[attr] !== 'string') {
- return false;
- }
+_self = {
+ LocationServiceProvider : function (prop) {
+ var _self;
+ _self = {
+ name : "",
+ metaData : Object,
+ attribution : "",
+ supportedOptions : [],
+ setOptions : function (options, successCB, errorCB) {},
+ connectivity : "" // "ONLINE" "OFFLINE" "HYBRID"
+ };
- return (obj[attr].search(_re) !== -1);
- };
- }
- return utils.filter(src, _stringMatch);
- },
+ if (prop.name !== null && prop.name !== undefined)
+ _self.name = String(prop.name);
+ if (prop.metaData !== null && prop.metaData !== undefined)
+ _self.metaData = prop.metaData;
- matchOptionString: function (src, attr, pattern) {
- /* src.obj[attr] is a string */
- var _stringMatch, _pattern, _re;
- _pattern = this._wac2_regexSanitize(pattern);
- _re = new RegExp("^" + _pattern + "$", "mi");
+ if (prop.attribution !== null && prop.attribution !== undefined)
+ _self.attribution = String(prop.attribution);
- _stringMatch = function (obj, index) {
- return (obj[attr].search(_re) !== -1);
- };
- return utils.filter(src, _stringMatch);
- },
+ if (prop.supportedOptions !== null && prop.supportedOptions !== undefined)
+ _self.supportedOptions = [prop.supportedOptions];
- matchOptionDate: function (src, attr, filterStart, filterEnd) {
- var _dateMatch;
- _dateMatch = function (obj, index) {
- var matched = true, valueDate = obj[attr];
+ if (prop.setOptions !== null && prop.setOptions !== undefined)
+ _self.setOptions = prop.setOptions;
- if (filterStart !== undefined && filterStart !== null) {
- matched = (valueDate.getTime() >= filterStart.getTime());
- }
- if (matched && (filterEnd !== undefined && filterEnd !== null)) {
- matched = (valueDate.getTime() <= filterEnd.getTime());
- }
- return matched;
- };
- return utils.filter(src, _dateMatch);
- },
+ if (prop.connectivity !== null && prop.connectivity !== undefined)
+ _self.connectivity = String(prop.connectivity);
- matchOptionShortArray: function (src, attr, filterArray) {
- /* src.obj[attr] is a short, filterArray is an array
- i.e. find status is [CONFRIMED or TENTATIVE] */
- var arraySome = function (obj, index) {
- return filterArray.some(function (f) {
- return f === obj[attr];
- });
- };
- return utils.filter(src, arraySome);
+ return _self;
},
- validateArgumentType: function (arg, argType, errorObj) {
- var invalidArg = false;
-
- switch (argType) {
- case "array":
- if (!arg instanceof Array) {
- invalidArg = true;
- }
- break;
- case "date":
- if (!arg instanceof Date) {
- invalidArg = true;
- }
- break;
- case "integer":
- if (typeof Number(arg) !== "number" || Number(arg) !== Math.floor(arg)) {
- invalidArg = true;
- }
- break;
- default:
- if (typeof arg !== argType) {
- invalidArg = true;
- }
- break;
+ GeoCoordinates : function (prop) {
+ var _self = new CoordinateProperties(prop);
+ if (tizen1_utils.isEmptyObject(_self)) {
+ return undefined;
}
- if (invalidArg) {
- throw errorObj;
- }
+ return _self;
},
- validateCallbackType: function (successCallback, errorCallback) {
- if (successCallback) {
- this.validateArgumentType(successCallback, "function",
- new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
- if (errorCallback) {
- this.validateArgumentType(errorCallback, "function",
- new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ StructuredAddress : function (prop) {
+ var _self;
+ _self = new AddressProperties(prop);
+ if (tizen1_utils.isEmptyObject(_self)) {
+ return undefined;
}
- },
- validateEqualArrays: function (arrayOne, arrayTwo) {
- var isEqual = false, i;
+ return _self;
+ }
+};
- if (Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
- Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
- arrayOne.length === arrayTwo.length) {
- isEqual = true;
- for (i in arrayOne) {
- if (arrayOne[i] !== arrayTwo[i]) {
- isEqual = false;
- break;
- }
- }
- }
- return isEqual;
- },
+module.exports = _self;
- validateTypeMismatch: function (onSuccess, onError, name, callback) {
+});
+define('ripple/platform/tizen/2.0/AccountBase', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- if (onSuccess === undefined || onSuccess === null) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
- this.validateArgumentType(onSuccess, "function",
- new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- if (onError !== null && onError !== undefined) {
- this.validateArgumentType(onError, "function",
- new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
- }
+module.exports = function (appId, userName, displayName, service) {
+ var _self,
+ _id = Math.uuid(null, 16);
- return callback && callback();
- },
+ _self = {
+ appId : appId || "",
+ userName : userName || "",
+ displayName : displayName || "",
+ service : service || {}
+ };
- isEmptyObject: function (obj) {
- var prop;
+ _self.__defineGetter__("id", function () {
+ return _id;
+ });
- for (prop in obj) {
- return false;
- }
- return true;
- },
+ return _self;
+};
- arrayComposite: function (mode, arrayA, arrayB) {
- var combinedArray = arrayA.concat(arrayB),
- intersectionArray = arrayA.filter(function (value) {
- if (utils.arrayContains(arrayB, value)) {
- return true;
- }
+});
+define('ripple/platform/tizen/2.0/AlarmAbsolute', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- return false;
- });
+var AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ _byDayValue = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"],
+ PERIOD_WEEK = (7 * 24 * 60 * 60), MILLI_SECOND = 1000,
+ AlarmAbsolute;
- switch (mode) {
- case "AND":
- case "INTERSECTION":
- return intersectionArray;
- case "OR":
- case "UNION":
- return intersectionArray.concat(combinedArray.filter(function (value) {
- if (utils.arrayContains(intersectionArray, value)) {
- return false;
- }
+AlarmAbsolute = function () {
+ var alarm, period = null, daysOfTheWeek = [], ascDays = [], voc, date;
- return true;
- }));
- default:
- return undefined;
+ function getScheduleDateByPeriod(current, date, period) {
+ var diff = period * MILLI_SECOND,
+ triggerDate = new Date(date);
+
+ while (current > (triggerDate - MILLI_SECOND)) { // In advance 1s - MILLI_SECOND
+ triggerDate.setTime(triggerDate.getTime() + diff);
}
- },
+ return triggerDate;
+ }
- isEqual: function (srcObj, aimObj) {
- var i;
+ function getSchedulteDateByDay(current, triggerTime, startDay, endDay) {
+ startDay = (7 + (endDay - startDay)) % 7;
+ current.setHours(triggerTime.getHours());
+ current.setMinutes(triggerTime.getMinutes());
+ current.setSeconds(triggerTime.getSeconds());
+ current.setMilliseconds(triggerTime.getMilliseconds());
+ current.setDate(current.getDate() + startDay);
+ return current;
+ }
- if (typeof srcObj !== typeof aimObj) {
- return false;
+ function getAscDays() { // Get asc order array
+ for (var i in daysOfTheWeek) {
+ ascDays.push(_byDayValue.lastIndexOf(daysOfTheWeek[i]));
}
+ return ascDays.sort();
+ }
- if (srcObj === null || srcObj === undefined || typeof srcObj === 'number' ||
- typeof srcObj === 'string' || typeof srcObj === 'boolean') {
- return srcObj === aimObj;
- }
+ /*
+ * Return
+ * true: A is bigger than B
+ * false: otherwise
+ */
+ function compareTime(current, triggerTime) {
+ var diff = current.getHours() - triggerTime.getHours();
+ if (diff !== 0)
+ return (diff > 0);
- for (i in srcObj) {
- if (!aimObj.hasOwnProperty(i) || !self.isEqual(srcObj[i], aimObj[i])) {
- return false;
- }
- }
+ diff = current.getMinutes() - triggerTime.getMinutes();
+ if (diff !== 0)
+ return (diff > 0);
+
+ diff = current.getSeconds() - triggerTime.getSeconds();
+ if (diff < -1) // Delay 1s
+ return false;
return true;
- },
+ }
- query: function (objects, filter, sortMode, count, offset) {
- function isCompositeFilter(filter) {
- return (filter.type) ? true : false;
- }
+ alarm = new AlarmBase(this);
- function isAttributeFilter(filter) {
- return (filter.matchFlag) ? true : false;
+ voc = [
+ function (_date, _daysOfTheWeek) {
+ date = _date;
+ daysOfTheWeek = _daysOfTheWeek;
+ period = PERIOD_WEEK;
+ },
+ function (_date, _period) {
+ date = _date;
+ period = _period;
+ },
+ function (_date) {
+ date = _date;
}
+ ];
- function getValue(obj, key) {
- var keys = key.split("."),
- value = obj[keys[0]],
- i;
+ t.AlarmAbsolute(arguments, this, voc);
- for (i = 1; i < keys.length; i++) {
- if (value[keys[i]]) {
- value = value[keys[i]];
- }
- }
+ this.getNextScheduledDate = function () {
+ var current = new Date(),
+ diff, isPass, today, total, i, nextDate;
- return value;
- }
+ diff = current - date;
+ if (diff < -1000) // Advance 1s
+ return date; // Before first trigger, return date
- function _filter(objects, filter) {
- var i, results, eachResult, filterFunc;
+ if (period === null)
+ return null;
- if (isCompositeFilter(filter)) {
- for (i in filter.filters) {
- eachResult = _filter(objects, filter.filters[i]);
- results = (results === undefined) ? eachResult : self.arrayComposite(filter.type, results, eachResult);
- }
- return results;
- }
+ if (period !== PERIOD_WEEK)
+ return getScheduleDateByPeriod(current, date, period); // Repeat by period
- if (isAttributeFilter(filter)) {
- for (i in objects) {
- if (filter.attributeName in objects[i])
- break;
+ today = current.getDay(); // 0~6
+ ascDays = getAscDays();
+ total = ascDays.length;
+
+ if ((ascDays[0] <= today) && (today <= ascDays[total - 1])) { // Today out of ascDays
+ for (i in ascDays) { // Today in ascDays
+ if (ascDays[i] < today) {
+ continue;
+ } else if (ascDays[i] > today) {
+ nextDate = ascDays[i];
+ break;
+ } else {
+ isPass = compareTime(current, date); // Is triggerTime pass
+ if (isPass) {
+ nextDate = ascDays[(i < total - 1) ? (parseInt(i, 10) + 1) : 0];
+ } else {
+ nextDate = today;
+ }
+ break;
}
- filterFunc = self.isValidArray(objects[i][filter.attributeName]) ? self.matchAttributeArrayFilter : self.matchAttributeFilter;
- results = filterFunc(objects, filter.attributeName, filter.matchFlag, filter.matchValue);
- } else {
- results = self.matchAttributeRangeFilter(objects, filter.attributeName, filter.initialValue, filter.endValue);
}
-
- return results;
- }
-
- function _sort(objects, sortMode) {
- objects.sort(function (a, b) {
- return (sortMode.order === "ASC") ?
- (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
- (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
- });
-
- return objects;
+ } else {
+ nextDate = ascDays[0];
}
- var res = objects;
+ return getSchedulteDateByDay(current, date, today, nextDate);
+ };
- if (filter) {
- res = _filter(res, filter);
- }
+ this.__defineGetter__("date", function () {
+ return new Date(date);
+ });
- if (sortMode) {
- _sort(res, sortMode);
- }
+ this.__defineGetter__("period", function () {
+ return period;
+ });
- if (offset || count) {
- offset = (offset > 0) ? offset : 0;
- res = (count > 0) ? res.slice(offset, offset + count) : res.slice(offset);
- }
+ this.__defineGetter__("daysOfTheWeek", function () {
+ return daysOfTheWeek;
+ });
+};
- return res;
- },
+module.exports = AlarmAbsolute;
- copyString: function (str) {
- var newStr, charConvert = [], i;
+});
+define('ripple/platform/tizen/2.0/ContactPhoneNumber', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if (typeof str !== 'string') {
- return str;
- }
- for (i = 0; i < str.length; i++) {
- charConvert[i] = str.charAt(i);
- }
- newStr = charConvert.join("");
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactPhoneNumber;
- return newStr;
- },
+ContactPhoneNumber = function (number, types, isDefault) {
+ var contactPhoneNumber = {};
- copy: function (obj) {
- var i,
- newObj = jQuery.isArray(obj) ? [] : {};
+ t.ContactPhoneNumber(arguments, this);
- if (typeof obj === 'number' ||
- typeof obj === 'string' ||
- typeof obj === 'boolean' ||
- obj === null ||
- obj === undefined) {
- return obj;
- }
+ contactPhoneNumber.number = number;
+ contactPhoneNumber.isDefault = isDefault || false;
+ contactPhoneNumber.types = (types && types[0]) ? types : ["VOICE"];
- if (obj instanceof Date) {
- return new Date(obj);
+ this.__defineGetter__("number", function () {
+ return contactPhoneNumber.number;
+ });
+ this.__defineSetter__("number", function (val) {
+ try {
+ contactPhoneNumber.number = t.DOMString(val);
+ } catch (e) {
}
+ });
- if (obj instanceof RegExp) {
- return new RegExp(obj);
+ this.__defineGetter__("isDefault", function () {
+ return contactPhoneNumber.isDefault;
+ });
+ this.__defineSetter__("isDefault", function (val) {
+ try {
+ contactPhoneNumber.isDefault = t.boolean(val);
+ } catch (e) {
}
+ });
- for (i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (obj.__lookupGetter__(i)) {
- newObj.__defineGetter__(i, (function (key) {
- return function () {
- return self.copy(obj[key]);
- };
- }(i)));
- }
- else {
- newObj[i] = self.copy(obj[i]);
- }
- }
+ this.__defineGetter__("types", function () {
+ return contactPhoneNumber.types;
+ });
+ this.__defineSetter__("types", function (val) {
+ try {
+ contactPhoneNumber.types = t.DOMString(val, "[]");
+ } catch (e) {
}
-
- return newObj;
- }
+ });
};
+module.exports = ContactPhoneNumber;
+
});
-define('ripple/platform/tizen/2.0/touchEvent', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/SyncInfo', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var emulatorBridge = require('ripple/emulatorBridge'),
- event = require('ripple/event'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- Touch,
- TouchList,
- TouchEvent,
- _touchCanvasElements = [],
- _dataEnlargeRatio = 4,
- _self;
-
-function _isValidTouch(touches) {
- var touche, _touches = [], i;
- if (!touches) {
- return false;
- }
- if (!tizen1_utils.isValidArray(touches)) {
- _touches = [touches];
- }
-
- for (i = 0; i < _touches.length; i++) {
- touche = _touches[i];
- if ((touche !== undefined) &&
- ((typeof touche !== "object") ||
- (typeof touche.target !== "object") ||
- (touche.identifier !== undefined) && (typeof touche.identifier !== "number") ||
- (touche.screenX !== undefined) && (typeof touche.screenX !== "number") ||
- (touche.screenY !== undefined) && (typeof touche.screenY !== "number") ||
- (touche.clientX !== undefined) && (typeof touche.clientX !== "number") ||
- (touche.clientY !== undefined) && (typeof touche.clientY !== "number") ||
- (touche.pageX !== undefined) && (typeof touche.pageX !== "number") ||
- (touche.pageY !== undefined) && (typeof touche.pageY !== "number")))
- return false;
- }
- return true;
-}
-
-function _dispatchAllEvents(event) {
- _touchCanvasElements.forEach(function (value) {
- if (value !== undefined) {
- value.dispatchEvent(event);
- }
- });
-}
-
-function _touchMove(event) {
- var data = event.data,
- touches = [],
- removedTouches = [],
- touchList,
- simulatedEvent,
- dataId,
- ids = [],
- intervalId,
- currentIndex,
- item = {};
-
- if (_touchCanvasElements.length === 0)
- return;
+var db = require('ripple/db'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ SyncInfo,
+ _accounts = {},
+ _counter = 0;
- for (dataId in data) {
- if (!data[dataId].length || data[dataId].length === 0)
- return;
+SyncInfo = function () {
+ var voc, syncInfo = {}, index;
- ids.push(dataId);
- item = data[dataId][0];
- touches.push(new Touch(item.target, dataId, item.pageX * _dataEnlargeRatio, item.pageY * _dataEnlargeRatio, item.screenX * _dataEnlargeRatio,
- item.screenY * _dataEnlargeRatio, item.offsetX * _dataEnlargeRatio, item.offsetY * _dataEnlargeRatio));
+ function save() {
+ _accounts[index] = {
+ id: syncInfo.id,
+ password: syncInfo.password
+ };
+ db.saveObject("save-syncinfo", _accounts);
}
- // touch start
- touchList = new TouchList(touches);
- simulatedEvent = new TouchEvent("touchstart", true, true, touchList, touchList, touchList, event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
- _dispatchAllEvents(simulatedEvent);
- currentIndex = 0;
-
- // touch move and touch end
- intervalId = setInterval(function () {
- touches = [];
- removedTouches = [];
-
- ids.forEach(function (id) {
- var points = data[id],
- touchItem, removedItem;
+ function construct(url, id, password, mode) {
+ syncInfo.url = url;
+ syncInfo.id = id;
+ syncInfo.password = password;
+ syncInfo.mode = mode;
+ syncInfo.type = null;
+ syncInfo.interval = null;
- if (currentIndex < points.length) {
- touchItem = points[currentIndex];
- } else {
- removedItem = points[points.length - 1];
+ this.__defineGetter__("url", function () {
+ return syncInfo.url;
+ });
+ this.__defineSetter__("url", function (url) {
+ try {
+ syncInfo.url = t.DOMString(url);
+ } catch (e) {
}
-
- if (touchItem)
- touches.push(new Touch(touchItem.target, id, touchItem.pageX * _dataEnlargeRatio, touchItem.pageY * _dataEnlargeRatio, touchItem.screenX * _dataEnlargeRatio,
- touchItem.screenY * _dataEnlargeRatio, touchItem.offsetX * _dataEnlargeRatio, touchItem.offsetY * _dataEnlargeRatio));
- if (removedItem)
- removedTouches.push(new Touch(removedItem.target, id, removedItem.pageX * _dataEnlargeRatio, removedItem.pageY * _dataEnlargeRatio, removedItem.screenX * _dataEnlargeRatio,
- removedItem.screenY * _dataEnlargeRatio, removedItem.offsetX * _dataEnlargeRatio, removedItem.offsetY * _dataEnlargeRatio));
});
- if (touches.length > 0) {
- simulatedEvent = new TouchEvent("touchmove", true, true, new TouchList(touches), new TouchList(touches), new TouchList(touches),
- event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
- _dispatchAllEvents(simulatedEvent);
- } else {
- clearInterval(intervalId);
- }
-
- if (removedTouches.length > 0) {
- simulatedEvent = new TouchEvent("touchend", true, true, new TouchList(removedTouches), new TouchList(removedTouches), new TouchList(removedTouches),
- event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
- _dispatchAllEvents(simulatedEvent);
- }
- currentIndex++;
- }, 50);
-}
-
-function _touchCancel(event) {
- var mousedownEvent = event.touchEvent,
- simulatedEvent;
-
- simulatedEvent = new TouchEvent("touchcancel", true, true, new TouchList([]), new TouchList([]), new TouchList([]),
- event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
- _dispatchAllEvents(simulatedEvent);
-}
-
-function _initialize() {
- event.on("touchCancel", _touchCancel);
- event.on("touchEvent", _touchMove);
-}
-
-Touch = function (target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
- var _identifier = Number(identifier) || 0,
- _screenX = Number(screenX) || 0,
- _screenY = Number(screenY) || 0,
- _clientX = Number(clientX) || 0,
- _clientY = Number(clientY) || 0,
- _pageX = Number(pageX) || 0,
- _pageY = Number(pageY) || 0;
-
- this.__defineGetter__("identifier", function () {
- return _identifier;
- });
- this.__defineGetter__("target", function () {
- return target;
- });
- this.__defineGetter__("screenX", function () {
- return _screenX;
- });
- this.__defineGetter__("screenY", function () {
- return _screenY;
- });
- this.__defineGetter__("clientX", function () {
- return _clientX;
- });
- this.__defineGetter__("clientY", function () {
- return _clientY;
- });
- this.__defineGetter__("pageX", function () {
- return _pageX;
- });
- this.__defineGetter__("pageY", function () {
- return _pageY;
- });
-};
-
-TouchList = function (touches) {
- var _touches = _isValidTouch(touches) ? tizen1_utils.copy(touches) : [],
- i, _self;
+ this.__defineGetter__("id", function () {
+ return null;
+ });
+ this.__defineSetter__("id", function (id) {
+ try {
+ syncInfo.id = t.DOMString(id);
+ save();
+ } catch (e) {
+ }
+ });
- _self = {
- item : function (index) {
- if (typeof index !== "number") {
- return null;
+ this.__defineGetter__("password", function () {
+ return null;
+ });
+ this.__defineSetter__("password", function (password) {
+ try {
+ syncInfo.password = t.DOMString(password);
+ save();
+ } catch (e) {
}
- if (index.toString().indexOf(".") !== -1) {
- return null;
+ });
+
+ this.__defineGetter__("mode", function () {
+ return syncInfo.mode;
+ });
+ this.__defineSetter__("mode", function (mode) {
+ try {
+ syncInfo.mode = t.SyncMode(mode);
+ } catch (e) {
}
- if (/^\\d+$/.test(index) || index >= _touches.length) {
- return null;
+ });
+
+ this.__defineGetter__("type", function () {
+ return syncInfo.type;
+ });
+ this.__defineSetter__("type", function (type) {
+ if (mode !== "MANUAL") {
+ return;
}
- if (!_touches) {
- return null;
+ try {
+ syncInfo.type = t.SyncType(type);
+ } catch (e) {
}
- return _touches[index];
- },
+ });
- identifiedTouch : function (identifier) {
- if (typeof identifier !== "number") {
- return null;
- }
- if (!_touches) {
- return null;
+ this.__defineGetter__("interval", function () {
+ return syncInfo.interval;
+ });
+ this.__defineSetter__("interval", function (interval) {
+ if (mode !== "PERIODIC") {
+ return;
}
- for (var i in _touches) {
- if (_touches[i].identifier === identifier) {
- return _touches[i];
- }
+ try {
+ syncInfo.interval = t.SyncInterval(interval);
+ } catch (e) {
}
- return null;
- }
- };
-
- for (i = 0; i < _touches.length; i++) {
- _self.__defineGetter__(i, (function (index) {
- return function () {
- return _touches[index];
- };
- }(i)));
+ });
}
- _self.__defineGetter__("length", function () {
- return _touches.length;
- });
-
- return _self;
-};
-
-TouchEvent = function (type, canBubble, cancelable, touches, targetTouches, changedTouches, altKey, metaKey, ctrlKey, shiftKey) {
- var touchEvent = emulatorBridge.document().createEvent("UIEvents");
- touchEvent.initUIEvent(type, canBubble, cancelable, emulatorBridge.window(), 1);
-
- touchEvent.__defineGetter__("touches", function () {
- return touches;
- });
- touchEvent.__defineGetter__("targetTouches", function () {
- return targetTouches;
- });
- touchEvent.__defineGetter__("changedTouches", function () {
- return changedTouches;
- });
- touchEvent.__defineGetter__("altKey", function () {
- return altKey;
- });
- touchEvent.__defineGetter__("metaKey", function () {
- return metaKey;
- });
- touchEvent.__defineGetter__("ctrlKey", function () {
- return ctrlKey;
- });
- touchEvent.__defineGetter__("shiftKey", function () {
- return shiftKey;
- });
- return touchEvent;
-};
-
-_self = {
- mask: function (frame) {
- frame.addEventListener("DOMContentLoaded", function () {
- /*
- var widgetDocument = frame.contentDocument,
- getElementByIdOri = widgetDocument.getElementById;
-
- widgetDocument.getElementById = function () {
- var element, addEventListenerOri;
+ voc = [
+ function (url, id, password, mode, type) {
+ construct.apply(this, arguments);
- element = getElementByIdOri.apply(widgetDocument, Array.prototype.slice.call(arguments));
+ if (mode === "MANUAL") {
+ syncInfo.type = type;
+ }
+ },
+ function (url, id, password, mode, interval) {
+ construct.apply(this, arguments);
- if (element) {
- addEventListenerOri = element.addEventListener;
- element.addEventListener = function (event, callback, useCapture) {
- if (event === "touchstart") {
- _touchCanvasElements.push(element);
- }
- addEventListenerOri.apply(element, arguments);
- };
- }
- return element;
- };
+ if (mode === "PERIODIC") {
+ syncInfo.interval = interval;
+ }
+ },
+ function (url, id, password, mode) {
+ construct.apply(this, arguments);
+ }
+ ];
- widgetDocument.createTouch = function (view, target, identifier, pageX, pageY, screenX, screenY) {
- return new Touch(view, target, identifier, pageX, pageY, screenX, screenY);
- };
+ t.SyncInfo(arguments, this, voc);
- widgetDocument.createTouchList = function (pattern) {
- if (arguments.length !== 1) {
- return null;
- }
- return new TouchList(pattern);
- };
- */
- });
- }
+ index = _counter++;
+ Object.defineProperty(this, "__syncInfoID__", {
+ "configurable": false,
+ "enumerable": false,
+ "get": (function (_id_) {
+ return function () { return _id_; };
+ })(index)
+ });
+ save();
};
-_initialize();
-
-module.exports = _self;
+module.exports = SyncInfo;
});
-define('ripple/platform/tizen/2.0/typecast', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/alarm', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var typedef = require('ripple/platform/tizen/2.0/typedef'),
+var db = require('ripple/db'),
errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
- TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
- _self = {};
+ AlarmRelative = require('ripple/platform/tizen/2.0/AlarmRelative'),
+ AlarmAbsolute = require('ripple/platform/tizen/2.0/AlarmAbsolute'),
+ AlarmStore,
+ _DB_ALARMS_KEY = "tizen1.0-db-alarms",
+ PERIOD_MINUTE = 60,
+ PERIOD_HOUR = 60 * PERIOD_MINUTE,
+ PERIOD_DAY = 24 * PERIOD_HOUR,
+ PERIOD_WEEK = 7 * PERIOD_DAY,
+ _alarms = {}, _alarmStack = [],
+ _security = {
+ "http://tizen.org/privilege/alarm": ["add", "remove", "removeAll"]
+ },
+ _isInitialized = false, _self;
-function _cast(pattern, obj, isDuplicate) {
- var tc, tcFunc;
+function _initialize() {
+ _alarms = db.retrieveObject(_DB_ALARMS_KEY);
+ utils.forEach(_alarms, function (alarmStore) {
+ alarmStore.date = new Date(alarmStore.date);
+ _alarmStack.push(alarmStore);
+ });
+ _isInitialized = true;
+}
- if (pattern === null)
- return;
+function _get() {
+ if (!_isInitialized) {
+ _initialize();
+ }
+}
- tc = new TypeCoerce(pattern);
- tcFunc = isDuplicate ? tc.copy : tc.cast;
+function _save() {
+ db.saveObject(_DB_ALARMS_KEY, _alarmStack);
+}
- if ((obj = tcFunc(obj)) === null) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+function _updateDB(alarmStore) {
+ _alarmStack.push(alarmStore);
+ _save();
+}
+
+function _getCurrentAppId() {
+ return db.retrieve("current-url");
+}
+
+function _checkTriggerAlarm(alarm) {
+ var remainingTime, nextTriggerDate;
+
+ if (alarm.delay !== undefined) { // Alarm is relative
+ if (alarm.period !== null)
+ return false;
+
+ remainingTime = alarm.getRemainingSeconds();
+ if (remainingTime === null)
+ return true; // This alarm is triggered, remove it
+ } else if (alarm.period !== undefined) { // Alarm is absolute,no repeat
+ nextTriggerDate = alarm.getNextScheduledDate();
+ if (nextTriggerDate === null)
+ return true; // Already triggered
}
- return obj;
+ return false; // Alarm is repeat, not expired
}
-function _castType(pattern) {
- /*
- * Type cast for each known type. The function name is the exact name of the
- * corresponding type.
- *
- * obj
- * Variable to be casted
- *
- * aux
- * Auxiliary descriptor of obj. It can be any one or combination of below
- * strings, or ignored in most cases.
- *
- * "?" Nullable types
- * "[]" Array
- * "+" Deep copy
- *
- * Return
- * Casted or duplicated object.
- */
+function _convertToAlarm(alarmStore) {
+ var alarm, frequency;
- return function (obj, aux) {
- var type, isNullable, isDuplicate;
+ if (alarmStore.delay !== null) { // AlarmRelative
+ alarm = new AlarmRelative(alarmStore.delay, alarmStore.period);
+ alarm.date = alarmStore.date;
+ } else { // AlarmAbsolute
+ if (alarmStore.period !== null && alarmStore.period !== PERIOD_WEEK) {
+ frequency = alarmStore.period;
+ } else if (alarmStore.period === PERIOD_WEEK) {
+ frequency = alarmStore.daysOfTheWeek;
+ }
+ alarm = new AlarmAbsolute(alarmStore.date, frequency);
+ }
- aux = aux ? String(aux) : "";
- type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
- isNullable = (aux.indexOf("?") !== -1);
- isDuplicate = (aux.indexOf("+") !== -1);
+ alarm.__defineGetter__("id", function () {
+ return alarmStore.id;
+ });
- if ((obj === null) || (obj === undefined)) {
- if (!isNullable) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ return alarm;
+}
+
+function _eventCheckAlarm(id) {
+ var alarm, diff;
+
+ _get();
+ utils.forEach(_alarmStack, function (alarmStore) {
+ if (alarmStore.id !== id)
+ return;
+
+ alarm = _convertToAlarm(alarmStore);
+ if (alarm.delay !== undefined) {
+ diff = alarm.getRemainingSeconds();
+ if (0 < diff && diff < 2) {
+ event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
+ }
+ } else {
+ diff = (new Date()) - alarm.getNextScheduledDate();
+ if (-2000 < diff && diff < 2000) {
+ event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
}
- return obj;
}
-
- return _cast(type, obj, isDuplicate);
- };
+ });
}
-function _castConstructor(name) {
- var constructors, hook, vtc, isOverloaded, castConstructor;
- /*
- * Type cast for constructor. The function name is the exact name of the
- * object type.
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- */
+_self = function () {
+ var currentAppId, alarm;
- function castUnique(argv) {
- _cast(constructors, argv, false);
- }
+ alarm = {
+ add: function (alarm, applicationId, appControl) {
+ var id, alarmStore;
- /*
- * Type cast for overloaded constructors. The function name is the exact
- * name of the object type.
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- *
- * scope
- * 'this' of the original constructor.
- *
- * voc
- * Array of overloaded constructors callback
- */
+ if (!_security.add) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- function castOverload(argv, scope, voc) {
- var iOverload;
+ t.AlarmManager("add", arguments);
- if (!vtc) {
- vtc = [];
- constructors.forEach(function (c) {
- vtc.push((c === null) ? null : new TypeCoerce(c));
+ alarm.__defineGetter__("id", function () {
+ return id;
});
- }
- vtc.some(function (tc, index) {
- if (tc && (tc.cast(argv) === null))
- return false;
+ id = Math.uuid(null, 16);
+ currentAppId = _getCurrentAppId(); // Update The Current URL.
+ alarmStore = new AlarmStore(alarm, applicationId, currentAppId, appControl);
+ _updateDB(alarmStore);
+ },
- iOverload = index;
- return true;
- });
+ remove: function (id) {
+ var isFound = false, i;
- if (iOverload === undefined) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
- }
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- return (voc && voc[iOverload].apply(scope, argv));
- }
+ t.AlarmManager("remove", arguments);
- constructors = typedef.constructor[name];
+ for (i in _alarmStack) {
+ if (_alarmStack[i].id !== id)
+ continue;
- if (name in _self) {
- hook = _self[name];
- }
+ _alarmStack.splice(i, 1);
+ _save();
+ isFound = true;
+ }
- isOverloaded = (Object.prototype.toString.call(constructors) ===
- "[object Array]");
- castConstructor = isOverloaded ? castOverload : castUnique;
+ if (!isFound) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ },
- return function (argv, scope) {
- if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
- return (hook && hook.apply(this, arguments));
- }
+ removeAll: function () {
+ var availableStack = [], i;
- if (!(scope instanceof argv.callee)) {
- throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
- }
+ if (!_security.removeAll)
+ throw new WebAPIException(errorcode.SECURITY_ERR);
- castConstructor.apply(this, arguments);
- };
-}
+ t.AlarmManager("removeAll", arguments);
-function _castInterface(name) {
- var interface, hook;
+ for (i in _alarmStack) {
+ if (_alarmStack[i].currentAppId === currentAppId)
+ continue;
- interface = typedef.interface[name];
+ availableStack.push(_alarmStack[i]);
+ }
+ _alarmStack = availableStack;
+ _save();
+ },
- if (name in _self) {
- hook = _self[name];
- }
+ get: function (id) {
+ var isFound = false, item, isExpired, alarm;
- /*
- * Type cast for each known method of interface. The function name is the
- * exact name of the corresponding interface.
- *
- * method
- * String of method name
- *
- * argv
- * arguments. The keyword 'arguments' will always be passed in.
- *
- * isDuplicate
- * A boolean value to indicate whether arguments will be copied or not.
- */
+ t.AlarmManager("get", arguments);
- return function (method, argv, isDuplicate) {
- if ((typeof method !== "string") || (typeof argv !== "object")) {
- return (hook && hook.apply(this, arguments));
- }
+ for (item in _alarmStack) {
+ if (_alarmStack[item].id === id) {
+ alarm = _convertToAlarm(_alarmStack[item]);
+ isExpired = _checkTriggerAlarm(alarm);
+ if (isExpired) {
+ _alarmStack.splice(item, 1);
+ _save();
+ } else {
+ isFound = true;
+ }
+ break;
+ }
+ }
+ if (!isFound) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- _cast(interface[method], argv, isDuplicate);
+ return alarm;
+ },
+
+ getAll: function () {
+ var availableStack = [], backAlarms = [], isExpired, alarm, i;
+
+ t.AlarmManager("getAll", arguments);
+
+ for (i in _alarmStack) {
+ alarm = _convertToAlarm(_alarmStack[i]); // alarmStore --> alarm
+ isExpired = _checkTriggerAlarm(alarm); // Check if the alarm is expired
+ if (isExpired)
+ continue;
+
+ availableStack.push(_alarmStack[i]);
+ if (_alarmStack[i].currentAppId === currentAppId)
+ backAlarms.push(alarm);
+ }
+ _alarmStack = availableStack;
+ _save();
+ return backAlarms;
+ },
+
+ handleSubFeatures: function (subFeatures) {
+ var i, subFeature;
+
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
};
-}
-(function () {
- var i;
+ currentAppId = _getCurrentAppId();
+ _get();
- for (i in typedef) {
- _self[i] = _castType(typedef[i]);
- }
+ alarm.__defineGetter__("PERIOD_MINUTE", function () {
+ return PERIOD_MINUTE;
+ });
- for (i in typedef.constructor) {
- _self[i] = _castConstructor(i);
- typedef[i]._constructor = i;
- }
+ alarm.__defineGetter__("PERIOD_HOUR", function () {
+ return PERIOD_HOUR;
+ });
- for (i in typedef.interface) {
- _self[i] = _castInterface(i);
- }
-}());
+ alarm.__defineGetter__("PERIOD_DAY", function () {
+ return PERIOD_DAY;
+ });
+
+ alarm.__defineGetter__("PERIOD_WEEK", function () {
+ return PERIOD_WEEK;
+ });
+
+ return alarm;
+};
+
+AlarmStore = function (alarmObject, applicationId, currentAppId, appControl) {
+ var _self;
+ _self = {
+ id: alarmObject.id,
+ delay: alarmObject.delay || null,
+ date: alarmObject.date || null,
+ period: alarmObject.period || null,
+ daysOfTheWeek: alarmObject.daysOfTheWeek || null,
+ applicationId: applicationId,
+ currentAppId: currentAppId,
+ appControl: appControl || null
+ };
+ return _self;
+};
+
+event.on("CheckAlarm", function (id) {
+ _eventCheckAlarm(id);
+});
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/typecoerce', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/CalendarEvent', function (require, exports, module) {
/*
* Copyright 2013 Intel Corporation.
*
* limitations under the License.
*/
-var t = require('ripple/platform/tizen/2.0/typedef'),
- _self;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ typedef = require('ripple/platform/tizen/2.0/typedef'),
+ CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
+ CalendarEvent;
-_self = function (pattern) {
- var typeCoerce, typeOfPattern;
+CalendarEvent = function () {
+ var voc, calendarEvent = {};
// private
- function getExtendedType(val) {
- var type, attr;
-
- if (typeof val === "object") {
- if ("_dictionary" in val) {
- return "dictionary";
- }
-
- type = "Object";
+ function construct(eventInitDict) {
+ CalendarItem.call(this, eventInitDict);
- for (attr in val) {
- if (attr === "0") {
- type = "Arguments";
- } else if (val[attr] === "Callback") {
- type = "Callback";
- }
- break;
- }
+ this.status = "CONFIRMED";
- return type;
- }
+ calendarEvent.convertToString = this.convertToString;
+ calendarEvent.isDetached = false;
+ calendarEvent.endDate = null;
+ calendarEvent.availability = "BUSY";
+ calendarEvent.recurrenceRule = null;
- switch (val) {
- case "Callback":
- type = "Function";
- break;
+ this.__defineGetter__("isDetached", function () {
+ return calendarEvent.isDetached;
+ });
- case "TZDate":
- case "any": // Any type
- case "byte":
- case "octet":
- case "unsigned long":
- case "unsigned short":
- type = val;
- break;
+ this.__defineGetter__("endDate", function () {
+ return calendarEvent.endDate;
+ });
+ this.__defineSetter__("endDate", function (val) {
+ try {
+ calendarEvent.endDate = t.TZDate(val, "?");
+ } catch (e) {
+ }
+ });
- case "double":
- case "float":
- type = "float";
- break;
+ this.__defineGetter__("availability", function () {
+ return calendarEvent.availability;
+ });
+ this.__defineSetter__("availability", function (val) {
+ try {
+ calendarEvent.availability = t.EventAvailability(val);
+ } catch (e) {
+ }
+ });
- default: // Derivative type name: e.g., "AbstractFilter"
- type = "";
- break;
- }
+ this.__defineGetter__("recurrenceRule", function () {
+ return calendarEvent.recurrenceRule;
+ });
+ this.__defineSetter__("recurrenceRule", function (val) {
+ try {
+ calendarEvent.recurrenceRule = t.CalendarRecurrenceRule(val,
+ "?");
+ } catch (e) {
+ }
+ });
- return type;
+ this.convertToString = convertToString;
+ this.clone = clone(this);
+ this.expandRecurrence = expandRecurrence;
}
- function getType(val, isPattern) {
- var type = Object.prototype.toString.call(val);
-
- switch (type) {
- case "[object Array]":
- type = (isPattern && (val.length > 1) &&
- (typeof val[0] === "string")) ? "enum" : "Array";
- break;
-
- case "[object Arguments]":
- type = "Arguments";
- break;
-
- case "[object Boolean]":
- type = "boolean";
- break;
-
- case "[object Date]":
- type = "Date";
- break;
+ function clone(self) {
+ return function () {
+ return new CalendarEvent(self);
+ };
+ }
- case "[object Function]":
- type = "Function";
- break;
+ // public
+ function convertToString(format) {
+ var str;
- case "[object Number]":
- type = "Number";
- break;
+ str = calendarEvent.convertToString.call(this, format);
+ str = str.replace(/#TYPE#/g, "VEVENT");
- case "[object Object]":
- type = isPattern ? getExtendedType(val) : "Object";
- break;
+ // TODO: endDate is not supported
+ // TODO: recurrenceRule is not supported
+ str = str.replace(/#AVAILABILITY#/g, "FREEBUSY;FBTYPE=" +
+ calendarEvent.availability);
- case "[object String]":
- type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
- break;
- }
+ str = str.replace(/#[^#]*#/g, "");
- return type;
+ return str;
}
- function instanceOfPattern(pattern, obj) {
- var ret, i, derived;
-
- if ("_constructor" in pattern) {
- if (obj instanceof window.tizen[pattern._constructor]) {
- return -1;
- }
- ret = NaN;
- } else {
- ret = -1;
- }
+ function expandRecurrence(startDate, endDate, successCallback,
+ errorCallback) {
+ }
- if (!("_derived" in pattern)) {
- return ret;
- }
+ // Constructor
+ function CalendarEvent_CalendarEventInit(eventInitDict) {
+ var attr;
- for (i in pattern._derived) {
- derived = pattern._derived[i];
+ construct.call(this, eventInitDict);
- if (typeof derived !== "object") {
- return (typeof derived === typeof obj) ? i : NaN;
- }
- if (!isNaN(instanceOfPattern(derived, obj))) {
- return i;
+ if (eventInitDict) {
+ for (attr in eventInitDict) {
+ if (attr in typedef.CalendarEventInit) {
+ calendarEvent[attr] = eventInitDict[attr];
+ }
}
}
-
- return NaN;
}
- function toInteger(x) {
- return (x < 0) ? Math.ceil(x) : Math.floor(x);
+ function CalendarEvent_DOMString_CalendarTextFormat(stringRepresentation,
+ format) {
}
- function modulo(a, b) {
- return a - Math.floor(a / b) * b;
- }
+ voc = [CalendarEvent_CalendarEventInit,
+ CalendarEvent_DOMString_CalendarTextFormat];
+ t.CalendarEvent(arguments, this, voc);
+};
- function toUInt(x, bits) {
- x = Number(x);
+module.exports = CalendarEvent;
- if (isNaN(x) || !isFinite(x))
- return null;
+});
+define('ripple/platform/tizen/2.0/ContactBase', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- return modulo(toInteger(x), Math.pow(2, bits));
- }
+var decorator = require('ripple/platform/tizen/2.0/decorator'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactName = require('ripple/platform/tizen/2.0/ContactName'),
+ ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
+ ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
+ ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
+ ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
+ ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
+ ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
+ Contact;
- function toUInt16(x) {
- return toUInt(x, 16);
- }
+Contact = function () {
+ var voc;
- function toUInt32(x) {
- return toUInt(x, 32);
+ // private
+ function construct() {
+ this.name = null;
+ this.addresses = [];
+ this.photoURI = null;
+ this.phoneNumbers = [];
+ this.emails = [];
+ this.birthday = null;
+ this.anniversaries = [];
+ this.organizations = [];
+ this.notes = [];
+ this.urls = [];
+ this.ringtoneURI = null;
+ this.groupIds = [];
}
- // public
- function cast(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
-
- typeMap = {
- "Arguments": function () {
- var i, isNullable, ret;
-
- for (i in pattern) {
- if (i === "_optional")
- continue;
+ // Constructor
+ function Contact_ContactInit(contactInitDict) {
+ var i, attr, arr;
- isNullable = !!(pattern._optional && pattern._optional[i]);
+ construct.apply(this);
- if (i > obj.length - 1) {
- if (!isNullable) {
- return null;
- }
- obj[i] = null;
- continue;
- }
+ for (attr in contactInitDict) {
+ switch (attr) {
+ case "name":
+ this[attr] = new ContactName(contactInitDict[attr]);
+ break;
- if ((obj[i] === null) || (obj[i] === undefined)) {
- if (!isNullable || ((i in obj) && (obj[i] !== null))) {
- return null;
- }
- } else {
- ret = _self(pattern[i]).cast(obj[i]);
- if (ret === null) {
- return null;
- }
- obj[i] = ret;
+ case "addresses":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactAddress(arr[i]);
}
}
+ break;
- return obj;
- },
-
- "Array": function () {
- var elementType, i, ret;
-
- if (typeOfObj !== typeOfPattern) {
- return null;
+ case "phoneNumbers":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactPhoneNumber(arr[i].number,
+ arr[i].types || null, arr[i].isDefault || null);
+ }
}
+ break;
- elementType = _self(pattern[0]);
- for (i in obj) {
- ret = elementType.cast(obj[i]);
- if (ret === null) {
- return null;
+ case "emails":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactEmailAddress(arr[i].email,
+ arr[i].types || null, arr[i].isDefault || null);
}
- obj[i] = ret;
}
+ break;
- return obj;
- },
-
- "Callback": function () {
- var attr;
+ case "birthday":
+ this[attr] = new Date(contactInitDict[attr]);
+ break;
- if (typeOfObj !== "Object") {
- return null;
+ case "anniversaries":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactAnniversary(arr[i].date,
+ arr[i].label || null);
+ }
}
+ break;
- for (attr in pattern) {
- if (attr in obj) {
- obj[attr] = _self(pattern[attr]).cast(obj[attr]);
- if (obj[attr] === null) {
- return null;
- }
+ case "organizations":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactOrganization(arr[i]);
}
}
+ break;
- return obj;
- },
-
- "DOMString": function () {
- switch (typeOfObj) {
- case "Date":
- case "DOMString":
- case "Number":
- obj = String(obj).trim();
- break;
-
- default:
- obj = null;
- break;
+ case "notes":
+ case "groupIds":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = arr[i];
+ }
}
+ break;
- return obj;
- },
-
- "Date": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
-
- "Function": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
-
- "Number": function () {
- var n = toInteger(obj);
-
- if (isNaN(n))
- return null;
-
- return (obj === n) ? n : parseFloat(obj);
- },
-
- "Object": function () {
- var attr, iInstance, ret;
-
- if (!("_derived" in pattern) &&
- (typeOfObj !== typeOfPattern)) {
- return null;
+ case "urls":
+ arr = contactInitDict[attr];
+ if (arr) {
+ for (i in arr) {
+ this[attr][i] = new ContactWebSite(arr[i].url,
+ arr[i].type || null);
+ }
}
+ break;
- iInstance = instanceOfPattern(pattern, obj);
- if (isNaN(iInstance)) {
- return null;
- }
+ default:
+ this[attr] = contactInitDict[attr];
+ break;
+ }
+ }
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ decorator.Contact(this);
+ }
- case "_derived":
- if (iInstance !== -1) {
- ret = _self(pattern._derived[iInstance]).cast(obj);
- if (ret === null) {
- return null;
- }
- }
- break;
+ function Contact_DOMString(stringRepresentation) {
+ }
- default:
- if (!pattern._optional || !pattern._optional[attr] ||
- (obj[attr] !== undefined) &&
- (obj[attr] !== null)) {
- ret = _self(pattern[attr]).cast(obj[attr]);
- if (ret === null) {
- return null;
- }
- obj[attr] = ret;
- }
- break;
- }
- }
+ voc = [Contact_ContactInit, Contact_DOMString];
+ t.Contact(arguments, this, voc);
+};
- return obj;
- },
+module.exports = Contact;
- "TZDate": function () {
- if (typeOfObj !== "Object") {
- return null;
- }
- return (obj instanceof window.tizen.TZDate) ? obj : null;
- },
+});
+define('ripple/platform/tizen/2.0/ContactAnniversary', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- "any": function () {
- return obj;
- },
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactAnniversary;
- "boolean": function () {
- return (typeOfObj === typeOfPattern) ? obj : null;
- },
+ContactAnniversary = function (date, label) {
+ var contactAnniversary = {};
- "dictionary": function () {
- var attr, ret;
+ t.ContactAnniversary(arguments, this);
- if (typeOfObj !== "Object") {
- return null;
- }
+ contactAnniversary.date = date;
+ contactAnniversary.label = label || null;
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- ret = _self(pattern._dictionary).cast(obj);
- if (ret === null) {
- return null;
- }
- }
- break;
+ this.__defineGetter__("date", function () {
+ return contactAnniversary.date;
+ });
+ this.__defineSetter__("date", function (val) {
+ try {
+ contactAnniversary.date = t.Date(val);
+ } catch (e) {
+ }
+ });
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- ret = _self(pattern[attr]).cast(obj[attr]);
- if (ret === null) {
- return null;
- }
- obj[attr] = ret;
- }
- break;
- }
- }
+ this.__defineGetter__("label", function () {
+ return contactAnniversary.label;
+ });
+ this.__defineSetter__("label", function (val) {
+ try {
+ contactAnniversary.label = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+};
- return obj;
- },
+module.exports = ContactAnniversary;
- "enum": function () {
- var i;
+});
+define('ripple/platform/tizen/2.0/SortMode', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- obj = String(obj).trim();
- for (i in pattern) {
- if (obj === pattern[i]) {
- return obj;
- }
- }
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ SortMode;
- return null;
- },
+SortMode = function (attributeName, order) {
+ var sortMode = {};
- "float": function () {
- var f = parseFloat(obj, 10);
+ t.SortMode(arguments, this);
- return (isNaN(f) ? null : f);
- },
+ this.__defineGetter__("attributeName", function () {
+ return sortMode.attributeName;
+ });
+ this.__defineSetter__("attributeName", function (val) {
+ try {
+ sortMode.attributeName = t.DOMString(val);
+ } catch (e) {
+ }
+ });
- "unsigned long": function () {
- var n;
+ this.__defineGetter__("order", function () {
+ return sortMode.order;
+ });
+ this.__defineSetter__("order", function (val) {
+ try {
+ sortMode.order = t.SortModeOrder(val);
+ } catch (e) {
+ }
+ });
- n = toUInt32(obj);
+ sortMode.attributeName = attributeName;
+ sortMode.order = order || "ASC";
+};
- return (n === null) ? null : n;
- },
+module.exports = SortMode;
- "unsigned short": function () {
- var n;
+});
+define('ripple/platform/tizen/2.0/AlarmRelative', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- n = toUInt16(obj);
+var AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ AlarmRelative;
- return (n === null) ? null : n;
- },
+AlarmRelative = function (delay, period) {
+ var alarm, date;
- "octet": function () {
- var n;
+ t.AlarmRelative(arguments, this);
- try {
- n = Number(obj);
+ alarm = new AlarmBase(this);
+ period = period || null;
+ date = new Date(); // Alarm settime
- return ((!isNaN(n) && (n == obj) &&
- (0 <= n) && (n <= 0xff)) ? n : null);
- } catch (e) {
- return null;
- }
- },
+ this.getRemainingSeconds = function () {
+ var current, diff, triggerDate, MILLI_SECOND = 1000;
+ current = new Date();
+ triggerDate = new Date(delay * MILLI_SECOND + date.getTime()); // First triggerDate
+ diff = Math.round((triggerDate - current) / MILLI_SECOND);
- "byte": function () {
- var n, ch;
+ if (diff > 0) // Before first trigger
+ return diff;
- switch (typeOfObj) {
- case "Number":
- try {
- n = Number(obj);
+ if (period === null)
+ return null; // Alarm is expired
- return ((!isNaN(n) && (n == obj) &&
- (0 <= n) && (n <= 0xff)) ? n : null);
- } catch (e) {
- return null;
- }
- break;
+ while (current - triggerDate >= 0) { // Trigger repeatly
+ triggerDate = new Date(period * MILLI_SECOND + triggerDate.getTime());
+ }
+ diff = Math.round(((triggerDate - current) / MILLI_SECOND));
+ return diff;
+ };
- case "DOMString":
- if (obj.length > 1)
- return null;
+ this.__defineGetter__("delay", function () {
+ return delay;
+ });
- try {
- ch = obj.charCodeAt();
+ this.__defineGetter__("period", function () {
+ return period;
+ });
+};
- return ((!isNaN(ch) && (0 <= ch) &&
- (ch <= 0xff)) ? String(obj) : null);
- } catch (e) {
- return null;
- }
- break;
+module.exports = AlarmRelative;
+
+});
+define('ripple/platform/tizen/2.0/DeviceMotionEvent', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- default:
- break;
- }
+var utils = require('ripple/utils'),
+ Event = require('ripple/platform/tizen/2.0/EventBase');
- return null;
+module.exports = function () {
+ var _self = {
+ acceleration: {
+ x: null,
+ y: null,
+ z: null
},
-
- "": function () {
- return _self(t[pattern]).cast(obj);
- }
+ accelerationIncludingGravity: {
+ x: null,
+ y: null,
+ z: null
+ },
+ rotationRate: {
+ alpha: null,
+ beta: null,
+ gamma: null
+ },
+ interval: 0
};
- return typeMap[typeOfPattern]();
- }
-
- function copy(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
+ Event.call(this);
- typeMap = {
- "Arguments": function () {
- var i, isNullable, ret = [];
+ this.__defineGetter__("acceleration", function () {
+ return _self.acceleration;
+ });
- for (i in pattern) {
- if (i === "_optional")
- continue;
+ this.__defineGetter__("accelerationIncludingGravity", function () {
+ return _self.accelerationIncludingGravity;
+ });
- isNullable = !!(pattern._optional && pattern._optional[i]);
+ this.__defineGetter__("rotationRate", function () {
+ return _self.rotationRate;
+ });
- if (i > obj.length - 1) {
- if (!isNullable) {
- return null;
- }
- ret[i] = null;
- continue;
- }
+ this.__defineGetter__("interval", function () {
+ return _self.interval;
+ });
- if ((obj[i] === null) || (obj[i] === undefined)) {
- if (!isNullable || ((i in obj) && (obj[i] !== null))) {
- return null;
- }
- } else if ((ret[i] = _self(pattern[i])
- .copy(obj[i])) === null) {
- return null;
- }
- }
+ this.initAccelerometerEvent = function (accelerometerType, accelerometerBubbles, accelerometerCancelable,
+ accelerationData, accelerationGData, rotationRateData, intervalValue) {
+ this.initEvent(accelerometerType, accelerometerBubbles, accelerometerCancelable);
- for (i in ret) {
- obj[i] = ret[i];
- }
+ _self.acceleration = utils.copy(accelerationData);
+ _self.accelerationIncludingGravity = utils.copy(accelerationGData);
+ _self.rotationRate = utils.copy(rotationRateData);
+ _self.interval = intervalValue;
+ };
+};
- return obj;
- },
- "Array": function () {
- var arr = [], elementType, i;
+});
+define('ripple/platform/tizen/2.0/sensors', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- if (typeOfObj !== typeOfPattern) {
- return null;
- }
+var utils = require('ripple/utils'),
+ sensors = require('ripple/platform/tizen/2.0/spec/sensor'),
+ _sensors = ["Accelerometer", "MagneticField", "Rotation", "Orientation"],
+ _permission = true,
+ _isWriteable = false,
+ _self;
- elementType = _self(pattern[0]);
- for (i in obj) {
- if (obj[i]) {
- arr[i] = elementType.copy(obj[i]);
- if (arr[i] === null)
- return null;
- }
- }
+function SensorError(code, msg) {
+ this.__defineGetter__("message", function () {
+ return msg;
+ });
+ this.__defineGetter__("code", function () {
+ return code;
+ });
- return arr;
- },
+ this.PERMISSION_DENIED = -100;
+}
- "Callback": function () {
- var ret = {}, attr;
+function SensorRequest() {
+ var _self = {
+ result: [],
+ error: null,
+ readyState: "processing"
+ };
- if (typeOfObj !== "Object") {
- return null;
- }
+ this.__defineGetter__("result", function () {
+ return _self.result;
+ });
+ this.__defineSetter__("result", function (resultData) {
+ if (_isWriteable) {
+ _self.result = utils.copy(resultData);
+ _isWriteable = false;
+ return;
+ }
+ });
- for (attr in pattern) {
- if (attr in obj) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- }
+ this.__defineGetter__("error", function () {
+ return _self.error;
+ });
+ this.__defineSetter__("error", function (errorData) {
+ if (_isWriteable) {
+ _self.error = utils.copy(errorData);
+ _isWriteable = false;
+ return;
+ }
+ });
- return ret;
- },
+ this.__defineGetter__("readyState", function () {
+ return _self.readyState;
+ });
+ this.__defineSetter__("readyState", function (readyStateData) {
+ if (_isWriteable) {
+ _self.readyState = readyStateData;
+ _isWriteable = false;
+ return;
+ }
+ });
+}
- "Object": function () {
- var ret = {}, iInstance, attr, derived, i;
+_self = {
+ findSensors: function (type) {
+ var sensorRequest = new SensorRequest(), index, sensorName = "";
- if (typeOfObj !== typeOfPattern) {
- return null;
+ setTimeout(function () {
+ if (_permission) {
+ for (index = 0; index < _sensors.length; index++) {
+ sensorName = _sensors[index];
+ if (type === null || type === undefined || type === sensorName) {
+ _isWriteable = true;
+ sensorRequest.result.push(sensors[sensorName]);
+ }
}
- iInstance = instanceOfPattern(pattern, obj);
- if (isNaN(iInstance)) {
- return null;
- }
+ _isWriteable = true;
+ sensorRequest.readyState = "done";
- if ("_constructor" in pattern) {
- ret.__proto__ = window.tizen[pattern._constructor].prototype;
+ if (sensorRequest.onsuccess) {
+ sensorRequest.onsuccess();
+ }
+ }
+ else {
+ // error event on the request with error code PERMISSION_DENIED must be fired.
+ sensorRequest.error = new SensorError(-100, "permission denied!");
+ if (sensorRequest.onerror) {
+ sensorRequest.onerror();
}
+ }
+ }, 1);
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ return sensorRequest;
+ }
+};
- case "_derived":
- if (iInstance !== -1) {
- derived = _self(pattern._derived[iInstance])
- .copy(obj);
+module.exports = _self;
- for (i in derived) {
- ret[i] = derived[i];
- }
- }
- break;
- default:
- if (!pattern._optional || !pattern._optional[attr] ||
- (obj[attr] !== undefined) &&
- (obj[attr] !== null)) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- break;
- }
- }
+});
+define('ripple/platform/tizen/2.0/callHistory', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- return ret;
- },
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ _DB_CALL_KEY = "tizen1-db-callhistory",
+ _data = {
+ observers: {},
+ callHistory: []
+ },
+ _security = {
+ "http://tizen.org/privilege/callhistory.read": ["find", "addChangeListener", "removeChangeListener"],
+ "http://tizen.org/privilege/callhistory.write": ["remove", "removeBatch", "removeAll"]
+ },
+ _self;
- "dictionary": function () {
- var ret = {}, attr, base, i;
+function _getValue(inputValue, key) {
+ var keys = key.split("."),
+ value = inputValue[keys[0]],
+ index;
- if (typeOfObj !== "Object") {
- return null;
- }
+ for (index = 1; index < keys.length; index++) {
+ if (value[keys[index]]) {
+ value = value[keys[index]];
+ }
+ }
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- base = _self(pattern._dictionary).copy(obj);
- if (base === null) {
- return null;
- }
- for (i in base) {
- ret[i] = base[i];
- }
- }
- break;
+ return value;
+}
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- ret[attr] = _self(pattern[attr]).copy(obj[attr]);
- if (ret[attr] === null) {
- return null;
- }
- }
- break;
- }
- }
+function _filter(inputArray, filter) {
+ var index, filterResults = [], compositeResultArray;
- return ret;
- },
+ if (filter === null || filter === undefined) {
+ return inputArray;
+ }
- "": function () {
- return _self(t[pattern]).copy(obj);
- }
- };
+ if (filter.type && filter.filters) {
+ filterResults = _filter(inputArray, filter.filters[0]);
+ for (index = 1; index < filter.filters.length; index++) {
+ compositeResultArray = _filter(inputArray, filter.filters[index]);
- return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
- cast(obj);
+ filterResults = tizen1_utils.arrayComposite(filter.type, filterResults, compositeResultArray);
+ }
+ return filterResults;
}
- function match(obj) {
- var typeMap,
- typeOfObj = getType(obj, false);
+ if (filter.attributeName === null || filter.attributeName === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- typeMap = {
- "Array": function () {
- var elementType, i;
+ if (filter.matchFlag) {
+ if (filter.attributeName === 'features') {
+ filterResults = tizen1_utils.matchAttributeArrayFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
+ } else {
+ filterResults = tizen1_utils.matchAttributeFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
+ }
+ }
+ else if (filter.initialValue || filter.endValue) {
+ filterResults = tizen1_utils.matchAttributeRangeFilter(inputArray, filter.attributeName, filter.initialValue, filter.endValue);
+ }
- if (typeOfObj !== typeOfPattern)
- return false;
+ return filterResults;
+}
- elementType = _self(pattern[0]);
- for (i in obj) {
- if (!elementType.match(obj[i])) {
- return false;
- }
- }
+function _sort(inputArray, sortMode) {
+ if (sortMode.attributeName === null || sortMode.attributeName === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- return true;
- },
+ inputArray.sort(function (a, b) {
+ return sortMode.order === "ASC" ? _getValue(a, sortMode.attributeName) - _getValue(b, sortMode.attributeName) :
+ _getValue(b, sortMode.attributeName) - _getValue(a, sortMode.attributeName);
+ });
- "Callback": function () {
- var attr, isMatched = true;
+ return inputArray;
+}
- if (typeOfObj !== "Object") {
- return false;
- }
+function _save() {
+ db.saveObject(_DB_CALL_KEY, _data.callHistory);
+}
- for (attr in pattern) {
- if (attr in obj) {
- isMatched = _self(pattern[attr]).match(obj[attr]);
- if (!isMatched) {
- break;
- }
- }
- }
+function _retrieve() {
+ var index;
- return isMatched;
- },
+ _data.callHistory = db.retrieveObject(_DB_CALL_KEY) || [];
- "DOMString": function () {
- return (typeOfObj === typeOfPattern);
- },
+ for (index = 0; index < _data.callHistory.length; index++) {
+ _data.callHistory[index].startTime = new Date(_data.callHistory[index].startTime);
+ }
+}
- "Date": function () {
- return (typeOfObj === typeOfPattern);
- },
+function _isValidCallHistoryEntry(arg) {
+ return arg && arg.hasOwnProperty("uid") && arg.hasOwnProperty("type") &&
+ arg.hasOwnProperty("features") && arg.hasOwnProperty("remoteParties") &&
+ arg.hasOwnProperty("startTime") && arg.hasOwnProperty("duration") &&
+ arg.hasOwnProperty("direction");
+}
- "Function": function () {
- return (typeOfObj === typeOfPattern);
- },
+function _rtnRmtPty(pty) {
+ var _remoteParty = pty.remoteParty,
+ _personId = pty.personId,
+ _self = {};
+ _self.__defineGetter__("remoteParty", function () {
+ return _remoteParty;
+ });
+ _self.__defineGetter__("personId", function () {
+ return _personId;
+ });
+ return _self;
+}
- "Number": function () {
- return (typeOfObj === typeOfPattern);
- },
+function _rtnEntry(entry) {
+ var _uid = entry.uid,
+ _type = entry.type,
+ _features = tizen1_utils.copy(entry.features),
+ _remoteParties = [],
+ _startTime = new Date(entry.startTime),
+ _duration = entry.duration,
+ _direction = entry.direction,
+ _self = {}, i;
- "Object": function () {
- var iInstance, attr, isMatched = false;
+ for (i = 0; i < entry.remoteParties.length; i++) {
+ _remoteParties.push(_rtnRmtPty(entry.remoteParties[i]));
+ }
+ _self.__defineGetter__("uid", function () {
+ return _uid;
+ });
+ _self.__defineGetter__("type", function () {
+ return _type;
+ });
+ _self.__defineGetter__("features", function () {
+ return _features;
+ });
+ _self.__defineGetter__("remoteParties", function () {
+ return _remoteParties;
+ });
+ _self.__defineGetter__("startTime", function () {
+ return _startTime;
+ });
+ _self.__defineGetter__("duration", function () {
+ return _duration;
+ });
+ _self.direction = _direction;
- if (typeOfObj !== typeOfPattern)
- return false;
+ return _self;
+}
- iInstance = instanceOfPattern(pattern, obj);
- if (isNaN(iInstance)) {
- return false;
- }
+function _initialize() {
+ _retrieve();
- for (attr in pattern) {
- switch (attr) {
- case "_optional":
- case "_constructor":
- break;
+ event.on("CallInProgress", function () {
+ });
- case "_derived":
- if (iInstance !== -1) {
- isMatched = _self(pattern._derived[iInstance])
- .match(obj);
- }
- break;
+ event.on("CallRecorded", function (record) {
+ var historyEntry = tizen1_utils.copy(record);
+ historyEntry.uid = Math.uuid(8, 16);
- default:
- if (pattern._optional && pattern._optional[attr]) {
- isMatched = ((obj[attr] === null) ||
- (obj[attr] === undefined) ||
- _self(pattern[attr]).match(obj[attr]));
- } else {
- isMatched = (obj[attr] !== undefined) &&
- _self(pattern[attr]).match(obj[attr]);
- }
- break;
- }
+ _data.callHistory.push(historyEntry);
+ _save();
- if (!isMatched)
- break;
- }
+ utils.forEach(_data.observers, function (observer) {
+ observer.onadded([historyEntry]);
+ });
+ });
+}
- /*// Check if verbose attributes are present
- if (isMatched) {
- for (attr in obj) {
- if (pattern[attr] === undefined) {
- isMatched = false;
- break;
- }
- }
- }*/
+_self = function () {
+ this.find = function (successCallback, errorCallback, filter, sortMode, limit, offset) {
+ var i, rtn = [],
+ filterResults,
+ limitValue = limit | 0,
+ offsetValue = offset | 0;
- return isMatched;
- },
+ if (!_security.find) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- "any": function () {
- return true;
- },
+ t.CallHistory("find", arguments);
- "boolean": function () {
- return (typeOfObj === typeOfPattern);
- },
+ filterResults = tizen1_utils.copy(_data.callHistory);
+ if (filter !== null && filter !== undefined) {
+ filterResults = _filter(filterResults, filter);
+ }
- "dictionary": function () {
- var attr, isMatched = true;
+ if (sortMode !== null && sortMode !== undefined) {
+ _sort(filterResults, sortMode);
+ }
- if (typeOfObj !== "Object") {
- return false;
- }
+ setTimeout(function () {
+ if (limitValue > 0) {
+ offsetValue = offsetValue > 0 ? offsetValue : 0;
+ filterResults = filterResults.slice(offsetValue, limitValue);
+ }
- for (attr in pattern) {
- switch (attr) {
- case "_dictionary":
- if (pattern._dictionary !== null) {
- isMatched = _self(pattern._dictionary).match(obj);
- if (!isMatched)
- break;
- }
- break;
+ for (i = 0; i < filterResults.length; i++) {
+ rtn.push(_rtnEntry(filterResults[i]));
+ }
+ successCallback(rtn);
+ }, 1);
+ };
+ this.remove = function (entry) {
+ var isFound = false, rtn = [];
- default:
- if ((attr in obj) && (obj[attr] !== null) &&
- (obj[attr] !== undefined)) {
- isMatched = _self(pattern[attr]).match(obj[attr]);
- if (!isMatched)
- break;
- }
- break;
- }
- }
+ if (!_security.remove) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- return isMatched;
- },
+ t.CallHistory("remove", arguments);
- "enum": function () {
- for (var i in pattern) {
- if (obj === pattern[i]) {
- return true;
- }
+ _data.callHistory = _data.callHistory.filter(function (element) {
+ return utils.some(element, function (value, key) {
+ if (tizen1_utils.isEqual(entry[key], value)) {
+ isFound = true;
+ return false;
}
+ return true;
+ });
+ });
- return false;
- },
-
- "float": function () {
- return (typeOfObj === "Number");
- },
+ if (!isFound) {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
- "unsigned long": function () {
- var n;
+ _save();
+ rtn.push(_rtnEntry(entry));
+ utils.forEach(_data.observers, function (observer) {
+ observer.onchanged(rtn);
+ });
- n = toUInt32(obj);
+ };
+ this.removeBatch = function (entries, successCallback, errorCallback) {
+ var isFound = false, i, rtn = [];
- return (n !== null);
- },
+ if (!_security.removeBatch) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- "unsigned short": function () {
- var n;
+ t.CallHistory("removeBatch", arguments);
- n = toUInt16(obj);
+ setTimeout(function () {
+ isFound = entries.every(function (element) {
+ return _data.callHistory.some(function (callHistory) {
+ return element.uid === callHistory.uid;
+ });
+ });
- return (n !== null);
- },
+ if (!isFound) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
- "octet": function () {
- var n;
+ _data.callHistory = _data.callHistory.filter(function (element) {
+ return !entries.some(function (entryValue, entryIndex) {
+ return tizen1_utils.isEqual(element, entryValue);
+ });
+ });
- try {
- n = Number(obj);
+ _save();
- return (!isNaN(n) && (n == obj) &&
- (0 <= n) && (n <= 0xff));
- } catch (e) {
- return false;
- }
- },
+ if (successCallback) {
+ successCallback();
+ }
+ for (i = 0; i < entries.length; i++) {
+ rtn.push(_rtnEntry(entries[i]));
+ }
+ utils.forEach(_data.observers, function (observer) {
+ observer.onchanged(rtn);
+ });
+ }, 1);
+ };
+ this.removeAll = function (successCallback, errorCallback) {
+ var i, rtn = [];
- "byte": function () {
- var n, ch;
+ if (!_security.removeAll) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- switch (typeOfObj) {
- case "Number":
- try {
- n = Number(obj);
+ t.CallHistory("removeAll", arguments);
- return (!isNaN(n) && (n == obj) &&
- (0 <= n) && (n <= 0xff));
- } catch (e) {
- return false;
- }
- break;
+ for (i = 0; i < _data.callHistory.length; i++) {
+ rtn.push(_rtnEntry(_data.callHistory[i]));
+ }
- case "DOMString":
- if (obj.length > 1)
- return false;
+ _data.callHistory = [];
+ _save();
- try {
- ch = obj.charCodeAt();
+ utils.forEach(_data.observers, function (observer) {
+ observer.onchanged(rtn);
+ });
- return (!isNaN(ch) && (0 <= ch) && (ch <= 0xff));
- } catch (e) {
- return false;
- }
- break;
+ if (successCallback) {
+ setTimeout(function () {
+ successCallback();
+ }, 1);
+ }
- default:
- break;
- }
+ };
+ this.addChangeListener = function (observerObj) {
+ var handle = Number(Math.uuid(8, 10));
- return false;
- },
+ if (!_security.addChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- "Arguments": function () {
- return true;
- },
+ t.CallHistory("addChangeListener", arguments);
- "": function () {
- return _self(t[pattern]).match(obj);
- }
- };
+ _data.observers[handle] = observerObj;
- return typeMap[typeOfPattern]();
- }
+ return handle;
+ };
+ this.removeChangeListener = function (handle) {
+ if (!_security.removeChangeListener) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- typeOfPattern = getType(pattern, true);
+ if (!_data.observers[handle])
+ return;
- typeCoerce = {
- cast: cast,
- copy: copy,
- match: match
+ delete _data.observers[handle];
};
+ this.handleSubFeatures = function (subFeatures) {
+ function setSecurity(method) {
+ _security[method] = true;
+ }
- return typeCoerce;
+ for (var subFeature in subFeatures) {
+ utils.forEach(_security[subFeature], setSecurity);
+ }
+ };
};
+_initialize();
+
module.exports = _self;
});
-define('ripple/platform/tizen/2.0/typedef', function (require, exports, module) {
+define('ripple/platform/tizen/2.0/filesystem', function (require, exports, module) {
/*
- * Copyright 2013 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var _t, _c, _i;
+var event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ utils = require('ripple/utils'),
+ dbfs = require('ripple/platform/tizen/2.0/dbfs'),
+ tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ _maxPathLength = 256,
+ _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
+ _security = {
+ "http://tizen.org/privilege/filesystem": [],
+ "http://tizen.org/privilege/filesystem.read": ["copyTo", "moveTo", "createDirectory", "createFile", "deleteDirectory", "deleteFile", "openStreamR"],
+ "http://tizen.org/privilege/filesystem.write": ["readAsText", "openStreamW"],
+ all: true
+ },
+ _realRoots = dbfs.roots,
+ _r2vmap = {},
+ _v2rmap = {},
+ _initialized = false,
+ _readOnly = false,
+ _writeOnly = false,
+ _defaultMode = "rw",
+ _storages = [], // filesystem storages
+ _observers = [],
+ File,
+ FileStream,
+ FileFilter,
+ FileSystemStorage;
-/*
- * Primitive type definition
- */
+function _isValidChar(c) {
+ return (c >= '0' && c <= '9') ||
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c === ' ') ||
+ (c === '_') ||
+ (c === '-') ||
+ (c === '.');
+}
-_t = {
- // Basic
- Callback: "Callback",
- DOMString: "",
- Date: new Date(),
- Function: function () {},
- TZDate: "TZDate",
- any: "any",
- boolean: false,
- byte: "byte",
- double: "double",
- float: "float",
- long: 0,
- octet: "octet",
- short: 0,
- long_long: 0,
- unsigned_long: "unsigned long",
- unsigned_long_long: 0,
- unsigned_short: "unsigned short",
+function _isValidFileName(name) {
+ var _valid = true,
+ _c;
- // Common
- FilterMatchFlag: ["EXACTLY", "FULLSTRING", "CONTAINS",
- "STARTSWITH", "ENDSWITH", "EXISTS"],
- SortModeOrder: ["ASC", "DESC"],
- CompositeFilterType: ["UNION", "INTERSECTION"],
+ if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
+ _valid = false;
+ } else {
+ for (_c = 0; _c < name.length; _c++) {
+ if (!_isValidChar(name[_c])) {
+ _valid = false;
+ break;
+ }
+ }
+ }
- // Bluetooth
- BluetoothSocketState: ["CLOSED", "OPEN"],
- BluetoothProfileType: ["HEALTH", "HEALTH"],
- BluetoothHealthChannelType: ["RELIABLE", "STREAMING"],
+ return _valid;
+}
- // Calendar
- CalendarType: ["EVENT", "TASK"],
- CalendarTextFormat: ["ICALENDAR_20", "VCALENDAR_10"],
- AlarmMethod: ["SOUND", "DISPLAY"],
- RecurrenceRuleFrequency: ["DAILY", "WEEKLY", "MONTHLY",
- "YEARLY"],
- ByDayValue: ["MO", "TU", "WE", "TH", "FR", "SA",
- "SU"],
- EventAvailability: ["BUSY", "FREE"],
- AttendeeType: ["INDIVIDUAL", "GROUP", "RESOURCE",
- "ROOM", "UNKNOWN"],
- AttendeeStatus: ["PENDING", "ACCEPTED", "DECLINED",
- "TENTATIVE", "DELEGATED", "COMPLETED",
- "IN_PROCESS"],
- AttendeeRole: ["REQ_PARTICIPANT", "OPT_PARTICIPANT",
- "NON_PARTICIPANT", "CHAIR"],
- CalendarItemPriority: ["HIGH", "MEDIUM", "LOW"],
- CalendarItemVisibility: ["PUBLIC", "PRIVATE", "CONFIDENTIAL"],
- CalendarItemStatus: ["TENTATIVE", "CONFIRMED", "CANCELLED",
- "NEEDS_ACTION", "IN_PROCESS",
- "COMPLETED"],
+function _initialize() {
+ var _i;
- // Contact
- ContactTextFormat: ["VCARD_30", "VCARD_30"], // Enum must has more than one value
+ _storages.push(FileSystemStorage("InternalFlash", "INTERNAL", "MOUNTED" ));
+ _storages.push(FileSystemStorage("MMC", "EXTERNAL", "REMOVED"));
+ dbfs.initialize();
+
+ // set up the map between real path and virtual path
+ for (_i = 0; _i < _virtualRoots.length; _i++) {
+ _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
+ }
+
+ utils.forEach(_r2vmap, function (value, key) {
+ _v2rmap[value] = key;
+ });
+}
+
+function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
+ var _parts = srcLocation.replace(/\/$/, '').split("/"),
+ _header, _fullPath,
+ _i;
+
+ // TODO: Initialize at bootstrap and emulatorBridge.link
+ if (!_initialized) {
+ _initialize();
+ _initialized = true;
+ }
+
+ for (_i = 0; _i < _parts.length; _i++) {
+ if (!_isValidFileName(_parts[_i])) {
+ if (onError) {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ }
+
+ _header = _v2rmap[_parts[0]];
+ if (_header === undefined) {
+ if (onError) {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
+
+ if (_parts.length === 1) {
+ _fullPath = _header;
+ } else {
+ _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
+ }
+
+ dbfs.stat(_fullPath,
+ function (entry) {
+ onSuccess(new File(entry, accessMode));
+ },
+ function () {
+ if (onError) {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }
+ });
+}
+
+function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
+ _resolveSync(srcLocation,
+ function (file) {
+ setTimeout(function () {
+ onSuccess(file);
+ }, 1);
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ accessMode);
+}
+
+File = function (entry, mode) {
+ var _entry = entry,
+ _mode = mode,
+ _parent,
+ _self;
+
+ function _r2v(rpath) {
+ var i, v, r, regExp;
+
+ for (i = 0; i < _virtualRoots.length; i++) {
+ v = _virtualRoots[i];
+ r = _v2rmap[v];
+ if (rpath.match("^" + r)) {
+ regExp = new RegExp("^" + r);
+ return rpath.replace(regExp, v);
+ }
+ }
+
+ return "";
+ }
+
+ function _v2r(vpath) {
+ var i, v, r, regExp;
+
+ for (i = 0; i < _virtualRoots.length; i++) {
+ v = _virtualRoots[i];
+ r = _v2rmap[v];
+ if (vpath.match("^" + v)) {
+ regExp = new RegExp("^" + v);
+ return vpath.replace(regExp, r);
+ }
+ }
+
+ return "";
+ }
+
+ function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
+ var _srcName = String(src),
+ _dstName = String(dst),
+ _src = null,
+ _dst = null,
+ _error = false,
+ _dstParent = null,
+ _dstParts = _dstName.split("/"),
+ _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");
+
+ if (!_entry.isDirectory) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ _resolveSync(_srcName,
+ function (file) {
+ _src = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
+
+ if (_src) {
+ if (_src.parent.fullPath === _self.fullPath) {
+ if (!_readOnly && _mode !== "r") {
+ _resolveSync(_dstParentName,
+ function (file) {
+ _dstParent = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
+
+ if (_dstParent === null) {
+ return undefined;
+ }
+
+ _resolveSync(_dstName,
+ function (file) {
+ _dst = file;
+ },
+ function (e) {
+ if (e.code !== errorcode.NOT_FOUND_ERR) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ _error = true;
+ }
+ },
+ _mode);
+
+ if (_error) {
+ return undefined;
+ }
- // Content
- ContentDirectoryStorageType: ["INTERNAL", "EXTERNAL"],
- ContentType: ["IMAGE", "VIDEO", "AUDIO", "OTHER"],
- AudioContentLyricsType: ["SYNCHRONIZED", "UNSYNCHRONIZED"],
- ImageContentOrientation: ["NORMAL", "FLIP_HORIZONTAL",
- "ROTATE_180", "FLIP_VERTICAL",
- "TRANSPOSE", "ROTATE_90", "TRANSVERSE",
- "ROTATE_270"],
+ if (_src.isFile) {
+ if (_dst === null) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (_dst === null) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ }
- // Data Control
- DataType: ["MAP", "SQL"],
+ return undefined;
+ }
- // Data Synchronization
- SyncMode: ["MANUAL", "PERIODIC", "PUSH"],
- SyncType: ["TWO_WAY", "SLOW",
- "ONE_WAY_FROM_CLIENT",
- "REFRESH_FROM_CLIENT",
- "ONE_WAY_FROM_SERVER",
- "REFRESH_FROM_SERVER"],
- SyncInterval: ["5_MINUTES", "15_MINUTES", "1_HOUR",
- "4_HOURS", "12_HOURS", "1_DAY",
- "1_WEEK", "1_MONTH"],
- SyncServiceType: ["CONTACT", "EVENT"],
- SyncStatus: ["SUCCESS", "FAIL", "STOP", "NONE"],
+ _self = {
+ toURI: function () {
+ return "file://" + _entry.fullPath;
+ },
+ listFiles: function (onSuccess, onError, filter) {
+ var _filter, _filterName, _startCreated, _endCreated, _startModified, _endModified;
- // Download
- DownloadState: ["QUEUED", "DOWNLOADING", "PAUSED",
- "CANCELED", "COMPLETED", "FAILED"],
- DownloadNetworkType: ["CELLULAR", "WIFI", "ALL"],
+ if (filter !== null && filter !== undefined) {
- // Messaging
- MessageServiceTag: ["messaging.sms", "messaging.mms",
- "messaging.email"],
+ if (typeof filter === 'number' || typeof filter === 'string') {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ _filter = filter;
+ _filterName = _filter.name;
+ _startModified = _filter.startModified;
+ _endModified = _filter.endModified;
+ _startCreated = _filter.startCreated;
+ _endCreated = _filter.endCreated;
- // Network Bearer Selection
- NetworkType: ["CELLULAR", "UNKNOWN"],
+ }
+ if ((_filterName !== undefined && typeof _filterName !== 'string') ||
+ (_startModified !== undefined && !tizen1_utils.isValidDate(_startModified)) ||
+ (_endModified !== undefined && !tizen1_utils.isValidDate(_endModified)) ||
+ (_endCreated !== undefined && !tizen1_utils.isValidDate(_endCreated)) ||
+ (_startCreated !== undefined && !tizen1_utils.isValidDate(_startCreated))) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- // NFC
- NDEFRecordTextEncoding: ["UTF8", "UTF16"],
- NFCTagType: ["GENERIC_TARGET", "ISO14443_A",
- "ISO14443_4A", "ISO14443_3A",
- "MIFARE_MINI", "MIFARE_1K",
- "MIFARE_4K", "MIFARE_ULTRA",
- "MIFARE_DESFIRE", "ISO14443_B",
- "ISO14443_4B", "ISO14443_BPRIME",
- "FELICA", "JEWEL", "ISO15693",
- "UNKNOWN_TARGET"],
+ function _matchName(fileName) {
+ var _matched = true,
+ _name1 = String(_filterName).toLowerCase(),
+ _name2 = fileName.toLowerCase(),
+ _pattern;
- // Notification
- NotificationType: ["STATUS", "STATUS"],
- StatusNotificationType: ["SIMPLE", "THUMBNAIL", "ONGOING",
- "PROGRESS"],
- NotificationProgressType: ["PERCENTAGE", "BYTE"],
+ if (_filterName !== undefined && _filterName !== null) {
+ if (!_name1.match("\\\\%")) {
+ if (_name1.match("%")) {
+ _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
+ _matched = _name2.match(_pattern) ? true : false;
+ } else {
+ _matched = (_name1 === _name2);
+ }
+ } else {
+ // % is not allowed as a part of file name
+ _matched = false;
+ }
+ }
- // System Info
- SystemInfoPropertyId: ["BATTERY", "CPU", "STORAGE", "DISPLAY",
- "DEVICE_ORIENTATION", "BUILD",
- "LOCALE", "NETWORK", "WIFI_NETWORK",
- "CELLULAR_NETWORK", "SIM",
- "PERIPHERAL"],
- SystemInfoNetworkType: ["NONE", "2G", "2.5G", "3G", "4G",
- "WIFI", "ETHERNET", "UNKNOWN"],
- SystemInfoDeviceOrientationStatus: ["PORTRAIT_PRIMARY",
- "PORTRAIT_SECONDARY",
- "LANDSCAPE_PRIMARY",
- "LANDSCAPE_SECONDARY"],
- SystemInfoSimState: ["ABSENT", "INITIALIZING", "READY",
- "PIN_REQUIRED", "PUK_REQUIRED",
- "NETWORK_LOCKED", "SIM_LOCKED",
- "UNKNOWN"],
- SystemInfoProfile: ["MOBILE_FULL", "MOBILE_WEB"],
+ return _matched;
+ }
- // System Setting
- SystemSettingType: ["HOME_SCREEN", "LOCK_SCREEN",
- "INCOMING_CALL", "NOTIFICATION_EMAIL"],
+ function _matchDate(date) {
+ var _matched = true;
- // Time
- TimeDurationUnit: ["MSECS", "SECS", "MINS", "HOURS",
- "DAYS"]
-};
+ if (date === undefined) return true;
-/*
- * Derivative type definition
- */
+ if (_startModified !== undefined && _startModified !== null) {
+ _matched = (date.getTime() >= _startModified.getTime());
+ }
-/*
- * Object attributes
- * Contruct a prototype of an object. Specify a primitive type for each
- * attribute.
- *
- * _optional
- * Optional attributes table, which consists of two types of attributes,
- *
- * nullable
- * Nullable attributes, marked as '?' in IDL.
- *
- * undefined
- * Array type attributes, that not definitely specified to be
- * initialized as an empty array, i.e., undefined-initialized array.
- *
- * _derived
- * Derived types, which used in two cases of definition,
- *
- * Subtype list
- * An array consists of derived subtypes. It exists in the definition of
- * a base type.
- *
- * Union types
- * An array consists of member types. It exists in the definition of
- * a union type.
- *
- * _dictionary
- * Dictionary type, which indicates that the object is a dictionary type.
- */
+ if (_matched && (_endModified !== undefined && _endModified !== null)) {
+ _matched = (date.getTime() <= _endModified.getTime());
+ }
-/*
- * Common
- */
+ return _matched;
+ }
-_t.AttributeFilter = {
- attributeName: _t.DOMString,
- matchFlag: _t.FilterMatchFlag,
- matchValue: _t.any,
+ function _matchFilter(entry) {
+ return _matchName(entry.name) && _matchDate(entry.lastModifiedDate) && _matchDate(entry.createdDate);
+ }
- _optional: {
- // nullable
- matchValue: true
- }
-};
+ function _listFiles() {
+ var _files = [];
-_t.AttributeRangeFilter = {
- attributeName: _t.DOMString,
- initialValue: _t.any,
- endValue: _t.any,
+ if (!_entry.isDirectory) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- _optional: {
- // nullable
- initialValue: true,
- endValue: true
- }
-};
+ utils.forEach(_entry.children, function (child) {
+ if (_matchFilter(child)) {
+ _files.push(new File(child, _mode));
+ }
+ });
-_t.CompositeFilter = {
- type: _t.CompositeFilterType,
- filters: ["AbstractFilter"] // Recursive expansion
-};
+ setTimeout(function () {
+ onSuccess(_files);
+ }, 1);
-_t.AbstractFilter = {
- _derived: [_t.AttributeFilter, _t.AttributeRangeFilter, _t.CompositeFilter]
-};
+ return null;
+ }
-_t.SortMode = {
- attributeName: _t.DOMString,
- order: _t.SortModeOrder
-};
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
+ },
+ openStream: function (mode, onSuccess, onError, encoding) {
+ function _openStream() {
+ var _openMode = String(mode),
+ _encoding = encoding ? String(encoding) : "UTF-8";
-_t.SimpleCoordinates = {
- latitude: _t.double,
- longitude: _t.double
-};
+ if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
-_t.SuccessCallback = _t.Function;
-_t.ErrorCallback = _t.Function;
+ if (!_security.all && ((!_security.openStreamR && _openMode === "r") || (!_security.openStreamW && _openMode === "w"))) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-/*
- * Time
- */
+ if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
-_t.TimeDuration = {
- length: _t.long_long,
- unit: _t.TimeDurationUnit,
- difference: _t.Function,
- equalsTo: _t.Function,
- lessThan: _t.Function,
- greaterThan: _t.Function
-};
+ if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
+ (_writeOnly && _openMode === "r")) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
-/*
- * Alarm
- */
+ setTimeout(function () {
+ onSuccess(new FileStream(_entry, _openMode, _encoding));
+ }, 1);
-_t.AlarmId = _t.DOMString;
+ return null;
+ }
-_t.AlarmRelative = {
- delay: _t.unsigned_long_long,
- period: _t.unsigned_long_long,
- getRemainingSeconds: _t.Function,
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
+ },
+ readAsText: function (onSuccess, onError, encoding) {
+ if (!_security.all && !_security.readAsText) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- _optional: {
- // nullable
- period: true,
- getRemainingSeconds: true
- }
-};
+ function _readAsText() {
+ var _encoding = encoding ? String(encoding) : "UTF-8";
+ if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
-_t.AlarmAbsolute = {
- date: _t.Date,
- period: _t.unsigned_long_long,
- daysOfTheWeek: [_t.ByDayValue],
- getNextScheduledDate: _t.Function,
+ if (_writeOnly) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- _optional: {
- // nullable
- period: true,
- getNextScheduledDate: true
- }
-};
+ if (_self.isFile) {
+ dbfs.read(_entry.fullPath,
+ function (data) {
+ setTimeout(function () {
+ onSuccess(data);
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
-_t.Alarm = {
- id: _t.AlarmId,
+ return undefined;
+ }
- _optional: {
- // nullable
- id: true
- },
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
+ },
+ copyTo: function (src, dst, overwrite, onSuccess, onError) {
+ if (!_security.all && !_security.copyTo) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- _derived: [_t.AlarmRelative, _t.AlarmAbsolute]
-};
+ function _copyTo() {
+ return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
+ }
-/*
- * Application
- */
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
+ },
+ moveTo: function (src, dst, overwrite, onSuccess, onError) {
+ if (!_security.all && !_security.moveTo) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.ApplicationId = _t.DOMString;
-_t.ApplicationContextId = _t.DOMString;
-_t.ApplicationInformationArraySuccessCallback = _t.Function;
-_t.FindAppControlSuccessCallback = _t.Function;
-_t.ApplicationContextArraySuccessCallback = _t.Function;
+ function _moveTo() {
+ return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
+ }
-_t.ApplicationControlData = {
- key: _t.DOMString,
- value: [_t.DOMString]
-};
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
+ },
+ createDirectory: function (dirPath) {
+ var _path = String(dirPath),
+ _parts = _path.replace(/\/$/, "").split("/"),
+ _dir = null,
+ _exist = null,
+ _current = _entry.fullPath,
+ _i;
-_t.ApplicationControl = {
- operation: _t.DOMString,
- uri: _t.DOMString,
- mime: _t.DOMString,
- category: _t.DOMString,
- data: [_t.ApplicationControlData],
+ if (!_security.all && !_security.createDirectory) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- _optional: {
- // nullable
- uri: true,
- mime: true,
- category: true
- }
-};
+ function onSuccess(entry) {
+ _dir = entry;
+ }
-_t.ApplicationControlDataArrayReplyCallback = {
- onsuccess: _t.Callback,
- onfailure: _t.Callback
-};
+ for (_i = 0; _i < _parts.length; _i++) {
+ if (!_isValidFileName(_parts[_i])) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ }
-_t.ApplicationInformationEventCallback = {
- oninstalled: _t.Callback,
- onupdated: _t.Callback,
- onuninstalled: _t.Callback
-};
+ if (!entry.isDirectory) {
+ throw new WebAPIException(errorcode.IO_ERR);
+ }
-/*
- * Bluetooth
- */
+ _exist = _parts.reduce(function (obj, token) {
+ return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
+ }, _entry);
-_t.BluetoothAddress = _t.DOMString;
-_t.BluetoothUUID = _t.DOMString;
-_t.BluetoothDeviceSuccessCallback = _t.Function;
-_t.BluetoothDeviceArraySuccessCallback = _t.Function;
-_t.BluetoothSocketSuccessCallback = _t.Function;
-_t.BluetoothServiceSuccessCallback = _t.Function;
-_t.BluetoothHealthApplicationSuccessCallback = _t.Function;
-_t.BluetoothHealthChannelSuccessCallback = _t.Function;
+ if (_exist) {
+ throw new WebAPIException(errorcode.IO_ERR);
+ }
-_t.BluetoothClass = {
- major: _t.octet,
- minor: _t.octet,
- services: [_t.unsigned_short],
- hasService: _t.Function
-};
+ if (_readOnly || _mode === "r") {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.BluetoothDevice = {
- name: _t.DOMString,
- address: _t.BluetoothAddress,
- deviceClass: _t.BluetoothClass,
- isBonded: _t.boolean,
- isTrusted: _t.boolean,
- isConnected: _t.boolean,
- uuids: [_t.BluetoothUUID],
- connectToServiceByUUID: _t.Function
-};
+ for (_i = 0; _i < _parts.length; _i++) {
+ _current = _current + "/" + _parts[_i];
+ dbfs.mkdir(_current, onSuccess);
+ }
-_t.BluetoothHealthApplication = {
- dataType: _t.unsigned_short,
- name: _t.DOMString,
- onconnect: _t.BluetoothHealthChannelSuccessCallback,
- unregister: _t.Function,
+ return new File(_dir, _mode);
+ },
+ createFile: function (filePath) {
+ var _name = String(filePath),
+ _file = null;
- _optional: {
- onconnect: true
- }
-};
+ if (!_security.all && !_security.createFile) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.BluetoothAdapterChangeCallback = {
- onstatechanged: _t.Callback,
- onnamechanged: _t.Callback,
- onvisibilitychanged: _t.Callback
-};
+ if (!_isValidFileName(_name)) {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
-_t.BluetoothDiscoverDevicesSuccessCallback = {
- onstarted: _t.Callback,
- ondevicefound: _t.Callback,
- ondevicedisappeared: _t.Callback,
- onfinished: _t.Callback
-};
+ if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
+ throw new WebAPIException(errorcode.IO_ERR);
+ }
-_t.BluetoothHealthChannelChangeCallback = {
- onmessage: _t.Callback,
- onclose: _t.Callback
-};
+ if (_readOnly || _mode === "r") {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-/*
- * Bookmark
- */
+ dbfs.touch(_entry.fullPath + "/" + _name,
+ function (entry) {
+ _file = new File(entry, _mode);
+ },
+ function () {});
-_t.BookmarkFolder = {
- parent: "BookmarkFolder",
- title: _t.DOMString,
+ return _file;
+ },
+ resolve: function (filePath) {
+ var _fullPath = _self.fullPath + "/" + String(filePath),
+ _file = null;
- _optional: {
- // nullable
- parent: true
- }
-};
+ if (!_entry.isDirectory) {
+ throw new WebAPIException(errorcode.IO_ERR);
+ }
-_t.BookmarkItem = {
- parent: _t.BookmarkFolder,
- title: _t.DOMString,
- url: _t.DOMString,
+ _resolveSync(_fullPath,
+ function (file) {
+ _file = file;
+ },
+ function (e) {
+ throw (e);
+ },
+ _mode);
- _optional: {
- // nullable
- parent: true
- }
-};
+ return _file;
+ },
+ deleteDirectory: function (directory, recursive, onSuccess, onError) {
+ if (!_security.all && !_security.deleteDirectory) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.Bookmark = {
- _derived: [_t.BookmarkItem, _t.BookmarkFolder]
-};
+ function _deleteDirectory() {
+ var _dir = null,
+ _dirName = String(directory);
+ _resolveSync(_dirName,
+ function (file) {
+ _dir = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
-/*
- * Contact
- */
+ if (_dir) {
+ if (_dir.isDirectory &&
+ _dir.parent.fullPath === _self.fullPath &&
+ (!recursive && _dir.length === 0)) {
+ if (!_readOnly && _mode !== "r") {
+ dbfs.rmdir(_v2r(_dirName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ }
-_t.AddressBookId = _t.DOMString;
-_t.ContactId = _t.DOMString;
-_t.PersonId = _t.DOMString;
-_t.ContactGroupId = _t.DOMString;
+ return undefined;
+ }
-_t.Person = {
- id: _t.PersonId,
- displayName: _t.DOMString,
- contactCount: _t.long,
- hasPhoneNumber: _t.boolean,
- hasEmail: _t.boolean,
- isFavorite: _t.boolean,
- photoURI: _t.DOMString,
- ringtoneURI: _t.DOMString,
- displayContactId: _t.ContactId,
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
+ },
+ deleteFile: function (fileName, onSuccess, onError) {
+ if (!_security.all && !_security.deleteFile) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
- _optional: {
- // nullable
- photoURI: true,
- ringtoneURI: true
- }
-};
+ function _deleteFile() {
+ var _file = null;
+ _resolveSync(String(fileName),
+ function (file) {
+ _file = file;
+ },
+ function (e) {
+ if (onError) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ }
+ },
+ _mode);
-_t.ContactRef = {
- addressBookId: _t.AddressBookId,
- contactId: _t.ContactId
-};
+ if (_file) {
+ if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
+ if (!_readOnly && _mode !== "r") {
+ dbfs.rm(_v2r(fileName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ }
-_t.ContactName = {
- prefix: _t.DOMString,
- suffix: _t.DOMString,
- firstName: _t.DOMString,
- middleName: _t.DOMString,
- lastName: _t.DOMString,
- nicknames: [_t.DOMString],
- phoneticFirstName: _t.DOMString,
- phoneticLastName: _t.DOMString,
- displayName: _t.DOMString,
+ return undefined;
+ }
- _optional: {
- // nullable
- prefix: true,
- suffix: true,
- firstName: true,
- middleName: true,
- lastName: true,
- phoneticFirstName: true,
- phoneticLastName: true,
- displayName: true
- }
-};
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
+ }
+ };
-_t.ContactOrganization = {
- name: _t.DOMString,
- department: _t.DOMString,
- title: _t.DOMString,
- role: _t.DOMString,
- logoURI: _t.DOMString,
+ _self.__defineGetter__("parent", function () {
+ var _parts = _self.fullPath.split("/");
- _optional: {
- // nullable
- name: true,
- department: true,
- title: true,
- role: true,
- logoURI: true
- }
-};
+ if (_parent === undefined) {
+ if (_parts.length === 1) {
+ // virtual root's parent is null
+ _parent = null;
+ } else {
+ _resolveSync(_parts.splice(0, _parts.length - 1).join("/"),
+ function (file) {
+ _parent = file;
+ },
+ function () {},
+ _mode);
+ }
+ return _parent;
+ } else {
+ return _parent;
+ }
+ });
-_t.ContactWebSite = {
- url: _t.DOMString,
- type: _t.DOMString,
+ _self.__defineGetter__("readOnly", function () {
+ return false;
+ });
- _optional: {
- // nullable
- type: true
- }
-};
+ _self.__defineGetter__("isFile", function () {
+ return !_entry.isDirectory;
+ });
-_t.ContactAnniversary = {
- date: _t.Date,
- label: _t.DOMString,
+ _self.__defineGetter__("isDirectory", function () {
+ return _entry.isDirectory;
+ });
- _optional: {
- // nullable
- label: true
- }
-};
+ _self.__defineGetter__("created", function () {
+ return _entry.createdDate;
+ });
-_t.ContactAddress = {
- country: _t.DOMString,
- region: _t.DOMString,
- city: _t.DOMString,
- streetAddress: _t.DOMString,
- additionalInformation: _t.DOMString,
- postalCode: _t.DOMString,
- isDefault: _t.boolean,
- types: [_t.DOMString],
+ _self.__defineGetter__("modified", function () {
+ return _entry.lastModifiedDate;
+ });
- _optional: {
- // nullable
- country: true,
- region: true,
- city: true,
- streetAddress: true,
- additionalInformation: true,
- postalCode: true,
- // undefined
- types: true
- }
-};
+ _self.__defineGetter__("path", function () {
+ var _parts = _self.fullPath.split("/");
-_t.ContactPhoneNumber = {
- number: _t.DOMString,
- isDefault: _t.boolean,
- types: [_t.DOMString],
+ if (_parts.length === 1) {
+ // virtual root
+ return _parts.join("");
+ } else {
+ return _parts.splice(0, _parts.length - 1).join("/") + "/";
+ }
+ });
- _optional: {
- // undefined
- types: true
- }
-};
+ _self.__defineGetter__("name", function () {
+ return _entry.name;
+ });
-_t.ContactEmailAddress = {
- email: _t.DOMString,
- isDefault: _t.boolean,
- types: [_t.DOMString],
+ _self.__defineGetter__("fullPath", function () {
+ return _r2v(_entry.fullPath);
+ });
- _optional: {
- // undefined
- types: true
- }
-};
+ _self.__defineGetter__("fileSize", function () {
+ if (_entry.isDirectory) {
+ return undefined;
+ } else {
+ return _entry.data.length;
+ }
+ });
-_t.Contact = {
- id: _t.ContactId,
- personId: _t.PersonId,
- addressBookId: _t.AddressBookId,
- lastUpdated: _t.Date,
- isFavorite: _t.boolean,
- name: _t.ContactName,
- addresses: [_t.ContactAddress],
- photoURI: _t.DOMString,
- phoneNumbers: [_t.ContactPhoneNumber],
- emails: [_t.ContactEmailAddress],
- birthday: _t.Date,
- anniversaries: [_t.ContactAnniversary],
- organizations: [_t.ContactOrganization],
- notes: [_t.DOMString],
- urls: [_t.ContactWebSite],
- ringtoneURI: _t.DOMString,
- groupIds: [_t.ContactGroupId],
- convertToString: _t.Function,
- clone: _t.Function,
+ _self.__defineGetter__("length", function () {
+ var _l = 0;
+ if (_entry.isDirectory) {
+ utils.forEach(_entry.children, function () {
+ _l++;
+ });
+ return _l;
+ } else {
+ return undefined;
+ }
+ });
- _optional: {
- // nullable
- id: true,
- personId: true,
- addressBookId: true,
- lastUpdated: true,
- name: true,
- photoURI: true,
- birthday: true,
- ringtoneURI: true
- }
+ return _self;
};
-_t.ContactGroup = {
- id: _t.ContactGroupId,
- addressBookId: _t.AddressBookId,
- name: _t.DOMString,
- ringtoneURI: _t.DOMString,
- photoURI: _t.DOMString,
- readOnly: _t.boolean,
+FileStream = function (entry, mode, encoding) {
+ var _entry = entry,
+ _data = entry.data,
+ _mode = mode,
+ _position = (_mode === "a" ? _data.length : 0),
+ _self;
- _optional: {
- // nullable
- id: true,
- addressBookId: true,
- ringtoneURI: true,
- photoURI: true
- }
-};
+ _self = {
+ close: function () {
+ var _element;
+ if (mode === "a" || mode === "w") {
+ dbfs.write(_entry.fullPath, _data, function () {}, function () {});
+ }
+ for (_element in _self) {
+ delete _self[_element];
+ }
+ },
+ read: function (charCount) {
+ var _count = charCount | 0,
+ _substr = _data.substring(_position, _position + _count);
-_t.PersonArraySuccessCallback = _t.Function;
-_t.ContactArraySuccessCallback = _t.Function;
-_t.AddressBookArraySuccessCallback = _t.Function;
+ if (_position + _count > _data.length) {
+ _position = _data.length;
+ } else {
+ _position += _count;
+ }
-_t.AddressBookChangeCallback = {
- oncontactsadded: _t.Callback,
- oncontactsupdated: _t.Callback,
- oncontactsremoved: _t.Callback
-};
+ return _substr;
+ },
+ readBytes: function (byteCount) {
+ var _substr = _self.read(byteCount),
+ _bytes = [],
+ _i;
-_t.PersonsChangeCallback = {
- onpersonsadded: _t.Callback,
- onpersonsupdated: _t.Callback,
- onpersonsremoved: _t.Callback
-};
+ for (_i = 0; _i < _substr.length; _i++) {
+ _bytes.push(_substr.charCodeAt(_i));
+ }
-_t.ContactInit = {
- name: _t.ContactName,
- addresses: [_t.ContactAddress],
- photoURI: _t.DOMString,
- phoneNumbers: [_t.ContactPhoneNumber],
- emails: [_t.ContactEmailAddress],
- birthday: _t.Date,
- anniversaries: [_t.ContactAnniversary],
- organizations: [_t.ContactOrganization],
- notes: [_t.DOMString],
- urls: [_t.ContactWebSite],
- ringtoneURI: _t.DOMString,
- groupIds: [_t.ContactGroupId],
+ return _bytes;
+ },
+ readBase64: function (byteCount) {
+ var _substr = _self.read(byteCount);
- _dictionary: null
-};
+ return window.atob(_substr);
+ },
+ write: function (stringData) {
+ var _stringData = String(stringData),
+ _substr = _data.substring(0, _position);
-_t.ContactNameInit = {
- prefix: _t.DOMString,
- suffix: _t.DOMString,
- firstName: _t.DOMString,
- middleName: _t.DOMString,
- lastName: _t.DOMString,
- nicknames: [_t.DOMString],
- phoneticFirstName: _t.DOMString,
- phoneticLastName: _t.DOMString,
+ _data = _substr.concat(_stringData);
+ _position = _data.length;
+ },
+ writeBytes: function (byteData) {
+ _self.write(String.fromCharCode.apply(String, byteData));
+ },
+ writeBase64: function (base64Data) {
+ _self.write(window.btoa(String(base64Data)));
+ }
+ };
+
+ _self.__defineGetter__("eof", function () {
+ return _position === _data.length;
+ });
- _dictionary: null
-};
+ _self.__defineGetter__("position", function () {
+ return _position;
+ });
-_t.ContactOrganizationInit = {
- name: _t.DOMString,
- department: _t.DOMString,
- title: _t.DOMString,
- role: _t.DOMString,
- logoURI: _t.DOMString,
+ _self.__defineSetter__("position", function (value) {
+ var _value = value | 0;
- _dictionary: null
-};
+ if (_value >= 0 && _value <= _data.length) {
+ _position = _value;
+ } else {
+ throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
+ }
+ });
-_t.ContactAddressInit = {
- country: _t.DOMString,
- region: _t.DOMString,
- city: _t.DOMString,
- streetAddress: _t.DOMString,
- additionalInformation: _t.DOMString,
- postalCode: _t.DOMString,
- isDefault: _t.boolean,
- types: [_t.DOMString],
+ _self.__defineGetter__("bytesAvailable", function () {
+ return (_data.length - _position) || -1;
+ });
- _dictionary: null
+ return _self;
};
-/*
- * Calendar
- */
+FileFilter = function (name, startModified, endModified, startCreated, endCreated) {
+ var _self = {
+ name: name,
+ startModified: utils.copy(startModified),
+ endModified: utils.copy(endModified),
+ endCreated: utils.copy(endCreated)
+ };
-_t.CalendarId = _t.DOMString;
-_t.CalendarTaskId = _t.DOMString;
-_t.CalendarEventArraySuccessCallback = _t.Function;
-_t.CalendarItemArraySuccessCallback = _t.Function;
-_t.CalendarArraySuccessCallback = _t.Function;
+ return _self;
+};
-_t.CalendarEventId = {
- uid: _t.DOMString,
- rid: _t.DOMString,
+FileSystemStorage = function (label, type, state) {
+ var _self = {
+ label: label,
+ type: type,
+ state: state
+ };
- _optional: {
- // nullable
- rid: true
- }
+ return _self;
};
-_t.CalendarItemId = {
- _derived: [_t.CalendarEventId, _t.CalendarTaskId]
-};
+module.exports = {
+ maxPathLength: _maxPathLength,
+ resolve: function (srcLocation, onSuccess, onError, accessMode) {
+ function _resolve() {
+ var _mode = accessMode ? String(accessMode) : _defaultMode;
-_t.CalendarAlarm = {
- absoluteDate: _t.TZDate,
- before: _t.TimeDuration,
- method: _t.AlarmMethod,
- description: _t.DOMString,
+ if (_mode === "r" || _mode === "rw") {
+ _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
+ }
- _optional: {
- // nullable
- absoluteDate: true,
- before: true,
- description: true
- }
-};
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
+ },
-_t.CalendarAttendee = {
- uri: _t.DOMString,
- name: _t.DOMString,
- role: _t.AttendeeRole,
- status: _t.AttendeeStatus,
- RSVP: _t.boolean,
- type: _t.AttendeeType,
- group: _t.DOMString,
- delegatorURI: _t.DOMString,
- delegateURI: _t.DOMString,
- contactRef: _t.ContactRef,
+ getStorage: function (label, onSuccess, onError) {
+ var storage = null, _label = String(label);
- _optional: {
- // nullable
- name: true,
- group: true,
- delegatorURI: true,
- delegateURI: true,
- contactRef: true
- }
-};
+ _storages.some(function (value) {
+ if (value.label === _label) {
+ storage = utils.copy(value);
+ setTimeout(function () {
+ onSuccess(storage);
+ }, 1);
+ return true;
+ }
+ });
-_t.CalendarRecurrenceRule = {
- frequency: _t.RecurrenceRuleFrequency,
- interval: _t.unsigned_short,
- untilDate: _t.TZDate,
- occurrenceCount: _t.long,
- daysOfTheWeek: [_t.ByDayValue],
- setPositions: [_t.short],
- exceptions: [_t.TZDate],
+ if (!storage) {
+ if(onError) {
+ setTimeout(function () {
+ onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
+ }, 1);
- _optional: {
- // nullable
- untilDate: true
- }
-};
+ } else {
+ throw new WebAPIException(errorcode.NOT_FOUND_ERR);
+ }
+ }
+ },
-_t.CalendarTask = {
- dueDate: _t.TZDate,
- completedDate: _t.TZDate,
- progress: _t.unsigned_short,
+ listStorages: function (onSuccess, onError) {
+ function _listStorages() {
+ setTimeout(function () {
+ onSuccess(utils.copy(_storages));
+ }, 1);
+ }
- _optional: {
- // nullable
- dueDate: true,
- completedDate: true
- }
-};
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listStorages", _listStorages);
+ },
-_t.CalendarEvent = {
- isDetached: _t.boolean,
- endDate: _t.TZDate,
- availability: _t.EventAvailability,
- recurrenceRule: _t.CalendarRecurrenceRule,
- expandRecurrence: _t.Function,
+ addStorageStateChangeListener: function(onSuccess, onError) {
+ function _addStorageStateChangeListener() {
+ var watchId = (new Date()).getTime() || 0;
+ _observers[watchId] = function(storage) {//storage is which state is changed
+ onSuccess(storage);
+ };
- _optional: {
- // nullable
- endDate: true,
- recurrenceRule: true
- }
-};
+ // This event should be triggered from outside
+ event.on("StateChange", _observers[watchId]);
+ return Number(watchId);
+ }
-_t.CalendarItem = {
- id: _t.CalendarItemId,
- calendarId: _t.CalendarId,
- lastModificationDate: _t.TZDate,
- description: _t.DOMString,
- summary: _t.DOMString,
- isAllDay: _t.boolean,
- startDate: _t.TZDate,
- duration: _t.TimeDuration,
- location: _t.DOMString,
- geolocation: _t.SimpleCoordinates,
- organizer: _t.DOMString,
- visibility: _t.CalendarItemVisibility,
- status: _t.CalendarItemStatus,
- priority: _t.CalendarItemPriority,
- alarms: [_t.CalendarAlarm],
- categories: [_t.DOMString],
- attendees: [_t.CalendarAttendee],
- convertToString: _t.Function,
- clone: _t.Function,
+ return tizen1_utils.validateTypeMismatch(onSuccess, onError, "addStorageStateChangeListener", _addStorageStateChangeListener);
+ },
- _optional: {
- // nullable
- id: true,
- calendarId: true,
- lastModificationDate: true,
- description: true,
- summary: true,
- startDate: true,
- duration: true,
- location: true,
- geolocation: true,
- organizer: true
+ removeStorageStateChangeListener: function (watchId) {
+ if (!_observers[watchId])
+ return;
+
+ event.deleteEventHandler("StateChange", _observers[watchId]);
+ delete _observers[watchId];
},
- _derived: [_t.CalendarTask, _t.CalendarEvent]
+ handleSubFeatures: function (subFeatures) {
+ function setSecurity(_security) {
+ return function (method) {
+ _security[method] = true;
+ };
+ }
+
+ for (var subFeature in subFeatures) {
+ if (_security[subFeature].length === 0) {
+ _security.all = true;
+ return;
+ }
+ _security.all = false;
+ utils.forEach(_security[subFeature], setSecurity);
+ }
+ }
};
-_t.CalendarItemInit = {
- description: _t.DOMString,
- summary: _t.DOMString,
- isAllDay: _t.boolean,
- startDate: _t.TZDate,
- duration: _t.TimeDuration,
- location: _t.DOMString,
- geolocation: _t.SimpleCoordinates,
- organizer: _t.DOMString,
- visibility: _t.CalendarItemVisibility,
- status: _t.CalendarItemStatus,
- priority: _t.CalendarItemPriority,
- alarms: [_t.CalendarAlarm],
- categories: [_t.DOMString],
- attendees: [_t.CalendarAttendee],
- _dictionary: null
-};
+});
+define('ripple/platform/tizen/2.0/ContactName', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
-_t.CalendarTaskInit = {
- dueDate: _t.TZDate,
- completedDate: _t.TZDate,
- progress: _t.short,
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactName;
- _dictionary: _t.CalendarItemInit
-};
+ContactName = function (nameInitDict) {
+ var contactName = {}, attr;
-_t.CalendarEventInit = {
- endDate: _t.TZDate,
- availability: _t.EventAvailability,
- recurrenceRule: _t.CalendarRecurrenceRule,
+ t.ContactName(arguments, this);
- _dictionary: _t.CalendarItemInit
-};
+ contactName.prefix = null;
+ contactName.suffix = null;
+ contactName.firstName = null;
+ contactName.middleName = null;
+ contactName.lastName = null;
+ contactName.nicknames = [];
+ contactName.phoneticFirstName = null;
+ contactName.phoneticLastName = null;
-_t.CalendarAttendeeInit = {
- name: _t.DOMString,
- role: _t.AttendeeRole,
- status: _t.AttendeeStatus,
- RSVP: _t.boolean,
- type: _t.AttendeeType,
- group: _t.DOMString,
- delegatorURI: _t.DOMString,
- delegateURI: _t.DOMString,
- contactRef: _t.ContactRef,
+ this.__defineGetter__("prefix", function () {
+ return contactName.prefix;
+ });
+ this.__defineSetter__("prefix", function (val) {
+ try {
+ contactName.prefix = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- _dictionary: null
-};
+ this.__defineGetter__("suffix", function () {
+ return contactName.suffix;
+ });
+ this.__defineSetter__("suffix", function (val) {
+ try {
+ contactName.suffix = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-_t.CalendarRecurrenceRuleInit = {
- interval: _t.short,
- untilDate: _t.TZDate,
- occurrenceCount: _t.long,
- daysOfTheWeek: [_t.ByDayValue],
- setPositions: [_t.short],
- exceptions: [_t.TZDate],
+ this.__defineGetter__("firstName", function () {
+ return contactName.firstName;
+ });
+ this.__defineSetter__("firstName", function (val) {
+ try {
+ contactName.firstName = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- _dictionary: null
-};
+ this.__defineGetter__("middleName", function () {
+ return contactName.middleName;
+ });
+ this.__defineSetter__("middleName", function (val) {
+ try {
+ contactName.middleName = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-_t.CalendarChangeCallback = {
- onitemsadded: _t.Callback,
- onitemsupdated: _t.Callback,
- onitemsremoved: _t.Callback
-};
+ this.__defineGetter__("lastName", function () {
+ return contactName.lastName;
+ });
+ this.__defineSetter__("lastName", function (val) {
+ try {
+ contactName.lastName = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-/*
- * CallHistory
- */
+ this.__defineGetter__("nicknames", function () {
+ return contactName.nicknames;
+ });
+ this.__defineSetter__("nicknames", function (val) {
+ try {
+ contactName.nicknames = t.DOMString(val, "[]");
+ } catch (e) {
+ }
+ });
-_t.CallHistoryEntryArraySuccessCallback = _t.Function;
+ this.__defineGetter__("phoneticFirstName", function () {
+ return contactName.phoneticFirstName;
+ });
+ this.__defineSetter__("phoneticFirstName", function (val) {
+ try {
+ contactName.phoneticFirstName = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-_t.RemoteParty = {
- remoteParty: _t.DOMString,
- personId: _t.PersonId,
+ this.__defineGetter__("phoneticLastName", function () {
+ return contactName.phoneticLastName;
+ });
+ this.__defineSetter__("phoneticLastName", function (val) {
+ try {
+ contactName.phoneticLastName = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- _optional: {
- // nullable
- remoteParty: true,
- personId: true
+ this.__defineGetter__("displayName", function () {
+ return null;
+ });
+
+ if (nameInitDict) {
+ for (attr in nameInitDict) {
+ contactName[attr] = nameInitDict[attr];
+ }
}
};
-_t.CallHistoryEntry = {
- uid: _t.DOMString,
- type: _t.DOMString,
- features: [_t.DOMString],
- remoteParties: [_t.RemoteParty],
- startTime: _t.Date,
- duration: _t.unsigned_long,
- direction: _t.DOMString,
+module.exports = ContactName;
- _optional: {
- // nullable
- features: true
- }
-};
+});
+define('ripple/platform/tizen/2.0/Conversation', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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 utils = require('ripple/utils');
-_t.CallHistoryChangeCallback = {
- onadded: _t.Callback,
- onchanged: _t.Callback,
- onremoved: _t.Callback
+module.exports = function (opt) {
+ var conv = {}, priv = utils.copy(opt);
+
+ conv.__defineGetter__("id", function () {
+ return priv.id;
+ });
+ conv.__defineGetter__("type", function () {
+ return priv.type;
+ });
+ conv.__defineGetter__("timestamp", function () {
+ return priv.timestamp;
+ });
+ conv.__defineGetter__("messageCount", function () {
+ return priv.messageCount;
+ });
+ conv.__defineGetter__("unreadMessages", function () {
+ return priv.unreadMessages;
+ });
+ conv.__defineGetter__("preview", function () {
+ return priv.preview;
+ });
+ conv.__defineGetter__("subject", function () {
+ return priv.subject;
+ });
+ conv.__defineGetter__("isRead", function () {
+ return priv.isRead;
+ });
+ conv.__defineGetter__("from", function () {
+ return priv.from;
+ });
+ conv.__defineGetter__("to", function () {
+ return priv.to;
+ });
+ conv.__defineGetter__("cc", function () {
+ return priv.cc;
+ });
+ conv.__defineGetter__("bcc", function () {
+ return priv.bcc;
+ });
+ conv.__defineGetter__("lastMessageId", function () {
+ return priv.lastMessageId;
+ });
+ return conv;
};
+});
+define('ripple/platform/tizen/2.0/push', function (require, exports, module) {
/*
- * Content
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-_t.ContentId = _t.DOMString;
-_t.ContentDirectoryId = _t.DOMString;
-_t.ContentArraySuccessCallback = _t.Function;
-_t.ContentDirectoryArraySuccessCallback = _t.Function;
-_t.ContentScanSuccessCallback = _t.Function;
+var event = require('ripple/event'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ t = require('ripple/platform/tizen/2.0/typecast'),
+ Notification = require('ripple/platform/tizen/2.0/notification'),
+ StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ PushMessage,
+ _data = {
+ service: {
+/* "ID_APPLICATION_0": {
+ * appId: null,
+ * registrationId: null,
+ * appControl: null,
+ * isRegistered: false,
+ * isConnected: false,
+ * onpushed: null
+ * }
+ */
+ }
+ },
+ _security = {
+ "http://tizen.org/privilege/push": ["registerService",
+ "unregisterService", "connectService", "disconnectService",
+ "getRegistrationId"]
+ },
+ _self;
-_t.ContentChangeCallback = {
- oncontentadded: _t.Callback,
- oncontentupdated: _t.Callback,
- oncontentremoved: _t.Callback
-};
+function _initialize() {
+ event.on("PushNotified", function (appId, pushMessage) {
+ var appService, notificationDict, statusNotification, notification;
-_t.VideoContent = {
- geolocation: _t.SimpleCoordinates,
- album: _t.DOMString,
- artists: [_t.DOMString],
- duration: _t.unsigned_long,
- width: _t.unsigned_long,
- height: _t.unsigned_long,
+ appService = _data.service[appId];
- _optional: {
- // nullable
- geolocation: true,
- album: true,
- artists: true
- }
-};
+ if (!appService)
+ return;
-_t.AudioContentLyrics = {
- type: _t.AudioContentLyricsType,
- timestamps: [_t.unsigned_long],
- texts: [_t.DOMString]
-};
+ if (appService.isConnected) {
+ appService.onpushed(new PushMessage(pushMessage));
+ } else {
+ notificationDict = {
+ content: pushMessage.appData,
+ appControl: appService.appControl,
+ appId: appId
+ };
+ statusNotification = new StatusNotification("SIMPLE",
+ pushMessage.alertMessage, notificationDict);
+ notification = new Notification();
-_t.AudioContent = {
- album: _t.DOMString,
- genres: [_t.DOMString],
- artists: [_t.DOMString],
- composers: [_t.DOMString],
- lyrics: _t.AudioContentLyrics,
- copyright: _t.DOMString,
- bitrate: _t.unsigned_long,
- trackNumber: _t.unsigned_short,
- duration: _t.unsigned_long,
+ notification.post(statusNotification);
+ }
+ });
+}
- _optional: {
- // nullable
- album: true,
- genres: true,
- artists: true,
- composers: true,
- lyrics: true,
- copyright: true,
- trackNumber: true
- }
-};
+function _getCurrentApplicationId() {
+ return "ID_APPLICATION_0";
+}
-_t.ImageContent = {
- geolocation: _t.SimpleCoordinates,
- width: _t.unsigned_long,
- height: _t.unsigned_long,
- orientation: _t.ImageContentOrientation,
+_self = function () {
+ var push;
- _optional: {
- // nullable
- geolocation: true
- }
-};
+ function registerService(appControl, successCallback, errorCallback) {
+ if (!_security.registerService) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.Content = {
- editableAttributes: [_t.DOMString],
- id: _t.ContentId,
- name: _t.DOMString,
- type: _t.ContentType,
- mimeType: _t.DOMString,
- title: _t.DOMString,
- contentURI: _t.DOMString,
- thumbnailURIs: [_t.DOMString],
- releaseDate: _t.Date,
- modifiedDate: _t.Date,
- size: _t.unsigned_long,
- description: _t.DOMString,
- rating: _t.float,
+ t.PushManager("registerService", arguments, true);
- _optional: {
- // nullable
- thumbnailURIs: true,
- releaseDate: true,
- modifiedDate: true,
- description: true
- },
+ window.setTimeout(function () {
+ var appId, appService;
- _derived: [_t.VideoContent, _t.AudioContent, _t.ImageContent]
-};
+ appId = _getCurrentApplicationId();
+ appService = {
+ appId: appId,
+ registrationId: null,
+ appControl: appControl,
+ isRegistered: false
+ };
+ _data.service[appId] = appService;
-/*
- * Data Control
- */
+ event.trigger("PushRequest", ["REGISTER", appService], true);
-_t.DataControlSuccessCallback = _t.Function;
-_t.DataControlErrorCallback = _t.Function;
-_t.DataControlInsertSuccessCallback = _t.Function;
-_t.DataControlSelectSuccessCallback = _t.Function;
-_t.DataControlGetValueSuccessCallback = _t.Function;
+ if (appService.registrationId === null) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
+ }
+ return;
+ }
-_t.RowData = {
- columns: [_t.DOMString],
- values: [_t.DOMString]
-};
+ appService.isRegistered = true;
+ successCallback(appService.registrationId);
+ }, 1);
+ }
-/*
- * Data Synchronization
- */
+ function unregisterService(successCallback, errorCallback) {
+ if (!_security.unregisterService) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.SyncProfileId = _t.DOMString;
+ t.PushManager("unregisterService", arguments);
-_t.SyncInfo = {
- url: _t.DOMString,
- id: _t.DOMString,
- password: _t.DOMString,
- mode: _t.SyncMode,
- type: _t.SyncType,
- interval: _t.SyncInterval,
+ window.setTimeout(function () {
+ var appId;
- _optional: {
- // nullable
- id: true,
- password: true,
- type: true,
- interval: true
+ appId = _getCurrentApplicationId();
+ delete _data.service[appId];
+ event.trigger("PushRequest", ["UNREGISTER", appId]);
+ if (successCallback) {
+ successCallback();
+ }
+ }, 1);
}
-};
-_t.SyncServiceInfo = {
- enable: _t.boolean,
- serviceType: _t.SyncServiceType,
- serverDatabaseUri: _t.DOMString,
- id: _t.DOMString,
- password: _t.DOMString,
+ function connectService(notificationCallback) {
+ var appId, appService;
- _optional: {
- // nullable
- id: true,
- password: true
- }
-};
+ if (!_security.connectService) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.SyncProfileInfo = {
- profileId: _t.SyncProfileId,
- profileName: _t.DOMString,
- syncInfo: _t.SyncInfo,
- serviceInfo: [_t.SyncServiceInfo],
+ t.PushManager("connectService", arguments);
- _optional: {
- // nullable
- profileId: true,
- serviceInfo: true
+ appId = _getCurrentApplicationId();
+ appService = _data.service[appId];
+ if (!appService || !appService.isRegistered) {
+ throw new WebAPIException(errorcode.UNKNOWN_ERR);
+ }
+
+ appService.isConnected = true;
+ appService.onpushed = notificationCallback;
+ event.trigger("PushRequest", ["CONNECT", appId]);
}
-};
-_t.SyncProgressCallback = {
- onprogress: _t.Callback,
- oncompleted: _t.Callback,
- onstopped: _t.Callback,
- onfailed: _t.Callback
-};
+ function disconnectService() {
+ var appId, appService;
-/*
- * Download
- */
+ if (!_security.disconnectService) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.DownloadHTTPHeaderFields = {};
+ t.PushManager("disconnectService", arguments);
-_t.DownloadRequest = {
- url: _t.DOMString,
- destination: _t.DOMString,
- fileName: _t.DOMString,
- networkType: _t.DownloadNetworkType,
- httpHeader: _t.DownloadHTTPHeaderFields,
+ appId = _getCurrentApplicationId();
+ appService = _data.service[appId];
+ if (!appService || !appService.isRegistered ||
+ !appService.isConnected) {
+ return;
+ }
- _optional: {
- destination: true,
- fileName: true,
- networkType: true,
- httpHeader: true
+ appService.onpushed = null;
+ appService.isConnected = false;
+ event.trigger("PushRequest", ["DISCONNECT", appId]);
}
-};
-_t.DownloadCallback = {
- onprogress: _t.Callback,
- onpaused: _t.Callback,
- oncanceled: _t.Callback,
- oncompleted: _t.Callback,
- onfailed: _t.Callback
-};
+ function getRegistrationId() {
+ var appService;
-/*
- * Messaging
- */
+ if (!_security.getRegistrationId) {
+ throw new WebAPIException(errorcode.SECURITY_ERR);
+ }
-_t.MessageId = _t.DOMString;
-_t.MessageAttachmentId = _t.DOMString;
-_t.MessageConvId = _t.DOMString;
-_t.MessageFolderId = _t.DOMString;
-_t.MessageServiceArraySuccessCallback = _t.Function;
-_t.MessageRecipientsCallback = _t.Function;
-_t.MessageBodySuccessCallback = _t.Function;
-_t.MessageAttachmentSuccessCallback = _t.Function;
-_t.MessageArraySuccessCallback = _t.Function;
-_t.MessageConversationArraySuccessCallback = _t.Function;
-_t.MessageFolderArraySuccessCallback = _t.Function;
+ t.PushManager("getRegistrationId", arguments);
-_t.MessageFolder = {
- id: _t.MessageFolderId,
- parentId: _t.MessageFolderId,
- serviceId: _t.DOMString,
- contentType: _t.MessageServiceTag,
- name: _t.DOMString,
- path: _t.DOMString,
- type: _t.DOMString,
- synchronizable: _t.boolean,
+ appService = _data.service[_getCurrentApplicationId()];
+ if (!appService || !appService.isRegistered) {
+ return null;
+ }
- _optional: {
- // nullable
- parentId: true
+ return appService.registrationId;
}
-};
-_t.MessagesChangeCallback = {
- messagesadded: _t.Callback,
- messagesupdated: _t.Callback,
- messagesremoved: _t.Callback
-};
+ function handleSubFeatures(subFeatures) {
+ var i, subFeature;
-_t.MessageConversationsChangeCallback = {
- conversationsadded: _t.Callback,
- conversationsupdated: _t.Callback,
- conversationsremoved: _t.Callback
-};
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
-_t.MessageFoldersChangeCallback = {
- foldersadded: _t.Callback,
- foldersupdated: _t.Callback,
- foldersremoved: _t.Callback
+ push = {
+ registerService: registerService,
+ unregisterService: unregisterService,
+ connectService: connectService,
+ disconnectService: disconnectService,
+ getRegistrationId: getRegistrationId,
+ handleSubFeatures: handleSubFeatures
+ };
+
+ return push;
};
-/*
- * Network Bearer Selection
- */
+_initialize();
-_t.NetworkSuccessCallback = {
- onsuccess: _t.Callback,
- ondisconnected: _t.Callback
+PushMessage = function (pushMessageInitDict) {
+ var appData, alertMessage, date;
+
+ this.__defineGetter__("appData", function () {
+ return appData;
+ });
+
+ this.__defineGetter__("alertMessage", function () {
+ return alertMessage;
+ });
+
+ this.__defineGetter__("date", function () {
+ return date;
+ });
+
+ appData = pushMessageInitDict.appData || "";
+ alertMessage = pushMessageInitDict.alertMessage || "";
+ date = pushMessageInitDict.date || new Date();
};
+module.exports = _self;
+
+});
+define('ripple/platform/tizen/2.0/routeBackend_navigation', function (require, exports, module) {
/*
- * NFC
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
*/
-_t.NDEFMessageReadCallback = _t.Function;
-_t.ByteArraySuccessCallback = _t.Function;
+var tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
+ lbs_utils = require('ripple/platform/tizen/2.0/lbs_utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
+ RouteWaypoint,
+ RouteDistance,
+ RouteDuration,
+ RouteStep,
+ RouteSegment,
+ RouteRequestOptions,
+ RouteResultSummary,
+ RouteResult,
+ _data = {
+ positionDistance: {},
+ positionDuration: {},
+ routeProvider: {},
+ routes: [],
+ RouteDistanceUnit: ["M", "KM", "MI", "FT"],
+ providers: [],
+ path: []
+ },
+ _self;
-_t.NFCTagDetectCallback = {
- onattach: _t.Callback,
- ondetach: _t.Callback
+// The RouteWaypoint object
+RouteWaypoint = function () {
+ return {
+ position: {
+ latitude: 0,
+ longitude: 0
+ },
+ isStopover: true
+ };
};
-_t.NFCPeerDetectCallback = {
- onattach: _t.Callback,
- ondetach: _t.Callback
+// The RouteDistance object
+RouteDistance = function () {
+ return {
+ text : "Distance",
+ value : "0",
+ unit : "KM "
+ };
};
-_t.NDEFRecordText = {
- text: _t.DOMString,
- languageCode: _t.DOMString,
- encoding: _t.NDEFRecordTextEncoding
+// The RouteDuration object
+RouteDuration = function () {
+ return {
+ text : "Duration",
+ value : "0" // The duration in a seconds
+ };
};
-_t.NDEFRecordURI = {
- uri: _t.DOMString
-};
+// The RouteStep object
+RouteStep = function () {
+ var _self = {
+ mode: "", // The way of the travel, for example: car, bike, foot
+ instruction: "", // The instruction of this step
+ points: [] // The points of this step
+ };
-_t.NDEFRecordMedia = {
- mimeType: _t.DOMString
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.distance = new RouteDistance();
+ _self.duration = new RouteDuration();
+
+ return _self;
};
+// The RouteSegment object
+RouteSegment = function () {
+ var _self = {
+ steps: []
+ };
-_t.NDEFRecord = {
- tnf: _t.short,
- type: [_t.byte],
- id: [_t.byte],
- payload: [_t.byte],
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.distance = new RouteDistance();
+ _self.duration = new RouteDuration();
- _derived: [_t.NDEFRecordText, _t.NDEFRecordURI, _t.NDEFRecordMedia]
+ return _self;
};
-_t.NDEFMessage = {
- recordCount: _t.long,
- records: [_t.NDEFRecord],
- toByte: _t.Function
+// The RouteRequestOptions object
+RouteRequestOptions = function () {
+ return {
+ mode: "", // CAR, BIKE
+ unit: "KM",
+ routeGoal: "SHORTEST",
+ constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
+ wayPoints: [],
+ maxResults: 1
+ };
};
-/*
- * Notification
- */
+// The RouteResultSummary object
+RouteResultSummary = function () {
+ var _self = {};
-_t.NotificationId = _t.DOMString;
+ _self.origin = new SimpleCoordinates(0, 0);
+ _self.destination = new SimpleCoordinates(0, 0);
+ _self.totalDistance = new RouteDistance();
+ _self.totalDuration = new RouteDuration();
-_t.NotificationDetailInfo = {
- mainText: _t.DOMString,
- subText: _t.DOMString,
+ return _self;
+};
- _optional: {
- // nullable
- subText: true
- }
+// The RouteResult object
+RouteResult = function () {
+ var _self, jsonStr, jsonObj;
+ jsonObj = {
+ "type" : "Point",
+ "coordinates" : []
+ };
+ jsonStr = JSON.stringify(jsonObj);
+ _self = {
+ segments : [],
+ toGeoJSON : function () {
+ return jsonStr;
+ }
+ };
+ _self.summary = new RouteResultSummary();
+ return _self;
};
-_t.StatusNotificationInit = {
- content: _t.DOMString,
- iconPath: _t.DOMString,
- soundPath: _t.DOMString,
- vibration: _t.boolean,
- appControl: _t.ApplicationControl,
- appId: _t.ApplicationId,
- progressType: _t.NotificationProgressType,
- progressValue: _t.unsigned_long,
- number: _t.long,
- subIconPath: _t.DOMString,
- detailInfo: [_t.NotificationDetailInfo],
- ledColor: _t.DOMString,
- ledOnPeriod: _t.unsigned_long,
- ledOffPeriod: _t.unsigned_long,
- backgroundImagePath: _t.DOMString,
- thumbnails: [_t.DOMString],
+function calcDegree(distance) {
+ return distance * Math.PI / 180.0;
+}
- _dictionary: null
-};
+//calcute the distance
+function calculateDistance(lat1, lat2, lon1, lon2) {
+ var R = 6371, dLat, dLon, a, c, distance; // km
+ dLat = calcDegree(parseFloat(lat2) - parseFloat(lat1));
+ dLon = calcDegree(parseFloat(lon2) - parseFloat(lon1));
-_t.StatusNotification = {
- statusType: _t.StatusNotificationType,
- iconPath: _t.DOMString,
- subIconPath: _t.DOMString,
- number: _t.long,
- detailInfo: [_t.NotificationDetailInfo],
- ledColor: _t.DOMString,
- ledOnPeriod: _t.unsigned_long,
- ledOffPeriod: _t.unsigned_long,
- backgroundImagePath: _t.DOMString,
- thumbnails: [_t.DOMString],
- soundPath: _t.DOMString,
- vibration: _t.boolean,
- appControl: _t.ApplicationControl,
- appId: _t.ApplicationId,
- progressType: _t.NotificationProgressType,
- progressValue: _t.unsigned_long,
+ lat1 = calcDegree(lat1);
+ lat2 = calcDegree(lat2);
- _optional: {
- // nullable
- iconPath: true,
- subIconPath: true,
- number: true,
- detailInfo: true,
- ledColor: true,
- backgroundImagePath: true,
- thumbnails: true,
- soundPath: true,
- appControl: true,
- appId: true,
- progressValue: true
- }
-};
+ a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
+ Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
+ c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+ distance = R * c;
+ return distance;
+}
-_t.Notification = {
- id: _t.NotificationId,
- type: _t.NotificationType,
- postedTime: _t.Date,
- title: _t.DOMString,
- content: _t.DOMString,
+function calculateDuration(mode, distance) {
+ var duration, v;
+ switch (mode) {
+ case "motorcar" :
+ v = 50;
+ duration = distance / v;
+ break;
+ case "bicycle" :
+ v = 20;
+ duration = distance / v;
+ break;
+ case "foot" :
+ v = 5;
+ duration = distance / v;
+ break;
+ default:
+ duration = 0;
+ }
+ return duration;
+}
- _optional: {
- // nullable
- id: true,
- postedTime: true,
- content: true
- },
+function optimalWay(points, mode) {
+ var steps = [], startLatitude, startLongitude, originLocation, endLatitude, endLongitude,
+ destinationLocation, step, distance, i, routeDistance, routeDuration;
+ for (i = 0;i < points.length - 1;i++) {
+ startLatitude = points[i].lat;
+ startLongitude = points[i].lon;
+ originLocation = new SimpleCoordinates(startLatitude, startLongitude);
+ endLatitude = points[i + 1].lat;
+ endLongitude = points[i + 1].lon;
+ destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);
+ step = new RouteStep();
+ step.origin = originLocation;
+ step.destination = destinationLocation;
+ distance = calculateDistance(startLatitude, endLatitude, startLongitude, endLongitude);
+ routeDistance = new RouteDistance();
+ routeDistance.value = distance;
+ routeDistance.unit = "km";
+ step.distance = routeDistance;
+ routeDuration = new RouteDuration();
+ routeDuration.value = calculateDuration(mode, distance);
+ step.duration = routeDuration;
+ steps.push(step);
+ }
+ return steps;
+}
- _derived: [_t.StatusNotification]
-};
+function existInSupports(str, array) {
+ for (var i in array) {
+ if (str === array[i]) {
+ return true;
+ }
+ }
+ return false;
+}
-/*
- * Push
- */
+function navigation(searchStr, flat, flon, tlat, tlon, v, fast) {
+ var positions = [];
-_t.PushRegistrationId = _t.DOMString;
-_t.PushRegisterSuccessCallback = _t.Function;
-_t.PushNotificationCallback = _t.Function;
+ _data.positionDistance = {};
+ _data.positionDuration = {};
+ jQuery.ajax({
+ type : "get",
+ async : false,
+ url : searchStr,
+ data : {
+ flat : flat,
+ flon : flon,
+ tlat : tlat,
+ tlon : tlon,
+ v : v,
+ fast : fast,
+ layer : 'mapnik',
+ format : "geojson"
+ },
+ contentType : "application/json; charset=utf-8",
+ dataType : "json",
+ cache : false,
+ success : function (data) {
+ $.each(data.coordinates, function (i, item) {
+ var point = {};
+ point.lon = item[0];
+ point.lat = item[1];
+ positions.push(point);
+ });
+ $.each(data.properties, function (i, item) {
+ if (typeof item === "number") {
+ _data.positionDistance = new RouteDistance();
+ _data.positionDistance.value = item;
+ _data.positionDistance.unit = "km";
+ _data.positionDuration = new RouteDuration();
+ _data.positionDuration.value = calculateDuration(v, item);
+ }
+ });
+ },
+ error : function (errorCB) {
+ if (errorCB) {
+ setTimeout(function () {
+ errorCB(new WebAPIError(errorcode.NETWORK_ERR));
+ }, 1);
+ }
+ }
+ });
+ return positions;
+}
-/*
- * Package
- */
-_t.PackageId = _t.DOMString;
-_t.PackageInformationArraySuccessCallback = _t.Function;
+function filterWaypoints(routeWaypoints) {
+ var mathWaypoints = [], i;
+ for (i in routeWaypoints) {
+ if (routeWaypoints[i].position.latitude !== "" &&
+ routeWaypoints[i].position.latitude !== undefined &&
+ routeWaypoints[i].position.latitude !== null &&
+ routeWaypoints[i].position.longitude !== null &&
+ routeWaypoints[i].position.longitude !== "" &&
+ routeWaypoints[i].position.longitude !== undefined) {
+ mathWaypoints.push(routeWaypoints[i]);
+ }
+ }
+ return mathWaypoints;
+}
-_t.PackageProgressCallback = {
- onprogress: _t.Callback,
- oncomplete: _t.Callback
-};
+module.exports = function (prop) {
+ var _self = new lbs_utils.LocationServiceProvider(prop);
-_t.PackageInfomationEventCallback = {
- oninstalled: _t.Callback,
- onupdated: _t.Callback,
- onuninstalled: _t.Callback
-};
+ _self.supportedGoals = ["SHORTEST", "FASTEST", "MOST_SCENIC", "SIMPLEST", "CHEAPEST", "SAFEST" ];
+ _self.supportedModes = ["motorcar", "bicycle", "foot"];
+ _self.supportedConstraints = ["HIGHWAY", "TOLL", "UNPAVED", "BORDER", "GRAVEL_PAVING", "TUNNEL", "BRIDGE", "LEFT_TURN", "CARPOOL", "HAZARDOUS_CARGO" ];
+ _self.supportsWayPoints = true;
+ _self.find = function (origin, destination, successCallback, errorCallback, options) {
+ function _find() {
+ var flat, flon, tlat, tlon, v, fast, searchStr, result,
+ routeWaypoints = [],
+ segmentPositions = [],
+ positions = [],
+ segments = [],
+ totalDistances = 0, totalDurations = 0,
+ k, key, segment, startPosition, endPosition,
+ summary, distance, duration;
-/*
- * System Info
- */
+ v = options.mode;
+ //init
+ if (!existInSupports(v, _self.supportedModes)) {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ }
+ if (!existInSupports(options.routeGoal, _self.supportedGoals)) {
+ throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
+ }
+ switch (options.routeGoal) {
+ case "SHORTEST":
+ fast = 0;
+ break;
-_t.SystemInfoPropertySuccessCallback = _t.Callback;
+ case "FASTEST":
+ fast = 1;
+ break;
-_t.SystemInfoOptions = {
- timeout: _t.unsigned_long,
- highThreshold: _t.double,
- lowThreshold: _t.double,
+ case "SIMPLEST":
+ break;
- _dictionary: null
-};
+ case "MOST_SCENIC":
+ break;
-/*
- * System Setting
- */
+ case "CHEAPEST":
+ break;
-_t.SystemSettingSuccessCallback = _t.Function;
+ case "SAFEST":
+ break;
-/*
- * Vehicle
- */
-_t.SupportedPropertiesSuccessCallback = _t.Function;
+ default:
+ fast = 0;
+ }
+ searchStr = "http://www.yournavigation.org/api/dev/gosmore.php";
+ routeWaypoints = options.wayPoints;
+ routeWaypoints = filterWaypoints(routeWaypoints);
+ segmentPositions.push(origin);
-_t.VehiclePropertyErrorCallback = _t.Function;
+ if (routeWaypoints.length > 0) {
+ for (k in routeWaypoints) {
+ segmentPositions.push(routeWaypoints[k].position);
+ }
+ }
+ segmentPositions.push(destination);
-/*
- * Constructor list definition
- */
+ for (key = 0; key < segmentPositions.length - 1; key++) {
+ segment = new RouteSegment();
+ startPosition = segmentPositions[key];
+ endPosition = segmentPositions[key + 1];
+ segment.origin = startPosition;
+ segment.destination = endPosition;
+ flat = startPosition.latitude;
+ flon = startPosition.longitude;
+ tlat = endPosition.latitude;
+ tlon = endPosition.longitude;
+ positions = navigation(searchStr, flat, flon, tlat, tlon, v, fast);
+ segment.steps = optimalWay(positions, v);
+ segment.distance = _data.positionDistance;
+ totalDistances += _data.positionDistance.value;
+ segment.duration = _data.positionDuration;
+ totalDurations += _data.positionDuration.value;
+ segments.push(segment);
+ }
+ result = new RouteResult();
+ summary = new RouteResultSummary();
+ summary.origin = segmentPositions[0];
+ summary.destination = segmentPositions[segmentPositions.length - 1];
+ distance = new RouteDistance();
+ distance.value = totalDistances;
+ distance.unit = "km";
+ summary.totalDistance = distance;
+ duration = new RouteDuration();
+ duration.value = totalDurations;
+ summary.totalDuration = duration;
+ result.segments = segments;
+ result.summary = summary;
+ successCallback(result);
+ }
-/*
- * Generic constructor
- * Construct a prototype of constructor. A fake array of arguments type is
- * specified for constructor.
- *
- * Overloaded constructors
- * Construct an array of prototype of constructor. Each array element is
- * specified for one of constructors. The constructor with extra arguments
- * are recommended to be defined ahead of the one with fewer same arguments
- * for exact match.
- */
+ tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
+ };
-_c = {
- // Alarm
- AlarmAbsolute: [],
+ return _self;
+};
- // Calendar
- CalendarTask: [],
- CalendarEvent: [],
- CalendarAlarm: [],
+});
+define('ripple/platform/tizen/2.0/GeocodeOptions', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
+ */
- // Contact
- Contact: [],
+var errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
+ SortMode = require('ripple/platform/tizen/2.0/SortMode');
- // NFC
- NDEFMessage: [],
- NDEFRecord: [],
+module.exports = function (_sortMode, _maxResults) {
+ var _self;
+ if (_sortMode !== null && _sortMode !== undefined) {
+ if (typeof _sortMode !== "object") {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ try {
+ new SortMode(_sortMode.attributeName, _sortMode.order);
+ } catch (e) {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ }
+ if (_maxResults !== null && _maxResults !== undefined) {
+ if (typeof _maxResults !== "number") {
+ throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ }
- // Data Synchronization
- SyncInfo: [],
+ _self = {
+ sortMode : _sortMode,
+ maxResults : _maxResults || 0
+ };
- // Time
- TZDate: []
+ return _self;
};
+
+});
+define('ripple/platform/tizen/2.0/tizen1_utils', function (require, exports, module) {
/*
- * Common
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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.
*/
-// AttributeFilter
-_c.AttributeFilter = {
- 0: _t.DOMString,
- 1: _t.FilterMatchFlag,
- 2: _t.any,
-
- _optional: {
- 1: true,
- 2: true
- }
-};
-
-// AttributeRangeFilter
-_c.AttributeRangeFilter = {
- 0: _t.DOMString,
- 1: _t.any,
- 2: _t.any,
+var self,
+ utils = require('ripple/utils'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');
- _optional: {
- 1: true,
- 2: true
- }
-};
+self = module.exports = {
+ _wac2_regexSanitize: function (regexString) {
+ var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
+ return regexString.replace("^", "\\^")
+ .replace("$", "\\$")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ .replace("<", "\\<")
+ .replace("[", "\\[")
+ .replace("{", "\\{")
+ .replace(/\\([^%])/, "\\\\$1") /* don't replace \\% */
+ .replace("|", "\\|")
+ .replace(">", "\\>")
+ .replace(".", "\\.")
+ .replace("*", "\\*")
+ .replace("+", "\\+")
+ .replace("?", "\\?")
+ .replace(escapePattern, "$1.*") /* replace % with .* */
+ .replace(percentPattern, "%"); /* strip excape of % */
+ },
-// CompositeFilter
-_c.CompositeFilter = {
- 0: _t.CompositeFilterType,
- 1: [_t.AbstractFilter],
+ isValidDate: function (d) {
+ if (Object.prototype.toString.call(d) !== "[object Date]")
+ return false;
+ return !isNaN(d.getTime());
+ },
+ isValidTZDate: function (d) {
+ if (d && (d instanceof tizen.TZDate)) {
+ return true;
+ }
+ return false;
+ },
+ isValidArray: function (a) {
+ return (Object.prototype.toString.call(a) === "[object Array]");
+ },
- _optional: {
- 1: true
- }
-};
+ matchOptionArrayString: function (src, attr, pattern) {
+ /* src.obj[attr] is a StringArray */
+ var _pattern, re, _stringMatch;
+ _pattern = this._wac2_regexSanitize(pattern);
+ re = new RegExp("^" + _pattern + "$", "i");
-// SortMode
-_c.SortMode = {
- 0: _t.DOMString,
- 1: _t.SortModeOrder,
+ _stringMatch = function (obj, index) {
+ if (pattern.search(/^%*$/i) === 0)
+ return true;
+ if (obj[attr] === undefined || obj[attr] === null)
+ return false;
+ return obj[attr].some(function (f) {
+ return f.search(re) !== -1;
+ });
+ };
+ return utils.filter(src, _stringMatch);
+ },
- _optional: {
- 1: true
- }
-};
+ matchAttributeBooleanFilter: function (src, attr, value) {
+ // only support EXACTLY matchFlag
+ var _booleanMatch, atr = attr.split(".");
-// SimpleCoordinates
-_c.SimpleCoordinates = {
- 0: _t.double,
- 1: _t.double
-};
+ if (atr.length === 2) {
+ _booleanMatch = function (obj, index) {
+ if (!obj[atr[0]])
+ return false;
-/*
- * Alarm
- */
+ return (obj[atr[0]][atr[1]] === value);
+ };
+ } else {
+ _booleanMatch = function (obj, index) {
+ return (obj[attr] === value);
+ };
+ }
-// AlarmRelative
-_c.AlarmRelative = {
- 0: _t.long,
- 1: _t.long,
+ return utils.filter(src, _booleanMatch);
+ },
- _optional: {
- 1: true
- }
-};
+ matchAttributeArrayFilter: function (src, attr, matchFlag, value) {
+ var _re, _arrayMatch, atr = attr.split("."), _existMatch;
-// AlarmAbsolute
-_c.AlarmAbsolute[0] = {
- 0: _t.Date,
- 1: [_t.ByDayValue]
-};
+ if (atr.length === 2) {
+ _existMatch = function (obj, index) {
+ if (!obj[atr[0]])
+ return false;
-_c.AlarmAbsolute[1] = {
- 0: _t.Date,
- 1: _t.long
-};
+ return (obj[atr[0]][atr[1]] !== undefined);
+ };
+ } else {
+ _existMatch = function (obj, index) {
+ return (obj[attr] !== undefined);
+ };
+ }
-_c.AlarmAbsolute[2] = {
- 0: _t.Date
-};
+ if (value === undefined || value === null) {
+ return utils.filter(src, _existMatch);
+ }
-/*
- * Application
- */
+ switch (matchFlag)
+ {
+ case "EXACTLY":
+ _re = new RegExp("^" + value + "$");
+ break;
+ case "FULLSTRING":
+ _re = new RegExp("^" + value + "$", "i");
+ break;
+ case "CONTAINS":
+ _re = new RegExp(value, "i");
+ break;
+ case "STARTSWITH":
+ _re = new RegExp("^" + value, "i");
+ break;
+ case "ENDSWITH":
+ _re = new RegExp(value + "$", "i");
+ break;
+ case "EXISTS":
+ return utils.filter(src, _existMatch);
+ default:
+ return [];
+ }
-// ApplicationControlData
-_c.ApplicationControlData = {
- 0: _t.DOMString,
- 1: [_t.DOMString]
-};
+ if (atr.length === 2) {
+ _arrayMatch = function (obj, index) {
+ if (!obj[atr[0]])
+ return false;
-// ApplicationControl
-_c.ApplicationControl = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.DOMString,
- 4: [_t.ApplicationControlData],
+ return (obj[atr[0]][atr[1]] && obj[atr[0]][atr[1]].some(function (o) {
+ return (o.search(_re) !== -1);
+ }));
+ };
+ } else {
+ _arrayMatch = function (obj, index) {
+ return (obj[attr] && obj[attr].some(function (o) {
+ return (o.search(_re) !== -1);
+ }));
+ };
+ }
- _optional: {
- 1: true,
- 2: true,
- 3: true,
- 4: true
- }
-};
+ return utils.filter(src, _arrayMatch);
+ },
-/*
- * Bookmark
- */
+ matchAttributeRangeFilter: function (src, attr, low, high) {
+ var _rangeMatch, atr = attr.split(".");
-// BookmarkItem
-_c.BookmarkItem = {
- 0: _t.DOMString,
- 1: _t.DOMString
-};
+ if (atr.length === 2) {
+ _rangeMatch = function (obj, index) {
+ var matched = true;
-// BookmarkFolder
-_c.BookmarkFolder = {
- 0: _t.DOMString
-};
+ if (!obj[atr[0]])
+ return false;
-/*
- * Calendar
- */
+ if (low !== null && low !== undefined) {
+ matched = (obj[atr[0]][atr[1]] >= low);
+ }
+ if (matched && (high !== null && high !== undefined)) {
+ matched = (obj[atr[0]][atr[1]] <= high);
+ }
+ return matched;
+ };
+ } else {
+ _rangeMatch = function (obj, index) {
+ var matched = true;
-// CalendarTask
-_c.CalendarTask[0] = {
- 0: _t.CalendarTaskInit,
+ if (low !== null && low !== undefined) {
+ matched = (obj[attr] >= low);
+ }
+ if (matched && (high !== null && high !== undefined)) {
+ matched = (obj[attr] <= high);
+ }
+ return matched;
+ };
+ }
+ return utils.filter(src, _rangeMatch);
+ },
- _optional: {
- // nullable
- 0: true
- }
-};
+ matchAttributeFilter: function (src, attr, matchFlag, value) {
+ var _re, _stringMatch, atr = attr.split("."),
+ _existMatch;
-_c.CalendarTask[1] = {
- 0: _t.DOMString,
- 1: _t.CalendarTextFormat
-};
+ if (atr.length === 2) {
+ _existMatch = function (obj, index) {
+ if (!obj[atr[0]])
+ return false;
-// CalendarEvent
-_c.CalendarEvent[0] = {
- 0: _t.CalendarEventInit,
+ return (obj[atr[0]][atr[1]] !== undefined);
+ };
+ } else {
+ _existMatch = function (obj, index) {
+ return (obj[attr] !== undefined);
+ };
+ }
- _optional: {
- // nullable
- 0: true
- }
-};
+ if (value === undefined || value === null) {
+ return utils.filter(src, _existMatch);
+ }
-_c.CalendarEvent[1] = {
- 0: _t.DOMString,
- 1: _t.CalendarTextFormat
-};
+ switch (matchFlag)
+ {
+ case "EXACTLY":
+ _re = new RegExp("^" + value + "$");
+ break;
+ case "FULLSTRING":
+ _re = new RegExp("^" + value + "$", "i");
+ break;
+ case "CONTAINS":
+ _re = new RegExp(value, "i");
+ break;
+ case "STARTSWITH":
+ _re = new RegExp("^" + value, "i");
+ break;
+ case "ENDSWITH":
+ _re = new RegExp(value + "$", "i");
+ break;
+ case "EXISTS":
+ return utils.filter(src, _existMatch);
+ default:
+ return [];
+ }
+ if (atr.length === 2) {
+ _stringMatch = function (obj, index) {
+ if (!obj[atr[0]])
+ return false;
-// CalendarAttendee
-_c.CalendarAttendee = {
- 0: _t.DOMString,
- 1: _t.CalendarAttendeeInit,
+ if (matchFlag === "EXACTLY") {
+ return (obj[atr[0]][atr[1]] === value);
+ } else if (typeof obj[atr[0]][atr[1]] !== 'string') {
+ return false;
+ }
- _optional: {
- 1: true
- }
-};
+ return (obj[atr[0]][atr[1]].search(_re) !== -1);
+ };
+ } else {
+ _stringMatch = function (obj, index) {
+ if (matchFlag === "EXACTLY") {
+ return (obj[attr] === value);
+ } else if (typeof obj[attr] !== 'string') {
+ return false;
+ }
-// CalendarRecurrenceRule
-_c.CalendarRecurrenceRule = {
- 0: _t.RecurrenceRuleFrequency,
- 1: _t.CalendarRecurrenceRuleInit,
+ return (obj[attr].search(_re) !== -1);
+ };
+ }
+ return utils.filter(src, _stringMatch);
+ },
- _optional: {
- 1: true
- }
-};
+ matchOptionString: function (src, attr, pattern) {
+ /* src.obj[attr] is a string */
+ var _stringMatch, _pattern, _re;
+ _pattern = this._wac2_regexSanitize(pattern);
+ _re = new RegExp("^" + _pattern + "$", "mi");
-// CalendarEventId
-_c.CalendarEventId = {
- 0: _t.DOMString,
- 1: _t.DOMString,
+ _stringMatch = function (obj, index) {
+ return (obj[attr].search(_re) !== -1);
+ };
+ return utils.filter(src, _stringMatch);
+ },
- _optional: {
- 1: true
- }
-};
+ matchOptionDate: function (src, attr, filterStart, filterEnd) {
+ var _dateMatch;
+ _dateMatch = function (obj, index) {
+ var matched = true, valueDate = obj[attr];
-// CalendarAlarm
-_c.CalendarAlarm[0] = {
- 0: _t.TZDate,
- 1: _t.AlarmMethod,
- 2: _t.DOMString,
+ if (filterStart !== undefined && filterStart !== null) {
+ matched = (valueDate.getTime() >= filterStart.getTime());
+ }
+ if (matched && (filterEnd !== undefined && filterEnd !== null)) {
+ matched = (valueDate.getTime() <= filterEnd.getTime());
+ }
+ return matched;
+ };
+ return utils.filter(src, _dateMatch);
+ },
- _optional: {
- 2: true
- }
-};
+ matchOptionShortArray: function (src, attr, filterArray) {
+ /* src.obj[attr] is a short, filterArray is an array
+ i.e. find status is [CONFRIMED or TENTATIVE] */
+ var arraySome = function (obj, index) {
+ return filterArray.some(function (f) {
+ return f === obj[attr];
+ });
+ };
+ return utils.filter(src, arraySome);
+ },
-_c.CalendarAlarm[1] = {
- 0: _t.TimeDuration,
- 1: _t.AlarmMethod,
- 2: _t.DOMString,
+ validateArgumentType: function (arg, argType, errorObj) {
+ var invalidArg = false;
- _optional: {
- 2: true
- }
-};
+ switch (argType) {
+ case "array":
+ if (!arg instanceof Array) {
+ invalidArg = true;
+ }
+ break;
+ case "date":
+ if (!arg instanceof Date) {
+ invalidArg = true;
+ }
+ break;
+ case "integer":
+ if (typeof Number(arg) !== "number" || Number(arg) !== Math.floor(arg)) {
+ invalidArg = true;
+ }
+ break;
+ default:
+ if (typeof arg !== argType) {
+ invalidArg = true;
+ }
+ break;
+ }
-/*
- * Contact
- */
+ if (invalidArg) {
+ throw errorObj;
+ }
+ },
-// Contact
-_c.Contact[0] = {
- 0: _t.ContactInit,
+ validateCallbackType: function (successCallback, errorCallback) {
+ if (successCallback) {
+ this.validateArgumentType(successCallback, "function",
+ new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (errorCallback) {
+ this.validateArgumentType(errorCallback, "function",
+ new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
+ },
- _optional: {
- 0: true
- }
-};
+ validateEqualArrays: function (arrayOne, arrayTwo) {
+ var isEqual = false, i;
-_c.Contact[1] = {
- 0: _t.DOMString
-};
+ if (Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
+ Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
+ arrayOne.length === arrayTwo.length) {
+ isEqual = true;
+ for (i in arrayOne) {
+ if (arrayOne[i] !== arrayTwo[i]) {
+ isEqual = false;
+ break;
+ }
+ }
+ }
+ return isEqual;
+ },
-// ContactRef
-_c.ContactRef = {
- 0: _t.AddressBookId,
- 1: _t.ContactId
-};
+ validateTypeMismatch: function (onSuccess, onError, name, callback) {
-// ContactName
-_c.ContactName = {
- 0: _t.ContactNameInit,
+ if (onSuccess === undefined || onSuccess === null) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
+ this.validateArgumentType(onSuccess, "function",
+ new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ if (onError !== null && onError !== undefined) {
+ this.validateArgumentType(onError, "function",
+ new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
+ }
- _optional: {
- 0: true
- }
-};
+ return callback && callback();
+ },
-// ContactOrganization
-_c.ContactOrganization = {
- 0: _t.ContactOrganizationInit,
+ isEmptyObject: function (obj) {
+ var prop;
- _optional: {
- 0: true
- }
-};
+ for (prop in obj) {
+ return false;
+ }
+ return true;
+ },
-// ContactWebSite
-_c.ContactWebSite = {
- 0: _t.DOMString,
- 1: _t.DOMString,
+ arrayComposite: function (mode, arrayA, arrayB) {
+ var combinedArray = arrayA.concat(arrayB),
+ intersectionArray = arrayA.filter(function (value) {
+ if (utils.arrayContains(arrayB, value)) {
+ return true;
+ }
- _optional: {
- 1: true
- }
-};
+ return false;
+ });
-// ContactAnniversary
-_c.ContactAnniversary = {
- 0: _t.Date,
- 1: _t.DOMString,
+ switch (mode) {
+ case "AND":
+ case "INTERSECTION":
+ return intersectionArray;
+ case "OR":
+ case "UNION":
+ return intersectionArray.concat(combinedArray.filter(function (value) {
+ if (utils.arrayContains(intersectionArray, value)) {
+ return false;
+ }
- _optional: {
- 1: true
- }
-};
+ return true;
+ }));
+ default:
+ return undefined;
+ }
+ },
-// ContactAddress
-_c.ContactAddress = {
- 0: _t.ContactAddressInit,
+ isEqual: function (srcObj, aimObj) {
+ var i;
- _optional: {
- 0: true
- }
-};
+ if (typeof srcObj !== typeof aimObj) {
+ return false;
+ }
-// ContactPhoneNumber
-_c.ContactPhoneNumber = {
- 0: _t.DOMString,
- 1: [_t.DOMString],
- 2: _t.boolean,
+ if (srcObj === null || srcObj === undefined || typeof srcObj === 'number' ||
+ typeof srcObj === 'string' || typeof srcObj === 'boolean') {
+ return srcObj === aimObj;
+ }
- _optional: {
- 1: true,
- 2: true
- }
-};
+ for (i in srcObj) {
+ if (!aimObj.hasOwnProperty(i) || !self.isEqual(srcObj[i], aimObj[i])) {
+ return false;
+ }
+ }
-// ContactEmailAddress
-_c.ContactEmailAddress = {
- 0: _t.DOMString,
- 1: [_t.DOMString],
- 2: _t.boolean,
+ return true;
+ },
- _optional: {
- 1: true,
- 2: true
- }
-};
+ query: function (objects, filter, sortMode, count, offset) {
+ function isCompositeFilter(filter) {
+ return (filter.type) ? true : false;
+ }
-// ContactGroup
-_c.ContactGroup = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
+ function isAttributeFilter(filter) {
+ return (filter.matchFlag) ? true : false;
+ }
- _optional: {
- 1: true,
- 2: true
- }
-};
+ function getValue(obj, key) {
+ var keys = key.split("."),
+ value = obj[keys[0]],
+ i;
-/*
- * Data Synchronization
- */
+ for (i = 1; i < keys.length; i++) {
+ if (value[keys[i]]) {
+ value = value[keys[i]];
+ }
+ }
-// SyncInfo
-_c.SyncInfo[0] = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.SyncMode,
- 4: _t.SyncType
-};
+ return value;
+ }
-_c.SyncInfo[1] = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.SyncMode,
- 4: _t.SyncInterval
-};
+ function _filter(objects, filter) {
+ var i, results, eachResult, filterFunc;
-_c.SyncInfo[2] = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.SyncMode
-};
+ if (isCompositeFilter(filter)) {
+ for (i in filter.filters) {
+ eachResult = _filter(objects, filter.filters[i]);
+ results = (results === undefined) ? eachResult : self.arrayComposite(filter.type, results, eachResult);
+ }
+ return results;
+ }
-// SyncServiceInfo
-_c.SyncServiceInfo = {
- 0: _t.boolean,
- 1: _t.SyncServiceType,
- 2: _t.DOMString,
- 3: _t.DOMString,
- 4: _t.DOMString,
+ if (isAttributeFilter(filter)) {
+ for (i in objects) {
+ if (filter.attributeName in objects[i])
+ break;
+ }
+ filterFunc = self.isValidArray(objects[i][filter.attributeName]) ? self.matchAttributeArrayFilter : self.matchAttributeFilter;
+ results = filterFunc(objects, filter.attributeName, filter.matchFlag, filter.matchValue);
+ } else {
+ results = self.matchAttributeRangeFilter(objects, filter.attributeName, filter.initialValue, filter.endValue);
+ }
- _optional: {
- 3: true,
- 4: true
- }
-};
+ return results;
+ }
-// SyncProfileInfo
-_c.SyncProfileInfo = {
- 0: _t.DOMString,
- 1: _t.SyncInfo,
- 2: [_t.SyncServiceInfo],
+ function _sort(objects, sortMode) {
+ objects.sort(function (a, b) {
+ return (sortMode.order === "ASC") ?
+ (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
+ (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
+ });
- _optional: {
- 2: true
- }
-};
+ return objects;
+ }
-/*
- * Download
- */
+ var res = objects;
-// DownloadRequest
-_c.DownloadRequest = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.DownloadNetworkType,
- 4: _t.DownloadHTTPHeaderFields,
+ if (filter) {
+ res = _filter(res, filter);
+ }
- _optional: {
- 1: true,
- 2: true,
- 3: true,
- 4: true
- }
-};
+ if (sortMode) {
+ _sort(res, sortMode);
+ }
-/*
- * NFC
- */
+ if (offset || count) {
+ offset = (offset > 0) ? offset : 0;
+ res = (count > 0) ? res.slice(offset, offset + count) : res.slice(offset);
+ }
-// NDEFMessage
-_c.NDEFMessage[0] = {
- 0: [_t.NDEFRecord]
-};
+ return res;
+ },
-_c.NDEFMessage[1] = {
- 0: [_t.byte]
-};
+ copyString: function (str) {
+ var newStr, charConvert = [], i;
-_c.NDEFMessage[2] = null;
+ if (typeof str !== 'string') {
+ return str;
+ }
+ for (i = 0; i < str.length; i++) {
+ charConvert[i] = str.charAt(i);
+ }
+ newStr = charConvert.join("");
-// NDEFRecord
-_c.NDEFRecord[0] = {
- 0: _t.short,
- 1: [_t.byte],
- 2: [_t.byte],
- 3: [_t.byte],
+ return newStr;
+ },
- _optional: {
- 3: true
- }
-};
+ copy: function (obj) {
+ var i,
+ newObj = jQuery.isArray(obj) ? [] : {};
-_c.NDEFRecord[1] = {
- 0: [_t.byte]
-};
+ if (typeof obj === 'number' ||
+ typeof obj === 'string' ||
+ typeof obj === 'boolean' ||
+ obj === null ||
+ obj === undefined) {
+ return obj;
+ }
-// NDEFRecordText
-_c.NDEFRecordText = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DOMString,
+ if (obj instanceof Date) {
+ return new Date(obj);
+ }
- _optional: {
- 2: true
- }
-};
+ if (obj instanceof RegExp) {
+ return new RegExp(obj);
+ }
-// NDEFRecordURI
-_c.NDEFRecordURI = {
- 0: _t.DOMString
-};
+ for (i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (obj.__lookupGetter__(i)) {
+ newObj.__defineGetter__(i, (function (key) {
+ return function () {
+ return self.copy(obj[key]);
+ };
+ }(i)));
+ }
+ else {
+ newObj[i] = self.copy(obj[i]);
+ }
+ }
+ }
-// NDEFRecordMedia
-_c.NDEFRecordMedia = {
- 0: _t.DOMString,
- 1: [_t.byte]
+ return newObj;
+ }
};
+});
+define('ripple/platform/tizen/2.0/typecoerce', function (require, exports, module) {
/*
- * Notification
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-// StatusNotification
-_c.StatusNotification = {
- 0: _t.StatusNotificationType,
- 1: _t.DOMString,
- 2: _t.StatusNotificationInit,
+var t = require('ripple/platform/tizen/2.0/typedef'),
+ _self;
- _optional: {
- 2: true
- }
-};
+_self = function (pattern) {
+ var typeCoerce, typeOfPattern;
-// NotificationDetailInfo
-_c.NotificationDetailInfo = {
- 0: _t.DOMString,
- 1: _t.DOMString,
+ // private
+ function getExtendedType(val) {
+ var type = Object.prototype.toString.call(val), attr;
- _optional: {
- 1: true
- }
-};
+ switch (type) {
+ case "[object Array]":
+ if ((typeof val[0] === "string") && (val[0].length > 0)) {
+ type = "enum";
+ } else {
+ type = "Union";
+ }
+ return type;
-/*
- * Time
- */
+ case "[object Object]":
+ if ("_dictionary" in val) {
+ return "dictionary";
+ }
-// TZDate
-_c.TZDate[0] = {
- 0: _t.Date,
- 1: _t.DOMString,
+ type = "Object";
- _optional: {
- // nullable
- 0: true,
- 1: true
- }
-};
+ for (attr in val) {
+ if (attr === "0") {
+ type = "Arguments";
+ } else if (val[attr] === "Callback") {
+ type = "Callback";
+ }
+ break;
+ }
-_c.TZDate[1] = {
- 0: _t.long,
- 1: _t.long,
- 2: _t.long,
- 3: _t.long,
- 4: _t.long,
- 5: _t.long,
- 6: _t.long,
- 7: _t.DOMString,
+ return type;
+ }
- _optional: {
- // nullable
- 3: true,
- 4: true,
- 5: true,
- 6: true,
- 7: true
- }
-};
+ switch (val) {
+ case "Callback":
+ type = "Function";
+ break;
-// TimeDuration
-_c.TimeDuration = {
- 0: _t.long_long,
- 1: _t.TimeDurationUnit,
+ case "TZDate":
+ case "any":
+ case "byte":
+ case "float":
+ case "long":
+ case "long long":
+ case "octet":
+ case "short":
+ case "unsigned long":
+ case "unsigned long long":
+ case "unsigned short":
+ type = val;
+ break;
- _optional: {
- // nullable
- 1: true
- }
-};
+ case "double":
+ type = "float";
+ break;
-/*
- * Interface prototype definition
- */
+ default: // Derivative type name: e.g., "AbstractFilter"
+ type = "";
+ break;
+ }
-_i = {
- // Alarm
- AlarmManager: {},
+ return type;
+ }
- // Application
- ApplicationManager: {},
- Application: {},
- RequestedApplicationControl: {},
+ function getType(val, isPattern) {
+ var type = Object.prototype.toString.call(val);
- // Bluetooth
- BluetoothManager: {},
- BluetoothAdapter: {},
- BluetoothDevice: {},
- BluetoothSocket: {},
- BluetoothClass: {},
- BluetoothServiceHandler: {},
- BluetoothHealthProfileHandler: {},
- BluetoothHealthApplication: {},
- BluetoothHealthChannel: {},
+ switch (type) {
+ case "[object Array]":
+ type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
+ "Array";
+ break;
- // Bookmark
- BookmarkManager: {},
+ case "[object Arguments]":
+ type = "Arguments";
+ break;
- // Calendar
- CalendarManager: {},
- Calendar: {},
- CalendarItem: {},
- CalendarEvent: {},
+ case "[object Boolean]":
+ type = "boolean";
+ break;
- // Call History
- CallHistory: {},
+ case "[object Date]":
+ type = "Date";
+ break;
- // Contact
- ContactManager: {},
- AddressBook: {},
- Person: {},
- Contact: {},
+ case "[object Function]":
+ type = "Function";
+ break;
- // Content
- ContentManager: {},
+ case "[object Number]":
+ type = "Number";
+ break;
- // Data Control
- DataControlManager: {},
- SQLDataControlConsumer: {},
- MappedDataControlConsumer: {},
+ case "[object Object]":
+ type = isPattern ? getExtendedType(val) : "Object";
+ break;
- // Data Synchronization
- DataSynchronizationManager: {},
+ case "[object String]":
+ type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
+ break;
+ }
- // Download
- DownloadManager: {},
+ return type;
+ }
- // Network Bearer Selection
- NetworkBearerSelection: {},
+ function isConstructed(obj) {
+ if (!("_constructor" in pattern))
+ return true;
- // NFC
- NFCManager: {},
- NFCAdapter: {},
- NFCTag: {},
- NFCPeer: {},
- NDEFMessage: {},
+ if (obj instanceof window.tizen[pattern._constructor])
+ return true;
- // Notification
- NotificationManager: {},
+ return false;
+ }
- // Message
- Messaging: {},
- MessageService: {},
- MessageStorage: {},
+ function toInteger(x) {
+ return (x < 0) ? Math.ceil(x) : Math.floor(x);
+ }
- // Package
- PackageManager: {},
+ function modulo(a, b) {
+ return (a - Math.floor(a / b) * b);
+ }
- // Push
- PushManager: {},
+ function toInt(x, bits) {
+ var p;
- // System Info
- SystemInfo: {},
+ x = Number(x);
- // System Setting
- SystemSettingManager: {},
+ if (isNaN(x) || !isFinite(x))
+ return null;
- // Time
- TimeUtil: {},
- TZDate: {},
- TimeDuration: {},
+ p = Math.pow(2, bits);
+ x = modulo(toInteger(x), p);
- // Vehicle
- Vehicle: {}
-};
+ return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
+ }
-/*
- * Alarm
- */
+ function toUInt(x, bits) {
+ x = Number(x);
-// AlarmManager
-_i.AlarmManager.add = {
- 0: _t.Alarm,
- 1: _t.ApplicationId,
- 2: _t.ApplicationControl,
+ if (isNaN(x) || !isFinite(x))
+ return null;
- _optional: {
- 2: true
+ return modulo(toInteger(x), Math.pow(2, bits));
}
-};
-_i.AlarmManager.remove = {
- 0: _t.AlarmId
-};
+ function toInt8(x) {
+ return toInt(x, 8);
+ }
-_i.AlarmManager.removeAll = null;
+ function toInt16(x) {
+ return toInt(x, 16);
+ }
-_i.AlarmManager.get = {
- 0: _t.AlarmId
-};
+ function toInt32(x) {
+ return toInt(x, 32);
+ }
-_i.AlarmManager.getAll = null;
+ function toInt64(x) {
+ return toInt(x, 64);
+ }
-/*
- * Application
- */
+ function toUInt8(x) {
+ return toUInt(x, 8);
+ }
-// ApplicationManager
-_i.ApplicationManager.getCurrentApplication = null;
+ function toUInt16(x) {
+ return toUInt(x, 16);
+ }
-_i.ApplicationManager.kill = {
- 0: _t.ApplicationContextId,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ function toUInt32(x) {
+ return toUInt(x, 32);
+ }
- _optional: {
- 1: true,
- 2: true
+ function toUInt64(x) {
+ return toUInt(x, 64);
}
-};
-_i.ApplicationManager.launch = {
- 0: _t.ApplicationId,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ // public
+ function cast(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
- _optional: {
- 1: true,
- 2: true
- }
-};
+ typeMap = {
+ "Arguments": function () {
+ var i, isNullable, ret;
-_i.ApplicationManager.launchAppControl = {
- 0: _t.ApplicationControl,
- 1: _t.ApplicationId,
- 2: _t.SuccessCallback,
- 3: _t.ErrorCallback,
- 4: _t.ApplicationControlDataArrayReplyCallback,
+ for (i in pattern) {
+ if (i === "_optional")
+ continue;
- _optional: {
- 1: true,
- 2: true,
- 3: true,
- 4: true
- }
-};
+ isNullable = !!(pattern._optional && pattern._optional[i]);
-_i.ApplicationManager.findAppControl = {
- 0: _t.ApplicationControl,
- 1: _t.FindAppControlSuccessCallback,
- 2: _t.ErrorCallback,
+ if (i > obj.length - 1) {
+ if (!isNullable) {
+ return null;
+ }
+ break;
+ }
- _optional: {
- 2: true
- }
-};
+ if (!isNullable || (obj[i] !== null)) {
+ ret = _self(pattern[i]).cast(obj[i]);
+ if (ret === null) {
+ return null;
+ }
+ obj[i] = ret;
+ }
+ }
-_i.ApplicationManager.getAppsContext = {
- 0: _t.ApplicationContextArraySuccessCallback,
- 1: _t.ErrorCallback,
+ return obj;
+ },
- _optional: {
- 1: true
- }
-};
+ "Array": function () {
+ var elementType, i, ret;
-_i.ApplicationManager.getAppContext = {
- 0: _t.ApplicationContextId,
+ if (typeOfObj !== typeOfPattern) {
+ return null;
+ }
- _optional: {
- 0: true
- }
-};
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ ret = elementType.cast(obj[i]);
+ if (ret === null) {
+ return null;
+ }
+ obj[i] = ret;
+ }
-_i.ApplicationManager.getAppsInfo = {
- 0: _t.ApplicationInformationArraySuccessCallback,
- 1: _t.ErrorCallback,
+ return obj;
+ },
- _optional: {
- 1: true
- }
-};
+ "Callback": function () {
+ var attr;
-_i.ApplicationManager.getAppInfo = {
- 0: _t.ApplicationId,
+ if (typeOfObj !== "Object") {
+ return null;
+ }
- _optional: {
- 0: true
- }
-};
+ for (attr in pattern) {
+ if (attr in obj) {
+ obj[attr] = _self(pattern[attr]).cast(obj[attr]);
+ if (obj[attr] === null) {
+ return null;
+ }
+ }
+ }
-_i.ApplicationManager.getAppCerts = {
- 0: _t.ApplicationId,
+ return obj;
+ },
- _optional: {
- 0: true
- }
-};
+ "DOMString": function () {
+ switch (typeOfObj) {
+ case "DOMString":
+ case "Date":
+ case "Number":
+ case "boolean":
+ obj = String(obj);
+ break;
-_i.ApplicationManager.getAppSharedURI = {
- 0: _t.ApplicationId,
+ default:
+ if ((obj === null) || (obj === undefined)) {
+ obj = String(obj);
+ } else {
+ obj = null;
+ }
+ break;
+ }
- _optional: {
- 0: true
- }
-};
+ return obj;
+ },
-_i.ApplicationManager.getAppMetaData = {
- 0: _t.ApplicationId,
+ "Date": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
- _optional: {
- 0: true
- }
-};
+ "Function": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
-_i.ApplicationManager.addAppInfoEventListener = {
- 0: _t.ApplicationInformationEventCallback
-};
+ "Object": function () {
+ var ret, attr, i;
-_i.ApplicationManager.removeAppInfoEventListener = {
- 0: _t.long
-};
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return null;
+ }
+ if (!("_derived" in pattern)) {
+ return null;
+ }
+ }
-// Application
-_i.Application.exit = null;
-_i.Application.hide = null;
-_i.Application.getRequestedAppControl = null;
+ if (!isConstructed(obj)) {
+ return null;
+ }
-// RequestedApplicationControl
-_i.RequestedApplicationControl.replyResult = {
- 0: [_t.ApplicationControlData],
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
- _optional: {
- 0: true
- }
-};
+ case "_derived":
+ for (i in pattern._derived) {
+ ret = _self(pattern._derived[i]).cast(obj);
+ if (ret !== null)
+ break;
+ }
+ if (ret === null) {
+ return null;
+ }
+ break;
-_i.RequestedApplicationControl.replyFailure = null;
+ default:
+ if (!pattern._optional || !pattern._optional[attr] ||
+ (obj[attr] !== undefined) &&
+ (obj[attr] !== null)) {
+ ret = _self(pattern[attr]).cast(obj[attr]);
+ if (ret === null) {
+ return null;
+ }
+ obj[attr] = ret;
+ }
+ break;
+ }
+ }
-/*
- * Bluetooth
- */
+ return obj;
+ },
-// BluetoothManager
-_i.BluetoothManager.getDefaultAdapter = null;
+ "TZDate": function () {
+ if (typeOfObj !== "Object") {
+ return null;
+ }
+ return (obj instanceof window.tizen.TZDate) ? obj : null;
+ },
-// BluetoothAdapter
-_i.BluetoothAdapter.setName = {
- 0: _t.DOMString,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ "Union": function () {
+ var ret, i;
- _optional: {
- 1: true,
- 2: true
- }
-};
+ for (i in pattern) {
+ ret = _self(pattern[i]).cast(obj);
+ if (ret !== null)
+ break;
+ }
-_i.BluetoothAdapter.setPowered = {
- 0: _t.boolean,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ return ret;
+ },
- _optional: {
- 1: true,
- 2: true
- }
-};
+ "any": function () {
+ return obj;
+ },
-_i.BluetoothAdapter.setVisible = {
- 0: _t.boolean,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
- 3: _t.unsigned_short,
+ "boolean": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
- _optional: {
- 1: true,
- 2: true,
- 3: true
- }
-};
+ "byte": function () {
+ return toInt8(obj);
+ },
-_i.BluetoothAdapter.setChangeListener = {
- 0: _t.BluetoothAdapterChangeCallback
-};
+ "dictionary": function () {
+ var attr, ret;
-_i.BluetoothAdapter.unsetChangeListener = null;
+ if (typeOfObj !== "Object") {
+ return null;
+ }
-_i.BluetoothAdapter.discoverDevices = {
- 0: _t.BluetoothDiscoverDevicesSuccessCallback,
- 1: _t.ErrorCallback,
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ ret = _self(pattern._dictionary).cast(obj);
+ if (ret === null) {
+ return null;
+ }
+ }
+ break;
- _optional: {
- 1: true
- }
-};
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ ret = _self(pattern[attr]).cast(obj[attr]);
+ if (ret === null) {
+ return null;
+ }
+ obj[attr] = ret;
+ }
+ break;
+ }
+ }
-_i.BluetoothAdapter.stopDiscovery = {
- 0: _t.SuccessCallback,
- 1: _t.ErrorCallback,
+ return obj;
+ },
- _optional: {
- 0: true,
- 1: true
- }
-};
+ "enum": function () {
+ var i;
-_i.BluetoothAdapter.getKnownDevices = {
- 0: _t.BluetoothDeviceArraySuccessCallback,
- 1: _t.ErrorCallback,
+ obj = String(obj).trim();
+ for (i in pattern) {
+ if (obj === pattern[i]) {
+ return obj;
+ }
+ }
- _optional: {
- 1: true
- }
-};
+ return null;
+ },
-_i.BluetoothAdapter.getDevice = {
- 0: _t.BluetoothAddress,
- 1: _t.BluetoothDeviceSuccessCallback,
- 2: _t.ErrorCallback,
+ "float": function () {
+ var f = parseFloat(obj, 10);
- _optional: {
- 2: true
- }
-};
+ return (isNaN(f) ? null : f);
+ },
-_i.BluetoothAdapter.createBonding = {
- 0: _t.BluetoothAddress,
- 1: _t.BluetoothDeviceSuccessCallback,
- 2: _t.ErrorCallback,
+ "long": function () {
+ return toInt32(obj);
+ },
- _optional: {
- 2: true
- }
-};
+ "long long": function () {
+ return toInt64(obj);
+ },
-_i.BluetoothAdapter.destroyBonding = {
- 0: _t.BluetoothAddress,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ "octet": function () {
+ return toUInt8(obj);
+ },
- _optional: {
- 1: true,
- 2: true
- }
-};
+ "short": function () {
+ return toInt16(obj);
+ },
-_i.BluetoothAdapter.registerRFCOMMServiceByUUID = {
- 0: _t.BluetoothUUID,
- 1: _t.DOMString,
- 2: _t.BluetoothServiceSuccessCallback,
- 3: _t.ErrorCallback,
+ "unsigned long": function () {
+ return toUInt32(obj);
+ },
- _optional: {
- 3: true
- }
-};
+ "unsigned long long": function () {
+ return toUInt64(obj);
+ },
-_i.BluetoothAdapter.getBluetoothProfileHandler = {
- 0: _t.BluetoothProfileType
-};
+ "unsigned short": function () {
+ return toUInt16(obj);
+ },
-// BluetoothDevice
-_i.BluetoothDevice.connectToServiceByUUID = {
- 0: _t.BluetoothUUID,
- 1: _t.BluetoothSocketSuccessCallback,
- 2: _t.ErrorCallback,
+ "": function () {
+ return _self(t[pattern]).cast(obj);
+ }
+ };
- _optional: {
- 2: true
+ return typeMap[typeOfPattern]();
}
-};
-// BluetoothSocket
-_i.BluetoothSocket.readData = null;
-_i.BluetoothSocket.close = null;
+ function copy(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
-_i.BluetoothSocket.writeData = {
- 0: [_t.byte]
-};
+ typeMap = {
+ "Arguments": function () {
+ var i, isNullable, ret = [];
-// BluetoothClass
-_i.BluetoothClass.hasService = {
- 0: _t.unsigned_short
-};
+ for (i in pattern) {
+ if (i === "_optional")
+ continue;
-// BluetoothServiceHandler
-_i.BluetoothServiceHandler.unregister = {
- 0: _t.SuccessCallback,
- 1: _t.ErrorCallback,
+ isNullable = !!(pattern._optional && pattern._optional[i]);
- _optional: {
- 0: true,
- 1: true
- }
-};
+ if (i > obj.length - 1) {
+ if (!isNullable) {
+ return null;
+ }
+ break;
+ }
+
+ if (!isNullable || (obj[i] !== null)) {
+ ret[i] = _self(pattern[i]).copy(obj[i]);
+ if (ret[i] === null) {
+ return null;
+ }
+ }
+ }
+
+ for (i in ret) {
+ obj[i] = ret[i];
+ }
-// BluetoothHealthProfileHandler
-_i.BluetoothHealthProfileHandler.registerSinkApplication = {
- 0: _t.unsigned_short,
- 1: _t.DOMString,
- 2: _t.BluetoothHealthApplicationSuccessCallback,
- 3: _t.ErrorCallback,
+ return obj;
+ },
- _optional: {
- 3: true
- }
-};
+ "Array": function () {
+ var arr = [], elementType, i;
-_i.BluetoothHealthProfileHandler.connectToSource = {
- 0: _t.BluetoothDevice,
- 1: _t.BluetoothHealthApplication,
- 2: _t.BluetoothHealthChannelSuccessCallback,
- 3: _t.ErrorCallback,
+ if (typeOfObj !== typeOfPattern) {
+ return null;
+ }
- _optional: {
- 3: true
- }
-};
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ if (obj[i]) {
+ arr[i] = elementType.copy(obj[i]);
+ if (arr[i] === null)
+ return null;
+ }
+ }
-// BluetoothHealthApplication
-_i.BluetoothHealthApplication.unregister = {
- 0: _t.SuccessCallback,
- 1: _t.ErrorCallback,
+ return arr;
+ },
- _optional: {
- 0: true,
- 1: true
- }
-};
+ "Callback": function () {
+ var ret = {}, attr;
-// BluetoothHealthChannel
-_i.BluetoothHealthChannel.close = null;
-_i.BluetoothHealthChannel.unsetListener = null;
+ if (typeOfObj !== "Object") {
+ return null;
+ }
-_i.BluetoothHealthChannel.sendData = {
- 0: [_t.byte]
-};
+ for (attr in pattern) {
+ if (attr in obj) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ }
-_i.BluetoothHealthChannel.setListener = {
- 0: _t.BluetoothHealthChannelChangeCallback
-};
+ return ret;
+ },
-/*
- * Bookmark
- */
+ "Object": function () {
+ var ret = {}, attr, i, derived;
-// BookmarkManager
-_i.BookmarkManager.get = {
- 0: _t.BookmarkFolder,
- 1: _t.boolean,
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return null;
+ }
+ if (!("_derived" in pattern)) {
+ return null;
+ }
+ }
- _optional: {
- 0: true,
- 1: true
- }
-};
+ if (!isConstructed(obj)) {
+ return null;
+ }
+ if ("_constructor" in pattern) {
+ ret.__proto__ = window.tizen[pattern._constructor].prototype;
+ }
-_i.BookmarkManager.add = {
- 0: _t.Bookmark,
- 1: _t.BookmarkFolder,
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
- _optional: {
- 1: true
- }
-};
+ case "_derived":
+ for (i in pattern._derived) {
+ derived = _self(pattern._derived[i]).copy(obj);
+ if (derived !== null)
+ break;
+ }
+ if (derived === null) {
+ return null;
+ }
+ for (attr in derived) {
+ ret[attr] = derived[attr];
+ }
+ break;
-_i.BookmarkManager.remove = {
- 0: _t.Bookmark,
+ default:
+ if (!pattern._optional || !pattern._optional[attr] ||
+ (obj[attr] !== undefined) &&
+ (obj[attr] !== null)) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ break;
+ }
+ }
- _optional: {
- 0: true
- }
-};
+ return ret;
+ },
-/*
- * Calendar
- */
+ "Union": function () {
+ var ret, i;
-// CalendarManager
-_i.CalendarManager.getCalendars = {
- 0: _t.CalendarType,
- 1: _t.CalendarArraySuccessCallback,
- 2: _t.ErrorCallback,
+ for (i in pattern) {
+ ret = _self(pattern[i]).copy(obj);
+ if (ret !== null)
+ break;
+ }
- _optional: {
- 2: true
- }
-};
+ return ret;
+ },
-_i.CalendarManager.getUnifiedCalendar = {
- 0: _t.CalendarType
-};
+ "dictionary": function () {
+ var ret = {}, attr, base, i;
-_i.CalendarManager.getDefaultCalendar = {
- 0: _t.CalendarType
-};
+ if (typeOfObj !== "Object") {
+ return null;
+ }
-_i.CalendarManager.getCalendar = {
- 0: _t.CalendarType,
- 1: _t.CalendarId
-};
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ base = _self(pattern._dictionary).copy(obj);
+ if (base === null) {
+ return null;
+ }
+ for (i in base) {
+ ret[i] = base[i];
+ }
+ }
+ break;
-// Calendar
-_i.Calendar.get = {
- 0: _t.CalendarItemId
-};
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ break;
+ }
+ }
-_i.Calendar.add = {
- 0: _t.CalendarItem
-};
+ return ret;
+ },
-_i.Calendar.addBatch = {
- 0: [_t.CalendarItem],
- 1: _t.CalendarItemArraySuccessCallback,
- 2: _t.ErrorCallback,
+ "": function () {
+ return _self(t[pattern]).copy(obj);
+ }
+ };
- _optional: {
- 1: true,
- 2: true
+ return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
+ cast(obj);
}
-};
-_i.Calendar.update = {
- 0: _t.CalendarItem,
- 1: _t.boolean,
+ function match(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
- _optional: {
- 1: true
- }
-};
+ typeMap = {
+ "Array": function () {
+ var elementType, i;
-_i.Calendar.updateBatch = {
- 0: [_t.CalendarItem],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
- 3: _t.boolean,
+ if (typeOfObj !== typeOfPattern)
+ return false;
- _optional: {
- 1: true,
- 2: true,
- 3: true
- }
-};
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ if (!elementType.match(obj[i])) {
+ return false;
+ }
+ }
-_i.Calendar.remove = {
- 0: _t.CalendarItemId
-};
+ return true;
+ },
-_i.Calendar.removeBatch = {
- 0: [_t.CalendarItemId],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ "Callback": function () {
+ var attr, isMatched = true;
- _optional: {
- 1: true,
- 2: true
- }
-};
+ if (typeOfObj !== "Object") {
+ return false;
+ }
-_i.Calendar.find = {
- 0: _t.CalendarItemArraySuccessCallback,
- 1: _t.ErrorCallback,
- 2: _t.AbstractFilter,
- 3: _t.SortMode,
+ for (attr in pattern) {
+ if (attr in obj) {
+ isMatched = _self(pattern[attr]).match(obj[attr]);
+ if (!isMatched) {
+ break;
+ }
+ }
+ }
- _optional: {
- 1: true,
- 2: true,
- 3: true
- }
-};
+ return isMatched;
+ },
-_i.Calendar.addChangeListener = {
- 0: _t.CalendarChangeCallback
-};
+ "DOMString": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-_i.Calendar.removeChangeListener = {
- 0: _t.long
-};
+ "Date": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-// CalendarItem
-_i.CalendarItem.convertToString = {
- 0: _t.CalendarTextFormat
-};
+ "Function": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-_i.CalendarItem.clone = null;
+ "Object": function () {
+ var attr, isMatched = false, i;
-// CalendarEvent
-_i.CalendarEvent.expandRecurrence = {
- 0: _t.TZDate,
- 1: _t.TZDate,
- 2: _t.CalendarEventArraySuccessCallback,
- 3: _t.ErrorCallback,
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return false;
+ }
+ if (!("_derived" in pattern)) {
+ return false;
+ }
+ return false;
+ }
- _optional: {
- 3: true
- }
-};
+ if (!isConstructed(obj)) {
+ return false;
+ }
-/*
- * Call History
- */
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
-// CallHistory
-_i.CallHistory.find = {
- 0: _t.CallHistoryEntryArraySuccessCallback,
- 1: _t.ErrorCallback,
- 2: _t.AbstractFilter,
- 3: _t.SortMode,
- 4: _t.unsigned_long,
- 5: _t.unsigned_long,
+ case "_derived":
+ for (i in pattern._derived) {
+ isMatched = _self(pattern._derived[i]).match(obj);
+ if (isMatched)
+ break;
+ }
+ break;
- _optional: {
- // nullable
- 1: true,
- 2: true,
- 3: true,
- 4: true,
- 5: true
- }
-};
+ default:
+ if (pattern._optional && pattern._optional[attr]) {
+ isMatched = ((obj[attr] === null) ||
+ (obj[attr] === undefined) ||
+ _self(pattern[attr]).match(obj[attr]));
+ } else {
+ isMatched = (obj[attr] !== undefined) &&
+ _self(pattern[attr]).match(obj[attr]);
+ }
+ break;
+ }
-_i.CallHistory.remove = {
- 0: _t.CallHistoryEntry
-};
+ if (!isMatched)
+ break;
+ }
-_i.CallHistory.removeBatch = {
- 0: [_t.CallHistoryEntry],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ /*// Check if verbose attributes are present
+ if (isMatched) {
+ for (attr in obj) {
+ if (pattern[attr] === undefined) {
+ isMatched = false;
+ break;
+ }
+ }
+ }*/
- _optional: {
- // nullable
- 1: true,
- 2: true
- }
-};
+ return isMatched;
+ },
-_i.CallHistory.removeAll = {
- 0: _t.SuccessCallback,
- 1: _t.ErrorCallback,
+ "Union": function () {
+ var isMatched, i;
- _optional: {
- // nullable
- 0: true,
- 1: true
- }
-};
+ for (i in pattern) {
+ isMatched = _self(pattern[i]).match(obj);
+ if (isMatched)
+ break;
+ }
-_i.CallHistory.addChangeListener = {
- 0: _t.CallHistoryChangeCallback
-};
+ return isMatched;
+ },
-_i.CallHistory.removeChangeListener = {
- 0: _t.long
-};
+ "any": function () {
+ return true;
+ },
-/*
- * Contact
- */
+ "boolean": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-// ContactManager
-_i.ContactManager.getAddressBooks = {
- 0: _t.AddressBookArraySuccessCallback,
- 1: _t.ErrorCallback,
+ "byte": function () {
+ return (obj === toInt8(obj));
+ },
- _optional: {
- 1: true
- }
-};
+ "dictionary": function () {
+ var attr, isMatched = true;
-_i.ContactManager.getUnifiedAddressBook = null;
-_i.ContactManager.getDefaultAddressBook = null;
+ if (typeOfObj !== "Object") {
+ return false;
+ }
-_i.ContactManager.getAddressBook = {
- 0: _t.AddressBookId
-};
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ isMatched = _self(pattern._dictionary).match(obj);
+ if (!isMatched)
+ break;
+ }
+ break;
-_i.ContactManager.get = {
- 0: _t.PersonId
-};
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ isMatched = _self(pattern[attr]).match(obj[attr]);
+ if (!isMatched)
+ break;
+ }
+ break;
+ }
+ }
-_i.ContactManager.update = {
- 0: _t.Person
-};
+ return isMatched;
+ },
-_i.ContactManager.updateBatch = {
- 0: [_t.Person],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ "enum": function () {
+ for (var i in pattern) {
+ if (obj === pattern[i]) {
+ return true;
+ }
+ }
- _optional: {
- 1: true,
- 2: true
- }
-};
+ return false;
+ },
-_i.ContactManager.remove = {
- 0: _t.PersonId
-};
+ "float": function () {
+ return (typeOfObj === "Number");
+ },
-_i.ContactManager.removeBatch = {
- 0: [_t.PersonId],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ "long": function () {
+ return (obj === toInt32(obj));
+ },
- _optional: {
- 1: true,
- 2: true
- }
-};
+ "long long": function () {
+ return (obj === toInt64(obj));
+ },
-_i.ContactManager.find = {
- 0: _t.PersonArraySuccessCallback,
- 1: _t.ErrorCallback,
- 2: _t.AbstractFilter,
- 3: _t.SortMode,
+ "octet": function () {
+ return (obj === toUInt8(obj));
+ },
- _optional: {
- 1: true,
- 2: true,
- 3: true
- }
-};
+ "short": function () {
+ return (obj === toInt16(obj));
+ },
-_i.ContactManager.addChangeListener = {
- 0: _t.PersonsChangeCallback
-};
+ "unsigned long": function () {
+ return (obj === toUInt32(obj));
+ },
-_i.ContactManager.removeChangeListener = {
- 0: _t.long
-};
+ "unsigned long long": function () {
+ return (obj === toUInt64(obj));
+ },
-// AddressBook
-_i.AddressBook.get = {
- 0: _t.ContactId
-};
+ "unsigned short": function () {
+ return (obj === toUInt16(obj));
+ },
-_i.AddressBook.add = {
- 0: _t.Contact
-};
+ "Arguments": function () {
+ return true;
+ },
-_i.AddressBook.addBatch = {
- 0: [_t.Contact],
- 1: _t.ContactArraySuccessCallback,
- 2: _t.ErrorCallback,
+ "": function () {
+ return _self(t[pattern]).match(obj);
+ }
+ };
- _optional: {
- 1: true,
- 2: true
+ return typeMap[typeOfPattern]();
}
-};
-_i.AddressBook.update = {
- 0: _t.Contact
-};
+ typeOfPattern = getType(pattern, true);
-_i.AddressBook.updateBatch = {
- 0: [_t.Contact],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ typeCoerce = {
+ cast: cast,
+ copy: copy,
+ match: match
+ };
- _optional: {
- 1: true,
- 2: true
- }
+ return typeCoerce;
};
-_i.AddressBook.remove = {
- 0: _t.ContactId
-};
+module.exports = _self;
-_i.AddressBook.removeBatch = {
- 0: [_t.ContactId],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+});
+define('ripple/platform/tizen/2.0/SyncProfileInfo', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- _optional: {
- 1: true,
- 2: true
- }
-};
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ SyncProfileInfo;
-_i.AddressBook.find = {
- 0: _t.ContactArraySuccessCallback,
- 1: _t.ErrorCallback,
- 2: _t.AbstractFilter,
- 3: _t.SortMode,
+SyncProfileInfo = function (profileName, syncInfo, serviceInfo) {
+ var syncProfileInfo = {};
- _optional:{
- 1: true,
- 2: true,
- 3: true
- }
-};
+ t.SyncProfileInfo(arguments, this);
-_i.AddressBook.addChangeListener = {
- 0: _t.AddressBookChangeCallback,
- 1: _t.ErrorCallback,
+ syncProfileInfo.profileName = profileName;
+ syncProfileInfo.syncInfo = syncInfo;
+ syncProfileInfo.serviceInfo = serviceInfo;
- _optional: {
- 1: true
- }
-};
+ this.__defineGetter__("profileId", function () {
+ return null;
+ });
-_i.AddressBook.removeChangeListener = {
- 0: _t.long
-};
+ this.__defineGetter__("profileName", function () {
+ return syncProfileInfo.profileName;
+ });
+ this.__defineSetter__("profileName", function (profileName) {
+ try {
+ syncProfileInfo.profileName = t.DOMString(profileName);
+ } catch (e) {
+ }
+ });
-_i.AddressBook.getGroup = {
- 0: _t.ContactGroupId
-};
+ this.__defineGetter__("syncInfo", function () {
+ return syncProfileInfo.syncInfo;
+ });
+ this.__defineSetter__("syncInfo", function (syncInfo) {
+ try {
+ t.SyncInfo(syncInfo);
+ syncProfileInfo.syncInfo = syncInfo;
+ } catch (e) {
+ }
+ });
-_i.AddressBook.addGroup = {
- 0: _t.ContactGroup
+ this.__defineGetter__("serviceInfo", function () {
+ return syncProfileInfo.serviceInfo;
+ });
+ this.__defineSetter__("serviceInfo", function (serviceInfo) {
+ try {
+ t.SyncServiceInfo(serviceInfo, "[]?");
+ syncProfileInfo.serviceInfo = serviceInfo;
+ } catch (e) {
+ }
+ });
};
-_i.AddressBook.updateGroup = {
- 0: _t.ContactGroup
-};
+module.exports = SyncProfileInfo;
-_i.AddressBook.removeGroup = {
- 0: _t.ContactGroupId
-};
+});
+define('ripple/platform/tizen/2.0/typecast', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
-_i.AddressBook.getGroups = null;
+var typedef = require('ripple/platform/tizen/2.0/typedef'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
+ _self = {};
-// Person
-_i.Person.link = {
- 0: _t.PersonId
-};
+function _cast(pattern, obj, isDuplicate) {
+ var tc, tcFunc;
-_i.Person.unlink = {
- 0: _t.ContactId
-};
+ if (pattern === null)
+ return;
-// Contact
-_i.Contact.convertToString = {
- 0: _t.ContactTextFormat,
+ tc = new TypeCoerce(pattern);
+ tcFunc = isDuplicate ? tc.copy : tc.cast;
- _optional: {
- 0: true
+ if ((obj = tcFunc(obj)) === null) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
}
-};
-_i.Contact.clone = null;
+ return obj;
+}
-/*
- * Content
- */
+function _castType(pattern) {
+ /*
+ * Type cast for each known type. The function name is the exact name of the
+ * corresponding type.
+ *
+ * obj
+ * Variable to be casted
+ *
+ * aux
+ * Auxiliary descriptor of obj. It can be any one or combination of below
+ * strings, or ignored in most cases.
+ *
+ * "?" Nullable types
+ * "[]" Array
+ * "+" Deep copy
+ *
+ * Return
+ * Casted or duplicated object.
+ */
-// ContentManager
-_i.ContentManager.update = {
- 0: _t.Content
-};
+ return function (obj, aux) {
+ var type, isNullable, isDuplicate;
-_i.ContentManager.updateBatch = {
- 0: [_t.Content],
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ aux = aux ? String(aux) : "";
+ type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
+ isNullable = (aux.indexOf("?") !== -1);
+ isDuplicate = (aux.indexOf("+") !== -1);
- _optional: {
- 1: true,
- 2: true
- }
-};
+ if (isNullable && ((obj === null) || (obj === undefined))) {
+ return obj;
+ }
-_i.ContentManager.getDirectories = {
- 0: _t.ContentDirectoryArraySuccessCallback,
- 1: _t.ErrorCallback,
+ return _cast(type, obj, isDuplicate);
+ };
+}
- _optional: {
- 1: true
- }
-};
+function _castConstructor(name) {
+ var constructors, hook, vtc, isOverloaded, castConstructor;
-_i.ContentManager.find = {
- 0: _t.ContentArraySuccessCallback,
- 1: _t.ErrorCallback,
- 2: _t.ContentDirectoryId,
- 3: _t.AbstractFilter,
- 4: _t.SortMode,
- 5: _t.unsigned_long,
- 6: _t.unsigned_long,
+ /*
+ * Type cast for constructor. The function name is the exact name of the
+ * object type.
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ */
- _optional: {
- 1: true,
- 2: true,
- 3: true,
- 4: true,
- 5: true,
- 6: true
+ function castUnique(argv) {
+ _cast(constructors, argv, false);
}
-};
-
-_i.ContentManager.scanFile = {
- 0: _t.DOMString,
- 1: _t.ContentScanSuccessCallback,
- 2: _t.ErrorCallback,
- _optional: {
- 1: true,
- 2: true
- }
-};
+ /*
+ * Type cast for overloaded constructors. The function name is the exact
+ * name of the object type.
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ *
+ * scope
+ * 'this' of the original constructor.
+ *
+ * voc
+ * Array of overloaded constructors callback
+ */
-_i.ContentManager.setChangeListener = {
- 0: _t.ContentChangeCallback
-};
+ function castOverload(argv, scope, voc) {
+ var iOverload;
-_i.ContentManager.unsetChangeListener = null;
+ if (!vtc) {
+ vtc = [];
+ constructors.forEach(function (c) {
+ vtc.push((c === null) ? null : new TypeCoerce(c));
+ });
+ }
-/*
- * Data Control
- */
+ vtc.some(function (tc, index) {
+ if (tc && (tc.cast(argv) === null))
+ return false;
-// DataControlManager
-_i.DataControlManager.getDataControlConsumer = {
- 0: _t.DOMString,
- 1: _t.DOMString,
- 2: _t.DataType
-};
+ iOverload = index;
+ return true;
+ });
-// SQLDataControlConsumer
-_i.SQLDataControlConsumer.insert = {
- 0: _t.unsigned_long,
- 1: _t.RowData,
- 2: _t.DataControlInsertSuccessCallback,
- 3: _t.DataControlErrorCallback,
+ if (iOverload === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ }
- _optional: {
- 2: true,
- 3: true
+ return (voc && voc[iOverload].apply(scope, argv));
}
-};
-_i.SQLDataControlConsumer.update = {
- 0: _t.unsigned_long,
- 1: _t.RowData,
- 2: _t.DOMString,
- 3: _t.DataControlSuccessCallback,
- 4: _t.DataControlErrorCallback,
+ constructors = typedef.constructor[name];
- _optional: {
- 3: true,
- 4: true
+ if (name in _self) {
+ hook = _self[name];
}
-};
-_i.SQLDataControlConsumer.remove = {
- 0: _t.unsigned_long,
- 1: _t.DOMString,
- 2: _t.DataControlSuccessCallback,
- 3: _t.DataControlErrorCallback,
+ isOverloaded = (Object.prototype.toString.call(constructors) ===
+ "[object Array]");
+ castConstructor = isOverloaded ? castOverload : castUnique;
- _optional: {
- 2: true,
- 3: true
- }
-};
+ return function (argv, scope) {
+ if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
+ return (hook && hook.apply(this, arguments));
+ }
-_i.SQLDataControlConsumer.select = {
- 0: _t.unsigned_long,
- 1: [_t.DOMString],
- 2: _t.DOMString,
- 3: _t.DataControlSelectSuccessCallback,
- 4: _t.DataControlErrorCallback,
- 5: _t.unsigned_long,
- 6: _t.unsigned_long,
+ if (!(scope instanceof argv.callee)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
+ }
- _optional: {
- 4: true,
- 5: true,
- 6: true
- }
-};
+ castConstructor.apply(this, arguments);
+ };
+}
-// MappedDataControlConsumer
-_i.MappedDataControlConsumer.addValue = {
- 0: _t.unsigned_long,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.DataControlSuccessCallback,
- 4: _t.DataControlErrorCallback,
+function _castInterface(name) {
+ var interface, hook;
- _optional: {
- 3: true,
- 4: true
+ interface = typedef.interface[name];
+
+ if (name in _self) {
+ hook = _self[name];
}
-};
-_i.MappedDataControlConsumer.removeValue = {
- 0: _t.unsigned_long,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.DataControlSuccessCallback,
- 4: _t.DataControlErrorCallback,
+ /*
+ * Type cast for each known method of interface. The function name is the
+ * exact name of the corresponding interface.
+ *
+ * method
+ * String of method name
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ *
+ * isDuplicate
+ * A boolean value to indicate whether arguments will be copied or not.
+ */
- _optional: {
- 4: true
- }
-};
+ return function (method, argv, isDuplicate) {
+ if ((typeof method !== "string") || (typeof argv !== "object")) {
+ return (hook && hook.apply(this, arguments));
+ }
-_i.MappedDataControlConsumer.getValue = {
- 0: _t.unsigned_long,
- 1: _t.DOMString,
- 2: _t.DataControlGetValueSuccessCallback,
- 3: _t.DataControlErrorCallback,
+ _cast(interface[method], argv, isDuplicate);
+ };
+}
- _optional: {
- 3: true
+(function () {
+ var i;
+
+ for (i in typedef) {
+ _self[i] = _castType(typedef[i]);
}
-};
-_i.MappedDataControlConsumer.updateValue = {
- 0: _t.unsigned_long,
- 1: _t.DOMString,
- 2: _t.DOMString,
- 3: _t.DOMString,
- 4: _t.DataControlSuccessCallback,
- 5: _t.DataControlErrorCallback,
+ for (i in typedef.constructor) {
+ _self[i] = _castConstructor(i);
+ typedef[i]._constructor = i;
+ }
- _optional: {
- 5: true
+ for (i in typedef.interface) {
+ _self[i] = _castInterface(i);
}
-};
+}());
+
+module.exports = _self;
+});
+define('ripple/platform/tizen/2.0/poi', function (require, exports, module) {
/*
- * Data Synchronization
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
*/
-// DataSynchronizationManager
-_i.DataSynchronizationManager.getMaxProfilesNum = null;
-_i.DataSynchronizationManager.getProfilesNum = null;
-_i.DataSynchronizationManager.getAll = null;
-
-_i.DataSynchronizationManager.add = {
- 0: _t.SyncProfileInfo
-};
-
-_i.DataSynchronizationManager.update = {
- 0: _t.SyncProfileInfo
-};
-
-_i.DataSynchronizationManager.remove = {
- 0: _t.SyncProfileId
-};
+var OpenMapQuestProvider = require('ripple/platform/tizen/2.0/poiBackend_openmapquest'), // opne.MapQuest.xapi service
+ _providers,
+ _security = {
+ "http://tizen.org/api/poi": [],
+ "http://tizen.org/api/poi.read": ["find"],
+ "http://tizen.org/api/poi.write": ["add", "remove", "update"],
+ all: true
+ },
+ _self;
-_i.DataSynchronizationManager.get = {
- 0: _t.SyncProfileId
-};
+function _initialize() {
+ _providers = [new OpenMapQuestProvider({name : "MapQuest", connectivity : "ONLINE", metaData : _security})];
+}
-_i.DataSynchronizationManager.startSync = {
- 0: _t.SyncProfileId,
- 1: _t.SyncProgressCallback,
+_self = function () {
+ var poi;
- _optional: {
- 1: true
- }
-};
+ poi = {
+ getDefaultProvider : function () {
+ return _providers[0];
+ },
+ getProviders : function () {
+ return _providers;
+ },
+ handleSubFeatures: function (subFeatures) {
+ var i, subFeature;
+ for (subFeature in subFeatures) {
+ if (_security[subFeature].length === 0) {
+ _security.all = true;
+ break;
+ }
+ _security.all = false;
+ for (i = 0; i < _security[subFeature].length; i++) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ _initialize();
+ }
+ };
-_i.DataSynchronizationManager.stopSync = {
- 0: _t.SyncProfileId
+ return poi;
};
-_i.DataSynchronizationManager.getLastSyncStatistics = {
- 0: _t.SyncProfileId
-};
+module.exports = _self;
+});
+define('ripple/platform/tizen/2.0/ContactGroup', function (require, exports, module) {
/*
- * Download
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-// DownloadManager
-_i.DownloadManager.start = {
- 0: _t.DownloadRequest,
- 1: _t.DownloadCallback,
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactGroup;
- _optional: {
- 1: true
- }
-};
+ContactGroup = function (name, ringtoneURI, photoURI) {
+ var contactGroup = {};
-_i.DownloadManager.cancel = {
- 0: _t.long
-};
+ t.ContactGroup(arguments, this);
-_i.DownloadManager.pause = {
- 0: _t.long
-};
+ contactGroup.name = name;
+ contactGroup.ringtoneURI = ringtoneURI || null;
+ contactGroup.photoURI = photoURI || null;
-_i.DownloadManager.resume = {
- 0: _t.long
-};
+ this.__defineGetter__("id", function () {
+ return null;
+ });
-_i.DownloadManager.getState = {
- 0: _t.long
-};
+ this.__defineGetter__("addressBookId", function () {
+ return null;
+ });
-_i.DownloadManager.getDownloadRequest = {
- 0: _t.long
-};
+ this.__defineGetter__("name", function () {
+ return contactGroup.name;
+ });
+ this.__defineSetter__("name", function (val) {
+ try {
+ contactGroup.name = t.DOMString(val);
+ } catch (e) {
+ }
+ });
-_i.DownloadManager.getMIMEType = {
- 0: _t.long
-};
+ this.__defineGetter__("ringtoneURI", function () {
+ return contactGroup.ringtoneURI;
+ });
+ this.__defineSetter__("ringtoneURI", function (val) {
+ try {
+ contactGroup.ringtoneURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-_i.DownloadManager.setListener = {
- 0: _t.long,
- 1: _t.DownloadCallback
+ this.__defineGetter__("photoURI", function () {
+ return contactGroup.photoURI;
+ });
+ this.__defineSetter__("photoURI", function (val) {
+ try {
+ contactGroup.photoURI = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("readOnly", function () {
+ return false;
+ });
};
+module.exports = ContactGroup;
+
+});
+define('ripple/platform/tizen/2.0/ContactWebSite', function (require, exports, module) {
/*
- * Network Bearer Selection
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-// NetworkBearerSelection
-_i.NetworkBearerSelection.requestRouteToHost = {
- 0: _t.NetworkType,
- 1: _t.DOMString,
- 2: _t.NetworkSuccessCallback,
- 3: _t.ErrorCallback,
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ContactWebSite;
- _optional: {
- 3: true
- }
-};
+ContactWebSite = function (url, type) {
+ var contactWebSite = {};
-_i.NetworkBearerSelection.releaseRouteToHost = {
- 0: _t.NetworkType,
- 1: _t.DOMString,
- 2: _t.SuccessCallback,
- 3: _t.ErrorCallback,
+ t.ContactWebSite(arguments, this);
- _optional: {
- 3: true
- }
+ contactWebSite.url = url;
+ contactWebSite.type = type || "HOMEPAGE";
+
+ this.__defineGetter__("url", function () {
+ return contactWebSite.url;
+ });
+ this.__defineSetter__("url", function (val) {
+ try {
+ contactWebSite.url = t.DOMString(val);
+ } catch (e) {
+ }
+ });
+
+ this.__defineGetter__("type", function () {
+ return contactWebSite.type;
+ });
+ this.__defineSetter__("type", function (val) {
+ try {
+ contactWebSite.type = t.DOMString(val);
+ } catch (e) {
+ }
+ });
};
+module.exports = ContactWebSite;
+
+});
+define('ripple/platform/tizen/2.0/DeviceOrientationEvent', function (require, exports, module) {
/*
- * NFC
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
*/
-// NFCManager
-_i.NFCManager.getDefaultAdapter = null;
-_i.NFCManager.setExclusiveMode = {
- 0: _t.boolean
-};
+var Event = require('ripple/platform/tizen/2.0/EventBase');
-// NFCAdapter
-_i.NFCAdapter.setPowered = {
- 0: _t.boolean,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+module.exports = function () {
+ var _self = {
+ alpha: null,
+ beta: null,
+ gamma: null,
+ absolute: false,
+ };
- _optional: {
- 1: true,
- 2: true
- }
-};
+ Event.call(this);
-_i.NFCAdapter.setTagListener = {
- 0: _t.NFCTagDetectCallback,
- 1: [_t.NFCTagType],
+ this.__defineGetter__("alpha", function () {
+ return _self.alpha;
+ });
- _optional: {
- 1: true
- }
-};
+ this.__defineGetter__("beta", function () {
+ return _self.beta;
+ });
-_i.NFCAdapter.setPeerListener = {
- 0: _t.NFCPeerDetectCallback
-};
+ this.__defineGetter__("gamma", function () {
+ return _self.gamma;
+ });
-_i.NFCAdapter.unsetTagListener = null;
-_i.NFCAdapter.unsetPeerListener = null;
-_i.NFCAdapter.getCachedMessage = null;
+ this.__defineGetter__("absolute", function () {
+ return _self.absolute;
+ });
-// NFCTag
-_i.NFCTag.readNDEF = {
- 0: _t.NDEFMessageReadCallback,
- 1: _t.ErrorCallback,
+ this.initDeviceOrientationEvent = function (orientationType, orientationBubbles, orientationCancelable,
+ alphaData, betaData, gammaData, isAbsolute) {
+ this.initEvent(orientationType, orientationBubbles, orientationCancelable);
- _optional: {
- 1: true
- }
+ _self.alpha = alphaData;
+ _self.beta = betaData;
+ _self.gamma = gammaData;
+ _self.absolute = isAbsolute;
+ };
};
-_i.NFCTag.writeNDEF = {
- 0: _t.NDEFMessage,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
- _optional: {
- 1: true,
- 2: true
- }
-};
+});
+define('ripple/platform/tizen/2.0/CompositeFilter', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
-_i.NFCTag.transceive = {
- 0: [_t.byte],
- 1: _t.ByteArraySuccessCallback,
- 2: _t.ErrorCallback,
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ CompositeFilter;
- _optional: {
- 2: true
- }
-};
+CompositeFilter = function (type, filters) {
+ var compositeFilter = {};
-// NFCPeer
-_i.NFCPeer.setReceiveNDEFListener = {
- 0: _t.NDEFMessageReadCallback
-};
+ t.CompositeFilter(arguments, this);
-_i.NFCPeer.unsetReceiveNDEFListener = null;
+ this.__defineGetter__("type", function () {
+ return compositeFilter.type;
+ });
+ this.__defineSetter__("type", function (val) {
+ try {
+ compositeFilter.type = t.CompositeFilterType(val);
+ } catch (e) {
+ }
+ });
-_i.NFCPeer.sendNDEF = {
- 0: _t.NDEFMessage,
- 1: _t.SuccessCallback,
- 2: _t.ErrorCallback,
+ this.__defineGetter__("filters", function () {
+ return compositeFilter.filters;
+ });
+ this.__defineSetter__("filters", function (val) {
+ try {
+ compositeFilter.filters = t.AbstractFilter(val, "[]");
+ } catch (e) {
+ }
+ });
- _optional: {
- 1: true,
- 2: true
- }
+ compositeFilter.type = type;
+ compositeFilter.filters = filters || [];
};
-// NDEFMessage
-_i.NDEFMessage.toByte = null;
+module.exports = CompositeFilter;
-/*
- * Notification
+});
+define('ripple/platform/tizen/2.0/GeocodeResult', function (require, exports, module) {
+/*
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
*/
-// NotificationManager
-_i.NotificationManager.post = {
- 0: _t.Notification
-};
+var SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates');
-_i.NotificationManager.update = {
- 0: _t.Notification
-};
+module.exports = function (lat, lon) {
+ var _self, _coordinates, jsonStr, jsonObj;
-_i.NotificationManager.remove = {
- 0: _t.NotificationId
-};
+ _coordinates = new SimpleCoordinates(lat, lon);
-_i.NotificationManager.get = {
- 0: _t.NotificationId
+ jsonObj = {
+ "type" : "Point",
+ "coordinates" : [lat, lon]
+ };
+
+ jsonStr = JSON.stringify(jsonObj);
+
+ _self = {
+ coordinates : _coordinates,
+ toGeoJSON : function () {
+ return jsonStr;
+ }
+ };
+ return _self;
};
-_i.NotificationManager.removeAll = null;
-_i.NotificationManager.getAll = null;
+});
+define('ripple/platform/tizen/2.0/TimeDuration', function (require, exports, module) {
/*
- * Package
+ * Copyright 2012 Intel Corporation.
+ *
+ * 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.
*/
-// PackageManager
-_i.PackageManager.install = {
- 0: _t.DOMString,
- 1: _t.PackageProgressCallback,
- 2: _t.ErrorCallback,
-
- _optional: {
- 2: true
- }
-};
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ errorcode = require('ripple/platform/tizen/2.0/errorcode'),
+ WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
+ TimeDuration;
-_i.PackageManager.uninstall = {
- 0: _t.PackageId,
- 1: _t.PackageProgressCallback,
- 2: _t.ErrorCallback,
+TimeDuration = function (_length, _unit) {
+ var timeDuration = {},
+ TimeDurationUnit = {"MSECS": 1,
+ "SECS": 1000,
+ "MINS": 60 * 1000,
+ "HOURS": 60 * 60 * 1000,
+ "DAYS": 24 * 60 * 60 * 1000
+ },
+ _simplifyDuration = function (ms) {
+ var TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
+ uni = "MSECS";
+ if ((ms % 1000) === 0) {
+ ms = ms / 1000;
+ uni = "SECS";
+ if ((ms % 60) === 0) {
+ ms = ms / 60;
+ uni = "MINS";
+ if ((ms % 60) === 0) {
+ ms = ms / 60;
+ uni = "HOURS";
+ if ((ms % 24) === 0) {
+ ms = ms / 24;
+ uni = "DAYS";
+ }
+ }
+ }
+ }
+ return (new TDur(ms, uni));
+ },
+ _toMSECS = function (unit) {
+ if (TimeDurationUnit[unit] === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
+ } else {
+ return TimeDurationUnit[unit];
+ }
+ };
- _optional: {
- 2: true
- }
-};
+ t.TimeDuration(arguments, this);
-_i.PackageManager.getPackagesInfo = {
- 0: _t.PackageInformationArraySuccessCallback,
- 1: _t.ErrorCallback,
+ this.__defineGetter__("length", function () {
+ return timeDuration.length;
+ });
+ this.__defineSetter__("length", function (val) {
+ try {
+ timeDuration.length = t.double(val);
+ } catch (e) {
+ }
+ });
- _optional: {
- 1: true
- }
-};
+ this.__defineGetter__("unit", function () {
+ return timeDuration.unit;
+ });
+ this.__defineSetter__("unit", function (val) {
+ try {
+ timeDuration.unit = t.TimeDurationUnit(val);
+ } catch (e) {
+ }
+ });
-_i.PackageManager.getPackageInfo = {
- 0: _t.PackageId,
+ timeDuration.length = _length;
+ timeDuration.unit = _unit || "MSECS";
- _optional: {
- 0: true
- }
-};
+ this.difference = function (o) {
-_i.PackageManager.setPackageInfoEventListener = {
- 0: _t.PackageInfomationEventCallback
-};
+ t.TimeDuration("difference", arguments);
-_i.PackageManager.unsetPackageInfoEventListener = null;
+ var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
+ otherMS = o.length * _toMSECS(o.unit);
+ return _simplifyDuration(thisMS - otherMS);
+ };
+ this.equalsTo = function (o) {
-/*
- * Push
- */
+ t.TimeDuration("equalsTo", arguments);
-// PushManager
-_i.PushManager.registerService = {
- 0: _t.ApplicationControl,
- 1: _t.PushRegisterSuccessCallback,
- 2: _t.ErrorCallback,
+ var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
+ otherMS = o.length * _toMSECS(o.unit);
+ return (thisMS === otherMS);
+ };
+ this.lessThan = function (o) {
- _optional: {
- 2: true
- }
-};
+ t.TimeDuration("lessThan", arguments);
-_i.PushManager.unregisterService = {
- 0: _t.SuccessCallback,
- 1: _t.ErrorCallback,
+ var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
+ otherMS = o.length * _toMSECS(o.unit);
+ return (thisMS < otherMS);
+ };
+ this.greaterThan = function (o) {
- _optional: {
- 0: true,
- 1: true
- }
-};
+ t.TimeDuration("greaterThan", arguments);
-_i.PushManager.connectService = {
- 0: _t.PushNotificationCallback
+ var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
+ otherMS = o.length * _toMSECS(o.unit);
+ return (thisMS > otherMS);
+ };
};
-_i.PushManager.disconnectService = null;
-_i.PushManager.getRegistrationId = null;
+module.exports = TimeDuration;
+});
+define('ripple/platform/tizen/2.0/ApplicationControl', function (require, exports, module) {
/*
- * System Info
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-// SystemInfo
-_i.SystemInfo.getCapabilities = null;
+var t = require('ripple/platform/tizen/2.0/typecast'),
+ ApplicationControlData = require('ripple/platform/tizen/2.0/ApplicationControlData');
-_i.SystemInfo.getPropertyValue = {
- 0: _t.SystemInfoPropertyId,
- 1: _t.SystemInfoPropertySuccessCallback,
- 2: _t.ErrorCallback,
+var ApplicationControl = function (operation, uri, mime, category, data) {
+ var applicationControl = {}, i;
- _optional: {
- 2: true
- }
-};
+ t.ApplicationControl(arguments, this);
-_i.SystemInfo.addPropertyValueChangeListener = {
- 0: _t.SystemInfoPropertyId,
- 1: _t.SystemInfoPropertySuccessCallback,
- 2: _t.SystemInfoOptions,
+ applicationControl.operation = operation;
+ applicationControl.uri = uri || null;
+ applicationControl.mime = mime || null;
+ applicationControl.category = category || null;
+ applicationControl.data = [];
- _optional: {
- 2: true
+ if (data) {
+ for (i in data) {
+ applicationControl.data[i] = new ApplicationControlData(data[i].key,
+ data[i].value);
+ }
}
-};
-_i.SystemInfo.removePropertyValueChangeListener = {
- 0: _t.unsigned_long
-};
+ this.__defineGetter__("operation", function () {
+ return applicationControl.operation;
+ });
+ this.__defineSetter__("operation", function (val) {
+ try {
+ applicationControl.operation = t.DOMString(val);
+ } catch (e) {
+ }
+ });
-/*
- * System Setting
- */
+ this.__defineGetter__("uri", function () {
+ return applicationControl.uri;
+ });
+ this.__defineSetter__("uri", function (val) {
+ try {
+ applicationControl.uri = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-// SystemSettingManager
-_i.SystemSettingManager.setProperty = {
- 0: _t.SystemSettingType,
- 1: _t.DOMString,
- 2: _t.SuccessCallback,
- 3: _t.ErrorCallback,
+ this.__defineGetter__("mime", function () {
+ return applicationControl.mime;
+ });
+ this.__defineSetter__("mime", function (val) {
+ try {
+ applicationControl.mime = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
- _optional: {
- 3: true
- }
-};
+ this.__defineGetter__("category", function () {
+ return applicationControl.category;
+ });
+ this.__defineSetter__("category", function (val) {
+ try {
+ applicationControl.category = t.DOMString(val, "?");
+ } catch (e) {
+ }
+ });
-_i.SystemSettingManager.getProperty = {
- 0: _t.SystemSettingType,
- 1: _t.SystemSettingSuccessCallback,
- 2: _t.ErrorCallback,
+ this.__defineGetter__("data", function () {
+ return applicationControl.data;
+ });
+ this.__defineSetter__("data", function (val) {
+ var i;
- _optional: {
- 2: true
- }
+ try {
+ t.ApplicationControlData(val, "[]");
+ for (i in val) {
+ applicationControl.data[i] = new ApplicationControlData(
+ val[i].key, val[i].value);
+ }
+ } catch (e) {
+ }
+ });
};
+module.exports = ApplicationControl;
+
+});
+define('ripple/platform/ivi/3.0/errorcode', function (require, exports, module) {
/*
- * Time
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
*/
-// TimeUtil
-_i.TimeUtil.getCurrentDateTime = null;
-_i.TimeUtil.getLocalTimezone = null;
-_i.TimeUtil.getAvailableTimezones = null;
-_i.TimeUtil.getTimeFormat = null;
-
-_i.TimeUtil.getDateFormat = {
- 0: _t.boolean,
-
- _optional: {
- 0: true
- }
-};
-
-_i.TimeUtil.isLeapYear = {
- 0: _t.long
-};
-
-// TimeDuration
-_i.TimeDuration.difference = {
- 0: _t.TimeDuration
-};
-
-_i.TimeDuration.equalsTo = {
- 0: _t.TimeDuration
-};
+var _self = {};
-_i.TimeDuration.lessThan = {
- 0: _t.TimeDuration
-};
+_self.__defineGetter__("PERMISSION_DENIED", function () {
+ return 1;
+});
-_i.TimeDuration.greaterThan = {
- 0: _t.TimeDuration
-};
+_self.__defineGetter__("PROPERTY_UNAVAILABLE", function () {
+ return 2;
+});
-_i.Vehicle.getSupported = {
- 0: _t.SupportedPropertiesSuccessCallback,
- 1: _t.VehiclePropertyErrorCallback
-}
+_self.__defineGetter__("TIMEOUT", function () {
+ return 3;
+});
-// Exports
-_t.constructor = _c;
-_t.interface = _i;
+_self.__defineGetter__("UNKNOWN", function () {
+ return 10;
+});
-module.exports = _t;
+module.exports = _self;
});
-define('ripple/platform/tizen/2.0/vibration', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/VehiclePanelEngine', function (require, exports, module) {
+
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var event = require('ripple/event'),
- deviceSettings = require('ripple/deviceSettings'),
- constants = require('ripple/constants'),
- tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
- emulatorBridge = require('ripple/emulatorBridge'),
- curPost,
- _self;
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ dbinit = require('ripple/platform/ivi/3.0/dbinit'),
+ _vehicleMapStack = {},
+ _databaseName = "ivi-vehicle-database",
+ VehiclePanelEngine;
-function isVibratorOn() {
- return deviceSettings.retrieve("Config.vibratingMode");
+function _save (data) {
+ db.saveObject(_databaseName, data);
}
-var vibrator = (function () {
- var vibratorPattern,
- isVibrating = false,
- runTime = 0,
- vibrateTimeout = null,
- MILLILSECONDS_OF_ONE_VIBRATION = 100,
- node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
- movementIndex = 0,
- movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
- {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];
+function _get () {
+ var database = db.retrieveObject(_databaseName);
- function _clearTimeout() {
- if (vibrateTimeout) {
- clearInterval(vibrateTimeout);
- vibrateTimeout = null;
- }
+ if (!database) {
+ db.saveObject(_databaseName, dbinit.Vehicle);
+ database = db.retrieveObject(_databaseName);
}
- function stopVibrate() {
- isVibrating = false;
- _clearTimeout();
- node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
- }
+ return database;
+}
- function vibrate() {
- node.css(movement[movementIndex]);
- movementIndex = (movementIndex + 1) % 8;
- }
+VehiclePanelEngine = function () {
+ var _CONFIGURATION = "configuration", _AUTO = "auto",
+ _database,
+ _configuration, _currentConfiguration,
+ _supported, _settings, _autoRunning;
- function changePulse() {
- if (emulatorBridge.document().hidden) {
- return;
- }
+ function _init () {
+ _database = _get();
- //run time
- runTime = runTime + MILLILSECONDS_OF_ONE_VIBRATION;
- if (curPost >= vibratorPattern.length) {
- setTimeout(stopVibrate, 1);
- }
- if (runTime > vibratorPattern[curPost]) {
- curPost = curPost + 1;
- runTime = 0;
- } else {
- if ((curPost % 2) === 0) {
- vibrate();
- }
- }
- }
+ _settings = _database.settingData;
- function startVibrate(_pattern) {
- if (!isVibratorOn())
- return;
+ _configuration = _database.configurationData;
+ _currentConfiguration = _database.currentConfiguration;
- vibratorPattern = _pattern;
- _clearTimeout();
- movementIndex = 0;
- if (_pattern) {
- runTime = 0;
- vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
- }
- isVibrating = true;
+ _supported = _database.supported;
+
+ _autoRunning = _database.autoRunningData;
}
- return {
- isVibrating: isVibrating,
- startVibrate: startVibrate,
- stopVibrate: stopVibrate
+ this.saveData = function (supported, currentConfiguration, configuration, settings, autoRunning) {
+ _database.supported = supported;
+ _database.currentConfiguration = currentConfiguration;
+ _database.settingData = settings;
+ _database.configurationData[currentConfiguration] = configuration;
+ _database.autoRunningData[0] = autoRunning;
+
+ _save(_database);
};
-}());
-_self = {
- vibrate: function () {
- var pattern = arguments[0],
- i;
+ function _formatVehicleDB (map, db) {
+ var formatSettings = {},
+ VehicleMap = map, vehicleData = db,
+ property, name, item, i = 0;
- // If vibrator is off, stop the vibration
- event.on("VibratingModeChanged", function (value) {
- if (value === false) {
- vibrator.stopVibrate();
+ for (property in VehicleMap) {
+ name = property.split("-")[0];
+ item = property.split("-")[1];
+
+ if (!formatSettings[name]) {
+ formatSettings[name] = {};
}
- });
- //1. If the hidden attribute [PAGE-VISIBILITY] is set to true, abort these steps.
- if (emulatorBridge.document().hidden) {
- return;
+ formatSettings[name][item] = utils.copy(VehicleMap[property]);
+ formatSettings[name][item].value = vehicleData[i];
+
+ i++;
}
- //2. Let pattern be the value of the first argument.
- if (!tizen1_utils.isValidArray(pattern)) {
- pattern |= 0;
- } else {
- for (i = 0; i < pattern.length; i++) {
- pattern[i] |= 0;
+ return formatSettings;
+ }
+
+ /**
+ * get
+ * @return {Object}
+ */
+ this.getConfiguration = function () {
+ var configuration = {}, i, j, dataIndex, tempArray,
+ configurationMap = _vehicleMapStack.vehicleConfigurationMap,
+ configurationData = _configuration;
+
+ for (j = 0; j < configurationData.length; j++) {
+ dataIndex = _CONFIGURATION + j;
+ configuration[dataIndex] = {};
+
+ for (i = 0; i < configurationMap.length; i++) {
+ tempArray = configurationMap[i].split("-");
+
+ if (!configuration[dataIndex][tempArray[0]]) {
+ configuration[dataIndex][tempArray[0]] = {};
+ }
+ configuration[dataIndex][tempArray[0]][tempArray[1]] = configurationData[j][i];
}
}
- //3. If pattern is 0, or an empty list, cancel the pre-existing instance of the processing vibration patterns algorithm, if any, and abort these steps.
- if (pattern === 0 || (tizen1_utils.isValidArray(pattern) && pattern.length === 0)) {
- vibrator.stopVibrate();
- return;
- }
+ return configuration;
+ };
+
+ /**
+ * get
+ * @return {String}
+ */
+ this.getCurrentConfiguration = function () {
+ return _CONFIGURATION + _currentConfiguration;
+ };
+
+ /**
+ * get
+ * @return {Array}
+ */
+ this.getProperties = function () {
+ return _vehicleMapStack.vehicleProperties;
+ };
+
+ /**
+ * get supported vehicle properties name.
+ * @return {Array}
+ */
+ this.getSupported = function () {
+ return _supported;
+ };
+
+ /**
+ * get property unit.
+ * @param property
+ * @param item
+ * @return {String}
+ */
+ this.getPropertyUnit = function (property, item) {
+ var unitKey = property + "-" + item,
+ propertyUnitMap = _vehicleMapStack.vehiclePropertyUnitsMap;
+
+ return !propertyUnitMap[unitKey] ? "" : "(" + propertyUnitMap[unitKey] + ")";
+ };
+
+ this.getPropertyRange = function (property, item) {
+ var rangeKey = property + "-" + item,
+ propertyRangeMap = _vehicleMapStack.vehiclePropertyRangeMap;
+
+ return !propertyRangeMap[rangeKey] ? false : propertyRangeMap[rangeKey];
+ };
+
+ /**
+ * get
+ * @param property
+ * @param item
+ * @return {*}
+ */
+ this.getPropertyConstant = function (property, item) {
+ var propertyConstants = _vehicleMapStack.vehiclePropertyConstantsMap;
- //4. If pattern is a list, proceed to the next step. Otherwise run the following substeps:
- //a. Let list be an initially empty list, and add pattern to list.
- //b. Let pattern be list.
- if (!tizen1_utils.isValidArray(pattern)) {
- pattern = [pattern];
- }
+ return !propertyConstants[property] ? null : propertyConstants[property][item];
+ };
- //5. If any entry of pattern exceeds an implementation-dependent limit, then the user agent may throw a NotSupportedError exception and abort these steps.
+ this.getSettings = function () {
+ return _formatVehicleDB(_vehicleMapStack.vehicleSettingMap, _settings);
+ };
- //6. If the length of pattern is even, then remove the last entry in pattern.
- if (pattern.length % 2 === 0) {
- pattern.pop();
- }
+ this.getAutoRunning = function () {
+ var autoRunning = {}, i,
+ autoRunningMap = _vehicleMapStack.vehicleAutoRunningMap,
+ autoRunningData = _autoRunning;
- //7. Cancel the pre-existing instance of the processing vibration patterns algorithm, if any.
- if (vibrator.isVibrating) {
- vibrator.stopVibrate();
+ for (i = 0; i < _autoRunning.length; i++) {
+ autoRunning[_AUTO + i] = _formatVehicleDB(autoRunningMap, autoRunningData[i]);
}
+ return autoRunning;
+ };
- curPost = 0;
- vibrator.startVibrate(pattern);
- }
+ _init();
};
-module.exports = _self;
+//can support all properties.
+_vehicleMapStack.vehicleProperties = [
+ "VehicleSpeed", "EngineSpeed", "VehiclePowerMode", "TripMeter",
+ "Acceleration", "Transmission", "CruiseControlStatus", "WheelBrake",
+ "LightStatus", "InteriorLightStatus", "Horn", "Fuel", "EngineOil",
+ "Location", "ExteriorBrightness", "Temperature", "RainSensor",
+ "WindshieldWiper", "HVAC", "WindowStatus", "Sunroof", "ConvertibleRoof",
+ "VehicleId", "Size", "FuelInfo", "VehicleType", "Doors",
+ "TransmissionGearType", "WheelInformation", "Odometer", "Fluid", "Battery",
+ "TirePressure", "TireTemperature", "SecurityAlert", "ParkingBrake",
+ "ParkingLight", "HazardLight", "AntilockBrakingSystem", "TractionControlSystem",
+ "VehicleTopSpeedLimit", "AirbagStatus", "DoorStatus", "SeatBeltStatus",
+ "OccupantStatus", "ObstacleDistance", "NightMode", "DrivingMode",
+ "TurnSignal", "ButtonEvent"
+];
-});
-define('ripple/platform/w3c/1.0/Acceleration', function (require, exports, module) {
-module.exports = function (x, y, z) {
- return {
- x: x || 0, //Acceleration in the 'x' expressed in m/s^2. (Number)
- y: y || 0, //Acceleration in the 'y' expressed in m/s^2. (Number)
- z: z || 0 //Acceleration in the 'z' expressed in m/s^2. (Number)
- };
-};
+//Vehicle Configuration
+_vehicleMapStack.vehicleConfigurationMap = [
+ "VehicleId-WMI", "VehicleId-VIN",
+ "Size-width", "Size-height", "Size-length",
+ "FuelInfo-type", "FuelInfo-refuelPosition",
+ "VehicleType-type",
+ "Doors-doorsPerRow",
+ "TransmissionGearType-transmissionGearType",
+ "WheelInformation-frontWheelRadius", "WheelInformation-rearWheelRadius", "WheelInformation-wheelTrack", "WheelInformation-ABS"
+];
-});
-define('ripple/platform/w3c/1.0/Coordinates', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function (latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed) {
- return {
- latitude: latitude || 0, //Latitude in decimal degrees. (Number)
- longitude: longitude || 0, //Longitude in decimal degrees. (Number)
- altitude: altitude || 0, //Height of the position in meters above the ellipsoid. (Number)
- accuracy: accuracy || 0, //Accuracy level of the latitude and longitude coordinates in meters. (Number)
- altitudeAccuracy: altitudeAccuracy || 0, //Accuracy level of the altitude coordinate in meters. (Number)
- heading: heading || 0, //Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
- speed: speed || 0 //Current ground speed of the device, specified in meters per second. (Number)
- };
+//all ranged attributes' min. max and step.
+_vehicleMapStack.vehiclePropertyRangeMap = {
+ "VehicleSpeed-vehicleSpeed": [0, 400, 1],
+ "EngineSpeed-engineSpeed": [0, 10000, 20],
+ "Acceleration-x": [0, 200, 1],
+ "Acceleration-y": [0, 200, 1],
+ "Acceleration-z": [0, 200, 1],
+ "Fuel-level": [0, 100, 1],
+ "Fuel-range": [0, 1000, 1],
+ "Fuel-instantConsumption": [0, 100, 1],
+ "Fuel-instantEconomy": [0, 100, 1],
+ "Fuel-averageEconomy": [0, 100, 1],
+ "EngineOil-remaining": [0, 100, 1],
+ "EngineOil-temperature": [0, 100, 1],
+ "EngineOil-pressure": [0, 1000, 1],
+ "Location-latitude": [-180, 180, 1],
+ "Location-longitude": [-19, 90, 1],
+ "Location-altitude": [0, 100, 1],
+ "Location-direction": [0, 360, 1],
+ "ExteriorBrightness-exteriorBrightness": [0, 100, 1],
+ "Temperature-interior": [-5, 35, 1],
+ "Temperature-exterior": [-40, 60, 1],
+ "Odometer-odometer": [0, 10000, 10],
+ "CruiseControlStatus-speed": [1, 100, 1],
+ "HVAC-targetTemperature": [0, 35, 7],
+ "Sunroof-openness": [0, 100, 1],
+ "Sunroof-tilt": [0, 100, 1],
+ "ConvertibleRoof-openness": [0, 100, 1],
+ "WindowStatus-openness": [0, 100, 1],
+ "VehicleTopSpeedLimit-vehicleTopSpeedLimit": [0, 400, 1],
+ "ObstacleDistance-obstacleDistance": [0, 120, 1],
+ "Fluid-transmission": [0, 100, 1],
+ "Fluid-brake": [0, 100, 1],
+ "Fluid-washer": [0, 100, 1],
+ "Battery-voltage": [0, 12, 1],
+ "Battery-current": [0, 200, 1],
+ "TirePressure-leftFront": [0, 500, 1],
+ "TirePressure-rightFront": [0, 500, 1],
+ "TirePressure-leftRear": [0, 500, 1],
+ "TirePressure-rightRear": [0, 500, 1],
+ "TireTemperature-leftFront": [0, 60, 1],
+ "TireTemperature-rightFront": [0, 60, 1],
+ "TireTemperature-leftRear": [0, 60, 1],
+ "TireTemperature-rightRear": [0, 60, 1],
+ "TurnSignal-turnSignal": [0, 100, 1],
+ "ButtonEvent-buttonEvent": [0, 100, 1]
};
-});
-define('ripple/platform/w3c/1.0/Position', function (require, exports, module) {
-/*
- * Copyright 2011 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 Coordinates = require('ripple/platform/w3c/1.0/Coordinates');
-
-module.exports = function () {
- return {
- coords: new Coordinates(),
- timestamp: new Date().getTime()
- };
+//simulate car running attributes' controller-types.
+_vehicleMapStack.vehicleAutoRunningMap = {
+ "VehicleSpeed-vehicleSpeed": {
+ "type": "range"
+ },
+ "EngineSpeed-engineSpeed": {
+ "type": "range"
+ },
+ "VehiclePowerMode-vehiclePowerMode": {
+ "type": "select",
+ "options": [{"OFF": 0},{"ACCESSORY1": 1},{"ACCESSORY2": 2},{"RUN": 3}]
+ },
+ "TripMeter-tripMeters": {
+ "type": "text"
+ },
+ "Acceleration-x": {
+ "type": "range"
+ },
+ "Acceleration-y": {
+ "type": "range"
+ },
+ "Acceleration-z": {
+ "type": "range"
+ },
+ "Fuel-level": {
+ "type": "range"
+ },
+ "Fuel-range": {
+ "type": "range"
+ },
+ "Fuel-instantConsumption": {
+ "type": "range"
+ },
+ "Fuel-instantEconomy": {
+ "type": "range"
+ },
+ "Fuel-averageEconomy": {
+ "type": "range"
+ },
+ "EngineOil-remaining": {
+ "type": "range"
+ },
+ "EngineOil-temperature": {
+ "type": "range"
+ },
+ "EngineOil-pressure": {
+ "type": "range"
+ },
+ "Location-latitude": {
+ "type": "range"
+ },
+ "Location-longitude": {
+ "type": "range"
+ },
+ "Location-altitude": {
+ "type": "range"
+ },
+ "Location-direction": {
+ "type": "range"
+ },
+ "ExteriorBrightness-exteriorBrightness": {
+ "type": "range"
+ },
+ "Temperature-interior": {
+ "type": "range"
+ },
+ "Temperature-exterior": {
+ "type": "range"
+ },
+ "RainSensor-rainSensor": {
+ "type": "select",
+ "options": [{"No Rain": 0},{"Rain 1": 1},{"Rain 2": 2},{"Rain 3": 3},{"Rain 4": 4},{"Rain 5": 5},
+ {"Rain 6": 6},{"Rain 7": 7},{"Rain 8": 8},{"Rain 9": 9},{"Heaviest": 10}]
+ },
+ "Odometer-odometer": {
+ "type": "range"
+ },
+ "TurnSignal-turnSignal": {
+ "type": "range"
+ },
+ "ButtonEvent-buttonEvent": {
+ "type": "range"
+ }
};
-});
-define('ripple/platform/w3c/1.0/PositionError', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self = function () {
- return {
- code: undefined,
- message: undefined
- };
+//Vehicle Setting attributes' controller-types.
+_vehicleMapStack.vehicleSettingMap = {
+ "Transmission-gearPosition": {
+ "type": "select",
+ "options": [{"NEUTRAL": 0},{"FIRST": 1},{"SECOND": 2},{"THIRD": 3}, {"FORTH": 4},{"FIFTH": 5},
+ {"SIXTH": 6},{"SEVENTH": 7}, {"EIGHTH": 8},{"NINTH": 9},{"TENTH": 10},{"CVT": 64},
+ {"REVERSE": 128},{"PARK": 255}]
+ },
+ "Transmission-mode": {
+ "type": "select",
+ "options": [{"NORMAL": 0},{"SPORT": 1},{"ECONOMY": 2}, {"OEMCUSTOM1": 3},{"OEMCUSTOM2": 4}]
+ },
+ "CruiseControlStatus-activated": {
+ "type": "radio",
+ "options": [{"Active": true}, {"Inactive": false}]
+ },
+ "CruiseControlStatus-speed": {
+ "type": "range"
+ },
+ "WheelBrake-engaged": {
+ "type": "radio",
+ "options": [{"Engaged": true}, {"Disengaged": false}]
+ },
+ "LightStatus-head": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-rightTurn": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-leftTurn": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-brake": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-fog": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-hazard": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-parking": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "LightStatus-highBeam": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "InteriorLightStatus-passenger": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "InteriorLightStatus-driver": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "InteriorLightStatus-center": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "Horn-on": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "WindshieldWiper-windshieldWiper": {
+ "type": "select",
+ "options": [{"OFF": 0},{"SLOWEST": 1},{"FASTEST": 5},{"AUTO": 10}]
+ },
+ "HVAC-airflowDirection": {
+ "type": "select",
+ "options": [{"FRONTPANEL": 0},{"FLOORDUCT": 1},{"FRONT": 0x02}, {"DEFROSTER": 0x04}]
+ },
+ "HVAC-fanSpeed": {
+ "type": "select",
+ "options": [{"0": 0},{"1": 1},{"2": 2},{"3": 3},{"4": 4},{"5": 5}, {"6": 6},{"7": 7}]
+ },
+ "HVAC-targetTemperature": {
+ "type": "range"
+ },
+ "HVAC-airConditioning": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "HVAC-airRecirculation": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "HVAC-heater": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "HVAC-steeringWheelHeater": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "HVAC-seatHeater": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "HVAC-seatCooler": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "Sunroof-openness": {
+ "type": "range"
+ },
+ "Sunroof-tilt": {
+ "type": "range"
+ },
+ "ConvertibleRoof-openness": {
+ "type": "range"
+ },
+ "SecurityAlert-securityAlert": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "ParkingBrake-parkingBrake": {
+ "type": "radio",
+ "options": [{"Engaged": true}, {"Disengaged": false}]
+ },
+ "ParkingLight-parkingLight": {
+ "type": "radio",
+ "options": [{"Engaged": true}, {"Disengaged": false}]
+ },
+ "HazardLight-hazardLight": {
+ "type": "radio",
+ "options": [{"Engaged": true}, {"Disengaged": false}]
+ },
+ "AntilockBrakingSystem-antilockBrakingSystem": {
+ "type": "radio",
+ "options":[{"Engaged": true}, {"Idle": false}]
+ },
+ "TractionControlSystem-tractionControlSystem": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "VehicleTopSpeedLimit-vehicleTopSpeedLimit": {
+ "type": "range"
+ },
+ "WindowStatus-openness": {
+ "type": "range"
+ },
+ "WindowStatus-defrost": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "AirbagStatus-airbagStatus": {
+ "type": "select",
+ "options": [{"INACTIVE": 0},{"ACTIVE": 1},{"DEPLOYED": 2}]
+ },
+ "DoorStatus-doorStatus": {
+ "type": "select",
+ "options": [{"CLOSED": 0},{"OPEN": 1},{"AJAR": 2}]
+ },
+ "DoorStatus-doorLockStatus": {
+ "type": "radio",
+ "options": [{"Locked": true}, {"Unlocked": false}]
+ },
+ "DoorStatus-childLockStatus": {
+ "type": "radio",
+ "options": [{"On": true}, {"Off": false}]
+ },
+ "SeatBeltStatus-seatBeltStatus": {
+ "type": "radio",
+ "options": [{"Fasten": true}, {"Unfastened": false}]
+ },
+ "OccupantStatus-occupantStatus": {
+ "type": "select",
+ "options": [{"VACANT": 0},{"CHILD": 1},{"ADULT": 2}]
+ },
+ "ObstacleDistance-obstacleDistance": {
+ "type": "range"
+ },
+ "NightMode-nightMode": {
+ "type": "radio",
+ "options": [{"Night": true}, {"Day": false}]
+ },
+ "DrivingMode-drivingMode": {
+ "type": "select",
+ "options": [{"Not Driving": 0},{"Driving": 1}]
+ },
+ "Fluid-transmission": {
+ "type": "range"
+ },
+ "Fluid-brake": {
+ "type": "range"
+ },
+ "Fluid-washer": {
+ "type": "range"
+ },
+ "Battery-voltage": {
+ "type": "range"
+ },
+ "Battery-current": {
+ "type": "range"
+ },
+ "TirePressure-leftFront": {
+ "type": "range"
+ },
+ "TirePressure-rightFront": {
+ "type": "range"
+ },
+ "TirePressure-leftRear": {
+ "type": "range"
+ },
+ "TirePressure-rightRear": {
+ "type": "range"
+ },
+ "TireTemperature-leftFront": {
+ "type": "range"
+ },
+ "TireTemperature-rightFront": {
+ "type": "range"
+ },
+ "TireTemperature-leftRear": {
+ "type": "range"
+ },
+ "TireTemperature-rightRear": {
+ "type": "range"
+ }
};
-_self.PERMISSION_DENIED = "PERMISSION_DENIED";
-_self.POSITION_UNAVAILABLE = "POSITION_UNAVAILABLE";
-_self.TIMEOUT = "TIMEOUT";
-
-module.exports = _self;
+//attributes units
+_vehicleMapStack.vehiclePropertyUnitsMap = {
+ "VehicleSpeed-vehicleSpeed": "kph",
+ "EngineSpeed-engineSpeed": "rpm",
+ "TripMeter-tripMeters": "[m,...]",
+ "CruiseControlStatus-speed": "kph",
+ "Fuel-level": "%",
+ "Fuel-instantConsumption": "ml/s",
+ "Fuel-instantEconomy": "km/l",
+ "Fuel-averageEconomy": "km/l",
+ "EngineOil-remaining": "%",
+ "EngineOil-temperature": "C",
+ "EngineOil-pressure": "kpa",
+ "ExteriorBrightness-exteriorBrightness": "lux",
+ "Temperature-interior": "C",
+ "Temperature-exterior": "C",
+ "HVAC-targetTemperature": "C",
+ "Sunroof-openness": "%",
+ "Sunroof-tilt": "%",
+ "ConvertibleRoof-openness": "%",
+ "WindowStatus-openness": "%",
+ "ObstacleDistance-obstacleDistance": "m",
+ "Size-width": "mm",
+ "Size-height": "mm",
+ "Size-length": "mm",
+ "WheelInformation-frontWheelRadius": "mm",
+ "WheelInformation-rearWheelRadius": "mm",
+ "WheelInformation-wheelTrack": "mm",
+ "Odometer-odometer": "km",
+ "Fluid-transmission": "%",
+ "Fluid-brake": "%",
+ "Fluid-washer": "%",
+ "Battery-voltage": "V",
+ "Battery-current": "A",
+ "TirePressure-leftFront": "kpa",
+ "TirePressure-rightFront": "kpa",
+ "TirePressure-leftRear": "kpa",
+ "TirePressure-rightRear": "kpa",
+ "TireTemperature-leftFront": "C",
+ "TireTemperature-rightFront": "C",
+ "TireTemperature-leftRear": "C",
+ "TireTemperature-rightRear": "C",
+ "VehicleTopSpeedLimit-vehicleTopSpeedLimit": "kph"
+};
-});
-define('ripple/platform/w3c/1.0/Rotation', function (require, exports, module) {
-module.exports = function (alpha, beta, gamma) {
- return {
- alpha: alpha || 0, //Rotation about the 'z' axis expressed in degrees [0, 360]. (Number)
- beta: beta || 0, //Rotation about the 'x' axis expressed in degrees [-180, 180]. (Number)
- gamma: gamma || 0 //Rotation about the 'y' axis expressed in degrees [-90, 90]. (Number)
- };
+//key and value of select types in attributes
+_vehicleMapStack.vehiclePropertyConstantsMap = {
+ "FuelInfo": {
+ "type": {
+ "val0": "GASOLINE",
+ "val1": "HIGH_OCTANE",
+ "val2": "DIESEL",
+ "val3": "ELECTRIC",
+ "val4": "HYDROGEN"
+ },
+ "refuelPosition": {
+ "val0": "LEFT",
+ "val1": "RIGHT",
+ "val2": "FRONT",
+ "val3": "REAR"
+ }
+ },
+ "VehicleType": {
+ "type": {
+ "val0": "SEDAN",
+ "val1": "COUPE",
+ "val2": "CABRIOLE",
+ "val3": "ROADSTER",
+ "val4": "SUV",
+ "val5": "TRUCK"
+ }
+ },
+ "TransmissionGearType": {
+ "transmissionGearType": {
+ "val0": "AUTO",
+ "val1": "MANUAL",
+ "val2": "CV"
+ }
+ },
+ "VehiclePowerMode": {
+ "vehiclePowerMode": {
+ "val0": "OFF",
+ "val1": "ACCESSORY1",
+ "val2": "ACCESSORY2",
+ "val3": "RUN"
+ }
+ }
};
+exports.VehiclePanelEngine = new VehiclePanelEngine();
+
});
-define('ripple/platform/w3c/1.0/SensorConnection', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/spec', function (require, exports, module) {
/*
* Copyright 2012 Intel Corporation.
*
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- platform = require('ripple/platform'),
- event = require('ripple/event'),
- sensorSettings = require('ripple/sensorSettings'),
- accelerometer = require('ripple/accelerometer'),
- exception = require('ripple/exception'),
-
- _permission = true,
- _self;
-
-function ErrorMsg() {
- this.__defineGetter__("UNKNOWN_ERROR", function () {
- return "An unknown error has occurred.";
- });
-
- this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
- return "The object type is incompatible with the expected type.";
- });
-
- this.__defineGetter__("INVALID_VALUES_ERROR", function () {
- return "The content of an object does not contain valid values.";
- });
-
- this.__defineGetter__("ILLEGAL_STATE", function () {
- return "The status of connection is illegal.";
- });
-}
-
-// TODO: Should be replaced by a global object in tizen 1.0
-function ErrorCode() {
- this.__defineGetter__("UNKNOWN_ERR", function () {
- return 0;
- });
-
- this.__defineGetter__("INVALID_VALUES_ERROR", function () {
- return 1;
- });
-
- this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
- return 2;
- });
-
- this.__defineGetter__("ILLEGAL_STATE", function () {
- return 3;
- });
-}
-
-function SensorError(code, msg) {
- this.__defineGetter__("message", function () {
- return msg;
- });
- this.__defineGetter__("code", function () {
- return code;
- });
-
- this.PERMISSION_DENIED = -100;
-}
-
-function Event() {
- var _self = {
- CAPTURING_PHASE: 1,
- AT_TARGET: 2,
- BUBBLING_PHASE: 3,
-
- type: '',
- target: null, //new EventTarget(),
- currentTarget: null, //new EventTarget(),
- eventPhase: 0,
- bubbles: false,
- cancelable: false,
- timeStamp: 0
- };
-
- this.__defineGetter__("type", function () {
- return _self.type;
- });
-
- this.__defineGetter__("target", function () {
- return _self.target;
- });
-
- this.__defineGetter__("currentTarget", function () {
- return _self.currentTarget;
- });
-
- this.__defineGetter__("eventPhase", function () {
- return _self.eventPhase;
- });
-
- this.__defineGetter__("bubbles", function () {
- return _self.bubbles;
- });
-
- this.__defineGetter__("cancelable", function () {
- return _self.cancelable;
- });
-
- this.__defineGetter__("timeStamp", function () {
- return _self.timeStamp;
- });
-
- this.stopPropagation = function () {};
-
- this.preventDefault = function () {};
-
- this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
- _self.type = eventTypeArg;
- _self.bubbles = canBubbleArg;
- _self.cancelable = cancelableArg;
- };
-
- return _self;
-}
-
-function SensorDataEvent() {
- var _self = {
- data: 0,
- accuracy: 0,
- timestamp: 0,
- reason: ''
- };
-
- // This type of event inherit from Event
- Event.call(this);
-
- this.__defineGetter__("data", function () {
- return _self.data;
- });
-
- this.__defineGetter__("accuracy", function () {
- return _self.accuracy;
- });
+module.exports = {
- this.__defineGetter__("timestamp", function () {
- return _self.timestamp;
- });
+ id: "ivi",
+ version: "3.0",
+ name: "IVI",
- this.__defineGetter__("reason", function () {
- return _self.reason;
- });
+ persistencePrefix: "ivi3-",
- this.initSensorDataEvent = function (type, bubbles, cancelable, reason, timestamp, accuracy, data) {
- this.initEvent(type, bubbles, cancelable);
+ config: require('ripple/platform/ivi/3.0/spec/config'),
+ ui: require('ripple/platform/ivi/3.0/spec/ui'),
+ device: require('ripple/platform/ivi/3.0/spec/device'),
+ sensor: require('ripple/platform/ivi/3.0/spec/sensor'),
+ DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
+ DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),
- _self.reason = reason;
- _self.timestamp = timestamp;
- _self.accuracy = accuracy;
-
- // If the data has only one part, just return the value, not the data object
- if (utils.count(data) === 1) {
- utils.forEach(data, function (section, key) {
- _self.data = data[key];
- });
- }
- else {
- _self.data = utils.copy(data);
+ objects: {
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ SensorConnection: {
+ path: "w3c/1.0/SensorConnection"
+ },
+ navigator: {
+ path: "tizen/2.0/navigator",
+ children: {
+ geolocation: {
+ path: "wac/2.0/geolocation"
+ },
+ battery: {
+ path: "tizen/2.0/battery"
+ }
+ }
+ },
+ tizen: {
+ feature: "http://tizen.org/privilege/tizen",
+ children: {
+ AlarmAbsolute: {
+ path: "tizen/2.0/AlarmAbsolute"
+ },
+ AlarmRelative: {
+ path: "tizen/2.0/AlarmRelative"
+ },
+ ApplicationControl: {
+ path: "tizen/2.0/ApplicationControl"
+ },
+ ApplicationControlData: {
+ path: "tizen/2.0/ApplicationControlData"
+ },
+ AttributeFilter: {
+ path: "tizen/2.0/AttributeFilter"
+ },
+ AttributeRangeFilter: {
+ path: "tizen/2.0/AttributeRangeFilter"
+ },
+ BookmarkFolder: {
+ path: "tizen/2.0/BookmarkFolder"
+ },
+ BookmarkItem: {
+ path: "tizen/2.0/BookmarkItem"
+ },
+ CalendarAlarm: {
+ path: "tizen/2.0/CalendarAlarm"
+ },
+ CalendarAttendee: {
+ path: "tizen/2.0/CalendarAttendee"
+ },
+ CalendarEvent: {
+ path: "tizen/2.0/CalendarEvent"
+ },
+ CalendarEventId: {
+ path: "tizen/2.0/CalendarEventId"
+ },
+ CalendarRecurrenceRule: {
+ path: "tizen/2.0/CalendarRecurrenceRule"
+ },
+ CalendarTask: {
+ path: "tizen/2.0/CalendarTask"
+ },
+ CompositeFilter: {
+ path: "tizen/2.0/CompositeFilter"
+ },
+ Contact: {
+ path: "tizen/2.0/ContactBase"
+ },
+ ContactAddress: {
+ path: "tizen/2.0/ContactAddress"
+ },
+ ContactAnniversary: {
+ path: "tizen/2.0/ContactAnniversary"
+ },
+ ContactEmailAddress: {
+ path: "tizen/2.0/ContactEmailAddress"
+ },
+ ContactGroup: {
+ path: "tizen/2.0/ContactGroup"
+ },
+ ContactName: {
+ path: "tizen/2.0/ContactName"
+ },
+ ContactOrganization: {
+ path: "tizen/2.0/ContactOrganization"
+ },
+ ContactPhoneNumber: {
+ path: "tizen/2.0/ContactPhoneNumber"
+ },
+ ContactRef: {
+ path: "tizen/2.0/ContactRef"
+ },
+ ContactWebSite: {
+ path: "tizen/2.0/ContactWebSite"
+ },
+ DownloadRequest: {
+ path: "tizen/2.0/DownloadRequest"
+ },
+ Message: {
+ path: "tizen/2.0/Message"
+ },
+ NDEFMessage: {
+ path: "tizen/2.0/NDEFMessage"
+ },
+ NDEFRecord: {
+ path: "tizen/2.0/NDEFRecord"
+ },
+ NDEFRecordMedia: {
+ path: "tizen/2.0/NDEFRecordMedia"
+ },
+ NDEFRecordText: {
+ path: "tizen/2.0/NDEFRecordText"
+ },
+ NDEFRecordURI: {
+ path: "tizen/2.0/NDEFRecordURI"
+ },
+ NotificationDetailInfo: {
+ path: "tizen/2.0/NotificationDetailInfo"
+ },
+ SimpleCoordinates: {
+ path: "tizen/2.0/SimpleCoordinates"
+ },
+ SortMode: {
+ path: "tizen/2.0/SortMode"
+ },
+ StatusNotification: {
+ path: "tizen/2.0/StatusNotification"
+ },
+ SyncInfo: {
+ path: "tizen/2.0/SyncInfo"
+ },
+ SyncServiceInfo: {
+ path: "tizen/2.0/SyncServiceInfo"
+ },
+ SyncProfileInfo: {
+ path: "tizen/2.0/SyncProfileInfo"
+ },
+ TZDate: {
+ path: "tizen/2.0/TZDate"
+ },
+ TimeDuration: {
+ path: "tizen/2.0/TimeDuration"
+ },
+ alarm: {
+ path: "tizen/2.0/alarm",
+ feature: "http://tizen.org/privilege/alarm",
+ handleSubfeatures: true
+ },
+ application: {
+ path: "tizen/2.0/application",
+ feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
+ handleSubfeatures: true
+ },
+ bluetooth: {
+ path: "tizen/2.0/bluetooth",
+ feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
+ handleSubfeatures: true
+ },
+ bookmark: {
+ path: "tizen/2.0/bookmark",
+ feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
+ handleSubfeatures: true
+ },
+ callhistory: {
+ path: "tizen/2.0/callHistory",
+ feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
+ handleSubfeatures: true
+ },
+ calendar: {
+ path: "tizen/2.0/calendar",
+ feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
+ handleSubfeatures: true
+ },
+ contact: {
+ path: "tizen/2.0/contact",
+ feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
+ handleSubfeatures: true
+ },
+ content: {
+ path: "tizen/2.0/content",
+ feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
+ handleSubfeatures: true
+ },
+ datacontrol: {
+ path: "tizen/2.0/datacontrol",
+ feature: "http://tizen.org/privilege/datacontrol.consumer",
+ handleSubfeatures: true
+ },
+ datasync: {
+ path: "tizen/2.0/datasync",
+ feature: "http://tizen.org/privilege/datasync",
+ handleSubfeatures: true
+ },
+ download: {
+ path: "tizen/2.0/download",
+ feature: "http://tizen.org/privilege/download",
+ handleSubfeatures: true
+ },
+ filesystem: {
+ path: "tizen/2.0/filesystem",
+ feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
+ },
+ messageport: {
+ path: "tizen/2.0/messageport"
+ },
+ messaging: {
+ path: "tizen/2.0/messaging",
+ feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
+ handleSubfeatures: true
+ },
+ networkbearerselection: {
+ path: "tizen/2.0/networkbearerselection",
+ feature: "http://tizen.org/privilege/networkbearerselection",
+ handleSubfeatures: true
+ },
+ nfc: {
+ path: "tizen/2.0/nfc",
+ feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
+ handleSubfeatures: true
+ },
+ notification: {
+ path: "tizen/2.0/notification",
+ feature: "http://tizen.org/privilege/notification",
+ handleSubfeatures: true
+ },
+ package: {
+ path: "tizen/2.0/package",
+ feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
+ handleSubfeatures: true
+ },
+ power: {
+ path: "tizen/2.0/power",
+ feature: "http://tizen.org/privilege/power",
+ handleSubfeatures: true
+ },
+ push: {
+ path: "tizen/2.0/push",
+ feature: "http://tizen.org/privilege/push",
+ handleSubfeatures: true
+ },
+ systeminfo: {
+ path: "tizen/2.0/systeminfo",
+ feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
+ handleSubfeatures: true
+ },
+ systemsetting: {
+ path: "tizen/2.0/systemsetting",
+ feature: "http://tizen.org/privilege/setting",
+ handleSubfeatures: true
+ },
+ time: {
+ path: "tizen/2.0/time",
+ feature: "http://tizen.org/privilege/time",
+ handleSubfeatures: true
+ },
+ vehicle: {
+ path: "ivi/3.0/vehicle",
+ feature: "http://tizen.org/privilege/vehicle",
+ handleSubfeatures: true
+ }
+ }
}
- };
-}
-
-// As only one sensor will be used during the simulation with a SensorConnection object,
-// we can get that sensor object first and then the following read or write operations will be simplified
-function _getSensorObj(type, name) {
- var settings = platform.current().sensor, _sensor;
+ }
+};
- utils.forEach(settings, function (settingSection, settingType) {
- if (settingSection.type === type) {
+});
+define('ripple/platform/ivi/3.0/dbinit', function (require, exports, module) {
+/*
+ * Copyright 2013 Intel Corporation.
+ *
+ * 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.
+ */
- if (settingSection.name && settingSection.name !== name) {
- return;
- }
+var exception = require('ripple/exception'),
+ DBBuilder,
+ _data = {
+ dbBuilder: null
+ },
+ _self = {};
- _sensor = utils.copy(settingSection);
- }
- });
+function _initialize() {
+ _data.dbBuilder = new DBBuilder();
- return _sensor;
+ _data.dbBuilder.register("Vehicle", "dbvehicle.json");
}
-function _getAccelerometerData(dataType) {
- var accelerometerData, data = {};
+DBBuilder = function () {
+ var self;
- switch (dataType) {
- case "Accelerometer":
- accelerometerData = accelerometer.getInfo();
- data = {
- x: accelerometerData.acceleration.x,
- y: accelerometerData.acceleration.y,
- z: accelerometerData.acceleration.z
- };
- break;
- case "Rotation":
- accelerometerData = accelerometer.getInfo();
- data = {
- x: accelerometerData.orientation.alpha,
- y: accelerometerData.orientation.beta,
- z: accelerometerData.orientation.gamma
- };
- break;
- case "Orientation":
- accelerometerData = accelerometer.getInfo();
- data = {
- alpha: accelerometerData.orientation.alpha,
- beta: accelerometerData.orientation.beta,
- gamma: accelerometerData.orientation.gamma
- };
- break;
- default:
- break;
+ // private
+ function formatString(str) {
+ return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, "");
}
- return data;
-}
+ // private
+ function formatHex(str) {
+ return str.replace(/,(0x[0-9a-fA-F]+?),/g, ',"$1",');
+ }
-// The parameter of event callback is an object that contains the latest value, not the value itself,
-// so we need a function to create such object.
-function _getSensorData(sensorType, sensor, onerror) {
- var data = {}, value;
+ // public
+ function register(type, dbFile, Extension) {
+ _data[type] = Extension ? new Extension() : {};
- if (sensorType === "Accelerometer" || sensorType === "Rotation" || sensorType === "Orientation") {
- return _getAccelerometerData(sensorType);
+ if (!dbFile)
+ return;
+
+ _self.__defineGetter__(type, function () {
+ var fnInit;
+
+ if (!_data[type].db) {
+ fnInit = _data[type].initdb || initdb;
+ _data[type].db = fnInit(dbFile);
+ }
+
+ return _data[type].db;
+ });
}
- utils.forEach(sensor, function (sensorSection, key) {
+ function initdb(dbFile) {
+ var xmlHttp, res;
+
try {
- value = sensorSettings.retrieve(sensorType + "." + key);
+ xmlHttp = new XMLHttpRequest();
+ xmlHttp.open("GET", "dbsamples/" + dbFile, false);
+ xmlHttp.send();
+ } catch (e) {
+ exception.handle(e);
}
- catch (e) {
- if (onerror) {
- onerror(e);
- }
+
+ if (!xmlHttp.responseText) {
+ return null;
}
-
- if (value) {
- data[key] = value;
- }
- });
-
- return data;
-}
-// As the event type in sensor.js file are named in this way, so we can get it with this function.
-function _getSensorEventTypes(type, sensor) {
- var types = [];
+ res = formatHex(formatString(xmlHttp.responseText));
- if (type === "Accelerometer" || type === "Rotation" || type === "Orientation") {
- return ["AccelerometerInfoChangedEvent"];
+ return JSON.parse(res);
}
- utils.forEach(sensor, function (sensorSection, sensorType) {
- if (typeof sensorSection === "object") {
- types.push(type + "-" + sensorType + "Changed");
- }
- });
-
- return types;
-}
+ self = {
+ register: register,
+ initdb: initdb
+ };
-function _onEventCallback(type, options, currentSensor, length, eventCallback, onerror) {
- return function (values) {
- var sensorEvent = new SensorDataEvent();
+ return self;
+};
- // Only the sensor that has one attribute could be compared with the threshold
- if (options && options.threshold && length === 1 && values[0] < options.threshold) {
- return;
- }
+_initialize();
- if (eventCallback) {
- sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(),
- currentSensor.resolution, _getSensorData(type, currentSensor, onerror));
+module.exports = _self;
- eventCallback(sensorEvent);
- }
- };
-}
+});
+define('ripple/platform/ivi/3.0/spec/config', function (require, exports, module) {
+/*
+ * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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 utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants');
-function _bind(name, obj) {
- var callback = null;
+module.exports = {
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ // no xmlns:JIL in wac 2.0 spec
+ valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
- obj.__defineGetter__(name, function () {
- return callback;
- });
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
+ }
- obj.__defineSetter__(name, function (cb) {
- callback = cb;
- });
+ var widgetInfo = {},
+ configFeatures,
+ configPreferences,
+ preferenceName,
+ platform, rst, i, j,
+ settingRst = {
+ 'screen-orientation': 'portrait',
+ 'context-menu': 'enable',
+ 'background-support': 'disable',
+ encryption: 'disable',
+ 'install-location': 'auto',
+ 'hwkey-event': 'enable'
+ };
- return {
- get: function () {
- return callback;
- },
- set: function (value) {
- callback = value;
- },
- exec: function (arg) {
- return callback && callback(arg);
- },
- unbind: function (cb) {
- callback = cb === callback ? null : callback;
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+ if (configValidationObject.widget.children.application.validationResult[0].valid) {
+ widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
+ widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
}
- };
-}
-function SensorConnection(type, name) {
- var _self,
- currentSensor = _getSensorObj(type, name),
- sensorEvent = new SensorDataEvent(),
- sensorEventTypes = _getSensorEventTypes(type, currentSensor),
- watches = [],
- _errorCode = new ErrorCode(),
- _errorMsg = new ErrorMsg(),
- sensorListener;
+ widgetInfo.features = {};
- if (currentSensor) {
- _self = {
- sensor: {
- resolution: currentSensor.resolution,
- minDelay: currentSensor.minDelay,
- range: currentSensor.range,
- name: currentSensor.name,
- type: currentSensor.type
- },
- status: "open",
- error: null,
- read: function () {
+ if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
+ rst = configValidationObject.widget.children.setting.validationResult;
+ // the first one has higher priority per platform implementation
+ for (i = rst.length -1 ; i >= 0; i--) {
+ if (rst[i].valid === true) {
+ for (j in rst[i].attributes) {
+ if (rst[i].attributes[j].value !== undefined) {
+ settingRst[j] = rst[i].attributes[j].value;
+ }
+ }
+ }
+ }
+ db.save("layout", settingRst["screen-orientation"]);
+ }
- if (_self.status !== "open" && _self.status !== "watching") {
- exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
- return;
- }
+ configFeatures = configValidationObject.widget.children.feature.validationResult;
+ utils.forEach(configFeatures, function (f) {
+ if (f.valid === true) {
+ var feature = {id: f.attributes.name.value,
+ required: f.attributes.required.valid};
+ widgetInfo.features[feature.id] = feature;
+ }
+ });
- setTimeout(function () {
- if (sensorListener.get()) {
- sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(),
- currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));
+ widgetInfo.preferences = {};
- sensorListener.exec(sensorEvent);
- }
- }, 1);
+ configPreferences = configValidationObject.widget.children.preference.validationResult;
- return;
- },
+ platform = require('ripple/platform');
+ utils.forEach(configPreferences, function (preference) {
+ preferenceName = preference.attributes.name.value;
+ if (preferenceName) {
+ widgetInfo.preferences[preferenceName] = {
+ "key": preferenceName,
+ "value": preference.attributes.value.value || "",
+ "readonly": preference.attributes.readonly.value === "true"
+ };
- startWatch: function (options) {
- var index, watchId, watchObj = {};
+ db.save(preferenceName,
+ widgetInfo.preferences[preferenceName].value,
+ platform.getPersistencePrefix(widgetInfo.id));
+ }
+ });
- if (_self.status !== "open") {
- exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
- return;
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:tizen": {
+ attributeName: "xmlns:tizen",
+ required: false,
+ type: "list",
+ listValues: ["http://tizen.org/ns/widgets"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
+ },
+ defaultlocale: {
+ attributeName: "defaultlocale",
+ required: false,
+ type: "iso-language"
}
-
- if (typeof options !== "object") {
- if (_self.onerror) {
- _self.onerror(new SensorError(_errorCode.TYPE_MISMATCH_ERROR, _errorMsg.TYPE_MISMATCH_ERROR));
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ "short": {
+ attributeName: "short",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
}
- }
-
- setTimeout(function () {
- watchId = (new Date()).getTime();
-
- // As there will be many attributes for some sensor, each of them is needed to be watched.
- for (index = 0; index < sensorEventTypes.length; index++) {
- watchObj = {
- eventType: sensorEventTypes[index],
- onEvent: _onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror),
- };
-
- watches.push(watchObj);
- if (watchObj.eventType) {
- event.on(watchObj.eventType, watchObj.onEvent);
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
}
}
-
-
- if (options && options.interval) {
- watchObj.intervalId = setInterval(_onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror),
- options.interval);
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.URL
+ },
+ email: {
+ attributeName: "email",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.EMAIL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
}
-
- _self.status = "watching";
- if (_self.onstatuschange) {
- _self.onstatuschange();
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
}
-
- }, 1);
-
- return;
- },
-
- endWatch: function () {
- var index, watchObj;
-
- if (_self.status !== "watching") {
- exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
- return;
- }
-
- for (index = 0; index < watches.length; index++) {
- watchObj = watches[index];
-
- try {
- event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ encoding: {
+ attributeName: "encoding",
+ required: false,
+ type: "string"
+ },
+ type: {
+ attributeName: "type",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ setting: {
+ nodeName: "tizen:setting",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ 'screen-orientation': {
+ attributeName: "screen-orientation",
+ required: false,
+ type: "list",
+ listValues: ['portrait', 'landscape', 'auto']
+ },
+ 'context-menu': {
+ attributeName: "context-menu",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'background-support': {
+ attributeName: "background-support",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'encryption': {
+ attributeName: "encryption",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ },
+ 'install-location': {
+ attributeName: "install-location",
+ required: false,
+ type: "list",
+ listValues: ['auto', 'internal-only', 'perfer-external']
+ },
+ 'hwkey-event': {
+ attributeName: "hwkey-event",
+ required: false,
+ type: "list",
+ listValues: ['enable', 'disable']
+ }
+ }
+ },
+ application: {
+ nodeName: "tizen:application",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ },
+ required_version: {
+ attributeName: "required_version",
+ required: true,
+ type: "list",
+ listValues: ['1.0', '2.0', '2.1', '2.2']
+ },
+ package: {
+ attributeName: "package",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ "tizen:content": {
+ nodeName: "tizen:content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ control: {
+ nodeName: "tizen:app-control",
+ required: false,
+ occurrence: 0,
+ children: {
+ src: {
+ nodeName: "tizen:src",
+ required: true,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ operation: {
+ nodeName: "tizen:operation",
+ required: true,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ uri: {
+ nodeName: "tizen:uri",
+ required: false,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ mime: {
+ nodeName: "tizen:mime",
+ required: false,
+ occurence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ required: false,
+ type: "string"
+ }
+ }
+ }
+ }
+ },
+ "app-widget": {
+ nodeName: "tizen:app-widget",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ },
+ primary: {
+ attributeName: "primary",
+ required: true,
+ type: "list",
+ listValues: ['true', 'false']
+ },
+ "auto-launch": {
+ attributeName: "auto-launch",
+ required: false,
+ type: "list",
+ listValues: ['true', 'false']
+ },
+ "update-period": {
+ attributeName: "update-period",
+ required: false,
+ type: "integer"
+ }
+ },
+ children: {
+ "box-label": {
+ nodeName: "tizen:box-label",
+ required: true,
+ occurence: 1
+ },
+ "box-icon": {
+ nodeName: "tizen:box-icon",
+ required: true,
+ occurence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ "box-content": {
+ nodeName: "tizen:box-content",
+ required: true,
+ occurence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ "mouse-event": {
+ attributeName: "mouse-event",
+ required: false,
+ type: "string"
+ },
+ "touch-event": {
+ attributeName: "touch-event",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ "box-size": {
+ nodeName: "tizen:box-size",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "preview": {
+ attributeName: "preview",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ pd: {
+ nodeName: "tizen:pd",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "src": {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ "width": {
+ attributeName: "width",
+ required: true,
+ type: "integer"
+ },
+ "height": {
+ attributeName: "height",
+ required: true,
+ type: "integer"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ account: {
+ nodeName: "tizen:account",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "multiple-account-support": {
+ attributeName: "multiple-account-support",
+ required: true,
+ type: "list",
+ listValues: ['true', 'false']
+ }
+ },
+ children: {
+ icon: {
+ nodeName: "tizen:icon",
+ required: false,
+ occurence: 1,
+ attributes: {
+ section: {
+ attributeName: "section",
+ required: true,
+ type: "string"
+ }
+ }
+ },
+ "display-name": {
+ nodeName: "tizen:display-name",
+ required: false,
+ occurence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ capability: {
+ nodeName: "capability",
+ required: false,
+ occurence: 1
+ }
+ }
+ },
+ feature: {
+ nodeName: "tizen:privilege",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/TR/battery-status/",
+ "http://www.w3.org/TR/geolocation-API/",
+ "http://www.w3.org/TR/touch-events/",
+ "http://www.w3.org/TR/vibration/",
+ "http://tizen.org/privilege/tizen",
+ "http://tizen.org/privilege/alarm",
+ "http://tizen.org/privilege/application.launch",
+ "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
+ "http://tizen.org/privilege/bluetoothmanager", "http://tizen.org/privilege/bluetooth.admin",
+ "http://tizen.org/privilege/bluetooth.gap", "http://tizen.org/privilege/bluetooth.spp",
+ "http://tizen.org/privilege/bookmark.read", "http://tizen.org/privilege/bookmark.write",
+ "http://tizen.org/privilege/calendar.read", "http://tizen.org/privilege/calendar.write",
+ "http://tizen.org/privilege/callhistory.read", "http://tizen.org/privilege/callhistory.write",
+ "http://tizen.org/privilege/contact.read", "http://tizen.org/privilege/contact.write",
+ "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
+ "http://tizen.org/privilege/datacontrol.consumer",
+ "http://tizen.org/privilege/datasync",
+ "http://tizen.org/privilege/download",
+ "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
+ "http://tizen.org/privilege/messaging.read", "http://tizen.org/privilege/messaging.write",
+ "http://tizen.org/privilege/networkbearerselection",
+ "http://tizen.org/privilege/nfc.common", "http://tizen.org/privilege/nfc.admin",
+ "http://tizen.org/privilege/nfc.tag", "http://tizen.org/privilege/nfc.p2p",
+ "http://tizen.org/privilege/notification",
+ "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
+ "http://tizen.org/privilege/power",
+ "http://tizen.org/privilege/push",
+ "http://tizen.org/privilege/setting",
+ "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
+ "http://tizen.org/privilege/time",
+ "http://tizen.org/privilege/vehicle"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ },
+ children: {
+ param: {
+ nodeName: "param",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string"
+ },
+ value: {
+ attributeName: "value",
+ required: true,
+ type: "string"
+ }
+ }
+ }
}
- catch (e) {
- if (_self.onerror) {
- _self.onerror(e);
+ },
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string"
+ },
+ value: {
+ type: "string",
+ required: false,
+ attributeName: "value"
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
}
}
-
- if (watchObj.intervalId) {
- clearInterval(watchObj.intervalId);
- }
- }
-
- watches = [];
-
- _self.status = "open";
- if (_self.onstatuschange) {
- _self.onstatuschange();
}
- },
-
- // These functions are inherited from the EventTarget object
- addEventListener: function (eventType, callback, useCapture) {
- var sensorEvent;
-
- if (eventType === "sensordata") {
- sensorListener.set(callback);
-
- event.on("sensordata", function (data) {
- sensorEvent = new SensorDataEvent();
- sensorEvent.initSensorDataEvent("sensordata", false, false, "read", (new Date()).getTime(),
- currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));
-
- sensorListener.exec(sensorEvent);
- });
- }
- },
-
- removeEventListener: function (eventType, callback) {
- event.clear(eventType, callback);
- sensorListener.unbind(callback);
- },
-
- dispatchEvent: function (evt) {
- event.trigger("sensordata", evt);
}
- };
-
- sensorListener = _bind("onsensordata", _self);
- }
-
- return _self;
-}
-
-module.exports = function (option) {
-
- var connectionObj,
- _errorCode = new ErrorCode(),
- _errorMsg = new ErrorMsg();
-
- if (option === null || option === undefined) {
- return null;
- }
-
- // There are two ways to construct an object
- if (typeof option === "object") {
- if ((option.type === null || option.type === undefined) &&
- (option.name === null || option.name === undefined)) {
- // Spec: If none of the dictionary members are defined then raise an instantiation exception
- exception.raise(exception.types.Argument, "type illegal", new SensorError(_errorCode.ILLEGAL_TYPE, _errorMsg.ILLEGAL_TYPE));
}
-
- connectionObj = new SensorConnection(option.type, option.name);
- }
- else if (typeof option === "string") {
- connectionObj = new SensorConnection(option, option);
}
-
- return connectionObj;
};
});
-define('ripple/platform/w3c/1.0/geolocation', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/spec/device', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var geo = require('ripple/geo'),
- Position = require('ripple/platform/w3c/1.0/Position'),
- PositionError = require('ripple/platform/w3c/1.0/PositionError'),
- _watches = {},
- _self;
-
-function createPosition() {
- var position = new Position(),
- positionInfo = geo.getPositionInfo();
-
- position.coords.latitude = positionInfo.latitude;
- position.coords.longitude = positionInfo.longitude;
- position.coords.altitude = positionInfo.altitude;
- position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
- position.coords.accuracy = positionInfo.accuracy;
- position.coords.heading = positionInfo.heading;
- position.coords.speed = positionInfo.speed;
- position.timestamp = positionInfo.timeStamp.getTime();
+var event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ StorageTypeTable = {
+ "UNKNOWN": "UNKNOWN",
+ "INTERNAL": "INTERNAL",
+ "MMC": "MMC",
+ "USB_HOST": "USB_HOST"
+ },
+ NetworkTypeTable = {
+ "NONE": "NONE",
+ "2G": "2G",
+ "2.5G": "2.5G",
+ "3G": "3G",
+ "4G": "4G",
+ "WIFI": "WIFI",
+ "ETHERNET": "ETHERNET",
+ "UNKNOWN": "UNKNOWN"
+ },
+ LocaleTable = {
+ "eng_USA": "eng_USA",
+ "eng_CAN": "eng_CAN",
+ "deu_DEU": "deu_DEU",
+ "jpn_JPN": "jpn_JPN",
+ "zho_CHN": "zho_CHN",
+ "UNKNOWN": "UNKNOWN"
+ },
+ SimStateTable = {
+ "ABSENT": "ABSENT",
+ "INITIALIZING": "INITIALIZING",
+ "READY": "READY",
+ "PIN_REQUIRED": "PIN_REQUIRED",
+ "PUK_REQUIRED":"PUK_REQUIRED",
+ "NETWORK_LOCKED": "NETWORK_LOCKED",
+ "SIM_LOCKED": "SIM_LOCKED",
+ "UNKNOWN": "UNKNOWN"
+ };
- return position;
+function deviceStatusEventTrigger(setting) {
+ event.trigger("DeviceStatusChanged", [setting]);
}
-_self = {
- getCurrentPosition: function (onSuccess, onError) {
- var delay = ((geo.delay || 0) * 1000) || 1,
- timeout = geo.timeout;
-
- window.setTimeout(function () {
- if (timeout) {
- var error = new PositionError();
- error.code = PositionError.TIMEOUT;
- error.message = "postion timed out";
-
- onError(error);
+module.exports = {
+ "Config": {
+ "vibratingMode": {
+ "name": "Vibrator",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("VibratingModeChanged", [setting]);
}
- else {
- // TODO: build facility to trigger onError() from emulator
- // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
- _self.lastPosition = createPosition();
- onSuccess(_self.lastPosition);
+ },
+ "lockScreen": {
+ "name": "Lock Screen",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "callback": function (setting) {
+ event.trigger("LockScreenChanged", [setting]);
}
- }, delay);
+ }
},
-
- watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
- var watchId = (new Date()).getTime().toString(),
- watchObj = {},
- timeout;
-
- if (geolocationOptions) {
- timeout = geolocationOptions.timeout || 10000;
-
- watchObj = {
- onSuccess: geolocationSuccess,
- onError: geolocationError,
- interval: timeout
- };
-
- _watches[watchId] = watchObj;
-
- _watches[watchId].intervalId = window.setInterval(function () {
- _self.getCurrentPosition(_watches[watchId].onSuccess, _watches[watchId].onError);
- }, timeout);
-
+ "DEVICE_ORIENTATION": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "label",
+ "innertext": "PORTRAIT_PRIMARY",
+ "value": "PORTRAIT_PRIMARY"
+ },
+ "event": "LayoutChanged"
+ },
+ "isAutoRotation": {
+ "name": "Is Auto Rotation",
+ "control": {
+ "type": "label",
+ "value": false
+ }
}
- else {
- if (typeof geolocationError === "function") {
- window.setTimeout(function () {
- geolocationError();
- }, 1);
+ },
+ "CPU": {
+ "load": {
+ "name": "Load",
+ "control": {
+ "type": "number",
+ "value": 0.1
+ },
+ "event": "CpuLoadChanged",
+ "callback": function (setting) {
+ if (setting > 1) setting = 1;
+ if (setting < 0) setting = 0;
+ event.trigger("CpuLoadChanged", [setting]);
}
}
-
- return watchId;
},
+ "STORAGE": {
+ "type": {
+ "name": "Type",
+ "control": {
+ "type": "select",
+ "value": StorageTypeTable["INTERNAL"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(StorageTypeTable, function (key, value) {
+ optionList[key] = StorageTypeTable[value];
+ });
- lastPosition: null,
-
- clearWatch: function (watchId) {
- window.clearInterval(_watches[watchId].intervalId);
- delete _watches[watchId];
- }
-};
-
-module.exports = _self;
-
-});
-define('ripple/platform/w3c/1.0/navigator', function (require, exports, module) {
-/*
- * Copyright 2011 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 _original = window.navigator,
- utils = require('ripple/utils'),
- devices = require('ripple/devices'),
- constants = require('ripple/constants'),
- _self = {};
-
-(function () {
- var key,
- nav = window.navigator;
-
- function _handle(obj, key) {
- return typeof obj[key] !== "function" ? obj[key] : function () {
- return obj[key].apply(obj, Array.prototype.slice.call(arguments));
- };
- }
-
- for (key in nav) {
- _self[key] = _handle(nav, key);
- }
-}());
-
-_self.__defineGetter__('userAgent', function () {
- var currentUserAgent = devices.getCurrentDevice().userAgent;
-
- return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
- _original.userAgent : currentUserAgent;
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/wac/1.0/AccelerometerInfo', function (require, exports, module) {
-/*
- * Copyright 2011 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 accelerometer = require('ripple/accelerometer'),
- _self = {};
-
-_self.__defineGetter__("xAxis", function () {
- return accelerometer.getInfo().accelerationIncludingGravity.x;
-});
-
-_self.__defineGetter__("yAxis", function () {
- return accelerometer.getInfo(true).accelerationIncludingGravity.y;
-});
-
-_self.__defineGetter__("zAxis", function () {
- return accelerometer.getInfo(true).accelerationIncludingGravity.z;
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/wac/1.0/Account', function (require, exports, module) {
-/*
- * Copyright 2011 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 deviceSettings = require('ripple/deviceSettings'),
- _self;
-
-_self = {
- accountName: undefined,
- accountId: undefined
-};
-
-_self.__defineGetter__("accountName", function () {
- return deviceSettings.retrieve("Account.accountName");
-});
-
-_self.__defineGetter__("accountId", function () {
- return deviceSettings.retrieve("Account.accountId");
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/wac/1.0/AccountInfo', function (require, exports, module) {
-/*
- * Copyright 2011 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 deviceSettings = require('ripple/deviceSettings'),
- _self = {
- phoneUserUniqueId: undefined,
- phoneMSISDN: undefined,
- phoneOperatorName: undefined,
- userAccountBalance: undefined,
- userSubscriptionType: undefined
- };
-
-_self.__defineGetter__("phoneUserUniqueId", function () {
- return deviceSettings.retrieve("AccountInfo.phoneUserUniqueId");
-});
-
-_self.__defineGetter__("phoneMSISDN", function () {
- return deviceSettings.retrieve("AccountInfo.phoneMSISDN");
-});
-
-_self.__defineGetter__("phoneOperatorName", function () {
- return deviceSettings.retrieve("AccountInfo.phoneOperatorName");
-});
-
-_self.__defineGetter__("userAccountBalance", function () {
- return deviceSettings.retrieve("AccountInfo.userAccountBalance");
-});
-
-_self.__defineGetter__("userSubscriptionType", function () {
- return deviceSettings.retrieve("AccountInfo.userSubscriptionType");
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/wac/1.0/AddressBookItem', function (require, exports, module) {
-/*
- * Copyright 2011 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 utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- db = require('ripple/db'),
- constants = require('ripple/constants'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
-
-function _validateArgs(min, max, len) {
- utils.validateNumberOfArguments(min, max, len,
- ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
-}
-
-function _validateType(arg, argType) {
- utils.validateArgumentType(arg, argType,
- ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
- new Exception());
-}
-
-module.exports = function () {
- function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
- }
-
- this.addressBookItemId = undefined;
- this.fullName = undefined;
- this.mobilePhone = undefined;
- this.homePhone = undefined;
- this.workPhone = undefined;
- this.eMail = undefined;
- this.company = undefined;
- this.title = undefined;
- this.address = undefined;
-
- this.setAttributeValue = function (attribute, value) {
- _validateArgs(2, 2, arguments.length);
- _validateType(attribute, "string");
- this[attribute] = value;
- };
- this.setAddressGroupNames = function (groups) {
- _throwUnsupportedException("PIM.AddressBookItem.setAddressGroupNames");
- };
- this.getAttributeValue = function (attribute) {
- _validateArgs(1, 1, arguments.length);
- _validateType(attribute, "string");
- return this[attribute];
- };
- this.getAddressGroupNames = function () {
- _throwUnsupportedException("PIM.AddressBookItem.getAddressGroupNames");
- };
- this.getAvailableAttributes = function () {
- return utils.reduce(this, function (attributes, value, key) {
- if (typeof(value) !== 'function') {
- attributes.push(key);
+ return optionList;
+ }())
+ },
+ "capacity": {
+ "name": "Capacity(bytes)",
+ "control": {
+ "type": "label",
+ "value": 16000000000
+ }
+ },
+ "availableCapacity": {
+ "name": "AvailableCapacity(bytes)",
+ "control": {
+ "type": "number",
+ "value": 12000000000
+ },
+ "callback": function (setting) {
+ event.trigger("AvailCapacityChanged", [setting]);
+ }
+ },
+ "isRemovable": {
+ "name": "IsRemovable",
+ "control": {
+ "type": "checkbox",
+ "value": true
}
- return attributes;
- }, []).sort();
- };
- this.update = function () {
- var items = db.retrieveObject(constants.PIM.ADDRESS_LIST_KEY),
- that = this,
- itemIndex = items.reduce(function (current, value, i) {
- return value.addressBookItemId === that.addressBookItemId ?
- i : current;
- }, -1);
-
- if (itemIndex >= 0) {
- items[itemIndex] = this;
- db.saveObject(constants.PIM.ADDRESS_LIST_KEY, items);
}
- else {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "Address Book Item not found: " + (this.addressBookItemId || ""), new Exception());
+ },
+ "BUILD": {
+ "model": {
+ "name": "Model",
+ "control": {
+ "type": "label",
+ "innertext": "tizen-2.2 build",
+ "value": "tizen-2.2 build"
+ }
+ },
+ "manufacturer": {
+ "name": "Manufacturer",
+ "control": {
+ "type": "label",
+ "innertext": "Tizen",
+ "value": "Tizen"
+ }
+ },
+ "buildVersion": {
+ "name": "Build Version",
+ "control": {
+ "type": "label",
+ "innertext": "TIZEN_WEB_SIMULATOR_000001",
+ "value": "TIZEN_WEB_SIMULATOR_000001"
+ }
}
+ },
+ "LOCALE": {
+ "language": {
+ "name": "Language",
+ "control": {
+ "type": "select",
+ "value": LocaleTable["eng_USA"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(LocaleTable, function (key, value) {
+ optionList[key] = LocaleTable[value];
+ });
- };
-};
-
-});
-define('ripple/platform/wac/1.0/ApplicationTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- _self = {};
-
-utils.forEach(constants.PLATFORMS.WAC.APPLICATIONS, function (application) {
- _self.__defineGetter__(application, function () {
- return application;
- });
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/wac/1.0/Attachment', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function () {
- this.fileName = "";
- this.MIMEType = "";
- this.size = 0;
-};
-
-});
-define('ripple/platform/wac/1.0/AudioPlayer', function (require, exports, module) {
-/*
- * Copyright 2011 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 constants = require('ripple/constants'),
- event = require('ripple/event'),
- exception = require('ripple/exception'),
- utils = require('ripple/utils'),
- fileSystem = require('ripple/fileSystem'),
- _console = require('ripple/console'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- _self,
- _state = null,
- _STATES = constants.MULTIMEDIA.AUDIO_STATES,
- _currentAudioFile,
- _audio, _loopCount;
-
-event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
- _state = state;
- if (typeof _self.onStateChange === 'function') {
- _self.onStateChange.apply(_self, arguments);
- }
-});
-
-_audio = utils.createElement("audio", {
- "id": "multimedia-audio"
-});
-
-_audio.addEventListener('error', function () {
- _console.warn("AudioPlayer encountered an error: " + _audio.error.code);
- if (_audio.error.code === 4) {
- _console.warn("AudioPlayer error 4 could be caused by missing codecs");
- }
- _state = null;
- event.trigger("MultimediaAudioStateChanged", [null], true);
-});
-
-_audio.addEventListener('ended', function handleAudioEnded() {
- event.trigger("MultimediaAudioStateChanged", [_STATES.COMPLETED], true);
- if (_loopCount > 1) {
- _self.open(_currentAudioFile);
- _self.play(_loopCount--);
- }
-});
-
-document.getElementById("ui").appendChild(_audio);
-
-function _validateAndSet(state, validStates, callbackBeforeSuccess) {
- var i, valid = false;
+ return optionList;
+ }())
+ },
+ "country": {
+ "name": "Country",
+ "control": {
+ "type": "select",
+ "value": LocaleTable["eng_USA"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(LocaleTable, function (key, value) {
+ optionList[key] = LocaleTable[value];
+ });
- for (i = 0; i < validStates.length; i++) {
- if (validStates[i] === _state) {
- valid = true;
+ return optionList;
+ }())
}
- }
-
- if (!valid) {
- _console.warn("Attempted to initiate AudioPlayer." + state +
- " in invalid state. current state: " + _state);
- } else {
- if (typeof(callbackBeforeSuccess) === "function") {
- callbackBeforeSuccess.apply();
+ },
+ "DISPLAY": {
+ "resolutionWidth": {
+ "name": "Resolution Width(pixels)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "resolutionHeight": {
+ "name": "Resolution Height(pixels)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "dotsPerInchWidth": {
+ "name": "DPI-X",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "dotsPerInchHeight": {
+ "name": "DPI-Y",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "physicalWidth": {
+ "name": "Physical Width(millimeters)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "physicalHeight": {
+ "name": "Physical Height(millimeters)",
+ "control": {
+ "type": "label",
+ "value": 0
+ }
+ },
+ "brightness": {
+ "name": "Brightness",
+ "control": {
+ "type": "number",
+ "value": 1
+ },
+ "event": "DisplayBrightnessChanged",
+ "callback": function (setting) {
+ if (setting > 1) setting = 1;
+ if (setting < 0) setting = 0;
+ event.trigger("DisplayBrightnessChanged", [setting]);
+ }
}
- event.trigger("MultimediaAudioStateChanged", [state], true);
- }
-
- return valid;
-}
-
-function _validateAudioType(fileUrl) {
- var matched = fileUrl.match(/\.(\w*)$/),
- type = matched ? matched[1] : "";
-
- if (_audio && _audio.canPlayType("audio/" + type) === "") {
- _console.warn("Attempting to load an audio that might not work in the current browser [" + fileUrl + "]");
- }
-}
-
-_self = {
- onStateChange: undefined,
-
- open: function (fileUrl) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open wrong number of arguments", new Exception());
- utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open invalid parameter! expected string, fileUrl: " +
- fileUrl, new Exception());
+ },
+ "NETWORK": {
+ "networkType": {
+ "name": "Network Type",
+ "control" : {
+ "type": "select",
+ "value": NetworkTypeTable["NONE"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(NetworkTypeTable, function (key, value) {
+ optionList[key] = NetworkTypeTable[value];
+ });
- if (fileUrl.match(/^rtsp:\/\//)) {
- exception.raise(exception.types.MethodNotImplemented, "rtsp:// scheme not yet supported. sorry :(");
+ return optionList;
+ }())
}
-
- _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
- _validateAudioType(fileUrl);
- _currentAudioFile = fileSystem.getURI(fileUrl);
- _audio.setAttribute("src", _currentAudioFile);
- _audio.load();
- });
},
+ "WIFI_NETWORK": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "event": "WiFiNetworkStatusChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiNetworkStatusChanged", [setting]);
+ }
+ },
+ "ssid": {
+ "name": "SSID",
+ "control": {
+ "type": "text",
+ "value": "Tizen WiFi"
+ }
+ },
+ "ipAddress": {
+ "name": "IP Address",
+ "control": {
+ "type": "text",
+ "value": "192.168.0.1"
+ }
+ },
+ "ipv6Address": {
+ "name": "IPv6 Address",
+ "control": {
+ "type": "text",
+ "value": "2001:db8:85a3:0:0:0:70:7334"
+ }
+ },
+ "signalStrength": {
+ "name": "Signal Strength",
+ "control": {
+ "type": "select",
+ "value": 0
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- play: function (repeatTimes) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play wrong number of arguments", new Exception());
- utils.validateArgumentType(repeatTimes, "integer", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play invalid parameter! expected integer, repeatTimes: " + repeatTimes, new Exception());
-
- if (repeatTimes < 0) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "value of repeatTimes must be greater than 0", new Exception());
- }
+ for (i = 0; i <= 10; i++) {
+ optionList[i] = i;
+ }
- if (repeatTimes !== 0) {
- _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
- _loopCount = repeatTimes;
- _audio.play();
- });
+ return optionList;
+ }())
}
},
-
- pause: function () {
- _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
- _audio.pause();
- });
+ "CELLULAR_NETWORK": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "CellularNetworkStatusChanged",
+ "callback": function (setting) {
+ event.trigger("CellularNetworkStatusChanged", [setting]);
+ }
+ },
+ "apn": {
+ "name": "APN",
+ "control": {
+ "type": "text",
+ "value": "Tizen"
+ }
+ },
+ "ipAddress": {
+ "name": "IP Address",
+ "control": {
+ "type": "text",
+ "value": "10.0.2.16"
+ }
+ },
+ "ipv6Address": {
+ "name": "IPv6 Address",
+ "control": {
+ "type": "text",
+ "value": "2001:db8:85a3:0:0:0:70:7334"
+ }
+ },
+ "mcc": {
+ "name": "MCC",
+ "control": {
+ "type": "number",
+ "value": 460
+ }
+ },
+ "mnc": {
+ "name": "MNC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "cellId": {
+ "name": "Cell ID",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "lac": {
+ "name": "LAC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "isRoaming": {
+ "name": "Roaming",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "isFlightMode": {
+ "name": "Flight Mode",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "callback": function (setting) {
+ event.trigger("FlightModeChanged", [setting]);
+ }
+ },
+ "imei": {
+ "name": "IMEI",
+ "control": {
+ "type": "text",
+ "value": "012417005203000"
+ }
+ }
},
+ "SIM": {
+ "state": {
+ "name": "State",
+ "control": {
+ "type": "select",
+ "value": SimStateTable["READY"]
+ },
+ "options": (function () {
+ var optionList = {};
+ utils.forEach(SimStateTable, function (key, value) {
+ optionList[key] = SimStateTable[value];
+ });
- resume: function () {
- _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
- _audio.play();
- });
+ return optionList;
+ }())
+ },
+ "operatorName": {
+ "name": "Operator Name",
+ "control": {
+ "type": "text",
+ "value": "Tizen"
+ }
+ },
+ "msisdn": {
+ "name": "MSISDN",
+ "control": {
+ "type": "text",
+ "value": "088123456789"
+ }
+ },
+ "iccid": {
+ "name": "ICCID",
+ "control": {
+ "type": "text",
+ "value": "123000MFSSYYGXXXXXXP"
+ }
+ },
+ "mcc": {
+ "name": "MCC",
+ "control": {
+ "type": "number",
+ "value": 460
+ }
+ },
+ "mnc": {
+ "name": "MNC",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "msin": {
+ "name": "MSIN",
+ "control": {
+ "type": "text",
+ "value": "H1 H2 H3 S 12345"
+ }
+ },
+ "spn": {
+ "name": "SPN",
+ "control": {
+ "type": "text",
+ "value": "TizenSPN"
+ }
+ }
},
-
- stop: function () {
- _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
- try {
- _audio.pause();
- _audio.currentTime = 0;
- } catch (e) {
- //HACK: do nothing, this could throw a dom exception 11 sometimes when playing an mp3 or before the file has loaded.
- //see http://developer.palm.com/distribution/viewtopic.php?f=11&t=7568
+ "PERIPHERAL": {
+ "isVideoOutputOn": {
+ "name": "Video Output",
+ "control": {
+ "type": "checkbox",
+ "value": false
}
- });
+ }
}
};
-module.exports = _self;
-
});
-define('ripple/platform/wac/1.0/CalendarItem', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/spec/sensor', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2012 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- db = require('ripple/db'),
- exception = require('ripple/exception'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
+var event = require('ripple/event');
-module.exports = function () {
- this.calendarItemId = undefined;
- this.alarmDate = undefined;
- this.eventStartTime = undefined;
- this.eventEndTime = undefined;
- this.eventName = undefined;
- this.eventNotes = undefined;
- this.alarmed = undefined;
+function sensorStatusEventTrigger(setting) {
+ event.trigger("SensorStatusChanged", [setting]);
+}
- this.update = function () {
- var events = db.retrieveObject(constants.PIM.CALENDAR_LIST_KEY) || [],
- that = this,
- eventIndex = events.reduce(function (match, value, i) {
- return value.calendarItemId === that.calendarItemId ?
- i : match;
- }, -1);
+module.exports = {
+ "Accelerometer": {
+ "resolution": 0.039239998906850815,
+ "minDelay": 20,
+ "range": 20.051639556884766,
+ "name": "Accelerometer",
+ "type": "Accelerometer"
+ },
+ "MagneticField": {
+ "x": {
+ "name": "X",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-xChanged", [setting]);
+ }
+ },
+ "y": {
+ "name": "Y",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-yChanged", [setting]);
+ }
+ },
- if (eventIndex >= 0) {
- events[eventIndex] = this;
- db.saveObject(constants.PIM.CALENDAR_LIST_KEY, events);
- }
- else {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "Calendar Item not found: " + (this.calendarItemId || ""), new Exception());
- }
- };
+ "z": {
+ "name": "Z",
+ "control": {
+ "type": "range",
+ "value": 100.0000000000000000,
+ "min": 0.0000000000000000,
+ "max": 200.0000000000000000,
+ "step": 0.0000000000000001
+ },
+ "callback": function (setting) {
+ event.trigger("MagneticField-zChanged", [setting]);
+ }
+ },
+
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "MagneticField",
+ "type": "MagneticField"
+ },
+ "Rotation": {
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "Rotation",
+ "type": "Rotation"
+ },
+ "Orientation": {
+ "resolution": 1,
+ "minDelay": 20,
+ "range": 359,
+ "name": "Orientation",
+ "type": "Orientation"
+ }
};
});
-define('ripple/platform/wac/1.0/CallRecord', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/spec/ui', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = function () {
- this.callRecordType = undefined;
- this.callRecordId = undefined;
- this.callRecordAddress = undefined;
- this.callRecordName = undefined;
- this.durationSeconds = undefined;
- this.startTime = undefined;
+module.exports = {
+ plugins: [
+ "vehicle",
+ "sensors",
+ "communication",
+ "geoView",
+ "widgetConfig",
+ "deviceSettings",
+ "application",
+ "network",
+ "power",
+ "download",
+ "notifications",
+ "package",
+ "messagePort"
+ ]
};
});
-define('ripple/platform/wac/1.0/CallRecordTypes', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/WebAPIError', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- RECEIVED: "received",
- OUTGOING: "outgoing",
- MISSED: "missed"
+
+var errorcode = require('ripple/platform/ivi/3.0/errorcode');
+
+var msg = {
+ 1: "Permission denied.",
+ 2: "Unsupported property.",
+ 3: "Timeout.",
+ 10: "Unknown."
+},
+ errType = {
+ 1: "PermissionDeniedError",
+ 2: "PropertyUnavailableError",
+ 3: "TimeoutError",
+ 10: "UnknownError"
+};
+
+module.exports = function (code, message, name) {
+ var _code, _message, _name;
+
+ if (typeof code !== 'number') {
+ _code = errorcode.UNKNOWN;
+ _message = msg[_code];
+ _name = errType[_code];
+ } else {
+ _code = code;
+ if (typeof message === 'string') {
+ _message = message;
+ } else {
+ _message = msg[_code];
+ }
+ if (typeof name === 'string') {
+ _name = name;
+ } else {
+ _name = errType[_code];
+ }
+ }
+
+ this.__defineGetter__("code", function () {
+ return _code;
+ });
+ this.__defineGetter__("message", function () {
+ return _message;
+ });
+ this.__defineGetter__("name", function () {
+ return _name;
+ });
};
});
-define('ripple/platform/wac/1.0/Camera', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/typedef', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var exception = require('ripple/exception'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- constants = require('ripple/constants'),
- _console = require('ripple/console'),
- utils = require('ripple/utils'),
- notifications = require('ripple/notifications'),
- _currentlySet,
- _img,
- _buttons,
- _self,
- _videoCapture;
+var _t, _c, _i;
-function _populateWindow(domObject) {
- var record = document.createElement("button"),
- pause = document.createElement("button"),
- stop = document.createElement("button");
+/*
+ * Primitive type definition
+ */
- _img = document.createElement("img");
- _img.setAttribute("id", "jil-camera-window");
- //_img.setAttribute("src", document.querySelector("#extension-url").innerHTML + constants.CAMERA.WINDOW_ANIMATION);
- _img.setAttribute("src", document.documentURI.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION);
- _img.setAttribute("width", "100%");
- _currentlySet = domObject;
- domObject.appendChild(_img);
+_t = {
+ // Basic
+ Callback: "Callback",
+ DOMString: "",
+ Date: new Date(),
+ Function: function () {},
+ TZDate: "TZDate",
+ any: "any",
+ boolean: false,
+ byte: "byte",
+ double: "double",
+ float: "float",
+ long: "long",
+ octet: "octet",
+ short: "short",
+ long_long: "long long",
+ unsigned_long: "unsigned long",
+ unsigned_long_long: "unsigned long long",
+ unsigned_short: "unsigned short"
+};
- _buttons = document.createElement("div");
- _buttons.setAttribute("id", "jil-camera-window-buttons");
- _buttons.setAttribute("style", "display: none");
+/*
+ * Derivative type definition
+ */
- record.setAttribute("id", "jil-camera-window-buttons-record");
- record.innerHTML = "Record";
- pause.setAttribute("id", "jil-camera-window-buttons-pause");
- pause.innerHTML = "Pause";
- stop.setAttribute("id", "jil-camera-window-buttons-stop");
- stop.innerHTML = "Stop";
- stop.addEventListener("click", _self.stopVideoCapture);
+/*
+ * Object attributes
+ * Contruct a prototype of an object. Specify a primitive type for each attribute.
+ *
+ * _optional
+ * Optional attributes table, which consists of two types of attributes,
+ *
+ * nullable
+ * Nullable attributes, marked as '?' in IDL.
+ *
+ * undefined
+ * Array type attributes, that not definitely specified to be
+ * initialized as an empty array, i.e., undefined-initialized array.
+ *
+ * _derived
+ * Derived types, which used in two cases of definition,
+ *
+ * Subtype list
+ * An array consists of derived subtypes. It exists in the definition of
+ * a base type.
+ *
+ * Union types
+ * An array consists of member types. It exists in the definition of
+ * a union type.
+ *
+ * _dictionary
+ * Dictionary type, which indicates that the object is a dictionary type.
+ */
- _buttons.appendChild(record);
- _buttons.appendChild(pause);
- _buttons.appendChild(stop);
+/*
+ * Vehicle
+ */
+_t.SupportedPropertiesSuccessCallback = _t.Function;
- domObject.appendChild(_buttons);
+_t.VehiclePropertyErrorCallback = _t.Function;
-}
+_t.VehiclePropertyCallback = _t.Function;
-function _verifySetWindow(method) {
- if (!_img) {
- exception.raise(ExceptionTypes.UNKNOWN, "Camera." +
- method + " was (most likely) called before using the setWindow method.", new Exception());
- }
-}
+_t.VehiclePropertyListCallback = _t.Function;
-_self = {
- onCameraCaptured: undefined, //function (fileName) { }
+/*
+ * VehicleSpeed
+ */
+_t.VehicleSpeed = {
+ vehicleSpeed: _t.unsigned_long
+};
- captureImage: function (fileName, lowRes) {
- utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "captureImage invalid number of parameters", new Exception());
- utils.validateMultipleArgumentTypes([fileName, lowRes], ['string', 'boolean'], ExceptionTypes.INVALID_PARAMETER, "invalid parameter type", new Exception());
+/*
+ * EngineSpeed
+ */
+_t.EngineSpeed = {
+ engineSpeed: _t.unsigned_long
+};
- _verifySetWindow("captureImage");
- var msg = constants.CAMERA.WARNING_TEXT;
- msg = msg.replace("{file}", fileName);
- notifications.openNotification("normal", msg);
- _console.log("simulated saved image as: " + fileName);
- if (_self.onCameraCaptured) {
- _self.onCameraCaptured.apply(_self, [fileName]);
- }
+/*
+ * VehiclePowerMode
+ */
+_t.VehiclePowerMode = {
+ vehiclePowerMode: _t.octet
+};
- return fileName;
- },
- setWindow: function (domObject) {
+/*
+ * TripMeters
+ */
+_t.TripMeter = {
+ tripMeters: [_t.unsigned_long]
+};
- if (_currentlySet) {
- _currentlySet.removeChild(_img);
- _currentlySet.removeChild(_buttons);
- _currentlySet = null;
- _img = null;
- _buttons = null;
- }
- if (domObject !== null) {
- _populateWindow(domObject);
- }
- },
- startVideoCapture: function (fileName, lowRes, maxDurationSeconds, showDefaultControls) {
- _verifySetWindow("startVideoCapture");
- utils.validateNumberOfArguments(1, 4, arguments.length, ExceptionTypes.INVALID_PARAMETER, "startVideoCapture invalid number of parameters", new Exception());
- utils.validateMultipleArgumentTypes(
- [fileName, lowRes, maxDurationSeconds, showDefaultControls],
- ['string', 'boolean', 'integer', 'boolean'],
- ExceptionTypes.INVALID_PARAMETER,
- "invalid parameter type", new Exception());
- _console.log("started recording video");
- var interval = window.setTimeout(function () {
- _self.stopVideoCapture();
- }, maxDurationSeconds * 1000);
+/*
+ * Acceleration
+ */
+_t.Acceleration = {
+ x: _t.unsigned_long,
+ y: _t.unsigned_long,
+ z: _t.unsigned_long
+};
- if (showDefaultControls) {
- _buttons.removeAttribute("style");
- }
+/*
+ * Transmission
+ */
+_t.Transmission = {
+ gearPosition: _t.octet,
+ mode: _t.octet
+};
- _videoCapture = {
- fileName: fileName,
- stop: function () {
- window.clearInterval(interval);
- var msg = constants.CAMERA.WARNING_TEXT;
- msg = msg.replace("{file}", fileName);
- notifications.openNotification("normal", msg);
- if (_self.onCameraCaptured) {
- _self.onCameraCaptured.apply(_self, [fileName]);
- }
- }
- };
+/*
+ * CruiseControlStatus
+ */
+_t.CruiseControlStatus = {
+ activated: _t.boolean,
+ speed: _t.unsigned_short
+};
+/*
+ * WheelBrake
+ */
+_t.WheelBrake = {
+ engaged: _t.boolean
+};
- return fileName;
- },
- stopVideoCapture: function () {
- utils.validateNumberOfArguments(0, 0, arguments.length, ExceptionTypes.INVALID_PARAMETER, "stopVideoCapture invalid number of parameters", new Exception());
- if (_videoCapture) {
- _console.log("simulated saving a video as: " + _videoCapture.fileName);
- if (_buttons) {
- _buttons.setAttribute("style", "display: none");
- }
- _videoCapture.stop();
- _videoCapture = null;
- }
- }
+/*
+ * LightStatus
+ */
+_t.LightStatus = {
+ head: _t.boolean,
+ rightTurn: _t.boolean,
+ leftTurn: _t.boolean,
+ brake: _t.boolean,
+ fog: _t.boolean,
+ hazard: _t.boolean,
+ parking: _t.boolean,
+ highBeam: _t.boolean
+};
+
+/*
+ * InteriorLightStatus
+ */
+_t.InteriorLightStatus = {
+ passenger: _t.boolean,
+ driver: _t.boolean,
+ center: _t.boolean
+};
+/*
+ * Horn
+ */
+_t.Horn = {
+ on: _t.boolean
};
-module.exports = _self;
+/*
+ * Fuel
+ */
+_t.Fuel = {
+ level: _t.unsigned_short,
+ range: _t.unsigned_short,
+ instantConsumption: _t.unsigned_short,
+ instantEconomy: _t.unsigned_short,
+ averageEconomy: _t.unsigned_short
+};
-});
-define('ripple/platform/wac/1.0/Config', function (require, exports, module) {
/*
- * Copyright 2011 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.
+ * EngineOil
*/
-var utils = require('ripple/utils'),
- notifications = require('ripple/notifications'),
- constants = require('ripple/constants'),
- deviceSettings = require('ripple/deviceSettings'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- _self = {
- ringtoneVolume: undefined,
- msgRingtoneVolume: undefined,
- vibrationSetting: undefined,
+_t.EngineOil = {
+ remaining: _t.unsigned_short,
+ temperature: _t.long,
+ pressure: _t.unsigned_short
+};
- setDefaultRingtone: function (ringtoneUrl) {
- utils.validateArgumentType(ringtoneUrl, "string", ExceptionTypes.INVALID_PARAMETER, "ringtoneUrl paramter is not a string", new Exception());
- notifications.openNotification("normal", "Setting default ringtone to: " + ringtoneUrl);
- },
+/*
+ * Location
+ */
+_t.Location = {
+ latitude: _t.double,
+ longitude: _t.double,
+ altitude: _t.double,
+ direction: _t.unsigned_short
+};
- setAsWallpaper: function (wallpaperUrl) {
- utils.validateArgumentType(wallpaperUrl, "string", ExceptionTypes.INVALID_PARAMETER, "wallpaperUrl paramter is not a string", new Exception());
- notifications.openNotification("normal", "Setting wallpaper to: " + wallpaperUrl);
- }
- };
+/*
+ * ExteriorBrightness
+ */
+_t.ExteriorBrightness = {
+ exteriorBrightness: _t.unsigned_long
+};
-_self.__defineGetter__("ringtoneVolume", function () {
- return deviceSettings.retrieve("Config.ringtoneVolume");
-});
+/*
+ * Temperature
+ */
+_t.Temperature = {
+ interior: _t.short,
+ exterior: _t.short
+};
-_self.__defineGetter__("msgRingtoneVolume", function () {
- return deviceSettings.retrieve("Config.msgRingtoneVolume");
-});
+/*
+ * RainSensor
+ */
+_t.RainSensor = {
+ rainSensor: _t.unsigned_short
+};
-_self.__defineGetter__("vibrationSetting", function () {
- return deviceSettings.retrieve("Config.vibrationSetting");
-});
+/*
+ * WindshieldWiper
+ */
+_t.WindshieldWiper = {
+ windshieldWiper: _t.unsigned_short
+};
-module.exports = _self;
+/*
+ * DefrostDictionary
+ */
+_t.DefrostDictionary = {
+ window: _t.unsigned_short,
+ defrost: _t.boolean,
+
+ _dictionary: true
+};
-});
-define('ripple/platform/wac/1.0/DataNetworkConnectionTypes', function (require, exports, module) {
/*
- * Copyright 2011 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.
+ * HVAC
*/
-var utils = require('ripple/utils'),
- _self = {
- "BLUETOOTH": undefined,
- "EDGE": undefined,
- "EVDO": undefined,
- "GPRS": undefined,
- "IRDA": undefined,
- "LTE": undefined,
- "ONEXRTT": undefined,
- "WIFI": undefined
- };
+_t.HVAC = {
+ airflowDirection: _t.unsigned_short,
+ fanSpeed: _t.unsigned_short,
+ targetTemperature: _t.unsigned_short,
+ airConditioning: _t.boolean,
+ airRecirculation: _t.boolean,
+ heater: _t.boolean,
+ steeringWheelHeater: _t.boolean,
+ seatHeater: _t.boolean,
+ seatCooler: _t.boolean
+};
-utils.forEach(_self, function (value, property) {
- _self.__defineGetter__(property, function () {
- return property;
- });
-});
+/*
+ * WindowStatus
+ */
+_t.WindowStatus = {
+ openness: _t.unsigned_short,
+ defrost: _t.boolean
+};
-module.exports = _self;
+/*
+ * Sunroof
+ */
+_t.Sunroof = {
+ openness: _t.unsigned_short,
+ tilt: _t.unsigned_short
+};
-});
-define('ripple/platform/wac/1.0/DataNetworkInfo', function (require, exports, module) {
/*
- * Copyright 2011 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.
+ * ConvertibleRoof
*/
-var event = require('ripple/event'),
- utils = require('ripple/utils'),
- _console = require('ripple/console'),
- deviceSettings = require('ripple/deviceSettings'),
- DataNetworkConnectionTypes = require('ripple/platform/wac/1.0/DataNetworkConnectionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+_t.ConvertibleRoof = {
+ openness: _t.unsigned_short
+};
-_self = {
- isDataNetworkConnected: undefined,
- networkConnectionType: undefined,
- onNetworkConnectionChanged: undefined,
+/*
+ * VehicleId
+ */
+_t.VehicleId = {
+ WMI: _t.DOMString,
+ VIN: _t.DOMString
+};
- getNetworkConnectionName: function (networkConnectionType) {
- var foundConnectionType;
- utils.validateArgumentType(networkConnectionType, "string", ExceptionTypes.INVALID_PARAMETER, "networkConnectionType is invalid, expected a string", new Exception());
- foundConnectionType = DataNetworkConnectionTypes[networkConnectionType.toUpperCase()];
- return foundConnectionType || null;
- }
+/*
+ * Size
+ */
+_t.Size = {
+ width: _t.unsigned_long,
+ height: _t.unsigned_long,
+ length: _t.unsigned_long
};
-event.on("DataNetworkConnectionChanged", function (newConnectionName) {
- var callback = _self.onNetworkConnectionChanged,
- msg = "Fired onNetworkConnectionChanged with newConnectionName: " + newConnectionName;
+/*
+ * FuelInfo
+ */
+_t.FuelInfo = {
+ type: _t.unsigned_short,
+ refuelPosition: _t.unsigned_short
+};
- if (callback && typeof callback === "function") {
- callback.apply(null, [newConnectionName]);
- }
- else {
- msg += " --> BUT there was no registered callback found.";
- }
+/*
+ * VehicleType
+ */
+_t.VehicleType = {
+ type: _t.unsigned_short
+};
- _console.log(msg);
-});
+/*
+ * Doors
+ */
+_t.Doors = {
+ doorsPerRow: [_t.unsigned_short]
+};
-_self.__defineGetter__("isDataNetworkConnected", function () {
- return deviceSettings.retrieveAsBoolean("DataNetworkInfo.isDataNetworkConnected");
-});
+/*
+ * TransmissionGearType
+ */
+_t.TransmissionGearType = {
+ transmissionGearType: _t.unsigned_short
+};
-_self.__defineGetter__("networkConnectionType", function () {
- var value = deviceSettings.retrieve("DataNetworkInfo.networkConnectionType");
- return value instanceof Array ? value : [value];
-});
+/*
+ * WheelInformation
+ */
+_t.WheelInformation = {
+ frontWheelRadius: _t.unsigned_short,
+ rearWheelRadius: _t.unsigned_short,
+ wheelTrack: _t.unsigned_long,
+ ABS: _t.boolean
+};
-module.exports = _self;
+/*
+ * Odometer
+ */
+_t.Odometer = {
+ odometer: _t.unsigned_long
+};
-});
-define('ripple/platform/wac/1.0/Device', function (require, exports, module) {
/*
- * Copyright 2011 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.
+ * Fluid
*/
-var constants = require('ripple/constants'),
- exception = require('ripple/exception'),
- _console = require('ripple/console'),
- utils = require('ripple/utils'),
- notifications = require('ripple/notifications'),
- ApplicationTypes = require('ripple/platform/wac/1.0/ApplicationTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- _applicationTypes = {
- FILES: "FILES",
- MEDIAPLAYER: "MEDIAPLAYER",
- PHONECALL: "PHONECALL",
- PICTURES: "PICTURES"
- },
- _self;
+_t.Fluid = {
+ transmission: _t.unsigned_short,
+ brake: _t.unsigned_short,
+ washer: _t.unsigned_short
+};
-function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
-}
+/*
+ * Battery
+ */
+_t.Battery = {
+ voltage: _t.double,
+ current: _t.double
+};
-_self = {
- // Properties
- clipboardString: undefined,
- widgetEngineName: undefined,
- widgetEngineProvider: undefined,
- widgetEngineVersion: undefined,
+/*
+ * TirePressure
+ */
+_t.TirePressure = {
+ leftFront: _t.double,
+ rightFront: _t.double,
+ leftRear: _t.double,
+ rightRear: _t.double
+};
- // Methods
- getAvailableApplications: function () {
- return constants.PLATFORMS.WAC.APPLICATIONS || [];
- },
+/*
+ * TireTemperature
+ */
+_t.TireTemperature = {
+ leftFront: _t.double,
+ rightFront: _t.double,
+ leftRear: _t.double,
+ rightRear: _t.double
+};
- getDirectoryFileNames: function () {
- _throwUnsupportedException("Device.getDirectoryFileNames");
- },
- getFile: function () {
- _throwUnsupportedException("Device.getFile");
- },
+/*
+ * SecurityAlert
+ */
+_t.SecurityAlert = {
+ securityAlert: _t.boolean
+};
+
+/*
+ * ParkingBrake
+ */
+_t.ParkingBrake = {
+ parkingBrake: _t.boolean
+};
+
+/*
+ * ParkingLight
+ */
+_t.ParkingLight = {
+ parkingLight: _t.boolean
+};
+
+/*
+ * HazardLight
+ */
+_t.HazardLight = {
+ hazardLight: _t.boolean
+};
+
+/*
+ * AntilockBrakingSystem
+ */
+_t.AntilockBrakingSystem = {
+ antilockBrakingSystem: _t.boolean
+};
+
+/*
+ * TractionControlSystem
+ */
+_t.TractionControlSystem = {
+ tractionControlSystem: _t.boolean
+};
+
+/*
+ * VehicleTopSpeedLimit
+ */
+_t.VehicleTopSpeedLimit = {
+ vehicleTopSpeedLimit: _t.unsigned_short
+};
+
+/*
+ * AirbagStatus
+ */
+_t.AirbagStatus = {
+ airbagStatus: _t.unsigned_short
+};
+
+/*
+ * DoorStatus
+ */
+_t.DoorStatus = {
+ doorStatus: _t.unsigned_short,
+ doorLockStatus: _t.boolean,
+ childLockStatus: _t.boolean
+};
+
+/*
+ * SeatBeltStatus
+ */
+_t.SeatBeltStatus = {
+ seatBeltStatus: _t.boolean
+};
+
+/*
+ * OccupantStatus
+ */
+_t.OccupantStatus = {
+ occupantStatus: _t.unsigned_short
+};
+
+/*
+ * ObstacleDistance
+ */
+_t.ObstacleDistance = {
+ obstacleDistance: _t.double
+};
+
+/*
+ * NightMode
+ */
+_t.NightMode = {
+ nightMode: _t.boolean
+};
+
+/*
+ * DrivingMode
+ */
+_t.DrivingMode = {
+ drivingMode: _t.unsigned_short
+};
+
+/*
+ * TurnSignal
+ */
+_t.TurnSignal = {
+ turnSignal: _t.unsigned_short
+};
+
+/*
+ * ButtonEvent
+ */
+_t.ButtonEvent = {
+ buttonEvent: _t.unsigned_short
+};
+
+/*
+ * VehiclePropertyType
+ */
+_t.VehiclePropertyType = {
+ time: _t.unsigned_long_long,
+ zone: _t.short,
+ source: _t.DOMString,
+
+ _derived: [_t.VehicleSpeed, _t.EngineSpeed, _t.VehiclePowerMode,
+ _t.TripMeter, _t.Acceleration, _t.Transmission,
+ _t.CruiseControlStatus, _t.WheelBrake, _t.LightStatus,
+ _t.InteriorLightStatus, _t.Horn, _t.Fuel, _t.EngineOil, _t.Location,
+ _t.ExteriorBrightness, _t.Temperature, _t.RainSensor,
+ _t.WindshieldWiper, _t.HVAC, _t.WindowStatus, _t.Sunroof,
+ _t.ConvertibleRoof, _t.VehicleId, _t.Size, _t.FuelInfo, _t.VehicleType,
+ _t.Doors, _t.TransmissionGearType, _t.WheelInformation, _t.Odometer,
+ _t.Fluid, _t.Battery, _t.TirePressure, _t.TireTemperature,
+ _t.SecurityAlert, _t.ParkingBrake, _t.ParkingLight, _t.HazardLight,
+ _t.AntilockBrakingSystem, _t.TractionControlSystem,
+ _t.VehicleTopSpeedLimit, _t.AirbagStatus, _t.DoorStatus,
+ _t.SeatBeltStatus, _t.OccupantStatus, _t.ObstacleDistance,
+ _t.NightMode, _t.TurnSignal, _t.ButtonEvent]
+};
+
+/*
+ * Constructor list definition
+ */
+
+/*
+ * Generic constructor
+ * Construct a prototype of constructor. A fake array of arguments type is
+ * specified for constructor.
+ *
+ * Overloaded constructors
+ * Construct an array of prototype of constructor. Each array element is
+ * specified for one of constructors. The constructor with extra arguments
+ * are recommended to be defined ahead of the one with fewer same arguments
+ * for exact match.
+ */
- launchApplication: function launchApplication(application, startParameter) {
- if (!application || typeof(application) !== "string") {
- exception.raise(ExceptionTypes.INVALID_PARAMETER,
- "Invalid argument 'application' at Device.launchApplication(): expected to be of type 'string' but was of type: " + (application ? typeof(application) : "null"),
- Exception);
- }
+_c = {};
- if (startParameter && typeof(startParameter) !== "string") {
- exception.raise(ExceptionTypes.INVALID_PARAMETER,
- "Invalid argument 'startParameter' at Device.launchApplication(): expected to be 'string' but was : " + typeof(startParameter),
- Exception);
- }
+/*
+ * Interface prototype definition
+ */
- // rudimentary implementation for now
- var message = "The widget has requested application: '" + application + "' to be launched. \n\n";
+_i = {
+ // Vehicle
+ Vehicle: {}
+};
- if (startParameter) {
- message += "The following start parameter was sent in: " + startParameter + "\n\n";
- }
+_i.Vehicle.get = {
+ 0: _t.DOMString,
+ 1: _t.short,
- if (_applicationTypes[application] && !startParameter) {
- message += "Launching this application can also be done with an optional startParameter which was not provided" + "\n\n";
- }
+ _optional: {
+ // nullable
+ 1: true
+ }
+};
- if (!ApplicationTypes[application]) {
- message += "Note: the application requested is not part of the common values specified by the WAC API.";
- }
+_i.Vehicle.getAsync = {
+ 0: _t.DOMString,
+ 1: _t.VehiclePropertyCallback,
+ 2: _t.VehiclePropertyErrorCallback,
+ 3: _t.short,
- notifications.openNotification("normal", message);
- _console.log(message);
- },
+ _optional: {
+ // nullable
+ 2: true,
+ 3: true
+ }
+};
- copyFile: function () {
- _throwUnsupportedException("Device.copyFile");
- },
- deleteFile: function () {
- _throwUnsupportedException("Device.deleteFile");
- },
- findFiles: function () {
- _throwUnsupportedException("Device.findFiles");
- },
- getFileSystemRoots: function () {
- _throwUnsupportedException("Device.getFileSystemRoots");
- },
- getFileSystemSize: function () {
- _throwUnsupportedException("Device.getFileSystemSize");
- },
- moveFile: function () {
- _throwUnsupportedException("Device.moveFile");
- },
- onFilesFound: function () {
- _throwUnsupportedException("Device.onFilesFound");
- },
- setRingtone: function () {
- _throwUnsupportedException("Device.setRingtone");
- },
+_i.Vehicle.subscribe = {
+ 0: _t.DOMString,
+ 1: _t.VehiclePropertyCallback,
+ 2: _t.short,
+ 3: _t.VehiclePropertyErrorCallback,
- vibrate: function (duration) {
- utils.validateArgumentType(duration, "number", ExceptionTypes.INVALID_PARAMETER, "duration paramter is not a number", new Exception());
- notifications.openNotification("normal", "Vibrating for " + duration + " second(s).");
+ _optional: {
+ // nullable
+ 2: true,
+ 3: true
}
+};
+
+_i.Vehicle.set = {
+ 0: _t.DOMString,
+ 1: _t.VehiclePropertyType,
+ 2: _t.VehiclePropertyErrorCallback,
+ _optional: {
+ // nullable
+ 2: true
+ }
};
-_self.__defineGetter__("widgetEngineName", function () {
- return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_NAME;
-});
+_i.Vehicle.getHistory = {
+ 0: _t.DOMString,
+ 1: _t.short,
+ 2: _t.Date,
+ 3: _t.Date,
+ 4: _t.VehiclePropertyListCallback,
+ 5: _t.VehiclePropertyErrorCallback,
-_self.__defineGetter__("widgetEngineProvider", function () {
- return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_PROVIDER;
-});
+ _optional: {
+ // nullable
+ 5: true
+ }
+};
-_self.__defineGetter__("widgetEngineVersion", function () {
- return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_VERSION;
-});
+_i.Vehicle.listZones = {
+ 0: _t.DOMString
+};
-module.exports = _self;
+// Exports
+_t.constructor = _c;
+_t.interface = _i;
+
+module.exports = _t;
});
-define('ripple/platform/wac/1.0/DeviceInfo', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/WebAPIException', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- deviceSettings = require('ripple/deviceSettings'),
- platform = require('ripple/platform'),
- devices = require('ripple/devices'),
- _self;
-
-_self = {
- ownerInfo: undefined, // return AddressBookItem
- phoneColorDepthDefault: undefined,
- phoneFirmware: undefined,
- phoneManufacturer: undefined,
- phoneModel: undefined,
- phoneOS: undefined,
- phoneSoftware: undefined,
- phoneScreenHeightDefault: undefined,
- phoneScreenWidthDefault: undefined,
- totalMemory: undefined
-};
-
-function _getDeviceAttribute(attr) {
- var devicePointer = devices.getCurrentDevice();
- utils.forEach(attr.split("."), function (dot) {
- devicePointer = devicePointer[dot];
- });
- return devicePointer;
-}
-
-_self.__defineGetter__("phoneColorDepthDefault", function () {
- return deviceSettings.retrieveAsInt("DeviceInfo.phoneColorDepthDefault");
-});
-_self.__defineGetter__("phoneFirmware", function () {
- return _getDeviceAttribute("firmware");
-});
-
-_self.__defineGetter__("phoneManufacturer", function () {
- return _getDeviceAttribute("manufacturer");
-});
-
-_self.__defineGetter__("phoneOS", function () {
- return _getDeviceAttribute("osName") + " " + _getDeviceAttribute("osVersion");
-});
-
-_self.__defineGetter__("phoneModel", function () {
- return _getDeviceAttribute("model");
-});
+var errorcode = require('ripple/platform/ivi/3.0/errorcode');
-_self.__defineGetter__("phoneSoftware", function () {
- return _getDeviceAttribute("osVersion");
-});
+var msg = {
+ 1: "Permission denied.",
+ 2: "Unsupported property.",
+ 3: "Timeout.",
+ 10: "Unknown."
+ },
+ errType = {
+ 1: "PermissionDeniedError",
+ 2: "PropertyUnavailableError",
+ 3: "TimeoutError",
+ 10: "UnknownError"
+ };
-_self.__defineGetter__("phoneScreenHeightDefault", function () {
- return _getDeviceAttribute("screen.height");
-});
+module.exports = function (code, message, name) {
+ var g, c, _code, _message, _name;
-_self.__defineGetter__("phoneScreenWidthDefault", function () {
- return _getDeviceAttribute("screen.width");
-});
+ for (c in errorcode) {
+ g = errorcode.__lookupGetter__(c);
+ if (g) {
+ this.__defineGetter__(c, g);
+ }
+ }
-_self.__defineGetter__("totalMemory", function () {
- return deviceSettings.retrieveAsInt("DeviceInfo.totalMemory");
-});
+ if (typeof code !== 'number') {
+ _code = errorcode.UNKNOWN;
+ _message = msg[_code];
+ _name = errType[_code];
+ } else {
+ _code = code;
+ if (typeof message === 'string') {
+ _message = message;
+ } else {
+ _message = msg[_code];
+ }
+ if (typeof name === 'string') {
+ _name = name;
+ } else {
+ _name = errType[_code];
+ }
+ }
-module.exports = _self;
+ this.__defineGetter__("code", function () {
+ return _code;
+ });
+ this.__defineGetter__("message", function () {
+ return _message;
+ });
+ this.__defineGetter__("name", function () {
+ return _name;
+ });
+};
});
-define('ripple/platform/wac/1.0/DeviceStateInfo', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/vehicle', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
var utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- _console = require('ripple/console'),
- geo = require('ripple/geo'),
event = require('ripple/event'),
- deviceSettings = require('ripple/deviceSettings'),
- PositionInfo = require('ripple/platform/wac/1.0/PositionInfo'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ t = require('ripple/platform/ivi/3.0/typecast'),
+ errorcode = require('ripple/platform/ivi/3.0/errorcode'),
+ WebAPIError = require('ripple/platform/ivi/3.0/WebAPIError'),
+ WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
+ VehiclePropertyType,
+ VehicleSpeed,
+ EngineSpeed,
+ VehiclePowerMode,
+ TripMeter,
+ Acceleration,
+ Transmission,
+ CruiseControlStatus,
+ WheelBrake,
+ LightStatus,
+ InteriorLightStatus,
+ Horn,
+ Fuel,
+ EngineOil,
+ Location,
+ ExteriorBrightness,
+ Temperature,
+ RainSensor,
+ WindshieldWiper,
+ HVAC,
+ WindowStatus,
+ Sunroof,
+ ConvertibleRoof,
+ VehicleId,
+ Size,
+ FuelInfo,
+ VehicleType,
+ Doors,
+ TransmissionGearType,
+ WheelInformation,
+ Odometer,
+ Fluid,
+ Battery,
+ TirePressure,
+ TireTemperature,
+ SecurityAlert,
+ ParkingBrake,
+ ParkingLight,
+ HazardLight,
+ AntilockBrakingSystem,
+ TractionControlSystem,
+ VehicleTopSpeedLimit,
+ AirbagStatus,
+ DoorStatus,
+ SeatBeltStatus,
+ OccupantStatus,
+ ObstacleDistance,
+ NightMode,
+ DrivingMode,
+ TurnSignal,
+ ButtonEvent,
+ VehicleFactory,
+ _vehicleCacheData = {
+ supported: null,
+ data: null
+ },
+ _vehicleEvent = {subscribe: {}},
+ _security = {
+ "http://tizen.org/privilege/vehicle": ["supported", "get", "getAsync",
+ "set", "getHistory", "subscribe", "listZones"]
+ },
_self;
-event.on("ScreenChangeDimensions", function (width, height) {
- try {
- if (typeof _self.onScreenChangeDimensions === 'function') {
- _self.onScreenChangeDimensions(width, height);
- }
- _console.log("called DeviceStateInfo.onScreenChangeDimensions callback function with width = " + width + " and height = " + height);
- } catch (e) {
- exception.handle(e, false);
- }
-});
-
-_self = {
- availableMemory: undefined,
- language: undefined,
- keypadLightOn: undefined,
- backLightOn: undefined,
- processorUtilizationPercent: undefined,
- audioPath: undefined,
+function _initialize () {
+ event.on("vehicle-cache-refresh", function (supported, data) {
+ _vehicleCacheData.supported = supported;
+ _vehicleCacheData.data = data;
+ });
- onPositionRetrieved: undefined,
+ event.trigger("vehicle-cache-request", [_vehicleCacheData]);
+}
- requestPositionInfo: function (method) {
- utils.validateNumberOfArguments(1, 1, arguments.length,
- ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid number of parameters", new Exception());
- utils.validateArgumentType(method, "string",
- ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid parameter", new Exception());
+_self = function () {
+ var vehicle;
- if (!(method.match(/gps|agps|cellid/))) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER,
- "Invalid method, expected (gps, agps or cellid)", Exception);
+ function supported () {
+ if (!_security.supported) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
}
- if (typeof _self.onPositionRetrieved === "function") {
- var delay = geo.delay * 1000,
- timeout = geo.timeout;
- setTimeout(function () {
- var pos = PositionInfo,
- errorObj = {};
+ return _vehicleCacheData.supported;
+ }
- if (timeout) {
- //create
- utils.forEach(pos, function (val, key) {
- errorObj[key] = undefined;
- });
- pos = errorObj;
- }
- _self.onPositionRetrieved(pos, method);
- }, delay);
+ function get (property, zone) {
+ if (!_security.get) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
}
- },
- onScreenChangeDimensions: undefined,
+ t.Vehicle("get", arguments);
- onFlipEvent: undefined
-};
+ if (_vehicleCacheData.supported.indexOf(property) === -1) {
+ throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ }
-_self.__defineGetter__("availableMemory", function () {
- return deviceSettings.retrieveAsInt("DeviceStateInfo.availableMemory");
-});
+ return new VehicleFactory(property, _vehicleCacheData.data[property]);
+ }
-_self.__defineGetter__("language", function () {
- return deviceSettings.retrieve("DeviceStateInfo.language");
-});
+ function getAsync (property, successCallback, errorCallback, zone) {
+ if (!_security.getAsync) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ }
-_self.__defineGetter__("keypadLightOn", function () {
- return deviceSettings.retrieveAsBoolean("DeviceStateInfo.keypadLightOn");
-});
+ t.Vehicle("getAsync", arguments);
-_self.__defineGetter__("backLightOn", function () {
- return deviceSettings.retrieveAsBoolean("DeviceStateInfo.backLightOn");
-});
+ if (_vehicleCacheData.supported.indexOf(property) === -1) {
+ throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ }
-_self.__defineGetter__("audioPath", function () {
- return deviceSettings.retrieve("DeviceStateInfo.audioPath");
-});
+ window.setTimeout(function () {
+ successCallback(new VehicleFactory(property,
+ _vehicleCacheData.data[property]));
+ }, 1);
+ }
-_self.__defineGetter__("processorUtilizationPercent", function () {
- return deviceSettings.retrieve("DeviceStateInfo.processorUtilizationPercent");
-});
+ function subscribe (property, successCallback, zone, errorCallback) {
+ if (!_security.subscribe) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ }
-module.exports = _self;
+ t.Vehicle("subscribe", arguments);
+ if (_vehicleCacheData.supported.indexOf(property) === -1) {
+ throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ }
-});
-define('ripple/platform/wac/1.0/EventRecurrenceTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- NOT_REPEAT: "NOT_REPEAT",
- DAILY: "DAILY",
- EVERY_WEEKDAY: "EVERY_WEEKDAY",
- WEEKLY_ON_DAY: "WEEKLY_ON_DAY",
- MONTHLY_ON_DAY: "MONTHLY_ON_DAY",
- MONTHLY_ON_DAY_COUNT: "MONTHLY_ON_DAY_COUNT",
- YEARLY: "YEARLY"
-};
+ _vehicleEvent.subscribe[property] = {
+ successCallback: successCallback,
+ errorCallback: errorCallback
+ };
-});
-define('ripple/platform/wac/1.0/Exception', function (require, exports, module) {
-/*
- * Copyright 2011 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 = function () {
- this.message = "";
- this.type = "";
+ window.setTimeout(function () {
+ if (! _vehicleEvent["vehicle-subscribe-response"]) {
+ event.on("vehicle-subscribe-response", function (propertyObj) {
+ var propertySub = _vehicleEvent.subscribe[propertyObj.type],
+ success = propertySub.successCallback,
+ error = propertySub.errorCallback;
- this.toString = function () {
- var result = this.type + ': "' + this.message + '"';
+ if (!propertyObj.supported) {
+ if (error) {
+ error(new WebAPIError(
+ errorcode.PROPERTY_UNAVAILABLE));
+ }
+ return;
+ }
- if (this.stack) {
- result += "\n" + this.stack;
- }
- return result;
- };
-};
+ success(new VehicleFactory(propertyObj.type,
+ propertyObj.val));
-});
-define('ripple/platform/wac/1.0/ExceptionTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self = {};
+ });
+ _vehicleEvent["vehicle-subscribe-response"] = true;
+ }
+ event.trigger("vehicle-subscribe-request", [property, true, zone]);
+ }, 1);
+ }
-_self.__defineGetter__("INVALID_PARAMETER", function () {
- return "invalid_parameter";
-});
+ function set (property, value, errorCallback) {
+ var val = utils.copy(value);
-_self.__defineGetter__("SECURITY", function () {
- return "security";
-});
+ if (!_security.set) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ }
-_self.__defineGetter__("UNKNOWN", function () {
- return "unknown";
-});
+ t.Vehicle("set", arguments);
-_self.__defineGetter__("UNSUPPORTED", function () {
- return "unsupported";
-});
+ if (_vehicleCacheData.supported.indexOf(property) === -1) {
+ throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ }
-module.exports = _self;
+ window.setTimeout(function () {
+ event.once("vehicle-set-response", function (status) {
+ if (!status) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.PROPERTY_UNAVAILABLE));
+ }
+ }
+ });
+ event.trigger("vehicle-set-request", [property, val]);
+ }, 1);
+ }
-});
-define('ripple/platform/wac/1.0/File', function (require, exports, module) {
-/*
- * Copyright 2011 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.expots = function () {
- this.createDate = undefined;
- this.fileName = undefined;
- this.filePath = undefined;
- this.fileSize = undefined;
- this.isDirectory = undefined;
- this.lastModifyDate = undefined;
-};
+ function getHistory (property, zone, startTime, endTime, successCallback,
+ errorCallback) {
+ var properties = [], i;
-});
-define('ripple/platform/wac/1.0/Message', function (require, exports, module) {
-/*
- * Copyright 2011 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 exception = require('ripple/exception'),
- Attachment = require('ripple/platform/wac/1.0/Attachment'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception');
+ if (!_security.getHistory) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
+ }
-function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
-}
+ t.Vehicle("getHistory", arguments);
-module.exports = function () {
- this.messageId = Math.uuid(undefined, 16);
- this.callbackNumber = undefined;
- this.destinationAddress = [];
- this.isRead = undefined;
- this.messagePriority = undefined;
- this.messageType = undefined;
- this.subject = undefined;
- this.body = undefined;
- this.sourceAddress = undefined;
- this.validityPeriodHours = undefined;
- this.time = undefined;
- this.ccAddress = [];
- this.bccAddress = [];
- this.attachments = [];
+ if (_vehicleCacheData.supported.indexOf(property) === -1) {
+ throw new WebAPIException(errorcode.PROPERTY_UNAVAILABLE);
+ }
- this.addAttachment = function (fileFullName) {
- var attachment = new Attachment();
- attachment.fileName = fileFullName;
- this.attachments.push(attachment);
- };
- this.deleteAttachment = function (attachment) {
+ startTime = startTime.getTime();
+ endTime = endTime.getTime();
- for (var i = this.attachments.length - 1; i >= 0; i--) {
- if (this.attachments[i].fileName === attachment.fileName) {
- this.attachments.splice(i, 1);
- }
- }
- };
- this.saveAttachment = function (fileFullName, attachment) {
- _throwUnsupportedException("Widget.Messaging.Message.addAddress");
- };
- this.addAddress = function (type, address) {
+ window.setTimeout(function () {
+ event.once("vehicle-history-response", function (values, status) {
+ if (!status) {
+ if (errorCallback) {
+ errorCallback(new WebAPIError(
+ errorcode.PROPERTY_UNAVAILABLE));
+ }
+ return;
+ }
- var addresses = address.split(";");
+ for (i = 0; i < values.length; i++) {
+ properties.push(new VehicleFactory(property, values[i]));
+ }
+ successCallback(properties);
+ });
+ event.trigger("vehicle-history-request", [property, zone,
+ startTime, endTime]);
+ }, 1);
+ }
- switch (type) {
- case "destination":
- this.destinationAddress = this.destinationAddress.concat(addresses);
- break;
- case "cc":
- this.ccAddress = this.ccAddress.concat(addresses);
- break;
- case "bcc":
- this.bccAddress = this.bccAddress.concat(addresses);
- break;
+ function listZones (property) {
+ if (!_security.listZones) {
+ throw new WebAPIException(errorcode.PERMISSION_DENIED);
}
- };
- this.deleteAddress = function (type, address) {
- var addresses = address.split(";"),
- filter = function (orig) {
- return orig.filter(function (address) {
- return !addresses.some(function (x) {
- return address === x;
- });
- });
- };
+ t.Vehicle("listZones", arguments);
- switch (type) {
- case "destination":
- this.destinationAddress = filter(this.destinationAddress);
- break;
- case "cc":
- this.ccAddress = filter(this.ccAddress);
- break;
- case "bcc":
- this.bccAddress = filter(this.bccAddress);
- break;
- }
- };
+ return [0];
+ }
-};
+ function handleSubFeatures (subFeatures) {
+ var i, subFeature;
-});
-define('ripple/platform/wac/1.0/MessageFolderTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- DRAFTS: "drafts",
- INBOX: "inbox",
- OUTBOX: "outbox",
- SENTBOX: "sentbox"
-};
+ for (subFeature in subFeatures) {
+ for (i in _security[subFeature]) {
+ _security[_security[subFeature][i]] = true;
+ }
+ }
+ }
-});
-define('ripple/platform/wac/1.0/MessageQuantities', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- totalMessageCnt: undefined,
- totalMessageReadCnt: undefined,
- totalMessageUnreadCnt: undefined
-};
+ vehicle = {
+ supported: supported,
+ get: get,
+ getAsync: getAsync,
+ subscribe: subscribe,
+ set: set,
+ getHistory: getHistory,
+ listZones: listZones,
+ handleSubFeatures: handleSubFeatures
+ };
-});
-define('ripple/platform/wac/1.0/MessageTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- EmailMessage: "email",
- MMSMessage: "mms",
- SMSMessage: "sms"
-};
+ vehicle.__defineGetter__("ZONE_None", function () {
+ return 0;
+ });
-});
-define('ripple/platform/wac/1.0/Messaging', function (require, exports, module) {
-/*
- * Copyright 2011 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 exception = require('ripple/exception'),
- utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- notifications = require('ripple/notifications'),
- _console = require('ripple/console'),
- Message = require('ripple/platform/wac/1.0/Message'),
- MessageTypes = require('ripple/platform/wac/1.0/MessageTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
+ vehicle.__defineGetter__("ZONE_Front", function () {
+ return 0x01;
+ });
-function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
-}
+ vehicle.__defineGetter__("ZONE_Middle", function () {
+ return 0x02;
+ });
-module.exports = {
- onMessageArrived: undefined,
- onMessageSendingFailure: undefined,
- onMessagesFound: undefined,
+ vehicle.__defineGetter__("ZONE_Right", function () {
+ return 0x04;
+ });
- createMessage: function (messageType) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "createMessage invalid number of arguments", new Exception());
- utils.validateArgumentType(messageType, "string", ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());
+ vehicle.__defineGetter__("ZONE_Left", function () {
+ return 0x08;
+ });
- if (!utils.some(MessageTypes, function (value) {
- return value === messageType;
- })) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());
- }
+ vehicle.__defineGetter__("ZONE_Rear", function () {
+ return 0x10;
+ });
- var message = new Message();
- message.messageType = messageType;
+ vehicle.__defineGetter__("ZONE_Center", function () {
+ return 0x20;
+ });
- return message;
- },
- deleteMessage: function () {
- _throwUnsupportedException("Messaging.deleteMessage");
- },
- getMessage: function () {
- _throwUnsupportedException("Messaging.getMessage");
- },
- getMessageQuantities: function () {
- _throwUnsupportedException("Messaging.getMessageQuantities");
- },
- sendMessage: function (msg) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.UNSUPPORTED, "sendMessage invalid number of arguments", new Exception());
- if (msg instanceof Message === false) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "expected a valid Message object", new Exception());
- }
+ return vehicle;
+};
- //TODO: Must be modded to fail and to then call the onMessageSendingFailure callback
- var message = "Sent " + msg.messageType + " " + msg.messageId + " to " + msg.destinationAddress;
+VehicleFactory = function (vehicleType, value) {
+ var instanceType;
- // insert fail check here
- notifications.openNotification("normal", message);
- _console.log(message);
- },
- moveMessageToFolder: function () {
- _throwUnsupportedException("Messaging.moveMessageToFolder");
- },
- copyMessageToFolder: function () {
- _throwUnsupportedException("Messaging.copyMessageToFolder");
- },
- createFolder: function () {
- _throwUnsupportedException("Messaging.createFolder");
- },
- deleteFolder: function () {
- _throwUnsupportedException("Messaging.deleteFolder");
- },
- getFolderNames: function () {
- _throwUnsupportedException("Messaging.getFolderNames");
- },
- findMessages: function () {
- _throwUnsupportedException("Messaging.findMessages");
- },
- getCurrentEmailAccount: function () {
- _throwUnsupportedException("Messaging.getCurrentEmailAccount");
- },
- getEmailAccounts: function () {
- _throwUnsupportedException("Messaging.getEmailAccounts");
- },
- setCurrentEmailAccount: function () {
- _throwUnsupportedException("Messaging.setCurrentEmailAccount");
- },
- deleteEmailAccount: function () {
- _throwUnsupportedException("Messaging.deleteEmailAccount");
+ switch (vehicleType) {
+ case "VehicleSpeed":
+ instanceType = new VehicleSpeed(value);
+ break;
+ case "EngineSpeed":
+ instanceType = new EngineSpeed(value);
+ break;
+ case "VehiclePowerMode":
+ instanceType = new VehiclePowerMode(value);
+ break;
+ case "TripMeter":
+ instanceType = new TripMeter(value);
+ break;
+ case "Acceleration":
+ instanceType = new Acceleration(value);
+ break;
+ case "Transmission":
+ instanceType = new Transmission(value);
+ break;
+ case "CruiseControlStatus":
+ instanceType = new CruiseControlStatus(value);
+ break;
+ case "WheelBrake":
+ instanceType = new WheelBrake(value);
+ break;
+ case "LightStatus":
+ instanceType = new LightStatus(value);
+ break;
+ case "InteriorLightStatus":
+ instanceType = new InteriorLightStatus(value);
+ break;
+ case "Horn":
+ instanceType = new Horn(value);
+ break;
+ case "Fuel":
+ instanceType = new Fuel(value);
+ break;
+ case "EngineOil":
+ instanceType = new EngineOil(value);
+ break;
+ case "Location":
+ instanceType = new Location(value);
+ break;
+ case "ExteriorBrightness":
+ instanceType = new ExteriorBrightness(value);
+ break;
+ case "Temperature":
+ instanceType = new Temperature(value);
+ break;
+ case "RainSensor":
+ instanceType = new RainSensor(value);
+ break;
+ case "WindshieldWiper":
+ instanceType = new WindshieldWiper(value);
+ break;
+ case "HVAC":
+ instanceType = new HVAC(value);
+ break;
+ case "WindowStatus":
+ instanceType = new WindowStatus(value);
+ break;
+ case "Sunroof":
+ instanceType = new Sunroof(value);
+ break;
+ case "ConvertibleRoof":
+ instanceType = new ConvertibleRoof(value);
+ break;
+ case "VehicleId":
+ instanceType = new VehicleId(value);
+ break;
+ case "Size":
+ instanceType = new Size(value);
+ break;
+ case "FuelInfo":
+ instanceType = new FuelInfo(value);
+ break;
+ case "VehicleType":
+ instanceType = new VehicleType(value);
+ break;
+ case "Doors":
+ instanceType = new Doors(value);
+ break;
+ case "TransmissionGearType":
+ instanceType = new TransmissionGearType(value);
+ break;
+ case "WheelInformation":
+ instanceType = new WheelInformation(value);
+ break;
+ case "Odometer":
+ instanceType = new Odometer(value);
+ break;
+ case "Fluid":
+ instanceType = new Fluid(value);
+ break;
+ case "Battery":
+ instanceType = new Battery(value);
+ break;
+ case "TirePressure":
+ instanceType = new TirePressure(value);
+ break;
+ case "TireTemperature":
+ instanceType = new TireTemperature(value);
+ break;
+ case "SecurityAlert":
+ instanceType = new SecurityAlert(value);
+ break;
+ case "ParkingBrake":
+ instanceType = new ParkingBrake(value);
+ break;
+ case "ParkingLight":
+ instanceType = new ParkingLight(value);
+ break;
+ case "HazardLight":
+ instanceType = new HazardLight(value);
+ break;
+ case "AntilockBrakingSystem":
+ instanceType = new AntilockBrakingSystem(value);
+ break;
+ case "TractionControlSystem":
+ instanceType = new TractionControlSystem(value);
+ break;
+ case "VehicleTopSpeedLimit":
+ instanceType = new VehicleTopSpeedLimit(value);
+ break;
+ case "AirbagStatus":
+ instanceType = new AirbagStatus(value);
+ break;
+ case "DoorStatus":
+ instanceType = new DoorStatus(value);
+ break;
+ case "SeatBeltStatus":
+ instanceType = new SeatBeltStatus(value);
+ break;
+ case "OccupantStatus":
+ instanceType = new OccupantStatus(value);
+ break;
+ case "ObstacleDistance":
+ instanceType = new ObstacleDistance(value);
+ break;
+ case "NightMode":
+ instanceType = new NightMode(value);
+ break;
+ case "DrivingMode":
+ instanceType = new DrivingMode(value);
+ break;
+ case "TurnSignal":
+ instanceType = new TurnSignal(value);
+ break;
+ case "ButtonEvent":
+ instanceType = new ButtonEvent(value);
+ break;
+ }
+
+ function _construct () {
+ var val;
+
+ for (val in value) {
+ instanceType[val] = value[val];
+ }
+ return instanceType;
}
+ return _construct();
};
-});
-define('ripple/platform/wac/1.0/Multimedia', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- VideoPlayer = require('ripple/platform/wac/1.0/VideoPlayer'),
- AudioPlayer = require('ripple/platform/wac/1.0/AudioPlayer'),
- constants = require('ripple/constants'),
- _volume = 5,
- _audioState,
- _videoState,
- _self;
+VehiclePropertyType = function (propertyTypes) {
+ var vehiclePropertyType = {};
-event.on("MultimediaVolumeChanged", function updateVolume(volume) {
- _volume = volume;
-});
+ vehiclePropertyType.time = propertyTypes.time || undefined;
+ vehiclePropertyType.zone = propertyTypes.zone || 0;
+ vehiclePropertyType.source = propertyTypes.source || "";
-event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
- _audioState = state;
-});
+ this.__defineGetter__("time", function () {
+ return vehiclePropertyType.time;
+ });
-event.on("MultimediaVideoStateChanged", function updateVideoState(state) {
- _videoState = state;
-});
+ this.__defineSetter__("time", function (val) {
+ try {
+ vehiclePropertyType.time = t.unsigned_long_long(val);
+ } catch (err) {
+ }
+ });
-_self = {
+ this.__defineGetter__("zone", function () {
+ return vehiclePropertyType.zone;
+ });
- isAudioPlaying: undefined,
- isVideoPlaying: undefined,
+ this.__defineSetter__("zone", function (val) {
+ try {
+ vehiclePropertyType.zone = t.short(val);
+ } catch (err) {
+ }
+ });
- getVolume: function () {
- return _volume;
- },
+ this.__defineGetter__("source", function () {
+ return vehiclePropertyType.source;
+ });
- stopAll: function () {
- VideoPlayer.stop();
- AudioPlayer.stop();
- }
+ this.__defineSetter__("source", function (val) {
+ try {
+ vehiclePropertyType.source = t.DOMString(val);
+ } catch (err) {
+ }
+ });
};
-_self.__defineGetter__("isAudioPlaying", function () {
- return _audioState === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
-});
+VehicleSpeed = function (propertyTypes) {
+ var vehicleSpeed = {};
-_self.__defineGetter__("isVideoPlaying", function () {
- return _videoState === "playing";
-});
+ VehiclePropertyType.call(this, propertyTypes);
-module.exports = _self;
+ vehicleSpeed.vehicleSpeed = propertyTypes.vehicleSpeed || 0;
-});
-define('ripple/platform/wac/1.0/PIM', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- exception = require('ripple/exception'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- AddressBookItem = require('ripple/platform/wac/1.0/AddressBookItem'),
- CalendarItem = require('ripple/platform/wac/1.0/CalendarItem'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants');
+ this.__defineGetter__("vehicleSpeed", function () {
+ return vehicleSpeed.vehicleSpeed;
+ });
-function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
-}
+ this.__defineSetter__("vehicleSpeed", function (val) {
+ try {
+ vehicleSpeed.vehicleSpeed = t.unsigned_long(val);
+ } catch (err) {
+ }
+ });
+};
-function _toAddressBookItem(contact) {
- if (!contact) {
- return null;
- }
+EngineSpeed = function (propertyTypes) {
+ var engineSpeed = {};
- var addressBookItem = new AddressBookItem();
+ VehiclePropertyType.call(this, propertyTypes);
- utils.forEach(contact, function (prop, key) {
- addressBookItem[key] = contact[key];
+ engineSpeed.engineSpeed = propertyTypes.engineSpeed || 0;
+
+ this.__defineGetter__("engineSpeed", function () {
+ return engineSpeed.engineSpeed;
});
- return addressBookItem;
-}
+ this.__defineSetter__("engineSpeed", function (val) {
+ try {
+ engineSpeed.engineSpeed = t.unsigned_long(val);
+ } catch (err) {
+ }
+ });
+};
-function _toCalendarItem(item) {
- if (!item) {
- return null;
- }
+VehiclePowerMode = function (propertyTypes) {
+ var vehiclePowerMode = {};
- var calendarItem = new CalendarItem();
+ VehiclePropertyType.call(this, propertyTypes);
- utils.forEach(item, function (prop, key) {
- calendarItem[key] = item[key];
+ vehiclePowerMode.vehiclePowerMode = propertyTypes.vehiclePowerMode || 0;
+
+ this.__defineGetter__("VEHICLEPOWERMODE_OFF", function () {
+ return 0;
});
- return calendarItem;
-}
+ this.__defineGetter__("VEHICLEPOWERMODE_ACCESSORY1", function () {
+ return 1;
+ });
-function _getData(type) {
- var data = db.retrieveObject(type) || [];
- return data;
-}
+ this.__defineGetter__("VEHICLEPOWERMODE_ACCESSORY2", function () {
+ return 2;
+ });
-function _saveData(type, items) {
- db.saveObject(type, items);
-}
+ this.__defineGetter__("VEHICLEPOWERMODE_RUN", function () {
+ return 3;
+ });
-function _getContacts() {
- var contacts = _getData(constants.PIM.ADDRESS_LIST_KEY),
- gord,
- dan,
- brent,
- pj,
- mark;
+ this.__defineGetter__("vehiclePowerMode", function () {
+ return vehiclePowerMode.vehiclePowerMode;
+ });
- if (contacts.length === 0) {
+ this.__defineSetter__("vehiclePowerMode", function (val) {
+ try {
+ val = t.octet(val);
+ if (val < 0 || val > 3) {
+ return;
+ }
+ vehiclePowerMode.vehiclePowerMode = val;
+ } catch (err) {
+ }
+ });
+};
- gord = new AddressBookItem();
- gord.addressBookItemId = "0";
- gord.fullName = "Gord Tanner";
- gord.eMail = "gord@tinyHippos.com";
- gord.company = "tinyHippos Inc";
- gord.title = "Code Poet";
- gord.address = "121 Charles Street W, Kitchener, Ontario, Canada";
+TripMeter = function (propertyTypes) {
+ var tripMeter = {};
- dan = new AddressBookItem();
- dan.addressBookItemId = "1";
- dan.fullName = "Dan Silivestru";
- dan.eMail = "dan@tinyHippos.com";
- dan.company = "tinyHippos Inc";
- dan.title = "Co-Founder And Chief Technology Officer";
- dan.address = "121 Charles Street W, Kitchener, Ontario, Canada";
+ VehiclePropertyType.call(this, propertyTypes);
- pj = new AddressBookItem();
- pj.addressBookItemId = "2";
- pj.fullName = "PJ Lowe";
- pj.eMail = "pj@tinyHippos.com";
- pj.company = "tinyHippos Inc";
- pj.title = "Co-Founder And Chief Operations Officer";
- pj.address = "121 Charles Street W, Kitchener, Ontario, Canada";
+ tripMeter.tripMeters = propertyTypes.tripMeters || [];
- brent = new AddressBookItem();
- brent.addressBookItemId = "2";
- brent.fullName = "Brent Lintner";
- brent.eMail = "brent@tinyHippos.com";
- brent.company = "tinyHippos Inc";
- brent.title = "Co-Founder And Chief Operations Officer";
- brent.address = "121 Charles Street W, Kitchener, Ontario, Canada";
+ this.__defineGetter__("tripMeters", function () {
+ return tripMeter.tripMeters;
+ });
- mark = new AddressBookItem();
- mark.addressBookItemId = "3";
- mark.fullName = "Mark McArdle";
- mark.eMail = "mark@tinyHippos.com";
- mark.company = "tinyHippos Inc";
- mark.title = "Chief Executive Officer";
- mark.address = "121 Charles Street W, Kitchener, Ontario, Canada";
+ this.__defineSetter__("tripMeters", function (val) {
+ try {
+ //Changing any items in the array will reset the item's value to '0';
+ tripMeter.tripMeters = t.unsigned_long(val, "[]");
+ }
+ catch (err) {
+ }
+ });
+};
- contacts.push(gord);
- contacts.push(dan);
- contacts.push(pj);
- contacts.push(brent);
- contacts.push(mark);
+Acceleration = function (propertyTypes) {
+ var acceleration = {};
- _saveData(constants.PIM.ADDRESS_LIST_KEY, contacts);
- }
- return contacts.map(_toAddressBookItem);
-}
+ VehiclePropertyType.call(this, propertyTypes);
-function _getEvents() {
- var events = _getData(constants.PIM.CALENDAR_LIST_KEY);
- return events.map(_toCalendarItem);
-}
+ acceleration.x = propertyTypes.x || 0;
+ acceleration.y = propertyTypes.y || 0;
+ acceleration.z = propertyTypes.z || 0;
-function _get(type, id, fetchIDFunc) {
- var items = _getData(type);
- return items.reduceRight(function (match, item) {
- return fetchIDFunc(item) === id ? item : match;
- }, null);
-}
+ this.__defineGetter__("x", function () {
+ return acceleration.x;
+ });
-function _getAddressBookID(item) {
- return item.addressBookItemId;
-}
+ this.__defineSetter__("x", function (val) {
+ try {
+ acceleration.x = t.unsigned_long(val);
+ }
+ catch (err) {
+ }
+ });
-function _getCalendarID(item) {
- return item.calendarItemId;
-}
+ this.__defineGetter__("y", function () {
+ return acceleration.y;
+ });
-function _getContact(id) {
- return _toAddressBookItem(_get(constants.PIM.ADDRESS_LIST_KEY, id, _getAddressBookID));
-}
+ this.__defineSetter__("y", function (val) {
+ try {
+ acceleration.y = t.unsigned_long(val);
+ }
+ catch (err) {
+ }
+ });
-function _getEvent(id) {
- return _toCalendarItem(_get(constants.PIM.CALENDAR_LIST_KEY, id, _getCalendarID));
-}
+ this.__defineGetter__("z", function () {
+ return acceleration.z;
+ });
-function _add(type, item, idProp) {
- var items = _getData(type);
+ this.__defineSetter__("z", function (val) {
+ try {
+ acceleration.z = t.unsigned_long(val);
+ } catch (err) {
+ }
+ });
+};
- if (!item[idProp]) {
- item[idProp] = Math.uuid(undefined, 16);
- }
+Transmission = function (propertyTypes) {
+ var transmission = {};
- items.push(item);
- _saveData(type, items);
-}
+ VehiclePropertyType.call(this, propertyTypes);
-function _delete(type, id, fetchIDFunc) {
- var items = _getData(type);
+ transmission.gearPosition = propertyTypes.gearPosition || 0;
+ transmission.mode = propertyTypes.mode || 0;
- _saveData(type, items.filter(function (item) {
- return fetchIDFunc(item) !== id;
- }));
-}
+ this.__defineGetter__("TRANSMISSIONPOSITION_NEUTRAL", function () {
+ return 0;
+ });
-function _validateArgs(min, max, len) {
- utils.validateNumberOfArguments(min, max, len,
- ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
-}
+ this.__defineGetter__("TRANSMISSIONPOSITION_FIRST", function () {
+ return 1;
+ });
-function _validateType(arg, argType) {
- utils.validateArgumentType(arg, argType,
- ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
- new Exception());
-}
+ this.__defineGetter__("TRANSMISSIONPOSITION_SECOND", function () {
+ return 2;
+ });
-function _validateAddressBookItem(item) {
- if ((item instanceof AddressBookItem) === false) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid contact, not instance of AddressBookItem.", new Exception());
- }
-}
+ this.__defineGetter__("TRANSMISSIONPOSITION_THIRD", function () {
+ return 3;
+ });
-_self = {
- addAddressBookItem: function (contact) {
- _validateArgs(1, 1, arguments.length);
- _validateAddressBookItem(contact);
+ this.__defineGetter__("TRANSMISSIONPOSITION_FORTH", function () {
+ return 4;
+ });
- _add(constants.PIM.ADDRESS_LIST_KEY, contact, "addressBookItemId");
- },
- createAddressBookGroup: function (groupName) {
- _throwUnsupportedException("Widget.PIM.createAddressBookGroup");
- },
- createAddressBookItem: function () {
- return new AddressBookItem();
- },
- deleteAddressBookItem: function (contactid) {
- _validateArgs(1, 1, arguments.length);
- _validateType(contactid, "string");
- _delete(constants.PIM.ADDRESS_LIST_KEY, contactid, _getAddressBookID);
- },
- deleteAddressBookGroup: function (groupName) {
- _throwUnsupportedException("Widget.PIM.deleteAddressBookGroup");
- },
- getAddressBookItem: function (contactid) {
- _validateArgs(1, 1, arguments.length);
- _validateType(contactid, "string");
- return _getContact(contactid);
- },
- getAddressBookItemsCount: function () {
- _validateArgs(0, 0, arguments.length);
- var items = _getContacts();
- return items.length;
- },
- getAvailableAddressGroupNames: function () {
- _throwUnsupportedException("Widget.PIM.getAvailableAddressGroupNames");
- },
- getAddressBookGroupMembers: function (groupName) {
- _throwUnsupportedException("Widget.PIM.getAddressBookGroupMembers");
- },
- findAddressBookItems: function (comparisonContact, startInx, endInx) {
- _validateArgs(3, 3, arguments.length);
- utils.validateMultipleArgumentTypes([comparisonContact, startInx, endInx], ["object", "number", "number"], ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
- new Exception());
+ this.__defineGetter__("TRANSMISSIONPOSITION_FIFTH", function () {
+ return 5;
+ });
- if (endInx < 0) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
- }
+ this.__defineGetter__("TRANSMISSIONPOSITION_SIXTH", function () {
+ return 6;
+ });
- startInx = startInx < 0 ? 0 : startInx;
+ this.__defineGetter__("TRANSMISSIONPOSITION_SEVENTH", function () {
+ return 7;
+ });
- var contacts = _getContacts();
- utils.find(comparisonContact, contacts, startInx, endInx, _self.onAddressBookItemsFound);
- },
+ this.__defineGetter__("TRANSMISSIONPOSITION_EIGHTH", function () {
+ return 8;
+ });
- addCalendarItem: function (calendarItem) {
- _validateArgs(1, 1, arguments.length);
- _add(constants.PIM.CALENDAR_LIST_KEY, calendarItem, "calendarItemId");
- },
- deleteCalendarItem: function (calendarId) {
- _validateArgs(1, 1, arguments.length);
- _delete(constants.PIM.CALENDAR_LIST_KEY, calendarId, _getCalendarID);
- },
- getCalendarItem: function (calendarId) {
- _validateArgs(1, 1, arguments.length);
- return _getEvent(calendarId);
- },
- findCalendarItems: function (itemToMatch, startInx, endInx) {
- _validateArgs(1, 3, arguments.length);
- var events = _getEvents();
- utils.find(itemToMatch, events, startInx, endInx, _self.onCalendarItemsFound);
- },
- getCalendarItems: function (startTime, endTime) {
- var events = _getEvents();
+ this.__defineGetter__("TRANSMISSIONPOSITION_NINTH", function () {
+ return 9;
+ });
- return events.reduce(function (matches, event) {
- if (event.eventStartTime >= startTime && event.eventStartTime <= endTime) {
- matches.push(event);
- }
- return matches;
- }, []);
- },
- exportAsVCard: function (addressBookItems) {
- _throwUnsupportedException("Widget.PIM.exportAsVCard");
- },
+ this.__defineGetter__("TRANSMISSIONPOSITION_TENTH", function () {
+ return 10;
+ });
- onAddressBookItemsFound: undefined, // function (addressBookItemsFound) { }
- onCalendarItemsFound: undefined, // function (calendarItemsFound) { }
- onCalendarItemAlert: undefined, // function (calendarItem) { }
- onVCardExportingFinish: undefined // function (vCardFilePath) { }
-};
+ this.__defineGetter__("TRANSMISSIONPOSITION_CVT", function () {
+ return 64;
+ });
-module.exports = _self;
+ this.__defineGetter__("TRANSMISSIONPOSITION_REVERSE", function () {
+ return 128;
+ });
-});
-define('ripple/platform/wac/1.0/PositionInfo', function (require, exports, module) {
-/*
- * Copyright 2011 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 geo = require('ripple/geo'),
- event = require('ripple/event'),
- exception = require('ripple/exception'),
- utils = require('ripple/utils'),
- _self = {
- latitude: undefined,
- longitude: undefined,
- altitude: undefined,
- cellID: undefined,
- accuracy: undefined,
- altitudeAccuracy: undefined,
- timeStamp: undefined
- };
+ this.__defineGetter__("TRANSMISSIONPOSITION_PARK", function () {
+ return 255;
+ });
-utils.forEach(_self, function (value, property) {
- _self.__defineGetter__(property, function () {
- return geo.getPositionInfo()[property];
+ this.__defineGetter__("TRANSMISSIONMODE_NORMAL", function () {
+ return 0;
});
-});
-module.exports = _self;
+ this.__defineGetter__("TRANSMISSIONMODE_SPORT", function () {
+ return 1;
+ });
-});
-define('ripple/platform/wac/1.0/PowerInfo', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- event = require('ripple/event'),
- _console = require('ripple/console'),
- deviceSettings = require('ripple/deviceSettings'),
- _lastPercentRemaining;
+ this.__defineGetter__("TRANSMISSIONMODE_ECONOMY", function () {
+ return 2;
+ });
-_self = {
- isCharging: undefined,
- percentRemaining: undefined,
+ this.__defineGetter__("TRANSMISSIONMODE_OEMCUSTOM1", function () {
+ return 3;
+ });
- onChargeStateChange: undefined,
- onLowBattery: undefined,
- onChargeLevelChange: undefined
-};
+ this.__defineGetter__("TRANSMISSIONMODE_OEMCUSTOM2", function () {
+ return 4;
+ });
-function _getCurrentChargeState(percentRemaining, isCharging) {
- var batteryState;
- if (percentRemaining === 100 && isCharging) {
- batteryState = "full";
- }
- else if (!isCharging) {
- batteryState = "discharging";
- }
- else {
- batteryState = "charging";
- }
- return batteryState;
-}
+ this.__defineGetter__("gearPosition", function () {
+ return transmission.gearPosition;
+ });
-event.on("DeviceBatteryStateChanged", function (isCharging) {
- var callback = _self.onChargeStateChange,
- msg = "",
- batteryLevel = _self.percentRemaining,
- batteryState;
+ this.__defineSetter__("gearPosition", function (val) {
+ try {
+ val = t.octet(val);
+ if ((val >= 0 && val <= 10) || val === 64 || val === 128 ||
+ val === 255) {
+ transmission.gearPosition = val;
+ }
+ } catch (err) {
+ }
+ });
- batteryState = _getCurrentChargeState(batteryLevel, isCharging);
+ this.__defineGetter__("mode", function () {
+ return transmission.mode;
+ });
- msg += "Fired onChargeStateChange with batteryState: " + batteryState;
+ this.__defineSetter__("mode", function (val) {
+ try {
+ val = t.octet(val);
+ if (val < 0 || val > 4) {
+ return;
+ }
+ transmission.mode = val;
+ } catch (err) {
+ }
+ });
+};
- if (callback && typeof callback === "function") {
- callback.apply(null, [batteryState]);
- }
- else {
- msg += " --> BUT there was no registered callback found.";
- }
+CruiseControlStatus = function (propertyTypes) {
+ var cruiseControlStatus = {};
- _console.log(msg);
-});
+ VehiclePropertyType.call(this, propertyTypes);
-event.on("DeviceBatteryLevelChanged", function (percentRemaining) {
+ cruiseControlStatus.activated = propertyTypes.activated || false;
+ cruiseControlStatus.speed = propertyTypes.speed || 0;
- var callback = _self.onChargeLevelChange,
- lowBatteryCallback = _self.onLowBattery,
- msg = "Fired onChargeLevelChange with percentRemaining: " + percentRemaining;
+ this.__defineGetter__("activated", function () {
+ return cruiseControlStatus.activated;
+ });
- // blah, stupid Options returning strings
- percentRemaining = parseInt(percentRemaining, 10);
+ this.__defineSetter__("activated", function (val) {
+ try {
+ cruiseControlStatus.activated = t.boolean(val);
+ } catch (err) {
+ }
+ });
- if (callback && typeof callback === "function") {
- callback.apply(null, [percentRemaining]);
- }
- else {
- msg += " --> BUT there was no registered callback found.";
- }
+ this.__defineGetter__("speed", function () {
+ return cruiseControlStatus.speed;
+ });
- _console.log(msg);
+ this.__defineSetter__("speed", function (val) {
+ try {
+ cruiseControlStatus.speed = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
+};
- if (percentRemaining <= 10) {
+WheelBrake = function (propertyTypes) {
+ var wheelBrake = {};
- msg = "Fired onLowBattery with percentRemaining: " + percentRemaining;
+ VehiclePropertyType.call(this, propertyTypes);
- if (lowBatteryCallback && typeof lowBatteryCallback === "function") {
- lowBatteryCallback.apply(null, [percentRemaining]);
- }
- else {
- msg += " --> BUT there was no registered callback found.";
+ wheelBrake.engaged = propertyTypes.engaged || false;
+
+ this.__defineGetter__("engaged", function () {
+ return wheelBrake.engaged;
+ });
+
+ this.__defineSetter__("engaged", function (val) {
+ try {
+ wheelBrake.engaged = t.boolean(val);
+ } catch (err) {
}
+ });
+};
- _console.log(msg);
- }
+LightStatus = function (propertyTypes) {
+ var lightStatus = {};
- if (percentRemaining === 100 || (percentRemaining < 100 && _lastPercentRemaining === 100)) {
- event.trigger("DeviceBatteryStateChanged", [_self.isCharging]);
- }
+ VehiclePropertyType.call(this, propertyTypes);
- _lastPercentRemaining = percentRemaining;
+ lightStatus.head = propertyTypes.head || false;
+ lightStatus.rightTurn = propertyTypes.rightTurn || false;
+ lightStatus.leftTurn = propertyTypes.leftTurn || false;
+ lightStatus.brake = propertyTypes.brake || false;
+ lightStatus.fog = propertyTypes.fog || false;
+ lightStatus.hazard = propertyTypes.hazard || false;
+ lightStatus.parking = propertyTypes.parking || false;
+ lightStatus.highBeam = propertyTypes.highBeam || false;
-});
+ this.__defineGetter__("head", function () {
+ return lightStatus.head;
+ });
-_self.__defineGetter__("isCharging", function () {
- return deviceSettings.retrieveAsBoolean("PowerInfo.isCharging");
-});
+ this.__defineSetter__("head", function (val) {
+ try {
+ lightStatus.head = t.boolean(val);
+ } catch (err) {
+ }
+ });
-_self.__defineGetter__("percentRemaining", function () {
- return deviceSettings.retrieveAsInt("PowerInfo.percentRemaining");
-});
+ this.__defineGetter__("rightTurn", function () {
+ return lightStatus.rightTurn;
+ });
-module.exports = _self;
+ this.__defineSetter__("rightTurn", function (val) {
+ try {
+ lightStatus.rightTurn = t.boolean(val);
+ } catch (err) {
+ }
+ });
-});
-define('ripple/platform/wac/1.0/RadioInfo', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- event = require('ripple/event'),
- _console = require('ripple/console'),
- deviceSettings = require('ripple/deviceSettings');
+ this.__defineGetter__("leftTurn", function () {
+ return lightStatus.leftTurn;
+ });
-_self = {
- isRoaming: undefined,
- radioSignalStrengthPercent: undefined,
- isRadioEnabled: undefined,
- radioSignalSource: undefined,
- onSignalSourceChange: undefined
-};
+ this.__defineSetter__("leftTurn", function (val) {
+ try {
+ lightStatus.leftTurn = t.boolean(val);
+ } catch (err) {
+ }
+ });
-event.on("RadioSignalSourceChanged", function () {
- var callback = _self.onSignalSourceChange,
- isRoaming = _self.isRoaming,
- signalSource = _self.radioSignalSource,
- msg = "Fired onSignalSourceChange. signalSource: " + signalSource + ", isRoaming: " + isRoaming;
+ this.__defineGetter__("brake", function () {
+ return lightStatus.brake;
+ });
- if (callback && typeof callback === "function") {
- callback.apply(null, [signalSource, isRoaming]);
- }
- else {
- msg += " --> BUT there was no registered callback found.";
- }
+ this.__defineSetter__("brake", function (val) {
+ try {
+ lightStatus.brake = t.boolean(val);
+ } catch (err) {
+ }
+ });
- _console.log(msg);
-});
+ this.__defineGetter__("fog", function () {
+ return lightStatus.fog;
+ });
-_self.__defineGetter__("radioSignalSource", function () {
- return deviceSettings.retrieve("RadioInfo.radioSignalSource");
-});
+ this.__defineSetter__("fog", function (val) {
+ try {
+ lightStatus.fog = t.boolean(val);
+ } catch (err) {
+ }
+ });
-_self.__defineGetter__("isRoaming", function () {
- return deviceSettings.retrieveAsBoolean("RadioInfo.isRoaming");
-});
+ this.__defineGetter__("hazard", function () {
+ return lightStatus.hazard;
+ });
-_self.__defineGetter__("isRadioEnabled", function () {
- return deviceSettings.retrieveAsBoolean("RadioInfo.isRadioEnabled");
-});
+ this.__defineSetter__("hazard", function (val) {
+ try {
+ lightStatus.hazard = t.boolean(val);
+ } catch (err) {
+ }
+ });
-_self.__defineGetter__("radioSignalStrengthPercent", function () {
- return deviceSettings.retrieveAsInt("RadioInfo.radioSignalStrengthPercent");
-});
+ this.__defineGetter__("parking", function () {
+ return lightStatus.parking;
+ });
-module.exports = _self;
+ this.__defineSetter__("parking", function (val) {
+ try {
+ lightStatus.parking = t.boolean(val);
+ } catch (err) {
+ }
+ });
-});
-define('ripple/platform/wac/1.0/RadioSignalSourceTypes', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- utils = require('ripple/utils');
+ this.__defineGetter__("highBeam", function () {
+ return lightStatus.highBeam;
+ });
-_self = {
- "CDMA": undefined,
- "GSM": undefined,
- "LTE": undefined,
- "TDSCDMA": undefined,
- "WCDMA": undefined
+ this.__defineSetter__("highBeam", function (val) {
+ try {
+ lightStatus.highBeam = t.boolean(val);
+ } catch (err) {
+ }
+ });
};
-utils.forEach(_self, function (value, property) {
- _self.__defineGetter__(property, function () {
- return property;
+InteriorLightStatus = function (propertyTypes) {
+ var interiorLightStatus = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ interiorLightStatus.passenger = propertyTypes.passenger || false;
+ interiorLightStatus.driver = propertyTypes.driver || false;
+ interiorLightStatus.center = propertyTypes.center || false;
+
+ this.__defineGetter__("passenger", function () {
+ return interiorLightStatus.passenger;
});
-});
-module.exports = _self;
+ this.__defineSetter__("passenger", function (val) {
+ try {
+ interiorLightStatus.passenger = t.boolean(val);
+ } catch (err) {
+ }
+ });
-});
-define('ripple/platform/wac/1.0/Telephony', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- exception = require('ripple/exception'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants'),
- Device = require('ripple/platform/wac/1.0/Device'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception');
+ this.__defineGetter__("driver", function () {
+ return interiorLightStatus.driver;
+ });
+
+ this.__defineSetter__("driver", function (val) {
+ try {
+ interiorLightStatus.driver = t.boolean(val);
+ } catch (err) {
+ }
+ });
+ this.__defineGetter__("center", function () {
+ return interiorLightStatus.center;
+ });
-function _throwUnsupportedException(method) {
- exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
-}
+ this.__defineSetter__("center", function (val) {
+ try {
+ interiorLightStatus.center = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
-_self = {
+Horn = function (propertyTypes) {
+ var horn = {};
- // Public Callbacks
- onCallEvent: undefined,// function (callType, phoneNumber) { },
- onCallRecordsFound: undefined,// function (callRecords) { };
+ VehiclePropertyType.call(this, propertyTypes);
- // Public Methods
- initiateVoiceCall: function (phoneNumber) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "initiateVoiceCall invalid number of parameters", new Exception());
- //HACK: should this be hardcoded?
- //I am still not even sure this is the correct behaviour
- Device.launchApplication("PHONECALL", phoneNumber);
+ horn.on = propertyTypes.on || false;
- if (_self.onCallEvent) {
- //HACK: shouldn't be hardcoded
- //also what should the context be? isn't spec'ed
- _self.onCallEvent.apply(_self, ["outgoing", phoneNumber]);
+ this.__defineGetter__("on", function () {
+ return horn.on;
+ });
+
+ this.__defineSetter__("on", function (val) {
+ try {
+ horn.on = t.boolean(val);
+ } catch (err) {
}
- },
- getCallRecordCnt: function (callRecordType) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecordCnt invalid number of parameters", new Exception());
- var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
+ });
+};
- return utils.sum(calls, function (call) {
- return call.callRecordType === callRecordType;
- });
- },
- getCallRecord: function (callRecordType, id) {
- utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecord invalid number of parameters", new Exception());
- var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
+Fuel = function (propertyTypes) {
+ var fuel = {};
- return utils.map(calls, function (call) {
- return call.callRecordType === callRecordType ? call : null;
- }).reduce(function (match, call) {
- return match || call.callRecordId === id || null;
- }, null);
- },
- deleteCallRecord: function (callRecordType, id) {
- utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteCallRecord invalid number of parameters", new Exception());
- var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
- indexToDelete = calls.reduce(function (result, call, index) {
- return call.callRecordType === callRecordType &&
- call.callRecordId === id ? index : result;
- }, -1);
+ VehiclePropertyType.call(this, propertyTypes);
- if (indexToDelete >= 0) {
- calls.splice(indexToDelete, 1);
- db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
+ fuel.level = propertyTypes.level || 0;
+ fuel.range = propertyTypes.range || 0;
+ fuel.instantConsumption = propertyTypes.instantConsumption || 0;
+ fuel.instantEconomy = propertyTypes.instantEconomy || 0;
+ fuel.averageEconomy = propertyTypes.averageEconomy || 0;
+
+ this.__defineGetter__("level", function () {
+ return fuel.level;
+ });
+
+ this.__defineSetter__("level", function (val) {
+ try {
+ fuel.level = t.unsigned_short(val);
+ } catch (err) {
}
+ });
- },
+ this.__defineGetter__("range", function () {
+ return fuel.range;
+ });
- deleteAllCallRecords: function (callRecordType) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteAllCallRecords invalid number of parameters", new Exception());
- var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
- indexesToDelete = calls.reduce(function (result, call, index) {
- if (call.callRecordType === callRecordType) {
- result.push(index);
- }
- return result;
- }, []);
+ this.__defineSetter__("range", function (val) {
+ try {
+ fuel.range = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
- utils.forEach(indexesToDelete, function (index) {
- calls.splice(index, 1);
- });
+ this.__defineGetter__("instantConsumption", function () {
+ return fuel.instantConsumption;
+ });
- if (indexesToDelete.length > 0) {
- db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
+ this.__defineSetter__("instantConsumption", function (val) {
+ try {
+ fuel.instantConsumption = t.unsigned_short(val);
+ } catch (err) {
}
+ });
- },
+ this.__defineGetter__("instantEconomy", function () {
+ return fuel.instantEconomy;
+ });
- findCallRecords: function (comparisonRecord, startInx, endInx) {
- utils.validateNumberOfArguments(1, 3, arguments.length, ExceptionTypes.INVALID_PARAMETER, "findCallRecords invalid number of parameters", new Exception());
- var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
- utils.find(comparisonRecord, calls, startInx, endInx, _self.onCallRecordsFound);
+ this.__defineSetter__("instantEconomy", function (val) {
+ try {
+ fuel.instantEconomy = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
- }
+ this.__defineGetter__("averageEconomy", function () {
+ return fuel.averageEconomy;
+ });
+ this.__defineSetter__("averageEconomy", function (val) {
+ try {
+ //Setting this to any value should reset the counter to '0'
+ fuel.averageEconomy = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
};
-module.exports = _self;
+EngineOil = function (propertyTypes) {
+ var engineOil = {};
-});
-define('ripple/platform/wac/1.0/VideoPlayer', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- _console = require('ripple/console'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- fileSystem = require('ripple/fileSystem'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- exception = require('ripple/exception'),
- _currentlySet,
- _currentVideoFile,
- _state = null,
- _loopCount, _video,
- _STATES = {
- "OPENED": "opened",
- "STOPPED": "stopped",
- "PAUSED": "paused",
- "PLAYING": "playing",
- "COMPLETED": "completed"
- };
+ VehiclePropertyType.call(this, propertyTypes);
-function _validateVideoType(fileUrl) {
- var matched = fileUrl.match(/\.(\w*)$/),
- maps = {
- "ogv": "ogg",
- "flv": "mp4"
- },
- type = matched ? matched[1] : "";
+ engineOil.remaining = propertyTypes.remaining || 0;
+ engineOil.temperature = propertyTypes.temperature || 0;
+ engineOil.pressure = propertyTypes.Pressure || 0;
- if (_video && _video.canPlayType("video/" + (maps[type] || type)) === "") {
- _console.warn("Attempting to load a video that might not work in the current browser [" + fileUrl + "]");
- }
-}
+ this.__defineGetter__("remaining", function () {
+ return engineOil.remaining;
+ });
-function _validateAndSet(state, validStates, callbackBeforeSuccess) {
- var i, valid = false;
+ this.__defineSetter__("remaining", function (val) {
+ try {
+ engineOil.remaining = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
- for (i = 0; i < validStates.length; i++) {
- if (validStates[i] === _state) {
- valid = true;
+ this.__defineGetter__("temperature", function () {
+ return engineOil.temperature;
+ });
+
+ this.__defineSetter__("temperature", function (val) {
+ try {
+ engineOil.temperature = t.long(val);
+ } catch (err) {
}
- }
+ });
- if (!valid) {
- _console.warn("Attempted to initiate VideoPlayer." + state +
- " in invalid state. current state: " + _state);
- } else {
- if (typeof(callbackBeforeSuccess) === "function") {
- callbackBeforeSuccess.apply();
+ this.__defineGetter__("pressure", function () {
+ return engineOil.pressure;
+ });
+
+ this.__defineSetter__("pressure", function (val) {
+ try {
+ engineOil.pressure = t.unsigned_short(val);
+ } catch (err) {
}
- event.trigger("MultimediaVideoStateChanged", [state], true);
- }
+ });
+};
- return valid;
-}
+Location = function (propertyTypes) {
+ var location = {};
-event.on("MultimediaVideoStateChanged", function (state) {
- _state = state;
- if (typeof _self.onStateChange === "function") {
- _self.onStateChange.apply(_self, [state]);
- }
-});
+ VehiclePropertyType.call(this, propertyTypes);
-_self = module.exports = {
- onStateChange: undefined,
+ location.latitude = propertyTypes.latitude || 0;
+ location.longitude = propertyTypes.longitude || 0;
+ location.altitude = propertyTypes.altitude || 0;
+ location.direction = propertyTypes.direction || 0;
- open: function (fileUrl) {
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
- "VideoPlayer.open invalid number of arguments", new Exception());
- utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER,
- "VideoPlayer.open expected valid fileUrl but got ->" + fileUrl, new Exception());
+ this.__defineGetter__("latitude", function () {
+ return location.latitude;
+ });
- if (!_video) {
- return;
+ this.__defineSetter__("latitude", function (val) {
+ try {
+ val = t.double(val);
+ if (val >= -180 && val <= 180) {
+ location.latitude = val;
+ }
+ } catch (err) {
}
+ });
- _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
- _validateVideoType(fileUrl);
- _currentVideoFile = fileSystem.getURI(fileUrl);
- _video.setAttribute("src", _currentVideoFile);
- _video.setAttribute("width", "100%");
- _video.addEventListener("ended", function () {
- event.trigger("MultimediaVideoStateChanged", [_STATES.COMPLETED], true);
- if (_loopCount > 1) {
- _self.open(_currentVideoFile);
- _self.play(_loopCount--);
- }
- }, false);
- });
- },
-
- setWindow: function (domObject) {
- utils.validateNumberOfArguments(0, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
- "VideoPlayer.setWindow invalid number of arguments", new Exception());
+ this.__defineGetter__("longitude", function () {
+ return location.longitude;
+ });
- if (_currentlySet) {
- _currentlySet.removeChild(_video);
- _currentlySet = null;
- _video = null;
+ this.__defineSetter__("longitude", function (val) {
+ try {
+ val = t.double(val);
+ if (val >= -90 && val <= 90) {
+ location.longitude = val;
+ }
+ } catch (err) {
}
+ });
- if (domObject !== null) {
- _video = utils.createElement("video", {
- "id": "multimedia-video"
- });
- domObject.appendChild(_video);
- _currentlySet = domObject;
- event.trigger("MultimediaAppVideoPlayerCreated", [_video], true);
+ this.__defineGetter__("altitude", function () {
+ return location.altitude;
+ });
+
+ this.__defineSetter__("altitude", function (val) {
+ try {
+ val = t.double(val);
+ if (val >= 0) {
+ location.altitude = val;
+ }
+ } catch (err) {
}
- },
+ });
- play: function (repeatTimes) {
- utils.validateNumberOfArguments(1, 1, arguments.length,
- ExceptionTypes.INVALID_PARAMETER, "invalid number of arguments (expected one)", new Exception());
+ this.__defineGetter__("direction", function () {
+ return location.direction;
+ });
- if (typeof repeatTimes !== "number" || repeatTimes < 0) {
- exception.raise(ExceptionTypes.INVALID_PARAMETER, "VideoPlayer.play was passed an invalid number of play times: " + repeatTimes, new Exception());
- }
- if (repeatTimes !== 0) {
- if (!_video) {
- return;
+ this.__defineSetter__("direction", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val < 360) {
+ location.direction = val;
}
- _loopCount = repeatTimes;
- _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
- _video.play();
- });
+ } catch (err) {
}
- },
+ });
+};
- pause: function () {
- if (!_video) {
- return;
- }
- _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
- _video.pause();
- });
- },
+ExteriorBrightness = function (propertyTypes) {
+ var eb = {};
- resume: function () {
- if (!_video) {
- return;
- }
- _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
- _video.play();
- });
- },
+ VehiclePropertyType.call(this, propertyTypes);
- stop: function () {
- if (!_video) {
- return;
- }
- _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
- _video.pause();
- _video.setAttribute("src", _currentVideoFile); // hack
- });
- }
+ eb.exteriorBrightness = propertyTypes.exteriorBrightness || 0;
+
+ this.__defineGetter__("exteriorBrightness", function () {
+ return eb.exteriorBrightness;
+ });
+ this.__defineSetter__("exteriorBrightness", function (val) {
+ try {
+ eb.exteriorBrightness = t.unsigned_long(val);
+ } catch (err) {
+ }
+ });
};
-});
-define('ripple/platform/wac/1.0/Widget', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- _console = require('ripple/console'),
- app = require('ripple/app'),
- platform = require('ripple/platform'),
- exception = require('ripple/exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- _self;
+Temperature = function (propertyTypes) {
+ var temperature = {};
-event.on("ScreenChangeDimensions", function (height, width) {
- try {
- // TODO: are these per spec to call?
- if (typeof app.onMaximize === 'function') {
- app.onMaximize();
- }
- if (typeof app.onRestore === 'function') {
- app.onRestore();
- }
- _console.log("called Widget.onRestore and Widget.onMaximize callback function");
- }
- catch (e) {
- exception.handle(e, false);
- }
-});
+ VehiclePropertyType.call(this, propertyTypes);
-event.on("WidgetWakeup", function () {
- if (_self.onWakeup) {
- _self.onWakeup();
- }
-});
+ temperature.interior = propertyTypes.interior || 0;
+ temperature.exterior = propertyTypes.exterior || 0;
-event.on("WidgetMaximize", function () {
- if (_self.onMaximize) {
- _self.onMaximize();
- }
-});
+ this.__defineGetter__("interior", function () {
+ return temperature.interior;
+ });
-event.on("WidgetFocus", function () {
- if (_self.onFocus) {
- _self.onFocus();
- }
-});
+ this.__defineSetter__("interior", function (val) {
+ try {
+ temperature.interior = t.short(val);
+ } catch (err) {
+ }
+ });
-event.on("WidgetRestore", function () {
- if (_self.onRestore) {
- _self.onRestore();
- }
-});
+ this.__defineGetter__("exterior", function () {
+ return temperature.exterior;
+ });
-_self = {
- onWakeup: undefined,
- onMaximize: undefined,
- onFocus: undefined,
- onRestore: undefined,
+ this.__defineSetter__("exterior", function (val) {
+ try {
+ temperature.exterior = t.short(val);
+ } catch (err) {
+ }
+ });
+};
- openURL: function (url) {
- window.open(url);
- },
+RainSensor = function (propertyTypes) {
+ var rainSensor = {};
- setPreferenceForKey: function (value, key) {
+ VehiclePropertyType.call(this, propertyTypes);
- utils.validateNumberOfArguments(1, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid number of paramters", new Exception());
- utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid parameter! Key:" +
- key + ", Value: " + value, new Exception());
+ rainSensor.rainSensor = propertyTypes.rainSensor || 0;
- var msg = "",
- prefix;
- if (app.isPreferenceReadOnly(key)) {
- msg += "Cannot modify a read only preference. Preference key: " + key;
- }
- else {
- prefix = platform.getPersistencePrefix();
- if (value === null) {
- msg += "deleting preference " + key;
- db.remove(key, prefix);
- }
- else {
- msg += "setting preference " + key + " == " + value;
- utils.validateArgumentType(value, "string", ExceptionTypes.INVALID_PARAMETER, msg, new Exception());
- db.save(key, value, prefix);
+ this.__defineGetter__("rainSensor", function () {
+ return rainSensor.rainSensor;
+ });
+
+ this.__defineSetter__("rainSensor", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 10) {
+ rainSensor.rainSensor = val;
}
+ } catch (err) {
}
+ });
+};
+WindshieldWiper = function (propertyTypes) {
+ var windshieldWiper = {};
- _console.log(msg);
-
- // Trigger storageUpdatedEvent
- event.trigger("StorageUpdatedEvent");
-
- },
+ VehiclePropertyType.call(this, propertyTypes);
- // return value or undefined
- preferenceForKey: function (key) {
+ windshieldWiper.windshieldWiper = propertyTypes.windshieldWiper || 0;
- utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid number of parameters", new Exception());
- utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid paramters", new Exception());
+ this.__defineGetter__("WIPERSPEED_OFF", function () {
+ return 0;
+ });
- var prefix = platform.getPersistencePrefix(),
- value = db.retrieve(key, prefix);
+ this.__defineGetter__("WIPERSPEED_SLOWEST", function () {
+ return 1;
+ });
- if (!value && value !== "") {
- value = undefined;
- }
+ this.__defineGetter__("WIPERSPEED_FASTEST", function () {
+ return 5;
+ });
- _console.log("retrieving preference " + key + " == " + value);
+ this.__defineGetter__("WIPERSPEED_AUTO", function () {
+ return 10;
+ });
- return value;
+ this.__defineGetter__("windshieldWiper", function () {
+ return windshieldWiper.windshieldWiper;
+ });
- }
+ this.__defineSetter__("windshieldWiper", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1 || val === 5 || val === 10) {
+ windshieldWiper.windshieldWiper = val;
+ }
+ } catch (err) {
+ }
+ });
};
-module.exports = _self;
+HVAC = function (propertyTypes) {
+ var hvac = {};
-});
-define('ripple/platform/wac/1.0/WidgetManager', function (require, exports, module) {
-/*
- * Copyright 2011 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 exception = require('ripple/exception'),
- ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
- Exception = require('ripple/platform/wac/1.0/Exception');
+ VehiclePropertyType.call(this, propertyTypes);
-module.exports = {
- // This method is used to check the installation status of a specific widget.
- checkWidgetInstallationStatus: function () {
+ hvac.airflowDirection = propertyTypes.airflowDirection || 0;
+ hvac.fanSpeed = propertyTypes.fanSpeed || 0;
+ hvac.targetTemperature = propertyTypes.targetTemperature || 0;
+ hvac.airConditioning = propertyTypes.airConditioning || false;
+ hvac.airRecirculation = propertyTypes.airRecirculation || false;
+ hvac.heater = propertyTypes.heater || false;
+ hvac.steeringWheelHeater = propertyTypes.steeringWheelHeater || false;
+ hvac.seatHeater = propertyTypes.seatHeater || false;
+ hvac.seatCooler = propertyTypes.seatCooler || false;
- exception.raise(ExceptionTypes.UNSUPPORTED, "WidgetManager.checkWidgetInstallationStatus not supported", new Exception());
- }
-};
+ this.__defineGetter__("AIRFLOWDIRECTION_FRONTPANEL", function () {
+ return 0;
+ });
-});
-define('ripple/platform/wac/1.0/spec/config', function (require, exports, module) {
-/*
- * Copyright 2011 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 platform = require('ripple/platform'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants');
+ this.__defineGetter__("AIRFLOWDIRECTION_FLOORDUCT", function () {
+ return 1;
+ });
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
- (!configValidationObject.widget.validationResult[0].attributes["xmlns:JIL"].valid));
+ this.__defineGetter__("AIRFLOWDIRECTION_FRONT", function () {
+ return 0x02;
+ });
- return valid;
- },
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
- }
+ this.__defineGetter__("AIRFLOWDIRECTION_DEFROSTER", function () {
+ return 0x04;
+ });
- var widgetInfo = {},
- configFeatures,
- configPreferences,
- preferenceName,
- platform;
+ this.__defineGetter__("airflowDirection", function () {
+ return hvac.airflowDirection;
+ });
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+ this.__defineSetter__("airflowDirection", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1 || val === 0x02 || val === 0x04) {
+ hvac.airflowDirection = val;
+ }
+ } catch (err) {
+ }
+ });
- widgetInfo.features = {};
+ this.__defineGetter__("fanSpeed", function () {
+ return hvac.fanSpeed;
+ });
- configFeatures = configValidationObject.widget.children.feature.validationResult;
- utils.forEach(configFeatures, function (f) {
- if (f.valid === true) {
- var feature = {id: f.attributes.name.value,
- required: f.attributes.required.valid};
- widgetInfo.features[feature.id] = feature;
+ this.__defineSetter__("fanSpeed", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 7) {
+ hvac.fanSpeed = val;
}
- });
+ } catch (err) {
+ }
+ });
- widgetInfo.preferences = {};
+ this.__defineGetter__("targetTemperature", function () {
+ return hvac.targetTemperature;
+ });
- configPreferences = configValidationObject.widget.children.preference.validationResult;
+ this.__defineSetter__("targetTemperature", function (val) {
+ try {
+ hvac.targetTemperature = t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
- platform = require('ripple/platform');
- utils.forEach(configPreferences, function (preference) {
- preferenceName = preference.attributes.name.value;
- if (preferenceName) {
- widgetInfo.preferences[preferenceName] = {
- "key": preferenceName,
- "value": preference.attributes.value.value || "",
- "readonly": preference.attributes.readonly.value === "true"
- };
+ this.__defineGetter__("airConditioning", function () {
+ return hvac.airConditioning;
+ });
- db.save(preferenceName,
- widgetInfo.preferences[preferenceName].value,
- platform.getPersistencePrefix(widgetInfo.id));
- }
- });
+ this.__defineSetter__("airConditioning", function (val) {
+ try {
+ hvac.airConditioning = t.boolean(val);
+ } catch (err) {
+ }
+ });
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,maximum_display_mode,update,feature,access,billing. \"widget\" element MAY have following attributes: id,version,height,width,xml:lang",
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:JIL": {
- attributeName: "xmlns:JIL",
- required: true,
- type: "list",
- listValues: ["http://www.jil.org/ns/widgets1.2"]
- },
- "xmlns:its": {
- attributeName: "xmlns:its",
- helpText: "Indicates Text Directionality can be used. According to W3C spec, this feature is at risk, therefore we don't currently validate this.",
- required: false,
- type: "string"
- },
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- },
- version: {
- attributeName: "version",
- helpText: "Version must be in the following format: jil-rec-version-tag = major-version \".\" minor-version [\".\" version-desc]",
- required: true,
- type: "regex",
- regex: /^\d{1,2}\.\d{1,2}(\.[A-Za-z0-9]{1,10})?$/
- },
- height: {
- attributeName: "height",
- required: true,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: true,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["floating", "fullscreen"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- }
- },
- children: {
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "string",
- required: true
- },
- value: {
- type: "string",
- attributeName: "value",
- required: false
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
- },
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "short": {
- attributeName: "short",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- email: {
- attributeName: "email",
- type: "regex",
- required: false,
- regex: constants.REGEX.EMAIL
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 1,
- type: "string",
- attributes: {
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- },
- "xml:lang": {
- attributeName: "xml:lang",
- type: "string",
- required: false,
- unique: true
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- encoding: {
- attributeName: "encoding",
- type: "string",
- required: false
- },
- type: {
- attributeName: "type",
- type: "string",
- required: false
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- name: {
- attributeName: "name",
- type: "list",
- required: true,
- listValues: ["http://jil.org/jil/api/1.1/widget", "http://jil.org/jil/api/1.1.5/exception",
- "http://jil.org/jil/api/1.1.5/exceptiontypes", "http://jil.org/jil/api/1.1/device",
- "http://jil.org/jil/api/1.1/accountinfo", "http://jil.org/jil/api/1.1/deviceinfo",
- "http://jil.org/jil/api/1.1.1/datanetworkinfo", "http://jil.org/jil/api/1.1/devicestateinfo",
- "http://jil.org/jil/api/1.1/accelerometerinfo", "http://jil.org/jil/api/1.1/config",
- "http://jil.org/jil/api/1.1.1/file", "http://jil.org/jil/api/1.1/positioninfo",
- "http://jil.org/jil/api/1.1/powerinfo", "http://jil.org/jil/api/1.1.1/radioinfo",
- "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes", "http://jil.org/jil/api/1.1.5/applicationtypes",
- "http://jil.org/jil/api/1.1/messaging", "http://jil.org/jil/api/1.1/account",
- "http://jil.org/jil/api/1.1/attachment", "http://jil.org/jil/api/1.1/message",
- "http://jil.org/jil/api/1.1.4/messagefoldertypes", "http://jil.org/jil/api/1.1/messagequantities",
- "http://jil.org/jil/api/1.1/messagetypes", "http://jil.org/jil/api/1.1/multimedia",
- "http://jil.org/jil/api/1.1/audioplayer", "http://jil.org/jil/api/1.1.2/camera",
- "http://jil.org/jil/api/1.1.2/videoplayer", "http://jil.org/jil/api/1.1.1/pim",
- "http://jil.org/jil/api/1.1/addressbookitem", "http://jil.org/jil/api/1.1/calendaritem",
- "http://jil.org/jil/api/1.1/eventrecurrencetypes", "http://jil.org/jil/api/1.1.1/telephony",
- "http://jil.org/jil/api/1.1/callrecord", "http://jil.org/jil/api/1.1.1/callrecordtypes",
- "http://jil.org/jil/api/1.1.1/widgetmanager"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- }
- },
- "JIL:maximum_display_mode": {
- nodeName: "JIL:maximum_display_mode",
- required: false,
- occurrence: 1,
- attributes: {
- height: {
- attributeName: "height",
- type: "integer",
- required: false
- },
- width: {
- attributeName: "width",
- type: "integer",
- required: false
- }
- }
- },
- "JIL:update": {
- nodeName: "JIL:update",
- required: false,
- occurrence: 1,
- attributes: {
- href: {
- attributeName: "href",
- type: "regex",
- required: true,
- regex: constants.REGEX.URL
- },
- period: {
- attributeName: "period",
- helpText: "Possible values for the period attribute are: 0, 1, 2, 3 meaning: every time the widget is opened in maximum display mode, every day, every week, every month; respectivly",
- type: "list",
- required: true,
- listValues: ["0", "1", "2", "3"]
- }
- }
- },
- "JIL:access": {
- nodeName: "JIL:access",
- required: false,
- occurrence: 1,
- attributes: {
- network: {
- attributeName: "network",
- type: "boolean",
- required: false
- },
- localfs: {
- attributeName: "localfs",
- type: "boolean",
- required: false
- },
- remote_scripts: {
- attributeName: "remote_scripts",
- type: "boolean",
- required: false
- }
- }
- },
- "JIL:billing": {
- nodeName: "JIL:billing",
- required: false,
- occurrence: 1,
- attributes: {
- required: {
- attributeName: "required",
- type: "boolean",
- required: true
- }
- }
- }
- }
+ this.__defineGetter__("airRecirculation", function () {
+ return hvac.airRecirculation;
+ });
+
+ this.__defineSetter__("airRecirculation", function (val) {
+ try {
+ hvac.airRecirculation = t.boolean(val);
+ } catch (err) {
}
- }
-};
+ });
-});
-define('ripple/platform/wac/1.0/spec/device', function (require, exports, module) {
-/*
- * Copyright 2011 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 constants = require('ripple/constants'),
- event = require('ripple/event');
+ this.__defineGetter__("heater", function () {
+ return hvac.heater;
+ });
-module.exports = {
- "AccountInfo": {
- "phoneUserUniqueId": {
- "name": "User Unique Id",
- "control": {
- "type": "text",
- "value": new Date().getTime().toString()
- }
- },
- "phoneMSISDN": {
- "name": "MSISDN",
- "control": {
- "type": "text",
- "value": "15199999999"
- }
- },
- "phoneOperatorName": {
- "name": "Operator Name",
- "control": {
- "type": "text",
- "value": ""
- }
- },
- "userAccountBalance": {
- "name": "Account Balance",
- "control": {
- "type": "number",
- "value": 0
- }
- },
- "userSubscriptionType": {
- "name": "Subscription Type",
- "control": {
- "type": "select",
- "value": "other"
- },
- "options": {
- "other": "other",
- "prepaid": "prepaid",
- "postpaid": "postpaid"
- }
+ this.__defineSetter__("heater", function (val) {
+ try {
+ hvac.heater = t.boolean(val);
+ } catch (err) {
}
- },
- "RadioInfo": {
- "isRoaming": {
- "name": "Is Roaming",
- "control": {
- "type": "checkbox",
- "value": false
- },
- "callback": function () {
- event.trigger("RadioSignalSourceChanged");
- }
- },
- "isRadioEnabled": {
- "name": "Is Radio Enabled",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "radioSignalSource": {
- "name": "Radio Signal Source",
- "control": {
- "type": "select",
- "value": "GSM"
- },
- // TODO: try not to duplicate from RadioSignalSourceTypes
- "options": {
- "CDMA": "cdma",
- "GSM": "gsm",
- "LTE": "lte",
- "TDSCDMA": "tdscdma",
- "WCDMA": "wcdma"
- },
- "callback": function () {
- event.trigger("RadioSignalSourceChanged");
- }
- },
- "radioSignalStrengthPercent": {
- "name": "Signal Strength %",
- "control": {
- "type": "select",
- "value": 80
- },
- "options": (function () {
- var i,
- optionList = {};
+ });
- for (i = 0; i <= 100; i++) {
- optionList[i] = i;
- }
+ this.__defineGetter__("steeringWheelHeater", function () {
+ return hvac.steeringWheelHeater;
+ });
- return optionList;
- }())
+ this.__defineSetter__("steeringWheelHeater", function (val) {
+ try {
+ hvac.steeringWheelHeater = t.boolean(val);
+ } catch (err) {
}
- },
- "Config": {
- "ringtoneVolume": {
- "name": "Ringtone Volume",
- "control": {
- "type": "select",
- "value": 10
- },
- "options": (function () {
- var i,
- optionList = {};
+ });
- for (i = 0; i <= 10; i++) {
- optionList[i] = i;
- }
+ this.__defineGetter__("seatHeater", function () {
+ return hvac.seatHeater;
+ });
- return optionList;
- }())
- },
- "msgRingtoneVolume": {
- "name": "Msg Ringtone Volume",
- "control": {
- "type": "select",
- "value": 10
- },
- "options": (function () {
- var i,
- optionList = {};
+ this.__defineSetter__("seatHeater", function (val) {
+ try {
+ hvac.seatHeater = t.boolean(val);
+ } catch (err) {
+ }
+ });
- for (i = 0; i <= 10; i++) {
- optionList[i] = i;
- }
+ this.__defineGetter__("seatCooler", function () {
+ return hvac.seatCooler;
+ });
- return optionList;
- }())
- },
- "vibrationSetting": {
- "name": "Vibration",
- "control": {
- "type": "select",
- "value": "off"
- },
- "options": {
- "on": "ON",
- "off": "OFF"
- }
+ this.__defineSetter__("seatCooler", function (val) {
+ try {
+ hvac.seatCooler = t.boolean(val);
+ } catch (err) {
}
- },
- "Account": {
- "accountName": {
- "name": "Name",
- "control": {
- "type": "text",
- "value": ""
- }
- },
- "accountId": {
- "name": "Id",
- "control": {
- "type": "text",
- "value": ""
+ });
+};
+
+WindowStatus = function (propertyTypes) {
+ var windowStatus = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ windowStatus.openness = propertyTypes.openness || 0;
+ windowStatus.defrost = propertyTypes.defrost || false;
+
+ this.__defineGetter__("WINDOWLOCATION_DRIVER", function () {
+ return 0;
+ });
+
+ this.__defineGetter__("WINDOWLOCATION_PASSENGER", function () {
+ return 1;
+ });
+
+ this.__defineGetter__("WINDOWLOCATION_LEFTREAR", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("WINDOWLOCATION_RIGHTREAR", function () {
+ return 3;
+ });
+
+ this.__defineGetter__("WINDOWLOCATION_REAR", function () {
+ return 4;
+ });
+
+ this.__defineGetter__("openness", function () {
+ return windowStatus.openness;
+ });
+
+ this.__defineSetter__("openness", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 100) {
+ windowStatus.openness = val;
}
+ } catch (err) {
}
- },
- "DeviceInfo": {
- "totalMemory": {
- "name": "Total Memory",
- "control": {
- "type": "range",
- "value": 262144,
- "min": 0,
- "max": 4096000
- }
- },
- "phoneColorDepthDefault": {
- "name": "Color Depth",
- "control": {
- "type": "number",
- "value": 24
- }
+ });
+
+ this.__defineGetter__("defrost", function () {
+ return windowStatus.defrost;
+ });
+
+ this.__defineSetter__("defrost", function (val) {
+ try {
+ windowStatus.defrost = t.boolean(val);
+ } catch (err) {
}
- },
- "DeviceStateInfo": {
- "availableMemory": {
- "name": "Available Memory",
- "control": {
- "type": "range",
- "value": 262144,
- "min": 0,
- "max": 4096000
- }
- },
- "keypadLightOn": {
- "name": "Keypad Light On",
- "control": {
- "type": "checkbox",
- "value": false
- }
- },
- "backLightOn": {
- "name": "Back Light On",
- "control": {
- "type": "checkbox",
- "value": false
- }
- },
- "audioPath": {
- "name": "Audio Path",
- "control": {
- "type": "select",
- "value": "receiver"
- },
- "options": {
- "speaker": "speaker",
- "receiver": "receiver",
- "earphone": "earphone"
- }
- },
- "processorUtilizationPercent": {
- "name": "CPU Utilization %",
- "control": {
- "type": "select",
- "value": "5"
- },
- "options": (function () {
- var i,
- optionList = {};
+ });
+};
- for (i = 0; i <= 100; i++) {
- optionList[i] = i;
- }
+Sunroof = function (propertyTypes) {
+ var sunroof = {};
- return optionList;
- }())
- },
- "language": {
- "name": "Language",
- "control": {
- "type": "select",
- "value": "eng"
- },
- "options": (function () {
- var i,
- optionList = {},
- iterator = constants.LANG.ISO6392_LIST;
+ VehiclePropertyType.call(this, propertyTypes);
- for (i = 0; i <= iterator.length; i++) {
- optionList[iterator[i]] = iterator[i];
- }
+ sunroof.openness = propertyTypes.openness || 0;
+ sunroof.tilt = propertyTypes.tilt || 0;
- return optionList;
- }())
+ this.__defineGetter__("openness", function () {
+ return sunroof.openness;
+ });
+
+ this.__defineSetter__("openness", function (val) {
+ try {
+ sunroof.openness = t.unsigned_short(val);
+ } catch (err) {
}
- },
- "DataNetworkInfo": {
- "isDataNetworkConnected": {
- "name": "Data Network Is Connected",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "networkConnectionType": {
- "name": "Network Connection Type",
- "control": {
- "type": "select",
- "value": ["GPRS"]
- },
- // TODO: try not to duplicate from DataNetworkConnectionTypes
- "options": {
- "BLUETOOTH": "bluetooth",
- "EDGE": "edge",
- "EVDO": "evdo",
- "GPRS": "gprs",
- "IRDA": "irda",
- "LTE": "lte",
- "ONEXRTT": "1xrtt",
- "WIFI": "wifi"
- },
- "callback": function (setting) {
- event.trigger("DataNetworkConnectionChanged", [setting]);
- }
+ });
+
+ this.__defineGetter__("tilt", function () {
+ return sunroof.tilt;
+ });
+
+ this.__defineSetter__("tilt", function (val) {
+ try {
+ sunroof.tilt = t.unsigned_short(val);
+ } catch (err) {
}
- },
- "PowerInfo": {
- "isCharging": {
- "name": "Battery Is Charging",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("DeviceBatteryStateChanged", [setting]);
- }
- },
- "percentRemaining": {
- "name": "Battery Remaining %",
- "control": {
- "type": "select",
- "value": 100
- },
- "options": (function () {
- var i,
- optionList = {};
+ });
+};
- for (i = 0; i <= 100; i++) {
- optionList[i] = i;
- }
+ConvertibleRoof = function (propertyTypes) {
+ var convertibleRoof = {};
- return optionList;
- }()),
- "callback": function (setting) {
- event.trigger("DeviceBatteryLevelChanged", [setting]);
- }
+ VehiclePropertyType.call(this, propertyTypes);
+
+ convertibleRoof.openness = propertyTypes.openness || 0;
+
+ this.__defineGetter__("openness", function () {
+ return convertibleRoof.openness;
+ });
+
+ this.__defineSetter__("openness", function (val) {
+ try {
+ convertibleRoof.openness = t.unsigned_short(val);
+ } catch (err) {
}
- }
+ });
};
-});
-define('ripple/platform/wac/1.0/spec/events', function (require, exports, module) {
-/*
- * Copyright 2011 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.
- */
+VehicleId = function (propertyTypes) {
+ var vehicleId = {};
-var event = require('ripple/event');
+ VehiclePropertyType.call(this, propertyTypes);
-module.exports = {
- "WidgetWakeup": {
- callback: function () {
- event.trigger("WidgetWakeup");
+ vehicleId.WMI = propertyTypes.WMI || "";
+ vehicleId.VIN = propertyTypes.VIN || "";
+
+ this.__defineGetter__("WMI", function () {
+ return vehicleId.WMI;
+ });
+
+ this.__defineSetter__("WMI", function (val) {
+ try {
+ //?
+ vehicleId.WMI = t.DOMString(val);
+ } catch (err) {
}
- },
- "WidgetMaximize": {
- callback: function () {
- event.trigger("WidgetMaximize");
+ });
+
+ this.__defineGetter__("VIN", function () {
+ return vehicleId.VIN;
+ });
+
+ this.__defineSetter__("VIN", function (val) {
+ try {
+ //?
+ vehicleId.VIN = t.DOMString(val);
+ } catch (err) {
}
- },
- "WidgetFocus": {
- callback: function () {
- event.trigger("WidgetFocus");
+ });
+};
+
+Size = function (propertyTypes) {
+ var size = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ size.width = propertyTypes.width || 0;
+ size.height = propertyTypes.height || 0;
+ size.length = propertyTypes.length || 0;
+
+ this.__defineGetter__("width", function () {
+ return size.width;
+ });
+
+ this.__defineSetter__("width", function (val) {
+ try {
+ size.width = t.unsigned_long(val);
+ } catch (err) {
}
- },
- "WidgetRestore": {
- callback: function () {
- event.trigger("WidgetRestore");
+ });
+
+ this.__defineGetter__("height", function () {
+ return size.height;
+ });
+
+ this.__defineSetter__("height", function (val) {
+ try {
+ size.height = t.unsigned_long(val);
+ } catch (err) {
}
- }
-};
+ });
-});
-define('ripple/platform/wac/1.0/spec/ui', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
- plugins: [
- "accelerometer",
- //"deviceSettings",
- "fileSystem",
- "geoView",
-/*
- "multimedia",
- "audioPlayer",
- "telephony",
-*/
- "platformEvents",
- "storage",
- "widgetConfig"
- ]
+ this.__defineGetter__("length", function () {
+ return size.length;
+ });
+
+ this.__defineSetter__("length", function (val) {
+ try {
+ size.length = t.unsigned_long(val);
+ } catch (err) {
+ }
+ });
};
-});
-define('ripple/platform/wac/1.0/spec', function (require, exports, module) {
-module.exports = {
+FuelInfo = function (propertyTypes) {
+ var fuelInfo = {};
- id: "wac",
- version: "1.0",
- name: "WAC",
- type: "plaform",
+ VehiclePropertyType.call(this, propertyTypes);
- persistencePrefix: "wac-",
+ fuelInfo.type = propertyTypes.type || 0;
+ fuelInfo.refuelPosition = propertyTypes.refuelPosition || 0;
- config: require('ripple/platform/wac/1.0/spec/config'),
- device: require('ripple/platform/wac/1.0/spec/device'),
- ui: require('ripple/platform/wac/1.0/spec/ui'),
- events: require('ripple/platform/wac/1.0/spec/events'),
+ this.__defineGetter__("FUELTYPE_GASOLINE", function () {
+ return 0;
+ });
- objects: {
- navigator: {
- path: "w3c/1.0/navigator"
- },
- WidgetManager: {
- path: "wac/1.0/WidgetManager",
- feature: "http://jil.org/jil/api/1.1.1/widgetmanager"
- },
- Widget: {
- path: "wac/1.0/Widget",
- feature: "http://jil.org/jil/api/1.1/widget",
- children: {
- Device: {
- path: "wac/1.0/Device",
- feature: "http://jil.org/jil/api/1.1/device",
- children: {
- AccountInfo: {
- path: "wac/1.0/AccountInfo",
- feature: "http://jil.org/jil/api/1.1/accountinfo"
- },
- ApplicationTypes: {
- path: "wac/1.0/ApplicationTypes",
- feature: "http://jil.org/jil/api/1.1.5/applicationtypes"
- },
- DataNetworkInfo: {
- path: "wac/1.0/DataNetworkInfo",
- feature: "http://jil.org/jil/api/1.1.1/datanetworkinfo",
- children: {
- DataNetworkConnectionTypes: {
- path: "wac/1.0/DataNetworkConnectionTypes"
- }
- }
- },
- DeviceInfo: {
- path: "wac/1.0/DeviceInfo",
- feature: "http://jil.org/jil/api/1.1/deviceinfo"
- },
- DeviceStateInfo: {
- path: "wac/1.0/DeviceStateInfo",
- feature: "http://jil.org/jil/api/1.1/devicestateinfo",
- children: {
- Config: {
- path: "wac/1.0/Config",
- feature: "http://jil.org/jil/api/1.1/config"
- },
- AccelerometerInfo: {
- path: "wac/1.0/AccelerometerInfo",
- feature: "http://jil.org/jil/api/1.1/accelerometerinfo"
- }
- }
- },
- File: {
- path: "wac/1.0/File",
- feature: "http://jil.org/jil/api/1.1.1/file"
- },
- PositionInfo: {
- path: "wac/1.0/PositionInfo",
- feature: "http://jil.org/jil/api/1.1/positioninfo"
- },
- RadioInfo: {
- path: "wac/1.0/RadioInfo",
- feature: "http://jil.org/jil/api/1.1.1/radioinfo",
- children: {
- RadioSignalSourceTypes: {
- path: "wac/1.0/RadioSignalSourceTypes",
- feature: "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes"
- }
- }
- },
- PowerInfo: {
- path: "wac/1.0/PowerInfo",
- feature: "http://jil.org/jil/api/1.1/powerinfo"
- }
- }
- },
- ExceptionTypes: {
- path: "wac/1.0/ExceptionTypes",
- feature: "http://jil.org/jil/api/1.1.5/exceptiontypes"
- },
- Exception: {
- path: "wac/1.0/Exception",
- feature: "http://jil.org/jil/api/1.1.5/exception"
- },
- Multimedia: {
- path: "wac/1.0/Multimedia",
- feature: "http://jil.org/jil/api/1.1/multimedia",
- children: {
- Camera: {
- path: "wac/1.0/Camera",
- feature: "http://jil.org/jil/api/1.1.2/camera"
- },
- AudioPlayer: {
- path: "wac/1.0/AudioPlayer",
- feature: "http://jil.org/jil/api/1.1/audioplayer"
- },
- VideoPlayer: {
- path: "wac/1.0/VideoPlayer",
- feature: "http://jil.org/jil/api/1.1.2/videoplayer"
- }
- }
- },
- Telephony: {
- path: "wac/1.0/Telephony",
- feature: "http://jil.org/jil/api/1.1.1/telephony",
- children: {
- CallRecord: {
- path: "wac/1.0/CallRecord",
- feature: "http://jil.org/jil/api/1.1/callrecord"
- },
- CallRecordTypes: {
- path: "wac/1.0/CallRecordTypes",
- feature: "http://jil.org/jil/api/1.1.1/callrecordtypes"
- }
- }
- },
- PIM: {
- path: "wac/1.0/PIM",
- feature: "http://jil.org/jil/api/1.1.1/pim",
- children: {
- AddressBookItem: {
- path: "wac/1.0/AddressBookItem",
- feature: "http://jil.org/jil/api/1.1/addressbookitem"
- },
- CalendarItem: {
- path: "wac/1.0/CalendarItem",
- feature: "http://jil.org/jil/api/1.1/calendaritem"
- },
- EventRecurrenceTypes: {
- path: "wac/1.0/EventRecurrenceTypes",
- feature: "http://jil.org/jil/api/1.1/eventrecurrencetypes"
- }
- }
- },
- Messaging: {
- path: "wac/1.0/Messaging",
- feature: "http://jil.org/jil/api/1.1/messaging",
- children: {
- Account: {
- path: "wac/1.0/Account",
- feature: "http://jil.org/jil/api/1.1/account"
- },
- Attachment: {
- path: "wac/1.0/Attachment",
- feature: "http://jil.org/jil/api/1.1/attachment"
- },
- Message: {
- path: "wac/1.0/Message",
- feature: "http://jil.org/jil/api/1.1/message"
- },
- MessageFolderTypes: {
- path: "wac/1.0/MessageFolderTypes",
- feature: "http://jil.org/jil/api/1.1.4/messagefoldertypes"
- },
- MessageQuantities: {
- path: "wac/1.0/MessageQuantities",
- feature: "http://jil.org/jil/api/1.1/messagequantities"
- },
- MessageTypes: {
- path: "wac/1.0/MessageTypes",
- feature: "http://jil.org/jil/api/1.1/messagetypes"
- }
- }
- }
+ this.__defineGetter__("FUELTYPE_HIGH_OCTANE", function () {
+ return 1;
+ });
+
+ this.__defineGetter__("FUELTYPE_DIESEL", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("FUELTYPE_ELECTRIC", function () {
+ return 3;
+ });
+
+ this.__defineGetter__("FUELTYPE_HYDROGEN", function () {
+ return 4;
+ });
+
+ this.__defineGetter__("REFUELPOSITION_LEFT", function () {
+ return 0;
+ });
+
+ this.__defineGetter__("REFUELPOSITION_RIGHT", function () {
+ return 1;
+ });
+
+ this.__defineGetter__("REFUELPOSITION_FRONT", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("REFUELPOSITION_REAR", function () {
+ return 3;
+ });
+
+ this.__defineGetter__("type", function () {
+ return fuelInfo.type;
+ });
+
+ this.__defineSetter__("type", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 4) {
+ fuelInfo.type = val;
}
+ } catch (err) {
}
- }
+ });
+
+ this.__defineGetter__("refuelPosition", function () {
+ return fuelInfo.refuelPosition;
+ });
+ this.__defineSetter__("refuelPosition", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 3) {
+ fuelInfo.refuelPosition = val;
+ }
+ } catch (err) {
+ }
+ });
};
-});
-define('ripple/platform/wac/2.0/accelerometer', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+VehicleType = function (propertyTypes) {
+ var vehicleType = {};
-var utils = require('ripple/utils'),
- event = require('ripple/event'),
- Acceleration = function (x, y, z) {
- return {
- xAxis: x || 0,
- yAxis: y || 0,
- zAxis: z || 0
- };
- },
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- _accelerometerInfo = new Acceleration(),
- _defaultInterval = 100,
- _watches = {},
- _self;
+ VehiclePropertyType.call(this, propertyTypes);
-module.exports = _self = {
- getCurrentAcceleration: function (onSuccess, onError) {
- function _getCurrentAcceleration() {
- setTimeout(function () {
- onSuccess(utils.copy(_accelerometerInfo));
- }, 1);
- return null;
+ vehicleType.type = propertyTypes.type || 0;
+
+ this.__defineGetter__("VEHICLETYPE_SEDAN", function () {
+ return 0;
+ });
+
+ this.__defineGetter__("VEHICLETYPE_COUPE", function () {
+ return 1;
+ });
+
+ this.__defineGetter__("VEHICLETYPE_CABRIOLE", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("VEHICLETYPE_ROADSTER", function () {
+ return 3;
+ });
+
+ this.__defineGetter__("VEHICLETYPE_SUV", function () {
+ return 4;
+ });
+
+ this.__defineGetter__("VEHICLETYPE_TRUCK", function () {
+ return 5;
+ });
+
+ this.__defineGetter__("type", function () {
+ return vehicleType.type;
+ });
+
+ this.__defineSetter__("type", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 5) {
+ vehicleType.type = val;
+ }
+ } catch (err) {
}
+ });
+};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentAcceleration", _getCurrentAcceleration);
- },
+Doors = function (propertyTypes) {
+ var doors = {};
- watchAcceleration: function (accelerometerSuccess, accelerometerError, options) {
- function _watchAcceleration() {
- var watchId = (new Date()).getTime() | 0,
- watchObj = {},
- opt = Object(options),
- minNotificationInterval = opt.minNotificationInterval | 0,
- accelerometerInterval = _defaultInterval;
+ VehiclePropertyType.call(this, propertyTypes);
- if (minNotificationInterval > 0) {
- accelerometerInterval = minNotificationInterval;
+ doors.doorsPerRow = propertyTypes.doorsPerRow || [];
+
+ this.__defineGetter__("doorsPerRow", function () {
+ return doors.doorsPerRow;
+ });
+
+ this.__defineSetter__("doorsPerRow", function (val) {
+ try {
+ doors.doorsPerRow = t.unsigned_short(val, "[]");
+ } catch (err) {
+ }
+ });
+};
+
+TransmissionGearType = function (propertyTypes) {
+ var trans = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ trans.transmissionGearType = propertyTypes.transmissionGearType || 0;
+
+ this.__defineGetter__("TRANSMISSIONGEARTYPE_AUTO", function () {
+ return 0;
+ });
+
+ this.__defineGetter__("TRANSMISSIONGEARTYPE_MANUAL", function () {
+ return 1;
+ });
+
+ this.__defineGetter__("TRANSMISSIONGEARTYPE_CV", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("transmissionGearType", function () {
+ return trans.transmissionGearType;
+ });
+
+ this.__defineSetter__("transmissionGearType", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 2) {
+ trans.transmissionGearType = val;
}
+ } catch (err) {
+ }
+ });
+};
- watchObj = {
- onSuccess: accelerometerSuccess,
- onError: accelerometerError,
- interval: accelerometerInterval
- };
+WheelInformation = function (propertyTypes) {
+ var wheelInfo = {};
- _watches[watchId] = watchObj;
+ VehiclePropertyType.call(this, propertyTypes);
- _watches[watchId].intervalId = setInterval(function () {
- _self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
- }, _watches[watchId].interval);
+ wheelInfo.frontWheelRadius = propertyTypes.frontWheelRadius || 0;
+ wheelInfo.rearWheelRadius = propertyTypes.rearWheelRadius || 0;
+ wheelInfo.wheelTrack = propertyTypes.wheelTrack || 0;
+ wheelInfo.ABS = propertyTypes.ABS || false;
- return watchId;
+ this.__defineGetter__("frontWheelRadius", function () {
+ return wheelInfo.frontWheelRadius;
+ });
+
+ this.__defineSetter__("frontWheelRadius", function (val) {
+ try {
+ wheelInfo.frontWheelRadius =t.unsigned_short(val);
+ } catch (err) {
}
+ });
- return wac2_utils.validateTypeMismatch(accelerometerSuccess, accelerometerError, "watchAcceleration", _watchAcceleration);
- },
+ this.__defineGetter__("rearWheelRadius", function () {
+ return wheelInfo.rearWheelRadius;
+ });
- clearWatch: function (watchId) {
+ this.__defineSetter__("rearWheelRadius", function (val) {
+ try {
+ wheelInfo.rearWheelRadius =t.unsigned_short(val);
+ } catch (err) {
+ }
+ });
- var id = watchId | 0;
+ this.__defineGetter__("wheelTrack", function () {
+ return wheelInfo.wheelTrack;
+ });
- if (_watches[id]) {
- clearInterval(_watches[id].intervalId);
- delete(_watches[id]);
- return null;
+ this.__defineSetter__("wheelTrack", function (val) {
+ try {
+ wheelInfo.wheelTrack =t.unsigned_long(val);
+ } catch (err) {
}
+ });
- return undefined;
- }
+ this.__defineGetter__("ABS", function () {
+ return wheelInfo.ABS;
+ });
+
+ this.__defineSetter__("ABS", function (val) {
+ try {
+ wheelInfo.ABS =t.boolean(val);
+ } catch (err) {
+ }
+ });
};
-event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
- _accelerometerInfo.xAxis = accelerometerInfo.accelerationIncludingGravity.x;
- _accelerometerInfo.yAxis = accelerometerInfo.accelerationIncludingGravity.y;
- _accelerometerInfo.zAxis = accelerometerInfo.accelerationIncludingGravity.z;
-});
+Odometer = function (propertyTypes) {
+ var odm = {};
+ VehiclePropertyType.call(this, propertyTypes);
-});
-define('ripple/platform/wac/2.0/calendar', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+ odm.odometer = propertyTypes.odometer || 0;
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- constants = require('ripple/constants'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- _console = require('ripple/console'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- _SIM_CALENDAR = 0, _DEVICE_CALENDAR = 1,
- _NO_RECURRENCE = 0, _DAILY_RECURRENCE = 1, _WEEKLY_RECURRENCE = 2,
- _MONTHLY_RECURRENCE = 3, _YEARLY_RECURRENCE = 4,
- _TENTATIVE_STATUS = 0, _CONFIRMED_STATUS = 1, _CANCELLED_STATUS = 2,
- _NO_ALARM = 0, _SILENT_ALARM = 1, _SOUND_ALARM = 2,
- _calendars = [], _DB_CALENDARS_KEY = "wac2-db-calendars",
- _FAKEWAITTIME = 5, _FAKE_LONG_WAITTIME = 10,
- _save_calendars, _eventPropCheck, _eventFilterCheck,
- _addEventAllowed = true, _deleteEventAllowed = true,
- _updateEventAllowed = true, _findEventsAllowed = true,
- CalendarEventProperties, Calendar, CalendarEvent;
+ this.__defineGetter__("odometer", function () {
+ return odm.odometer;
+ });
-_save_calendars = function (_name, _type, _events) {
- var i;
- for (i = 0; i < _calendars.length; i++) {
- if (_calendars[i].name === _name && _calendars[i].type === _type) {
- _calendars[i].events = _events;
- break;
+ this.__defineSetter__("odometer", function (val) {
+ try {
+ odm.odometer = t.unsigned_long(val);
+ } catch (err) {
}
- }
- db.saveObject(_DB_CALENDARS_KEY, _calendars);
+ });
};
-_eventPropCheck = function (prop, dst) {
- var i;
- if (prop.description !== null && prop.description !== undefined) {
- dst.description = String(prop.description);
- }
- if (prop.summary !== null && prop.summary !== undefined) {
- dst.summary = String(prop.summary);
- }
- if (prop.startTime !== null && prop.startTime !== undefined) {
- if (!wac2_utils.isValidDate(prop.startTime)) {
- return false;
+Fluid = function (propertyTypes) {
+ var fluid = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ fluid.transmission = propertyTypes.transmission || 0;
+ fluid.brake = propertyTypes.brake || 0;
+ fluid.washer = propertyTypes.washer || 0;
+
+ this.__defineGetter__("transmission", function () {
+ return fluid.transmission;
+ });
+
+ this.__defineSetter__("transmission", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 100) {
+ fluid.transmission = val;
+ }
+ } catch (err) {
}
- dst.startTime = new Date(prop.startTime);
- }
- dst.duration = prop.duration | 0;
- if (prop.location !== null && prop.location !== undefined) {
- dst.location = String(prop.location);
- }
- if (prop.categories !== null && prop.categories !== undefined) {
- if (!wac2_utils.isValidArray(prop.categories)) {
- return false;
+ });
+
+ this.__defineGetter__("brake", function () {
+ return fluid.brake;
+ });
+
+ this.__defineSetter__("brake", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 100) {
+ fluid.brake = val;
+ }
+ } catch (err) {
}
- dst.categories = [];
- for (i = 0; i < prop.categories.length; i++) {
- dst.categories.push(String(prop.categories[i]));
+ });
+
+ this.__defineGetter__("washer", function () {
+ return fluid.washer;
+ });
+
+ this.__defineSetter__("washer", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val >= 0 && val <= 100) {
+ fluid.washer = val;
+ }
+ } catch (err) {
}
- }
- if (prop.recurrence !== null && prop.recurrence !== undefined) {
- if (prop.recurrence === _NO_RECURRENCE ||
- prop.recurrence === _DAILY_RECURRENCE ||
- prop.recurrence === _WEEKLY_RECURRENCE ||
- prop.recurrence === _MONTHLY_RECURRENCE ||
- prop.recurrence === _YEARLY_RECURRENCE) {
- dst.recurrence = prop.recurrence | 0;
- } else {
- return false;
+ });
+};
+
+Battery = function (propertyTypes) {
+ var battery = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ battery.voltage = propertyTypes.voltage || 0;
+ battery.current = propertyTypes.current || 0;
+
+ this.__defineGetter__("voltage", function () {
+ return battery.voltage;
+ });
+
+ this.__defineSetter__("voltage", function (val) {
+ try {
+ battery.voltage = t.double(val);
+ } catch (err) {
}
- }
- if (dst.recurrence === _NO_RECURRENCE) {
- dst.expires = null;
- dst.interval = null;
- } else {
- // expires and interval matters when recurrence is not NO_RECURRENCE
- if (prop.expires !== null && prop.expires !== undefined) {
- if (!wac2_utils.isValidDate(prop.expires)) {
- return false;
- }
- dst.expires = new Date(prop.expires);
+ });
+
+ this.__defineGetter__("current", function () {
+ return battery.current;
+ });
+
+ this.__defineSetter__("current", function (val) {
+ try {
+ battery.current = t.double(val);
+ } catch (err) {
}
- // expires === undefined -> to recur indefinitely
- // expires === null -> keep dst.expires unchanged, even it's null
- if (prop.expires === undefined) {
- dst.expires = null;
+ });
+};
+
+TirePressure = function (propertyTypes) {
+ var tirePressure = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ tirePressure.leftFront = propertyTypes.leftFront || 0;
+ tirePressure.rightFront = propertyTypes.rightFront || 0;
+ tirePressure.leftRear = propertyTypes.leftRear || 0;
+ tirePressure.rightRear = propertyTypes.rightRear || 0;
+
+ this.__defineGetter__("leftFront", function () {
+ return tirePressure.leftFront;
+ });
+
+ this.__defineSetter__("leftFront", function (val) {
+ try {
+ tirePressure.leftFront = t.double(val);
+ } catch (err) {
}
- if (prop.interval !== null && prop.interval !== undefined) {
- dst.interval = prop.interval | 0;
+ });
+
+ this.__defineGetter__("rightFront", function () {
+ return tirePressure.rightFront;
+ });
+
+ this.__defineSetter__("rightFront", function (val) {
+ try {
+ tirePressure.rightFront = t.double(val);
+ } catch (err) {
}
- }
+ });
- if (prop.status !== null && prop.status !== undefined) {
- if (prop.status === _TENTATIVE_STATUS ||
- prop.status === _CONFIRMED_STATUS ||
- prop.status === _CANCELLED_STATUS) {
- dst.status = prop.status | 0;
- } else {
- return false;
+ this.__defineGetter__("leftRear", function () {
+ return tirePressure.leftRear;
+ });
+
+ this.__defineSetter__("leftRear", function (val) {
+ try {
+ tirePressure.leftRear = t.double(val);
+ } catch (err) {
}
- }
+ });
- if (prop.alarmType !== null && prop.alarmType !== undefined) {
- if (prop.alarmType === _NO_ALARM ||
- prop.alarmType === _SILENT_ALARM ||
- prop.alarmType === _SOUND_ALARM) {
- dst.alarmType = prop.alarmType;
- } else {
- return false;
+ this.__defineGetter__("rightRear", function () {
+ return tirePressure.rightRear;
+ });
+
+ this.__defineSetter__("rightRear", function (val) {
+ try {
+ tirePressure.rightRear = t.double(val);
+ } catch (err) {
}
- }
- if (dst.alarmType !== _NO_ALARM && prop.alarmTrigger !== undefined && prop.alarmTrigger !== undefined) {
- dst.alarmTrigger = prop.alarmTrigger | 0;
- }
+ });
};
-_eventFilterCheck = function (filter) {
- if (filter.id !== undefined && filter.id !== null) {
- filter.id = String(filter.id);
- } else {
- filter.id = undefined;
- }
- if (filter.summary !== undefined && filter.summary !== null) {
- filter.summary = String(filter.summary);
- } else {
- filter.summary = undefined;
- }
- if (filter.description !== undefined && filter.description !== null) {
- filter.description = String(filter.description);
- } else {
- filter.description = undefined;
- }
- if (filter.location !== undefined && filter.location !== null) {
- filter.location = String(filter.location);
- } else {
- filter.location = undefined;
- }
- if (filter.catetory !== undefined && filter.catetory !== null) {
- filter.catetory = String(filter.catetory);
- } else {
- filter.catetory = undefined;
- }
- if (filter.status !== undefined && filter.status !== null) {
- var i;
- if (!wac2_utils.isValidArray(filter.status)) {
- return false;
- }
- for (i = 0; i < filter.status.length; i++) {
- filter.status[i] = filter.status[i] | 0;
- if (filter.status[i] > _CANCELLED_STATUS || filter.status[i] < _TENTATIVE_STATUS)
- return false;
+TireTemperature = function (propertyTypes) {
+ var tireTemperature = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ tireTemperature.leftFront = propertyTypes.leftFront || 0;
+ tireTemperature.rightFront = propertyTypes.rightFront || 0;
+ tireTemperature.leftRear = propertyTypes.leftRear || 0;
+ tireTemperature.rightRear = propertyTypes.rightRear || 0;
+
+ this.__defineGetter__("leftFront", function () {
+ return tireTemperature.leftFront;
+ });
+
+ this.__defineSetter__("leftFront", function (val) {
+ try {
+ tireTemperature.leftFront = t.double(val);
+ } catch (err) {
}
- } else {
- filter.status = undefined;
- }
- if (filter.initialStartDate !== undefined && filter.initialStartDate !== null) {
- if (!wac2_utils.isValidDate(filter.initialStartDate)) {
- return false;
+ });
+
+ this.__defineGetter__("rightFront", function () {
+ return tireTemperature.rightFront;
+ });
+
+ this.__defineSetter__("rightFront", function (val) {
+ try {
+ tireTemperature.rightFront = t.double(val);
+ } catch (err) {
}
- filter.initialStartDate = new Date(filter.initialStartDate);
- } else {
- filter.initialStartDate = undefined;
- }
- if (filter.endStartDate !== undefined && filter.endStartDate !== null) {
- if (!wac2_utils.isValidDate(filter.endStartDate)) {
- return false;
+ });
+
+ this.__defineGetter__("leftRear", function () {
+ return tireTemperature.leftRear;
+ });
+
+ this.__defineSetter__("leftRear", function (val) {
+ try {
+ tireTemperature.leftRear = t.double(val);
+ } catch (err) {
}
- filter.endStartDate = new Date(filter.endStartDate);
- } else {
- filter.endStartDate = undefined;
- }
- return true;
-};
+ });
-CalendarEventProperties = function (prop) {
- var _self;
- _self = {
- description : "",
- summary : "",
- startTime : new Date(),
- duration : 0,
- location : "",
- categories : undefined,
- recurrence : _NO_RECURRENCE,
- expires : null, // ignored if recurrence == NO_RECURRENCE
- interval : null, // ignored if recurrence == NO_RECURRENCE
- status : _CONFIRMED_STATUS,
- alarmTrigger : 0,
- alarmType : _NO_ALARM
- };
- if (prop) {
- if (_eventPropCheck(prop, _self) === false) {
- return undefined;
+ this.__defineGetter__("rightRear", function () {
+ return tireTemperature.rightRear;
+ });
+
+ this.__defineSetter__("rightRear", function (val) {
+ try {
+ tireTemperature.rightRear = t.double(val);
+ } catch (err) {
}
- }
- return _self;
+ });
};
-CalendarEvent = function (prop, genNewID) {
- var id, _self = new CalendarEventProperties(prop);
+SecurityAlert = function (propertyTypes) {
+ var securityAlert = {};
- /* if error occurs during checking, _self is an empty object.
- so i randomly pick description to check if property check fails */
- if (_self.description === undefined) {
- return undefined;
- }
+ VehiclePropertyType.call(this, propertyTypes);
- if (genNewID === true) {
- id = Math.uuid(undefined, 16);
- } else {
- id = prop.id;
- }
- _self.__defineGetter__("id", function () {
- return id;
+ securityAlert.securityAlert = propertyTypes.securityAlert || false;
+
+ this.__defineGetter__("securityAlert", function () {
+ return securityAlert.securityAlert;
+ });
+
+ this.__defineSetter__("securityAlert", function (val) {
+ try {
+ securityAlert.securityAlert = t.boolean(val);
+ } catch (err) {
+ }
});
- return _self;
};
-Calendar = function (type, name, events) {
- var _type = type,
- _name = name,
- _events = events, _self;
+ParkingBrake = function (propertyTypes) {
+ var parkingBrake = {};
- _self = {
- createEvent: function (evtProp) {
- var rst = {};
- rst = new CalendarEventProperties(evtProp);
- /* if error occurs during checking, rst is an empty object.
- so i randomly pick description to check if property check fails */
- if (rst.description === undefined) {
- exception.raise(exception.types.Argument, "EventProperties: input parameter contains invalid values", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- return undefined;
- } else {
- return rst;
- }
- },
+ VehiclePropertyType.call(this, propertyTypes);
- addEvent: function (onSuccess, onError, calEvent) {
- var pendingOperation, pendingObj = {},
- newEvent = {}, _doAddEvent, _calEvent = Object(calEvent);
+ parkingBrake.parkingBrake = propertyTypes.parkingBrake || false;
- _doAddEvent = function () {
- if (!_addEventAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- newEvent = new CalendarEvent(_calEvent, true);
- /* if newEvent.id === undefined,
- means somthing wrong in calEvent */
- if (newEvent.id === undefined) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+ this.__defineGetter__("parkingBrake", function () {
+ return parkingBrake.parkingBrake;
+ });
- pendingObj = new PendingObject();
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
- _events[newEvent.id] = newEvent;
- _save_calendars(_name, _type, _events);
- onSuccess(new CalendarEvent(newEvent), false);
- }, _FAKEWAITTIME);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- };
+ this.__defineSetter__("parkingBrake", function (val) {
+ try {
+ parkingBrake.parkingBrake = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:addEvent", _doAddEvent);
- },
+ParkingLight = function (propertyTypes) {
+ var parkingLight = {};
- updateEvent: function (onSuccess, onError, calEvent) {
- var pendingOperation, pendingObj = {},
- chkEvent, _doUpdateEvent, _calEvent = Object(calEvent);
+ VehiclePropertyType.call(this, propertyTypes);
- _doUpdateEvent = function () {
- if (!_updateEventAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- if (!_events[_calEvent.id]) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
- }, 1);
- }
- return undefined;
- }
+ parkingLight.parkingLight = propertyTypes.parkingLight || false;
- chkEvent = new CalendarEvent(_events[_calEvent.id], false);
- /* _eventPropCheck will also update chkEvent btw */
- if (_eventPropCheck(_calEvent, chkEvent) === false) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- pendingObj = new PendingObject();
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
+ this.__defineGetter__("parkingLight", function () {
+ return parkingLight.parkingLight;
+ });
- _events[chkEvent.id] = chkEvent;
- _save_calendars(_name, _type, _events);
- onSuccess();
- }, _FAKEWAITTIME);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- };
+ this.__defineSetter__("parkingLight", function (val) {
+ try {
+ parkingLight.parkingLight = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:updateEvent", _doUpdateEvent);
- },
+HazardLight = function (propertyTypes) {
+ var hazardLight = {};
- deleteEvent: function (onSuccess, onError, id) {
- var pendingOperation, pendingObj = {},
- _doDeleteEvent;
+ VehiclePropertyType.call(this, propertyTypes);
- _doDeleteEvent = function () {
- /* according to spec "If any of the input parameters are not
- compatible with the expected type for that parameter,
- a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be
- synchronously thrown."
- so an error is raised synchronously */
- utils.validateArgumentType(id, "string", null,
- "Calendar:deleteEvent: " + " invalid id parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ hazardLight.hazardLight = propertyTypes.hazardLight || false;
- if (!_deleteEventAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- if (!_events[id]) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
- }, 1);
- }
- return undefined;
- }
+ this.__defineGetter__("hazardLight", function () {
+ return hazardLight.hazardLight;
+ });
- pendingObj = new PendingObject();
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
+ this.__defineSetter__("hazardLight", function (val) {
+ try {
+ hazardLight.hazardLight = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
- delete _events[id];
- _save_calendars(_name, _type, _events);
- onSuccess();
- }, _FAKEWAITTIME);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- };
+AntilockBrakingSystem = function (propertyTypes) {
+ var abs = {};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:deleteEvent", _doDeleteEvent);
- },
+ VehiclePropertyType.call(this, propertyTypes);
- findEvents: function (onSuccess, onError, eventFilter) {
- var pendingOperation, pendingObj = {}, i,
- tmp = [], valid_tmp = false, rst = [], _doFindEvents,
- _eventFilter = Object(eventFilter);
+ abs.antilockBrakingSystem = propertyTypes.antilockBrakingSystem || false;
- _doFindEvents = function () {
- if (!_eventFilterCheck(_eventFilter)) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- if (!_findEventsAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+ this.__defineGetter__("antilockBrakingSystem", function () {
+ return abs.antilockBrakingSystem;
+ });
- pendingObj = new PendingObject();
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
- if (_eventFilter.id !== undefined) {
- tmp = wac2_utils.matchOptionString(_events, "id", _eventFilter.id);
- valid_tmp = true;
- }
- if (_eventFilter.summary !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionString(tmp, "summary", _eventFilter.summary);
- } else {
- tmp = wac2_utils.matchOptionString(_events, "summary", _eventFilter.summary);
- valid_tmp = true;
- }
- }
- if (_eventFilter.description !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionString(tmp, "description", _eventFilter.description);
- } else {
- tmp = wac2_utils.matchOptionString(_events, "description", _eventFilter.description);
- valid_tmp = true;
- }
- }
- if (_eventFilter.location !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionString(tmp, "location", _eventFilter.location);
- } else {
- tmp = wac2_utils.matchOptionString(_events, "location", _eventFilter.location);
- valid_tmp = true;
- }
- }
- if (_eventFilter.category !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionArrayString(tmp, "categories", _eventFilter.category);
- } else {
- tmp = wac2_utils.matchOptionArrayString(_events, "categories", _eventFilter.category);
- valid_tmp = true;
- }
- }
- if (_eventFilter.status !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionShortArray(tmp, "status", _eventFilter.status);
- } else {
- tmp = wac2_utils.matchOptionShortArray(_events, "status", _eventFilter.status);
- valid_tmp = true;
- }
- }
- if (_eventFilter.initialStartDate !== undefined ||
- _eventFilter.endStartDate !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionDate(tmp, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
- } else {
- tmp = wac2_utils.matchOptionDate(_events, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
- valid_tmp = true;
- }
- }
+ this.__defineSetter__("antilockBrakingSystem", function (val) {
+ try {
+ abs.antilockBrakingSystem = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
- // to make id readonly
- if (valid_tmp) {
- for (i = 0; i < tmp.length; i++) {
- rst.push(new CalendarEvent(tmp[i], false));
- }
- } else {
- for (var e in _events) {
- rst.push(new CalendarEvent(_events[e], false));
- }
- }
- onSuccess(rst);
- }, _FAKE_LONG_WAITTIME);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- };
+TractionControlSystem = function (propertyTypes) {
+ var tcs = {};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:findEvent", _doFindEvents);
- },
- };
- _self.__defineGetter__("type", function () {
- return _type;
+ VehiclePropertyType.call(this, propertyTypes);
+
+ tcs.tractionControlSystem = propertyTypes.tractionControlSystem || false;
+
+ this.__defineGetter__("tractionControlSystem", function () {
+ return tcs.tractionControlSystem;
});
- _self.__defineGetter__("name", function () {
- return name;
+
+ this.__defineSetter__("tractionControlSystem", function (val) {
+ try {
+ tcs.tractionControlSystem = t.boolean(val);
+ } catch (err) {
+ }
});
- return _self;
};
-module.exports = function () {
- this.__defineGetter__("SIM_CALENDAR", function () {
- return 0;
+VehicleTopSpeedLimit = function (propertyTypes) {
+ var vtl = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ vtl.vehicleTopSpeedLimit = propertyTypes.vehicleTopSpeedLimit || false;
+
+ this.__defineGetter__("vehicleTopSpeedLimit", function () {
+ return vtl.vehicleTopSpeedLimit;
});
- this.__defineGetter__("DEVICE_CALENDAR", function () {
- return 1;
+
+ this.__defineSetter__("vehicleTopSpeedLimit", function (val) {
+ try {
+ vtl.vehicleTopSpeedLimit = t.unsigned_short(val);
+ } catch (err) {
+ }
});
- this.__defineGetter__("NO_RECURRENCE", function () {
+};
+
+AirbagStatus = function (propertyTypes) {
+ var airbagStatus = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ airbagStatus.airbagStatus = propertyTypes.airbagStatus || 0;
+
+ this.__defineGetter__("AIRBAGSTATUS_INACTIVE", function () {
return 0;
});
- this.__defineGetter__("DAILY_RECURRENCE", function () {
+
+ this.__defineGetter__("AIRBAGSTATUS_ACTIVE", function () {
return 1;
});
- this.__defineGetter__("WEEKLY_RECURRENCE", function () {
+
+ this.__defineGetter__("AIRBAGSTATUS_DEPLOYED", function () {
return 2;
});
- this.__defineGetter__("MONTHLY_RECURRENCE", function () {
- return 3;
+
+ this.__defineGetter__("airbagStatus", function () {
+ return airbagStatus.airbagStatus;
});
- this.__defineGetter__("YEARLY_RECURRENCE", function () {
- return 4;
+
+ this.__defineSetter__("airbagStatus", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1 || val === 2) {
+ airbagStatus.airbagStatus = val;
+ }
+ } catch (err) {
+ }
});
- this.__defineGetter__("TENTATIVE_STATUS", function () {
+};
+
+DoorStatus = function (propertyTypes) {
+ var doorStatus = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ doorStatus.doorStatus = propertyTypes.doorStatus || 0;
+ doorStatus.doorLockStatus = propertyTypes.doorLockStatus || false;
+ doorStatus.childLockStatus = propertyTypes.childLockStatus || false;
+
+ this.__defineGetter__("DOORSTATUS_CLOSED", function () {
return 0;
});
- this.__defineGetter__("CONFIRMED_STATUS", function () {
+
+ this.__defineGetter__("DOORSTATUS_OPEN", function () {
return 1;
});
- this.__defineGetter__("CANCELLED_STATUS", function () {
+
+ this.__defineGetter__("DOORSTATUS_AJAR", function () {
return 2;
});
- this.__defineGetter__("NO_ALARM", function () {
- return 0;
+
+ this.__defineGetter__("doorStatus", function () {
+ return doorStatus.doorStatus;
});
- this.__defineGetter__("SILENT_ALARM", function () {
- return 1;
+
+ this.__defineSetter__("doorStatus", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1 || val === 2) {
+ doorStatus.doorStatus = val;
+ }
+ } catch (err) {
+ }
});
- this.__defineGetter__("SOUND_ALARM", function () {
- return 2;
+
+ this.__defineGetter__("doorLockStatus", function () {
+ return doorStatus.doorLockStatus;
});
- this.getCalendars = function (onSuccess, onError) {
- var i, pendingOperation, pendingObj = {}, cal, _doGetCalendars;
+ this.__defineSetter__("doorLockStatus", function (val) {
+ try {
+ doorStatus.doorLockStatus = t.boolean(val);
+ } catch (err) {
+ }
+ });
- _doGetCalendars = function () {
- pendingObj = new PendingObject();
+ this.__defineGetter__("childLockStatus", function () {
+ return doorStatus.childLockStatus;
+ });
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
- cal = db.retrieveObject(_DB_CALENDARS_KEY) || [];
- _calendars = [];
- if (cal.length === 0) {
- _calendars.push(new Calendar(_SIM_CALENDAR, "sim cal", {}));
- _calendars.push(new Calendar(_DEVICE_CALENDAR, "dev cal", {}));
- } else {
- for (i = 0; i < cal.length; i++) {
- /* after getting Date out of DB, Date will become
- a string, so need to recast it back to Date */
- /* NOTE: id becomes writable, so need to recast it
- before passing to application */
- for (var e in cal[i].events) {
- if ((cal[i].events[e].startTime !== undefined) &&
- cal[i].events[e].startTime !== null) {
- cal[i].events[e].startTime = new Date(cal[i].events[e].startTime);
- }
- if ((cal[i].events[e].expires !== undefined) &&
- cal[i].events[e].expires !== null) {
- cal[i].events[e].expires = new Date(cal[i].events[e].expires);
- }
- }
- _calendars.push(new Calendar(cal[i].type, cal[i].name, cal[i].events));
- }
- }
- if (_calendars.length !== 0) {
- onSuccess(utils.copy(_calendars));
- } else {
- if (onError) {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }
- }
- }, _FAKEWAITTIME);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- };
-
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCalendars", _doGetCalendars);
- };
+ this.__defineSetter__("childLockStatus", function (val) {
+ try {
+ doorStatus.childLockStatus = t.boolean(val);
+ } catch (err) {
+ }
+ });
+};
- this.handleSubFeatures = function (subFeatures) {
- if (wac2_utils.isEmptyObject(subFeatures) ||
- subFeatures["http://wacapps.net/api/pim.calendar"] ||
- (subFeatures["http://wacapps.net/api/pim.calendar.read"] &&
- subFeatures["http://wacapps.net/api/pim.calendar.write"])) {
- return;
- }
- if (subFeatures["http://wacapps.net/api/pim.calendar.read"]) {
- _addEventAllowed = false;
- _deleteEventAllowed = false;
- _updateEventAllowed = false;
- return;
- }
- if (subFeatures["http://wacapps.net/api/pim.calendar.write"]) {
- _findEventsAllowed = false;
- return;
- }
- _console.warn("WAC-2.0-Calendar-handleSubFeatures: something wrong");
- };
+SeatBeltStatus = function (propertyTypes) {
+ var seatBeltStatus = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ seatBeltStatus.seatBeltStatus = propertyTypes.seatBeltStatus || false;
+
+ this.__defineGetter__("seatBeltStatus", function () {
+ return seatBeltStatus.seatBeltStatus;
+ });
+
+ this.__defineSetter__("seatBeltStatus", function (val) {
+ try {
+ seatBeltStatus.seatBeltStatus = t.boolean(val);
+ } catch (err) {
+ }
+ });
};
-});
-define('ripple/platform/wac/2.0/camera', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+OccupantStatus = function (propertyTypes) {
+ var occupantStatus = {};
-var utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- _console = require('ripple/console'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils');
+ VehiclePropertyType.call(this, propertyTypes);
-module.exports = function () {
- var _cameraArray, Camera, _videoStatus = {},
- _captureImage, _startVideoCapture,
- _doCaptureImage, _doStartVideoCapture,
- _doGetPreview, _doGetCameras,
- _stopVideoCapture, _createPreviewNode,
- _FAKEWAITTIME = 5,
- _defaultHighRes = true,
- _defaultImageFilename = "_capture.jpg",
- _defaultVideoFilename = "_capture.avi",
- _captureImageAllowed = true,
- _startVideoCaptureAllowed = true,
- _stopVideoCaptureAllowed = true,
- _createPreviewNodeAllowed = true;
+ occupantStatus.occupantStatus = propertyTypes.occupantStatus || 0;
- _doCaptureImage = function (onSuccess, onError, capFilename, capHighRes, pendingObj) {
- pendingObj.pendingID = setTimeout(function () {
- var dname = "", fname = "";
- //pretend to do sth.
- pendingObj.setCancelFlag(false); // too late to cancel
- if (capFilename.indexOf("/") !== -1) {
- dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
- fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
- //replace extension with jpg
- fname = fname.replace(/\.[^\/\.]+$/i, ".jpg");
- } else {
- dname = "";
- fname = capFilename.replace(/\.[^\/\.]+$/i, ".jpg");
- }
- if (fname === "") {
- fname = _defaultImageFilename;
- }
- if (fname.search(/\.jpg$/) === -1) {
- fname = fname + ".jpg";
- }
- if (capHighRes) {
- onSuccess(dname + "high-" + fname);
- } else {
- onSuccess(dname + "low-" + fname);
- }
- }, _FAKEWAITTIME);
- };
+ this.__defineGetter__("OCCUPANTSTATUS_VACANT", function () {
+ return 0;
+ });
- _captureImage = function (onSuccess, onError, options) {
- var pendingOperation = {}, pendingObj,
- filename = this.id + _defaultImageFilename,
- highRes = _defaultHighRes, opt;
+ this.__defineGetter__("OCCUPANTSTATUS_CHILD", function () {
+ return 1;
+ });
- if (onSuccess) {
- utils.validateArgumentType(onSuccess, "function", null, "captureImage: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (onError) {
- utils.validateArgumentType(onError, "function", null, "captureImage: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (options) {
- opt = new Object(options);
- /* NOTE: if desktinationFilename or highRes is not provided by
- user, i.e. undefined or null, a default value is used.
- */
- if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
- // TODO: validate filename via Filesystem.resolve()
- filename = String(opt.destinationFilename);
- }
- if (opt.highRes !== null && opt.highRes !== undefined) {
- highRes = Boolean(opt.highRes);
- }
- }
- if (!_captureImageAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+ this.__defineGetter__("OCCUPANTSTATUS_ADULT", function () {
+ return 2;
+ });
- if (onSuccess) {
- pendingObj = new PendingObject();
- _doCaptureImage(onSuccess, onError, filename, highRes, pendingObj);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- }
- return undefined;
- };
+ this.__defineGetter__("occupantStatus", function () {
+ return occupantStatus.occupantStatus;
+ });
- _stopVideoCapture = function () {
- var dname = "", fname = "", capFilename = _videoStatus[this.id].capFilename;
- if (_videoStatus[this.id]) {
- if (capFilename.indexOf("/") !== -1) {
- dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
- fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
- //replace extension with avi
- fname = fname.replace(/\.[^\/\.]+$/i, ".avi");
- } else {
- dname = "";
- fname = capFilename.replace(/\.[^\/\.]+$/i, ".avi");
- }
- if (fname === "") {
- fname = _defaultVideoFilename;
- }
- if (fname.search(/\.avi$/) === -1) {
- fname = fname + ".avi";
- }
- if (_videoStatus[this.id].capHighRes) {
- _videoStatus[this.id].capSuccess(dname + "high-" + fname);
- } else {
- _videoStatus[this.id].capSuccess(dname + "low-" + fname);
+ this.__defineSetter__("occupantStatus", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1 || val === 2) {
+ occupantStatus.occupantStatus = val;
}
- delete _videoStatus[this.id];
+ } catch (err) {
}
- };
+ });
+};
- _doStartVideoCapture = function (camID, onSuccess, onError, filename, highRes, pendingObj) {
- var videoStatus = {};
- _videoStatus[camID] = videoStatus;
- pendingObj.userCancel = function () {
- delete _videoStatus[camID];
- };
- pendingObj.getCancelFlag = function () {
- return !!_videoStatus[camID];
- };
- pendingObj.pendingID = setTimeout(function () {
- // waiting to be cancelled
- videoStatus = {
- capSuccess: onSuccess,
- capError: onError,
- capFilename: filename,
- capHighRes: highRes
- };
- _videoStatus[camID] = videoStatus;
- }, _FAKEWAITTIME);
- };
+ObstacleDistance = function (propertyTypes) {
+ var obstacleDistance = {};
- _startVideoCapture = function (onSuccess, onError, options) {
- var pendingOperation = {}, pendingObj,
- filename = this.id + _defaultVideoFilename,
- highRes = _defaultHighRes, opt;
+ VehiclePropertyType.call(this, propertyTypes);
- if (onSuccess) {
- utils.validateArgumentType(onSuccess, "function", null, "startVideoCapture: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (onError) {
- utils.validateArgumentType(onError, "function", null, "startVideoCapture: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (options) {
- opt = new Object(options);
- /* NOTE: if desktinationFilename or highRes is not provided by
- user, i.e. undefined or null, a default value is used.
- */
- if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
- // TODO: validate filename via Filesystem.resolve()
- filename = String(opt.destinationFilename);
- }
- if (opt.highRes !== null && opt.highRes !== undefined) {
- highRes = Boolean(opt.highRes);
- }
- }
- if (!_captureImageAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- if (_videoStatus[this.id]) {
- // capture already started
- _console.warn("WAC-2.0-startVideoCapture: capture already started");
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }, 1);
- }
- return undefined;
- }
+ obstacleDistance.obstacleDistance = propertyTypes.obstacleDistance || 0;
- if (onSuccess) {
- pendingObj = new PendingObject();
- _doStartVideoCapture(this.id, onSuccess, onError, filename, highRes, pendingObj);
-
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- }
- return undefined;
- };
+ this.__defineGetter__("DISTANCESENSORLOCATION_LEFTFRONT", function () {
+ return 0;
+ });
- _doGetPreview = function (camID, onSuccess, onError, pendingObj) {
- var container, demoImg, loc, imageSrc;
- container = document.createElement("div");
- container.setAttribute("id", camID + "-wac-2-0-camera-preview-container");
- demoImg = document.createElement("img");
- demoImg.setAttribute("id", camID + "-wac-2-0-camera-demo-image");
- loc = document.location;
- imageSrc = loc.protocol + "//" + loc.hostname + loc.pathname.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION;
- demoImg.setAttribute("src", imageSrc);
- demoImg.setAttribute("width", "100%");
- container.appendChild(demoImg);
-
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false); // too late to cancel
- onSuccess(container);
- }, _FAKEWAITTIME);
- };
+ this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTFRONT", function () {
+ return 1;
+ });
- _createPreviewNode = function (onSuccess, onError) {
- var pendingOperation, pendingObj = {};
- if (onSuccess) {
- utils.validateArgumentType(onSuccess, "function", null, "createPreviewNode: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (onError) {
- utils.validateArgumentType(onError, "function", null, "createPreviewNode: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
- if (!_createPreviewNodeAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- if (onSuccess) {
- pendingObj = new PendingObject();
- _doGetPreview(this.id, onSuccess, onError, pendingObj);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- }
- return undefined;
- };
+ this.__defineGetter__("DISTANCESENSORLOCATION_LEFTREAR", function () {
+ return 2;
+ });
+
+ this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTREAR", function () {
+ return 3;
+ });
- Camera = function (cameraID) {
- return {
- id: cameraID,
- captureImage: _captureImage,
- startVideoCapture: _startVideoCapture,
- stopVideoCapture: _stopVideoCapture,
- createPreviewNode: _createPreviewNode
- };
- };
+ this.__defineGetter__("DISTANCESENSORLOCATION_LEFTBLINDSPOT",
+ function () {
+ return 4;
+ });
- _cameraArray = [new Camera("rear"), new Camera("front")];
+ this.__defineGetter__("DISTANCESENSORLOCATION_RIGHTBLINDSPOT",
+ function () {
+ return 5;
+ });
- _doGetCameras = function (onSuccess, onError, pendingObj) {
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false); // too late to cancel
- if (_cameraArray.length !== 0) {
- onSuccess(utils.copy(_cameraArray));
- } else {
- // no camera
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }, 1);
- }
- }
- }, _FAKEWAITTIME);
- };
+ this.__defineGetter__("obstacleDistance", function () {
+ return obstacleDistance.obstacleDistance;
+ });
- this.getCameras = function (onSuccess, onError) {
- var pendingOperation, pendingObj = {};
- if (onSuccess) {
- utils.validateArgumentType(onSuccess, "function", null, "getCameras: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ this.__defineSetter__("obstacleDistance", function (val) {
+ try {
+ obstacleDistance.obstacleDistance = t.double(val);
+ } catch (err) {
}
- if (onError) {
- utils.validateArgumentType(onError, "function", null, "getCameras: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ });
+};
+
+NightMode = function (propertyTypes) {
+ var nightMode = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ nightMode.nightMode = propertyTypes.nightMode || false;
+
+ this.__defineGetter__("nightMode", function () {
+ return nightMode.nightMode;
+ });
+
+ this.__defineSetter__("nightMode", function (val) {
+ try {
+ nightMode.nightMode = t.boolean(val);
+ } catch (err) {
}
- if (onSuccess) {
- pendingObj = new PendingObject();
- _doGetCameras(onSuccess, onError, pendingObj);
- pendingOperation = new PendingOperation(pendingObj);
- return pendingOperation;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
+ });
+};
+
+DrivingMode = function (propertyTypes) {
+ var drivingMode = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ drivingMode.drivingMode = propertyTypes.drivingMode || 0;
+
+ this.__defineGetter__("drivingMode", function () {
+ return drivingMode.drivingMode;
+ });
+
+ this.__defineSetter__("drivingMode", function (val) {
+ try {
+ val = t.unsigned_short(val);
+ if (val === 0 || val === 1) {
+ drivingMode.drivingMode = val;
}
+ } catch (err) {
}
- return undefined;
- };
+ });
+};
- this.handleSubFeatures = function (subFeatures) {
- if (wac2_utils.isEmptyObject(subFeatures) ||
- subFeatures["http://wacapps.net/api/camera"] ||
- (subFeatures["http://wacapps.net/api/camera.capture"] &&
- subFeatures["http://wacapps.net/api/camera.show"])) {
- return;
- }
- if (subFeatures["http://wacapps.net/api/camera.show"] &&
- !subFeatures["http://wacapps.net/api/camera.capture"]) {
- _captureImageAllowed = false;
- _startVideoCaptureAllowed = false;
- _stopVideoCaptureAllowed = false;
- return;
+TurnSignal = function (propertyTypes) {
+ var turnSignal = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ turnSignal.turnSignal = propertyTypes.turnSignal || 0;
+
+ this.__defineGetter__("turnSignal", function () {
+ return turnSignal.turnSignal;
+ });
+
+ this.__defineSetter__("turnSignal", function (val) {
+ try {
+ turnSignal.turnSignal = t.unsigned_short(val);
+ } catch (err) {
}
- if (subFeatures["http://wacapps.net/api/camera.capture"] &&
- !subFeatures["http://wacapps.net/api/camera.show"]) {
- _createPreviewNodeAllowed = false;
- return;
+ });
+};
+
+ButtonEvent = function (propertyTypes) {
+ var buttonEvent = {};
+
+ VehiclePropertyType.call(this, propertyTypes);
+
+ buttonEvent.buttonEvent = propertyTypes.buttonEvent || 0;
+
+ this.__defineGetter__("buttonEvent", function () {
+ return buttonEvent.buttonEvent;
+ });
+
+ this.__defineSetter__("buttonEvent", function (val) {
+ try {
+ buttonEvent.buttonEvent = t.unsigned_short(val);
+ } catch (err) {
}
- _console.warn("WAC-2.0-Camera-handleSubFeatures: something wrong");
- };
+ });
};
+_initialize();
+
+module.exports = _self;
+
});
-define('ripple/platform/wac/2.0/contact', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/typecoerce', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants'),
- exception = require('ripple/exception'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
- Filter = require('ripple/platform/wac/2.0/contactfilter'),
- AddressBook,
- ContactProperties,
- Contact,
- Address,
- ContactAddress,
- PhoneNumber,
- EmailAddress,
- ContactFilter,
- _KEY = "wac2-pim-contact",
- _PENDING_TIME = 600,
- _addressBooks = [],
- _contacts = {},
- _security = {
- "http://wacapps.net/api/pim.contact": [],
- "http://wacapps.net/api/pim.contact.read": ["findContacts"],
- "http://wacapps.net/api/pim.contact.write": ["addContact", "updateContact", "deleteContact"],
- all: true
- },
+var t = require('ripple/platform/ivi/3.0/typedef'),
_self;
-function _errorOccurred(onError, code) {
- if (!onError)
- return;
+_self = function (pattern) {
+ var typeCoerce, typeOfPattern;
- setTimeout(function () {
- onError(new DeviceApiError(code));
- }, 1);
-}
+ // private
+ function getExtendedType(val) {
+ var type = Object.prototype.toString.call(val), attr;
-function _pendingOperate(operate, scope) {
- var i, argumentVector = [];
+ switch (type) {
+ case "[object Array]":
+ if ((typeof val[0] === "string") && (val[0].length > 0)) {
+ type = "enum";
+ } else {
+ type = "Union";
+ }
+ return type;
- for (i = 0; i < arguments.length - 2; i++)
- argumentVector[i] = arguments[i + 2];
+ case "[object Object]":
+ if ("_dictionary" in val) {
+ return "dictionary";
+ }
- return function () {
- var pendingObj, pendingOperation;
+ type = "Object";
- pendingObj = new PendingObject();
- pendingObj.pendingID = window.setTimeout(function () {
- pendingObj.setCancelFlag(false);
- operate.apply(scope, argumentVector);
- }, _PENDING_TIME);
+ for (attr in val) {
+ if (attr === "0") {
+ type = "Arguments";
+ } else if (val[attr] === "Callback") {
+ type = "Callback";
+ }
+ break;
+ }
- pendingOperation = new PendingOperation(pendingObj);
+ return type;
+ }
- return pendingOperation;
- };
-}
+ switch (val) {
+ case "Callback":
+ type = "Function";
+ break;
-function _defaultContacts() {
- var id1 = Math.uuid(null, 16),
- id2 = Math.uuid(null, 16),
- id3 = Math.uuid(null, 16),
- id4 = Math.uuid(null, 16),
- contacts = {};
+ case "TZDate":
+ case "any":
+ case "byte":
+ case "float":
+ case "long":
+ case "long long":
+ case "octet":
+ case "short":
+ case "unsigned long":
+ case "unsigned long long":
+ case "unsigned short":
+ type = val;
+ break;
- contacts.PHONE_ADDRESS_BOOK = {
- type: _self().PHONE_ADDRESS_BOOK,
- items: [{
- id: id1,
- firstName: "Leonardo",
- lastName: "Gates",
- nicknames: ["Leo"],
- phoneticName: "",
- addresses: [{streetAddress: "Gran Via, 32", postalCode: "50013", city: "Zaragoza", country: "ES"}],
- photoURI: "",
- phoneNumbers: [],
- emails: ["leo@underground.com"]
- }, {
- id: id2,
- firstName: "Jordan",
- lastName: "",
- nicknames: [""],
- phoneticName: "",
- addresses: [],
- photoURI: "",
- phoneNumbers: [],
- emails: ["jordan@underground.com"]
- }]
- };
+ case "double":
+ type = "float";
+ break;
- contacts.SIM_ADDRESS_BOOK = {
- type: _self().SIM_ADDRESS_BOOK,
- items: [{
- id: id3,
- firstName: "Raphael",
- lastName: "",
- nicknames: [""],
- phoneticName: "",
- addresses: [],
- photoURI: "",
- phoneNumbers: [],
- emails: ["raph@underground.com"]
- }]
- };
+ default: // Derivative type name: e.g., "AbstractFilter"
+ type = "";
+ break;
+ }
- contacts.DEVICE_ADDRESS_BOOK = {
- type: _self().DEVICE_ADDRESS_BOOK,
- items: [{
- id: id4,
- firstName: "Michelangelo",
- lastName: "",
- nicknames: [""],
- phoneticName: "",
- addresses: [],
- photoURI: "",
- phoneNumbers: [],
- emails: ["mike@underground.com"]
- }]
- };
+ return type;
+ }
- return contacts;
-}
+ function getType(val, isPattern) {
+ var type = Object.prototype.toString.call(val);
-function _get() {
- _contacts = db.retrieveObject(_KEY) || _defaultContacts();
-}
+ switch (type) {
+ case "[object Array]":
+ type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
+ "Array";
+ break;
-function _save() {
- db.saveObject(_KEY, _contacts);
-}
+ case "[object Arguments]":
+ type = "Arguments";
+ break;
-function _initAddressBooks() {
- _get();
- utils.forEach(_contacts, function (contactObj, name) {
- _addressBooks.push(new AddressBook(contactObj.type, name));
- });
-}
+ case "[object Boolean]":
+ type = "boolean";
+ break;
-_self = function () {
- var contact = {
- getAddressBooks: function (successCallback, errorCallback) {
- function _getAddressBooks() {
- if (_addressBooks.length === 0) {
- _initAddressBooks();
+ case "[object Date]":
+ type = "Date";
+ break;
+
+ case "[object Function]":
+ type = "Function";
+ break;
+
+ case "[object Number]":
+ type = "Number";
+ break;
+
+ case "[object Object]":
+ type = isPattern ? getExtendedType(val) : "Object";
+ break;
+
+ case "[object String]":
+ type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
+ break;
+ }
+
+ return type;
+ }
+
+ function isConstructed(obj) {
+ if (!("_constructor" in pattern))
+ return true;
+
+ if (obj instanceof window.tizen[pattern._constructor])
+ return true;
+
+ return false;
+ }
+
+ function toInteger(x) {
+ return (x < 0) ? Math.ceil(x) : Math.floor(x);
+ }
+
+ function modulo(a, b) {
+ return (a - Math.floor(a / b) * b);
+ }
+
+ function toInt(x, bits) {
+ var p;
+
+ x = Number(x);
+
+ if (isNaN(x) || !isFinite(x))
+ return null;
+
+ p = Math.pow(2, bits);
+ x = modulo(toInteger(x), p);
+
+ return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
+ }
+
+ function toUInt(x, bits) {
+ x = Number(x);
+
+ if (isNaN(x) || !isFinite(x))
+ return null;
+
+ return modulo(toInteger(x), Math.pow(2, bits));
+ }
+
+ function toInt8(x) {
+ return toInt(x, 8);
+ }
+
+ function toInt16(x) {
+ return toInt(x, 16);
+ }
+
+ function toInt32(x) {
+ return toInt(x, 32);
+ }
+
+ function toInt64(x) {
+ return toInt(x, 64);
+ }
+
+ function toUInt8(x) {
+ return toUInt(x, 8);
+ }
+
+ function toUInt16(x) {
+ return toUInt(x, 16);
+ }
+
+ function toUInt32(x) {
+ return toUInt(x, 32);
+ }
+
+ function toUInt64(x) {
+ return toUInt(x, 64);
+ }
+
+ // public
+ function cast(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
+
+ typeMap = {
+ "Arguments": function () {
+ var i, isNullable, ret;
+
+ for (i in pattern) {
+ if (i === "_optional")
+ continue;
+
+ isNullable = !!(pattern._optional && pattern._optional[i]);
+
+ if (i > obj.length - 1) {
+ if (!isNullable) {
+ return null;
+ }
+ break;
+ }
+
+ if (!isNullable || (obj[i] !== null)) {
+ ret = _self(pattern[i]).cast(obj[i]);
+ if (ret === null) {
+ return null;
+ }
+ obj[i] = ret;
+ }
}
- successCallback(_addressBooks);
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getAddressBooks", _getAddressBooks);
- },
- handleSubFeatures: function (subFeatures) {
- for (var subFeature in subFeatures) {
- if (_security[subFeature].length === 0) {
- _security.all = true;
- return;
+ return obj;
+ },
+
+ "Array": function () {
+ var elementType, i, ret;
+
+ if (typeOfObj !== typeOfPattern) {
+ return null;
}
- _security.all = false;
- utils.forEach(_security[subFeature], function (method) {
- _security[method] = true;
- });
- }
- }
- };
- contact.__defineGetter__("SIM_ADDRESS_BOOK", function () {
- return 0x0000;
- });
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ ret = elementType.cast(obj[i]);
+ if (ret === null) {
+ return null;
+ }
+ obj[i] = ret;
+ }
- contact.__defineGetter__("DEVICE_ADDRESS_BOOK", function () {
- return 0x000F;
- });
+ return obj;
+ },
- contact.__defineGetter__("PHONE_ADDRESS_BOOK", function () {
- return 0x00FF;
- });
+ "Callback": function () {
+ var attr;
- return contact;
-};
+ if (typeOfObj !== "Object") {
+ return null;
+ }
-AddressBook = function (type, name) {
- var addressBook,
- contactItems = _contacts[name].items;
+ for (attr in pattern) {
+ if (attr in obj) {
+ obj[attr] = _self(pattern[attr]).cast(obj[attr]);
+ if (obj[attr] === null) {
+ return null;
+ }
+ }
+ }
- addressBook = {
- createContact: function (contactProperties) {
- var cp, contact = new Contact();
+ return obj;
+ },
- if ((contactProperties !== undefined) &&
- (contactProperties !== null)) {
- cp = TypeCoerce(ContactProperties).cast(contactProperties);
- !cp.firstName || (contact.firstName = utils.copy(cp.firstName));
- !cp.lastName || (contact.lastName = utils.copy(cp.lastName));
- !cp.nicknames || (contact.nicknames = utils.copy(cp.nicknames));
- !cp.phoneticName || (contact.phoneticName = utils.copy(cp.phoneticName));
- !cp.addresses || (contact.addresses = utils.copy(cp.addresses));
- !cp.photoURI || (contact.photoURI = utils.copy(cp.photoURI));
- !cp.phoneNumbers || (contact.phoneNumbers = utils.copy(cp.phoneNumbers));
- !cp.emails || (contact.emails = utils.copy(cp.emails));
- }
+ "DOMString": function () {
+ switch (typeOfObj) {
+ case "DOMString":
+ case "Date":
+ case "Number":
+ case "boolean":
+ obj = String(obj);
+ break;
- return contact;
- },
+ default:
+ if ((obj === null) || (obj === undefined)) {
+ obj = String(obj);
+ } else {
+ obj = null;
+ }
+ break;
+ }
- addContact: function (successCallback, errorCallback, contact) {
- function _addContact() {
- var c;
+ return obj;
+ },
- if (!contact)
- exception.raise(exception.types.Argument, "addContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ "Date": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
- if (!_security.all && !_security.addContact)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+ "Function": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
- c = TypeCoerce(new Contact()).cast(contact);
- contactItems.push(c);
- _save();
- successCallback(c);
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "addContact", _pendingOperate(_addContact));
- },
+ "Object": function () {
+ var ret, attr, i;
- updateContact: function (successCallback, errorCallback, contact) {
- function _updateContact() {
- var c, isFound = false;
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return null;
+ }
+ if (!("_derived" in pattern)) {
+ return null;
+ }
+ }
- if (!contact)
- exception.raise(exception.types.Argument, "updateContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ if (!isConstructed(obj)) {
+ return null;
+ }
- if (!_security.all && !_security.updateContact)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
- c = TypeCoerce(new Contact()).cast(contact);
- utils.forEach(contactItems, function (contactItem) {
- if (contactItem.id === c.id) {
- !c.firstName || (contactItem.firstName = utils.copy(c.firstName));
- !c.lastName || (contactItem.lastName = utils.copy(c.lastName));
- !c.nicknames || (contactItem.nicknames = utils.copy(c.nicknames));
- !c.phoneticName || (contactItem.phoneticName = utils.copy(c.phoneticName));
- !c.addresses || (contactItem.addresses = utils.copy(c.addresses));
- !c.photoURI || (contactItem.photoURI = utils.copy(c.photoURI));
- !c.phoneNumbers || (contactItem.phoneNumbers = utils.copy(c.phoneNumbers));
- !c.emails || (contactItem.emails = utils.copy(c.emails));
+ case "_derived":
+ for (i in pattern._derived) {
+ ret = _self(pattern._derived[i]).cast(obj);
+ if (ret !== null)
+ break;
+ }
+ if (ret === null) {
+ return null;
+ }
+ break;
- _save();
- isFound = true;
- successCallback();
+ default:
+ if (!pattern._optional || !pattern._optional[attr] ||
+ (obj[attr] !== undefined) &&
+ (obj[attr] !== null)) {
+ ret = _self(pattern[attr]).cast(obj[attr]);
+ if (ret === null) {
+ return null;
+ }
+ obj[attr] = ret;
+ }
+ break;
}
- });
+ }
- if (!isFound)
- _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "updateContact", _pendingOperate(_updateContact));
- },
+ return obj;
+ },
- deleteContact: function (successCallback, errorCallback, id) {
- function _deleteContact() {
- var isFound = false;
+ "TZDate": function () {
+ if (typeOfObj !== "Object") {
+ return null;
+ }
+ return (obj instanceof window.tizen.TZDate) ? obj : null;
+ },
- if (!_security.all && !_security.deleteContact)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+ "Union": function () {
+ var ret, i;
- utils.forEach(contactItems, function (contactItem, index) {
- if (contactItem.id === id) {
- contactItems.splice(index, 1);
- _save();
- isFound = true;
- successCallback();
+ for (i in pattern) {
+ ret = _self(pattern[i]).cast(obj);
+ if (ret !== null)
+ break;
+ }
+
+ return ret;
+ },
+
+ "any": function () {
+ return obj;
+ },
+
+ "boolean": function () {
+ return (typeOfObj === typeOfPattern) ? obj : null;
+ },
+
+ "byte": function () {
+ return toInt8(obj);
+ },
+
+ "dictionary": function () {
+ var attr, ret;
+
+ if (typeOfObj !== "Object") {
+ return null;
+ }
+
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ ret = _self(pattern._dictionary).cast(obj);
+ if (ret === null) {
+ return null;
+ }
+ }
+ break;
+
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ ret = _self(pattern[attr]).cast(obj[attr]);
+ if (ret === null) {
+ return null;
+ }
+ obj[attr] = ret;
+ }
+ break;
}
- });
+ }
- if (!isFound)
- _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
+ return obj;
+ },
+
+ "enum": function () {
+ var i;
+
+ obj = String(obj).trim();
+ for (i in pattern) {
+ if (obj === pattern[i]) {
+ return obj;
+ }
+ }
+
+ return null;
+ },
+
+ "float": function () {
+ var f = parseFloat(obj, 10);
+
+ return (isNaN(f) ? null : f);
+ },
+
+ "long": function () {
+ return toInt32(obj);
+ },
+
+ "long long": function () {
+ return toInt64(obj);
+ },
+
+ "octet": function () {
+ return toUInt8(obj);
+ },
+
+ "short": function () {
+ return toInt16(obj);
+ },
+
+ "unsigned long": function () {
+ return toUInt32(obj);
+ },
+
+ "unsigned long long": function () {
+ return toUInt64(obj);
+ },
+
+ "unsigned short": function () {
+ return toUInt16(obj);
+ },
+
+ "": function () {
+ return _self(t[pattern]).cast(obj);
}
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "deleteContact", _pendingOperate(_deleteContact));
- },
+ };
- findContacts: function (successCallback, errorCallback, filter) {
- function _findContacts() {
- var contact, result = [];
+ return typeMap[typeOfPattern]();
+ }
- if (!_security.all && !_security.findContacts)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+ function copy(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
- utils.forEach(contactItems, function (contactItem) {
- if ((filter === undefined || filter === null) ||
- (filter.id === undefined || Filter(filter.id).match(contactItem.id)) &&
- (filter.firstName === undefined || Filter(filter.firstName).match(contactItem.firstName)) &&
- (filter.lastName === undefined || Filter(filter.lastName).match(contactItem.lastName)) &&
- (filter.phoneticName === undefined || Filter(filter.phoneticName).match(contactItem.phoneticName)) &&
- (filter.nickname === undefined || Filter(filter.nickname).match(contactItem.nicknames)) &&
- (filter.phoneNumber === undefined || Filter(filter.phoneNumber).match(contactItem.phoneNumbers)) &&
- (filter.email === undefined || Filter(filter.email).match(contactItem.emails)) &&
- (filter.address === undefined || Filter(filter.address).match(contactItem.addresses))) {
- contact = new Contact(contactItem.id);
+ typeMap = {
+ "Arguments": function () {
+ var i, isNullable, ret = [];
- contact.firstName = utils.copy(contactItem.firstName);
- contact.lastName = utils.copy(contactItem.lastName);
- contact.nicknames = utils.copy(contactItem.nicknames);
- contact.phoneticName = utils.copy(contactItem.phoneticName);
- contact.addresses = utils.copy(contactItem.addresses);
- contact.photoURI = utils.copy(contactItem.photoURI);
- contact.phoneNumbers = utils.copy(contactItem.phoneNumbers);
- contact.emails = utils.copy(contactItem.emails);
+ for (i in pattern) {
+ if (i === "_optional")
+ continue;
- result.push(contact);
+ isNullable = !!(pattern._optional && pattern._optional[i]);
+
+ if (i > obj.length - 1) {
+ if (!isNullable) {
+ return null;
+ }
+ break;
}
- });
- successCallback(result);
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findContacts", _pendingOperate(_findContacts));
- }
- };
- addressBook.__defineGetter__("type", function () {
- return type;
- });
+ if (!isNullable || (obj[i] !== null)) {
+ ret[i] = _self(pattern[i]).copy(obj[i]);
+ if (ret[i] === null) {
+ return null;
+ }
+ }
+ }
- addressBook.__defineGetter__("name", function () {
- return name;
- });
+ for (i in ret) {
+ obj[i] = ret[i];
+ }
- return addressBook;
-};
+ return obj;
+ },
-Address = {
- country: "",
- region: "",
- county: "",
- city: "",
- streetAddress: "",
- additionalInformation: "",
- postalCode: ""
-};
+ "Array": function () {
+ var arr = [], elementType, i;
-ContactAddress = function () {
- this.types = [""]; // "WORK", "PREF", "HOME"
-};
+ if (typeOfObj !== typeOfPattern) {
+ return null;
+ }
-ContactAddress.prototype = Address;
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ if (obj[i]) {
+ arr[i] = elementType.copy(obj[i]);
+ if (arr[i] === null)
+ return null;
+ }
+ }
+
+ return arr;
+ },
+
+ "Callback": function () {
+ var ret = {}, attr;
+
+ if (typeOfObj !== "Object") {
+ return null;
+ }
+
+ for (attr in pattern) {
+ if (attr in obj) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ "Object": function () {
+ var ret = {}, attr, i, derived;
+
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return null;
+ }
+ if (!("_derived" in pattern)) {
+ return null;
+ }
+ }
+
+ if (!isConstructed(obj)) {
+ return null;
+ }
+ if ("_constructor" in pattern) {
+ ret.__proto__ = window.tizen[pattern._constructor].prototype;
+ }
+
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
+
+ case "_derived":
+ for (i in pattern._derived) {
+ derived = _self(pattern._derived[i]).copy(obj);
+ if (derived !== null)
+ break;
+ }
+ if (derived === null) {
+ return null;
+ }
+ for (attr in derived) {
+ ret[attr] = derived[attr];
+ }
+ break;
+
+ default:
+ if (!pattern._optional || !pattern._optional[attr] ||
+ (obj[attr] !== undefined) &&
+ (obj[attr] !== null)) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ break;
+ }
+ }
+
+ return ret;
+ },
+
+ "Union": function () {
+ var ret, i;
+
+ for (i in pattern) {
+ ret = _self(pattern[i]).copy(obj);
+ if (ret !== null)
+ break;
+ }
+
+ return ret;
+ },
+
+ "dictionary": function () {
+ var ret = {}, attr, base, i;
+
+ if (typeOfObj !== "Object") {
+ return null;
+ }
+
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ base = _self(pattern._dictionary).copy(obj);
+ if (base === null) {
+ return null;
+ }
+ for (i in base) {
+ ret[i] = base[i];
+ }
+ }
+ break;
+
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ ret[attr] = _self(pattern[attr]).copy(obj[attr]);
+ if (ret[attr] === null) {
+ return null;
+ }
+ }
+ break;
+ }
+ }
+
+ return ret;
+ },
+
+ "": function () {
+ return _self(t[pattern]).copy(obj);
+ }
+ };
+
+ return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
+ cast(obj);
+ }
+
+ function match(obj) {
+ var typeMap,
+ typeOfObj = getType(obj, false);
+
+ typeMap = {
+ "Array": function () {
+ var elementType, i;
-PhoneNumber = {
- number: "",
- types: [""] // "WORK", "PREF", "HOME", "VOICE", "FAX", "MSG", "CELL",
- // "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO", "PCS"
-};
+ if (typeOfObj !== typeOfPattern)
+ return false;
-EmailAddress = {
- email: "",
- types: [""] // "WORK", "PREF", "HOME"
-};
+ elementType = _self(pattern[0]);
+ for (i in obj) {
+ if (!elementType.match(obj[i])) {
+ return false;
+ }
+ }
-ContactProperties = {
- firstName: "",
- lastName: "",
- nicknames: [""],
- phoneticName: "",
- addresses: [new ContactAddress()],
- photoURI: "",
- phoneNumbers: [PhoneNumber],
- emails: [EmailAddress]
-};
+ return true;
+ },
-Contact = function (id) {
- id = id || Math.uuid(null, 16);
+ "Callback": function () {
+ var attr, isMatched = true;
- this.__defineGetter__("id", function () {
- return id;
- });
-};
+ if (typeOfObj !== "Object") {
+ return false;
+ }
-Contact.prototype = ContactProperties;
+ for (attr in pattern) {
+ if (attr in obj) {
+ isMatched = _self(pattern[attr]).match(obj[attr]);
+ if (!isMatched) {
+ break;
+ }
+ }
+ }
-ContactFilter = {
- id: "",
- firstName: "",
- lastName: "",
- phoneticName: "",
- nickname: "",
- phoneNumber: "",
- email: "",
- address: ""
-};
+ return isMatched;
+ },
-module.exports = _self;
+ "DOMString": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-});
-define('ripple/platform/wac/2.0/contactfilter', function (require, exports, module) {
-/*\r
- * Copyright 2011 Intel Corporation.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-var utils = require('ripple/utils'),\r
- _self;\r
-\r
-_self = function (criteria) {\r
- var pattern,\r
- contactFilter;\r
-\r
- contactFilter = {\r
- match: function (target) {\r
- var result = false, key, value, index;\r
-\r
- switch (Object.prototype.toString.call(target)) {\r
- case "[object String]":\r
- result = pattern.test(target);\r
- break;\r
-\r
- case "[object Object]":\r
- for (key in criteria) {\r
- result = true;\r
- value = criteria[key];\r
- if ((value !== undefined) && (!_self(value).match(target[key])))\r
- return false;\r
- }\r
- break;\r
-\r
- case "[object Array]":\r
- for (index in target) {\r
- if (contactFilter.match(target[index]))\r
- return true;\r
- }\r
- break;\r
- }\r
-\r
- return result;\r
- }\r
- };\r
-\r
- if (typeof criteria === "string")\r
- pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");\r
-\r
- return contactFilter;\r
-};\r
-\r
-module.exports = _self;\r
+ "Date": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-});
-define('ripple/platform/wac/2.0/dbfs', function (require, exports, module) {
-/*
- * Copyright 2011 Research In Motion Limited.
- * Copyright 2011 Intel Corporation.
- *
- * 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": function () {
+ return (typeOfObj === typeOfPattern);
+ },
-/* We know the dbfs is not an accurate simulation of WAC 2.0 filesystem.
- *
- * 1) We have tried W3C File API, as some of WAC filesystem APIs are synchronous,
- * it is impossible to simulate them by using the asynchronous API in the main
- * UI thread and although we could use synchronous W3C API in a worker, it is
- * not reasonable to limit WAC filesystem API usage in a worker.
- *
- * 2) The problem is partially solved by using database to simulate the filesystem,
- * For the asynchronous aspect, actually all the files are read into memory (cache
- * object in this file) and the cache operation is synchronous. It is not perfect.
- * And the database has 5MB limitation when running in Chrome.
- *
- * In the future, we might use ajax or NPAPI to get a better simulation.
- */
+ "Object": function () {
+ var attr, isMatched = false, i;
-/* Note: The entry object is shared between this module and filesystem */
+ if (typeOfObj !== typeOfPattern) {
+ if ((obj === null) || (obj === undefined)) {
+ return false;
+ }
+ if (!("_derived" in pattern)) {
+ return false;
+ }
+ return false;
+ }
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- _console = require('ripple/console'),
- _cache = {},
- _self;
+ if (!isConstructed(obj)) {
+ return false;
+ }
-function _get(path) {
- return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
- return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
- }, _cache);
-}
+ for (attr in pattern) {
+ switch (attr) {
+ case "_optional":
+ case "_constructor":
+ break;
-function _getInfo(path) {
- var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
- name = parent.splice(parent.length - 1, 1).join("");
+ case "_derived":
+ for (i in pattern._derived) {
+ isMatched = _self(pattern._derived[i]).match(obj);
+ if (isMatched)
+ break;
+ }
+ break;
- return {
- name: name,
- parent: parent.join("/") || "/"
- };
-}
+ default:
+ if (pattern._optional && pattern._optional[attr]) {
+ isMatched = ((obj[attr] === null) ||
+ (obj[attr] === undefined) ||
+ _self(pattern[attr]).match(obj[attr]));
+ } else {
+ isMatched = (obj[attr] !== undefined) &&
+ _self(pattern[attr]).match(obj[attr]);
+ }
+ break;
+ }
-function _set(path, obj) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ if (!isMatched)
+ break;
+ }
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ /*// Check if verbose attributes are present
+ if (isMatched) {
+ for (attr in obj) {
+ if (pattern[attr] === undefined) {
+ isMatched = false;
+ break;
+ }
+ }
+ }*/
- parent.children = parent.children || {};
- parent.children[child] = obj;
-}
+ return isMatched;
+ },
-function _delete(path) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ "Union": function () {
+ var isMatched, i;
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ for (i in pattern) {
+ isMatched = _self(pattern[i]).match(obj);
+ if (isMatched)
+ break;
+ }
- delete parent.children[child];
-}
+ return isMatched;
+ },
-function _save() {
- db.saveObject("wac2-db-filesystem", _cache);
-}
+ "any": function () {
+ return true;
+ },
-function _walk(path, parent) {
- _self.ls(path, function (entries) {
- parent.children = parent.children || {};
+ "boolean": function () {
+ return (typeOfObj === typeOfPattern);
+ },
- entries.forEach(function (entry) {
- parent.children[entry.name] = entry;
+ "byte": function () {
+ return (obj === toInt8(obj));
+ },
- if (entry.isDirectory) {
- _walk(entry.fullPath, entry);
- } else {
- /* after getting Date out of DB, Date will become
- a string, so need to recast it back to Date */
- if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
- entry.lastModifiedDate = new Date(entry.lastModifiedDate);
+ "dictionary": function () {
+ var attr, isMatched = true;
- _self.read(entry.fullPath, function (data) {
- parent.children[entry.name].data = data;
- }, function (e) {
- _console.error(e);
- });
- }
- });
- }, function (e) {
- _console.error(e);
- });
-}
-
-function _createPath(path) {
- var parts = path.replace(/^\//, '').split("/"),
- workflow = jWorkflow.order();
-
- parts.forEach(function (part, index) {
- var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
-
- workflow.andThen(function (prev, baton) {
- baton.take();
- _self.mkdir(dir, baton.pass, baton.pass);
- });
- });
-
- workflow.start();
-}
+ if (typeOfObj !== "Object") {
+ return false;
+ }
-_self = {
- // The order is consistent with _virtualRoots in filesystem.js
- roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
- initialize: function () {
- // TODO: Initialize at bootstrap and emulatorBridge.link
- _cache = db.retrieveObject("wac2-db-filesystem") || {};
- // create real root paths if empty
- _self.roots.every(function (root) {
- _createPath(root);
- return true;
- });
- // build the file system cache so that we could access information synchronously
- _walk("/", _cache);
- },
- ls: function (path, success, error) {
- try {
- var dir = _get(path),
- items = [];
+ for (attr in pattern) {
+ switch (attr) {
+ case "_dictionary":
+ if (pattern._dictionary !== null) {
+ isMatched = _self(pattern._dictionary).match(obj);
+ if (!isMatched)
+ break;
+ }
+ break;
- if (dir) {
- utils.forEach(dir.children, function (item) {
- items.push(item);
- });
- }
- else {
- items = {};
- }
+ default:
+ if ((attr in obj) && (obj[attr] !== null) &&
+ (obj[attr] !== undefined)) {
+ isMatched = _self(pattern[attr]).match(obj[attr]);
+ if (!isMatched)
+ break;
+ }
+ break;
+ }
+ }
- success(items);
- }
- catch (e) {
- e.code = 1;
- error(e);
- }
- },
- rm: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
- rmdir: function (path, success, error, options) {
- _delete(path);
- _save();
- success();
- },
- mkdir: function (path, success, error) {
- var entry = _get(path),
- info = _getInfo(path);
+ return isMatched;
+ },
- if (!entry) {
- _set(path, {
- name: info.name,
- isDirectory: true,
- fullPath: path
- });
- entry = _get(path);
- _save();
- }
-
- if (entry) {
- success(entry);
- }
- else {
- error({code: 1});
- }
- },
- mv: function (from, to, success, error) {
- try {
- var fromEntry = _get(from),
- toInfo = _getInfo(to);
+ "enum": function () {
+ for (var i in pattern) {
+ if (obj === pattern[i]) {
+ return true;
+ }
+ }
- fromEntry.fullPath = to;
- fromEntry.name = toInfo.name;
+ return false;
+ },
- _set(to, fromEntry);
- _delete(from);
- _save();
- success();
- }
- catch (e) {
- e.code = 1;
- error(e);
- }
- },
- touch: function (path, success, error) {
- var entry = _get(path),
- info = _getInfo(path);
+ "float": function () {
+ return (typeOfObj === "Number");
+ },
- if (!entry) {
- _set(path, {
- lastModifiedDate: new Date(),
- name: info.name,
- isDirectory: false,
- fullPath: path,
- data: ""
- });
- entry = _get(path);
- }
- _save();
- success(entry);
- },
- cp: function (from, to, success, error) {
- try {
- var fromEntry = _get(from),
- copied = utils.copy(fromEntry);
+ "long": function () {
+ return (obj === toInt32(obj));
+ },
- copied.name = _getInfo(to).name;
- copied.fullPath = to;
- _set(to, copied);
- _save();
- success();
- }
- catch (e) {
- e.code = 1;
- error(e);
- }
- },
- stat: function (path, success, error) {
- var entry = _get(path);
-
- if (entry) {
- success(entry);
- } else {
- error({code: 1});
- }
- },
- write: function (path, contents, success, error, options) {
- var entry = _get(path);
+ "long long": function () {
+ return (obj === toInt64(obj));
+ },
- if (entry) {
- entry.lastModifiedDate = new Date();
- entry.data = contents;
- _save();
- success();
- } else {
- error({code: 1});
- }
+ "octet": function () {
+ return (obj === toUInt8(obj));
+ },
- },
- read: function (path, success, error) {
- var entry = _get(path);
+ "short": function () {
+ return (obj === toInt16(obj));
+ },
- if (entry) {
- success(utils.copy(entry.data));
- }
- else {
- error({code: 1});
- }
- }
-};
+ "unsigned long": function () {
+ return (obj === toUInt32(obj));
+ },
-module.exports = _self;
+ "unsigned long long": function () {
+ return (obj === toUInt64(obj));
+ },
+ "unsigned short": function () {
+ return (obj === toUInt16(obj));
+ },
-});
-define('ripple/platform/wac/2.0/deviceapierror', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+ "Arguments": function () {
+ return true;
+ },
-var errorcode = require('ripple/platform/wac/2.0/errorcode');
+ "": function () {
+ return _self(t[pattern]).match(obj);
+ }
+ };
-module.exports = function (code) {
- for (var c in errorcode) {
- var g = errorcode.__lookupGetter__(c);
- if (g) {
- this.__defineGetter__(c, g);
- }
+ return typeMap[typeOfPattern]();
}
- this.code = code;
- this.message = errorcode.message[code];
- this.type = "";
-
- this.toString = function () {
- var result = this.type + ': "' + this.message + '"';
+ typeOfPattern = getType(pattern, true);
- if (this.stack) {
- result += "\n" + this.stack;
- }
- return result;
+ typeCoerce = {
+ cast: cast,
+ copy: copy,
+ match: match
};
+
+ return typeCoerce;
};
+module.exports = _self;
});
-define('ripple/platform/wac/2.0/deviceapis', function (require, exports, module) {
+define('ripple/platform/ivi/3.0/typecast', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2013 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var platform = require('ripple/platform'),
- app = require('ripple/app'),
- utils = require('ripple/utils'),
- init_done = false,
- _activatedSet = {},
- _activatedFeatures = [],
- _availableSet = {},
- _availableFeatures = [],
- _features = {},
- initFeaturesSet,
- populateFeatures;
+var typedef = require('ripple/platform/ivi/3.0/typedef'),
+ errorcode = require('ripple/platform/ivi/3.0/errorcode'),
+ WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
+ TypeCoerce = require('ripple/platform/ivi/3.0/typecoerce'),
+ _self = {};
-populateFeatures = function (objects) {
- utils.forEach(objects, function (obj, key) {
- var objFeatures = {}, rpt, i, j;
- if (obj.feature) {
- objFeatures = obj.feature.split('|');
- utils.forEach(objFeatures, function (feature) {
- var avail = {uri: feature,
- required: false,
- param: null};
- _availableSet[feature] = avail;
- });
- if (_features) {
- rpt = objFeatures.length;
- j = 0;
- for (i = 0; i < rpt; i++) {
- if (!_features[objFeatures[j]]) {
- objFeatures.splice(j, 1);
- } else {
- j++;
- }
- }
- }
- utils.forEach(objFeatures, function (feature) {
- var avail = {uri: feature,
- required: true,
- param: null};
- _activatedSet[feature] = avail;
- });
- }
- if (obj.children) {
- populateFeatures(obj.children);
- }
- });
-};
+function _cast(pattern, obj, isDuplicate) {
+ var tc, tcFunc;
-initFeaturesSet = function () {
- _features = utils.copy(app.getInfo().features);
- populateFeatures(platform.current().objects);
- utils.forEach(_activatedSet, function (obj, key) {
- _activatedFeatures.push(obj);
- });
- utils.forEach(_availableSet, function (obj, key) {
- _availableFeatures.push(obj);
- });
- init_done = true;
-};
+ if (pattern === null)
+ return;
-module.exports = {
- listAvailableFeatures: function () {
- if (!init_done)
- initFeaturesSet();
- return _availableFeatures;
- },
+ tc = new TypeCoerce(pattern);
+ tcFunc = isDuplicate ? tc.copy : tc.cast;
- listActivatedFeatures: function () {
- if (!init_done)
- initFeaturesSet();
- return _activatedFeatures;
+ if ((obj = tcFunc(obj)) === null) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
}
-};
+ return obj;
+}
-});
-define('ripple/platform/wac/2.0/deviceinteraction', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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 _castType(pattern) {
+ /*
+ * Type cast for each known type. The function name is the exact name of the
+ * corresponding type.
+ *
+ * obj
+ * Variable to be casted
+ *
+ * aux
+ * Auxiliary descriptor of obj. It can be any one or combination of below
+ * strings, or ignored in most cases.
+ *
+ * "?" Nullable types
+ * "[]" Array
+ * "+" Deep copy
+ *
+ * Return
+ * Casted or duplicated object.
+ */
-var notifications = require('ripple/notifications'),
- constants = require('ripple/constants'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- utils = require('ripple/utils'),
- event = require('ripple/event'),
- deviceSettings = require('ripple/deviceSettings'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- _self,
- NOTIFY_DURATION_LIMIT = 5000;
+ return function (obj, aux) {
+ var type, isNullable, isDuplicate;
-function pendingOperation(f) {
- var _FAKEWAITTIME = 0,
- pendingObj;
-
- if (_FAKEWAITTIME === 0) {
- f();
- return undefined;
- }
- else {
- pendingObj = new PendingObject();
- pendingObj.pendingID = setTimeout(function () {
- pendingObj.setCancelFlag(false);
- f();
- }, _FAKEWAITTIME);
- return new PendingOperation(pendingObj);
- }
-}
+ aux = aux ? String(aux) : "";
+ type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
+ isNullable = (aux.indexOf("?") !== -1);
+ isDuplicate = (aux.indexOf("+") !== -1);
-function checkDuration(duration) {
- if (duration) {
- duration = duration | 0;
- if (duration <= 0 || duration > NOTIFY_DURATION_LIMIT) {
- return NOTIFY_DURATION_LIMIT;
- } else {
- return duration;
+ if (isNullable && ((obj === null) || (obj === undefined))) {
+ return obj;
}
- } else {
- return NOTIFY_DURATION_LIMIT;
- }
-}
-function isMute() {
- return deviceSettings.retrieve("Config.soundVolume") <= 0;
-}
-
-function isInVibrateMode() {
- return deviceSettings.retrieve("Config.vibratingMode");
+ return _cast(type, obj, isDuplicate);
+ };
}
-function isBacklightOn() {
- return deviceSettings.retrieve("Config.backlight");
-}
+function _castConstructor(name) {
+ var constructors, hook, vtc, isOverloaded, castConstructor;
-var vibrator = (function () {
- var isVibrating = false,
- terminateAfterPattern = false,
- pattern = null,
- pulseIndex = 0,
- vibrateTimeout = null,
- terminateTimeout = null,
- MILLILSECONDS_OF_ONE_VIBRATION = 100,
- node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
- movementIndex = 0,
- movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
- {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];
+ /*
+ * Type cast for constructor. The function name is the exact name of the
+ * object type.
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ */
- function _clearTimeout() {
- if (vibrateTimeout) {
- clearInterval(vibrateTimeout);
- vibrateTimeout = null;
- }
- if (terminateTimeout) {
- clearTimeout(terminateTimeout);
- terminateTimeout = null;
- }
- }
-
- function stopVibrate() {
- isVibrating = false;
- _clearTimeout();
- node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
- }
-
- function vibrate() {
- //node.animate(movement[movementIndex], MILLILSECONDS_OF_ONE_VIBRATION);
- node.css(movement[movementIndex]);
- movementIndex = (movementIndex + 1) % 8;
- }
-
- function changePulse() {
- //pattern != null
- var pulse = pattern[pulseIndex];
- if (pulse === '.') vibrate();
- ++pulseIndex;
- if (pulseIndex >= pattern.length) {
- if (terminateAfterPattern) {
- setTimeout(stopVibrate, 1);
- return;
- }
- pulseIndex = 0;
- }
- }
-
- function terminateVibrate() {
- terminateAfterPattern = true;
- terminateTimeout = null;
- if (pattern === null) {
- stopVibrate();
- }
- }
-
- function startVibrate(duration, _pattern) {
- if (!isInVibrateMode()) return;
- _clearTimeout();
- terminateAfterPattern = false;
- movementIndex = 0;
-
- if (_pattern) {
- pattern = _pattern;
- pulseIndex = 0;
- vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
- if (duration)
- terminateAfterPattern = false;
- else
- terminateAfterPattern = true;
- } else {
- pattern = null;
- vibrateTimeout = setInterval(vibrate, MILLILSECONDS_OF_ONE_VIBRATION);
- }
- terminateTimeout = setTimeout(terminateVibrate, checkDuration(duration));
- isVibrating = true;
+ function castUnique(argv) {
+ _cast(constructors, argv, false);
}
- event.on("VibratingModeChanged", function (value) {
- if (value === false) {
- stopVibrate();
- }
- });
+ /*
+ * Type cast for overloaded constructors. The function name is the exact
+ * name of the object type.
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ *
+ * scope
+ * 'this' of the original constructor.
+ *
+ * voc
+ * Array of overloaded constructors callback
+ */
- return {
- startVibrate: startVibrate,
- stopVibrate: stopVibrate
- };
-}()); //jslint style
+ function castOverload(argv, scope, voc) {
+ var iOverload;
-var backlight = (function () {
- var timeout = null,
- isNotifying = false,
- node = jQuery("#" + constants.COMMON.VIEWPORT_CONTAINER);
-
- function _clearTimeout() {
- if (timeout) {
- clearTimeout(timeout);
- timeout = null;
+ if (!vtc) {
+ vtc = [];
+ constructors.forEach(function (c) {
+ vtc.push((c === null) ? null : new TypeCoerce(c));
+ });
}
- }
-
- function _switch(on) {
- node.css('opacity', on ? '':'0.4');
- }
-
- function switchOff() {
- if (!isNotifying) return;
- _clearTimeout();
- _switch(false);
- isNotifying = false;
- }
-
- function switchOn(duration) {
- if (isBacklightOn()) return;
- _clearTimeout();
- _switch(true);
- timeout = setTimeout(switchOff, checkDuration(duration));
- isNotifying = true;
- }
- _switch(isBacklightOn());
- event.on("BacklightChanged", function (value) {
- _clearTimeout();
- isNotifying = false;
- _switch(value);
- });
+ vtc.some(function (tc, index) {
+ if (tc && (tc.cast(argv) === null))
+ return false;
- return {
- switchOn : switchOn,
- switchOff : switchOff
- };
-}()); //jslint style
+ iOverload = index;
+ return true;
+ });
-var beeper = (function () {
- var isBeeping = false,
- timeout = null,
- beepFile = "beep.wav", //TODO: license issues
- errorHandler = null,
- _beeper = utils.createElement("audio", {"id": "notify-beeper"});
-
- document.getElementById("ui").appendChild(_beeper);
- _beeper.setAttribute("src", beepFile);
- _beeper.setAttribute("loop", "true");
- _beeper.load();
-
- function _clearTimeout() {
- if (timeout) {
- clearTimeout(timeout);
- timeout = false;
+ if (iOverload === undefined) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
}
+
+ return (voc && voc[iOverload].apply(scope, argv));
}
-
- function raiseError() {
- if (errorHandler) {
- setTimeout(function () {
- errorHandler(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }, 1);
- }
+
+ constructors = typedef.constructor[name];
+
+ if (name in _self) {
+ hook = _self[name];
}
-
- function stopBeep() {
- _clearTimeout();
- if (isBeeping) {
- try {
- _beeper.pause();
- } catch (e) {}
- isBeeping = false;
+
+ isOverloaded = (Object.prototype.toString.call(constructors) ===
+ "[object Array]");
+ castConstructor = isOverloaded ? castOverload : castUnique;
+
+ return function (argv, scope) {
+ if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
+ return (hook && hook.apply(this, arguments));
}
- }
-
- _beeper.addEventListener('error', function () {
- stopBeep();
- raiseError();
- });
-
- function startBeep(onSuccess, onError, duration) {
- errorHandler = onError;
- try {
- stopBeep();
- _beeper.currentTime = 0;
- _beeper.play();
- isBeeping = true;
- timeout = setTimeout(stopBeep, checkDuration(duration));
- setTimeout(function () {
- onSuccess();
- }, 1);
- }catch (e) {
- raiseError();
+
+ if (!(scope instanceof argv.callee)) {
+ throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
}
- }
-
- event.on("VolumeChanged", function (value) {
- value = value | 0;
- if (value < 0) value = 0;
- else if (value > 100) value = 100;
- _beeper.volume = value / 100.0;
- });
-
- return {
- startBeep : startBeep,
- stopBeep : stopBeep
+
+ castConstructor.apply(this, arguments);
};
-}()); //jslint style
+}
+
+function _castInterface(name) {
+ var interface, hook;
+
+ interface = typedef.interface[name];
+
+ if (name in _self) {
+ hook = _self[name];
+ }
+
+ /*
+ * Type cast for each known method of interface. The function name is the
+ * exact name of the corresponding interface.
+ *
+ * method
+ * String of method name
+ *
+ * argv
+ * arguments. The keyword 'arguments' will always be passed in.
+ *
+ * isDuplicate
+ * A boolean value to indicate whether arguments will be copied or not.
+ */
+
+ return function (method, argv, isDuplicate) {
+ if ((typeof method !== "string") || (typeof argv !== "object")) {
+ return (hook && hook.apply(this, arguments));
+ }
-module.exports = _self = {
+ _cast(interface[method], argv, isDuplicate);
+ };
+}
- startNotify : function (onSuccess, onError, duration) {
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "startNotify", function () {
- if (!isMute()) {
- return pendingOperation(function () {
- beeper.startBeep(onSuccess, onError, duration);
- });
- } else if (isInVibrateMode()) {
- return _self.startVibrate(onSuccess, onError, duration);
- } else {
- return _self.lightOn(onSuccess, onError, duration);
- }
- });
- },
+(function () {
+ var i;
- stopNotify : function () {
- beeper.stopBeep();
- vibrator.stopVibrate();
- backlight.switchOff();
- },
+ for (i in typedef) {
+ _self[i] = _castType(typedef[i]);
+ }
- startVibrate : function (onSuccess, onError, duration, pattern) {
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "startVibrate", function () {
- if (pattern) {
- pattern = String(pattern);
- if (!pattern.match(/[\._]{1,10}/)) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- }
-
- if (!isInVibrateMode()) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }, 1);
- }
- return undefined;
- }
-
- setTimeout(function () {
- onSuccess();
- }, 1);
- return pendingOperation(function () {
- vibrator.startVibrate(duration, pattern);
- });
+ for (i in typedef.constructor) {
+ _self[i] = _castConstructor(i);
+ typedef[i]._constructor = i;
+ }
- });
- },
-
- stopVibrate : function () {
- vibrator.stopVibrate();
- },
+ for (i in typedef.interface) {
+ _self[i] = _castInterface(i);
+ }
+}());
- lightOn : function (onSuccess, onError, duration) {
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "lightOn", function () {
- if (isBacklightOn()) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
- }, 1);
- }
- return undefined;
- }
-
- setTimeout(function () {
- onSuccess();
- }, 1);
- return pendingOperation(function () {
- backlight.switchOn(duration);
- });
- });
- },
+module.exports = _self;
- lightOff : function () {
- backlight.switchOff();
- },
+});
+define('ripple/platform/spec', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ //"phonegap": {"1.0.0": require('ripple/platform/phonegap/1.0.0/spec')},
+ "tizen": {"2.0": require('ripple/platform/tizen/2.0/spec')},
+ "ivi": {"3.0": require('ripple/platform/ivi/3.0/spec')},
+ //"cordova": {"2.0.0": require('ripple/platform/cordova/2.0.0/spec')},
+ //"webworks.bb10": {"1.0.0": require('ripple/platform/webworks.bb10/1.0.0/spec')},
+ //"webworks.handset": {"2.0.0": require('ripple/platform/webworks.handset/2.0.0/spec')},
+ //"webworks.tablet": {"2.0.0": require('ripple/platform/webworks.tablet/2.0.0/spec')},
+ //"web": {"default": require('ripple/platform/web/default/spec')},
- setWallpaper : function (onSuccess, onError, fileName) {
- //TODO: file name, existance, extension checking.
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "setWallpaper", function () {
- return pendingOperation(function () {
- notifications.openNotification("normal", "setWallpaper:" + fileName);
- setTimeout(function () {
- onSuccess();
- }, 1);
- });
- });
+ "get": function (name, version) {
+ var platform = module.exports[name] || {};
+ return (platform[version] || platform[Object.keys(platform)[0]]);
}
};
-
});
-define('ripple/platform/wac/2.0/devicestatus', function (require, exports, module) {
+define('ripple/platform/builder', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
*/
var utils = require('ripple/utils'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- _console = require('ripple/console'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- deviceSettings = require('ripple/deviceSettings'),
- event = require('ripple/event'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- _getDeviceInfoAspect = true,
- _getNetworkInfoAspect = true,
- _deviceInfoAspect = ["Battery", "Device", "Display", "MemoryUnit", "OperatingSystem", "WebRuntime"],
- _networkInfoAspect = ["CellularHardware", "CellularNetwork", "WiFiHardware", "WiFiNetwork"],
- _aspectArray = [],
- _propertyMap = {},
- _watches = {},
- _self;
-
-function _asynchErrorCallback(errorCallback, errorCode) {
- if (errorCallback) {
- setTimeout(function () {
- errorCallback(errorCode);
- }, 1);
- }
-}
+ app = require('ripple/app');
-function _initialize() {
- var aspectName, index, i;
+function _objectFactory(context, objects/*, allowed*/) {
+ utils.forEach(objects, function (obj, key) {
+ var result = {}, objFeatures = {}, rst, f, widgetFeatures;
- _aspectArray = _deviceInfoAspect.concat(_networkInfoAspect);
- for (index = 0; index < _aspectArray.length; index++) {
- aspectName = _aspectArray[index];
- _propertyMap[aspectName] = [];
- for (i in deviceSettings.retrieve(aspectName)) {
- _propertyMap[aspectName].push(i);
+// if (allowed(obj)) {
+ result = obj.path ? require('ripple/platform/' + obj.path) : {};
+ if (typeof result === "function" && obj.handleSubfeatures && obj.handleSubfeatures === true) {
+ rst = new result();
+ if (obj.feature) {
+ objFeatures = obj.feature.split('|');
+ if (rst.handleSubFeatures) {
+ widgetFeatures = app.getInfo().features; // features in config.xml
+ f = {};
+ utils.forEach(objFeatures, function (o) {
+ if (widgetFeatures && !!widgetFeatures[o]) {
+ f[widgetFeatures[o].id] = widgetFeatures[o];
+ }
+ });
+ rst.handleSubFeatures(f);
+ delete rst.handleSubFeatures;
+ }
+ }
+ result = rst;
}
- }
-}
-
-function _isPropertyFound(aspect, property) {
- if (_aspectArray.length === 0) {
- _initialize();
- }
+// }
- if (_propertyMap[aspect]) {
- if (property) {
- return _propertyMap[aspect].some(function (prop) {
- return prop === property;
- });
+ if (obj.children) {
+ _objectFactory(result, obj.children/*, allowed*/);
}
- return true;
- }
- return false;
-}
-
-function _isPropertyAllowed(aspect) {
- function hasAspect(asp) {
- return asp === aspect;
- }
-
- if ((_deviceInfoAspect.some(hasAspect) && _getDeviceInfoAspect === false) ||
- (_networkInfoAspect.some(hasAspect) && _getNetworkInfoAspect === false)) {
- return false;
- }
- return true;
+ context.__defineGetter__(key, function () {
+ return result;
+ });
+ // inject into the context if it is allowed or it has children that were allowed
+// if (allowed(obj) || utils.count(result)) {
+// context[key] = result;
+// }
+// else {
+// if (context.hasOwnProperty(key))
+// console.log("delete " + key);
+// delete context[key];
+// }
+ });
}
-function _isPropertyValid(prop, errorCallback) {
- var _prop = Object(prop);
+module.exports = {
+ build: function (objects) {
+ return {
+ into: function (sandbox) {
+/* var features = utils.copy(app.getInfo().features);
+ allowed = function (obj) {
+ var contains = function (requirements) {
+ return requirements.split('|').some(function (feature) {
+ return !!features[feature];
+ });
+ };
+ //object is allowed if:
+ // 1. it has no feature requirement
+ // 2. the config file doesn't exist (features collection is null)
+ // 3. the feature exists in the defined features
+ return !obj.feature || !features || (features && contains(obj.feature));
+ };
+*/
- if (_prop && _prop.aspect && _prop.property) {
- if (_isPropertyFound(_prop.aspect, _prop.property) === false) {
- _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_FOUND_ERR));
- return false;
- }
- else if (_isPropertyAllowed(_prop.aspect) === false) {
- _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.SECURITY_ERR));
- return false;
- }
- }
- else {
- _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- return false;
+ _objectFactory(sandbox, objects/*, allowed*/);
+ }
+ };
}
- return true;
-}
-
-module.exports = function () {
- return {
- getComponents: function (aspect) {
- if (_isPropertyFound(aspect))
- return ["_default"];
- return null;
- },
-
- isSupported: function (aspect, property) {
- return _isPropertyFound(aspect, property);
- },
-
- getPropertyValue: function (successCallback, errorCallback, prop) {
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getPropertyValue", function () {
- if (_isPropertyValid(prop, errorCallback) !== true)
- return undefined;
-
- var value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
- if (value !== undefined) {
- successCallback(value, prop);
- }
- else {
- _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_AVAILABLE_ERR));
- }
-
- return null;
- });
- },
-
- watchPropertyChange: function (successCallback, errorCallback, prop, options) {
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "watchPropertyChange", function () {
- if (_isPropertyValid(prop, errorCallback) !== true)
- return undefined;
-
- var _options = Object(options),
- eventType = deviceSettings.retrieve(prop.aspect)[prop.property].event,
- watchObj = {
- eventType: eventType,
- onEvent: function (newValue) {
- if (watchObj.timeStamp &&
- ((new Date()).getTime() - watchObj.timeStamp < options.minNotificationInterval)) {
- return undefined;
- }
- else if (watchObj.value &&
- (newValue > watchObj.value * (1 - _options.minChangePercent) &&
- newValue < watchObj.value * (1 + _options.minChangePercent))) {
- return undefined;
- }
-
- if (watchObj.intervalId) {
- clearInterval(watchObj.intervalId);
- watchObj.intervalId = setInterval(function () {
- successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
- }, _options.maxNotificationInterval);
- }
- successCallback(newValue, prop);
- if (watchObj.timeStamp) {
- watchObj.timeStamp = (new Date()).getTime();
- }
- if (watchObj.value) {
- watchObj.value = newValue;
- }
- }
- },
- watchId = (new Date()).getTime() | 0;
+};
- if (options && _options.minNotificationInterval && _options.maxNotificationInterval &&
- (_options.minNotificationInterval < 0 || _options.maxNotificationInterval < 0 ||
- _options.minNotificationInterval >= _options.maxNotificationInterval)) {
- _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- return undefined;
- }
+});
+define('ripple/platform/w3c/1.0/Rotation', function (require, exports, module) {
+module.exports = function (alpha, beta, gamma) {
+ return {
+ alpha: alpha || 0, //Rotation about the 'z' axis expressed in degrees [0, 360]. (Number)
+ beta: beta || 0, //Rotation about the 'x' axis expressed in degrees [-180, 180]. (Number)
+ gamma: gamma || 0 //Rotation about the 'y' axis expressed in degrees [-90, 90]. (Number)
+ };
+};
- if (options && _options.maxNotificationInterval) {
- watchObj.intervalId = setInterval(function () {
- successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
- }, _options.maxNotificationInterval);
- }
+});
+define('ripple/platform/w3c/1.0/navigator', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _original = window.navigator,
+ utils = require('ripple/utils'),
+ devices = require('ripple/devices'),
+ constants = require('ripple/constants'),
+ _self = {};
- if (options && _options.minNotificationInterval) {
- watchObj.timeStamp = (new Date()).getTime();
- }
+(function () {
+ var key,
+ nav = window.navigator;
- if (options && _options.minChangePercent) {
- if (_options.minNotificationInterval || _options.maxNotificationInterval) {}
- else {
- watchObj.value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
- }
- }
-
- _watches[watchId] = watchObj;
- if (watchObj.eventType) {
- event.on(watchObj.eventType, watchObj.onEvent);
- }
+ function _handle(obj, key) {
+ return typeof obj[key] !== "function" ? obj[key] : function () {
+ return obj[key].apply(obj, Array.prototype.slice.call(arguments));
+ };
+ }
- return watchId;
- });
- },
+ for (key in nav) {
+ _self[key] = _handle(nav, key);
+ }
+}());
- clearPropertyChange: function (watchHandler) {
- var _handler = watchHandler | 0;
-
- if (_watches[_handler]) {
- event.deleteEventHandler(_watches[_handler].eventType, _watches[_handler].onEvent);
- if (_watches[_handler].intervalId) {
- clearInterval(_watches[_handler].intervalId);
- }
- delete(_watches[_handler]);
- }
- return null;
- },
+_self.__defineGetter__('userAgent', function () {
+ var currentUserAgent = devices.getCurrentDevice().userAgent;
- handleSubFeatures: function (subFeatures) {
- if (wac2_utils.isEmptyObject(subFeatures) ||
- subFeatures["http://wacapps.net/api/devicestatus"] ||
- (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"] &&
- subFeatures["http://wacapps.net/api/devicestatus.networkinfo"])) {
- return;
- }
- if (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"]) {
- _getNetworkInfoAspect = false;
- return;
- }
- if (subFeatures["http://wacapps.net/api/devicestatus.networkinfo"]) {
- _getDeviceInfoAspect = false;
- return;
- }
- _console.warn("WAC-2.0-Devicestatus-handleSubFeatures: something wrong");
- }
- };
-};
+ return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
+ _original.userAgent : currentUserAgent;
+});
+module.exports = _self;
});
-define('ripple/platform/wac/2.0/errorcode', function (require, exports, module) {
+define('ripple/platform/w3c/1.0/SensorConnection', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2012 Intel Corporation.
*
- * Licensed under the Apache License, Version 2.0 (the "License"),
+ * 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
*
* limitations under the License.
*/
-var _self = {
- message : []
-};
+var utils = require('ripple/utils'),
+ platform = require('ripple/platform'),
+ event = require('ripple/event'),
+ sensorSettings = require('ripple/sensorSettings'),
+ accelerometer = require('ripple/accelerometer'),
+ exception = require('ripple/exception'),
-_self.__defineGetter__("UNKNOWN_ERR", function () {
- return 0;
-});
+ _permission = true,
+ _self;
-_self.__defineGetter__("INDEX_SIZE_ERR", function () {
- return 1;
-});
+function ErrorMsg() {
+ this.__defineGetter__("UNKNOWN_ERROR", function () {
+ return "An unknown error has occurred.";
+ });
-_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
- return 2;
-});
+ this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
+ return "The object type is incompatible with the expected type.";
+ });
-_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
- return 3;
-});
+ this.__defineGetter__("INVALID_VALUES_ERROR", function () {
+ return "The content of an object does not contain valid values.";
+ });
-_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
- return 4;
-});
+ this.__defineGetter__("ILLEGAL_STATE", function () {
+ return "The status of connection is illegal.";
+ });
+}
-_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
- return 5;
-});
+// TODO: Should be replaced by a global object in tizen 1.0
+function ErrorCode() {
+ this.__defineGetter__("UNKNOWN_ERR", function () {
+ return 0;
+ });
-_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
- return 6;
-});
+ this.__defineGetter__("INVALID_VALUES_ERROR", function () {
+ return 1;
+ });
-_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
- return 7;
-});
+ this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
+ return 2;
+ });
-_self.__defineGetter__("NOT_FOUND_ERR", function () {
- return 8;
-});
+ this.__defineGetter__("ILLEGAL_STATE", function () {
+ return 3;
+ });
+}
-_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
- return 9;
-});
+function SensorError(code, msg) {
+ this.__defineGetter__("message", function () {
+ return msg;
+ });
+ this.__defineGetter__("code", function () {
+ return code;
+ });
-_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
- return 10;
-});
+ this.PERMISSION_DENIED = -100;
+}
-_self.__defineGetter__("INVALID_STATE_ERR", function () {
- return 11;
-});
+function Event() {
+ var _self = {
+ CAPTURING_PHASE: 1,
+ AT_TARGET: 2,
+ BUBBLING_PHASE: 3,
-_self.__defineGetter__("SYNTAX_ERR", function () {
- return 12;
-});
+ type: '',
+ target: null, //new EventTarget(),
+ currentTarget: null, //new EventTarget(),
+ eventPhase: 0,
+ bubbles: false,
+ cancelable: false,
+ timeStamp: 0
+ };
+
+ this.__defineGetter__("type", function () {
+ return _self.type;
+ });
-_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
- return 13;
-});
+ this.__defineGetter__("target", function () {
+ return _self.target;
+ });
-_self.__defineGetter__("NAMESPACE_ERR", function () {
- return 14;
-});
+ this.__defineGetter__("currentTarget", function () {
+ return _self.currentTarget;
+ });
-_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
- return 15;
-});
+ this.__defineGetter__("eventPhase", function () {
+ return _self.eventPhase;
+ });
-_self.__defineGetter__("VALIDATION_ERR", function () {
- return 16;
-});
+ this.__defineGetter__("bubbles", function () {
+ return _self.bubbles;
+ });
-_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
- return 17;
-});
+ this.__defineGetter__("cancelable", function () {
+ return _self.cancelable;
+ });
+
+ this.__defineGetter__("timeStamp", function () {
+ return _self.timeStamp;
+ });
-_self.__defineGetter__("SECURITY_ERR", function () {
- return 18;
-});
+ this.stopPropagation = function () {};
-_self.__defineGetter__("NETWORK_ERR", function () {
- return 19;
-});
+ this.preventDefault = function () {};
-_self.__defineGetter__("ABORT_ERR", function () {
- return 20;
-});
+ this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
+ _self.type = eventTypeArg;
+ _self.bubbles = canBubbleArg;
+ _self.cancelable = cancelableArg;
+ };
-_self.__defineGetter__("TIMEOUT_ERR", function () {
- return 21;
-});
+ return _self;
+}
-_self.__defineGetter__("INVALID_VALUES_ERR", function () {
- return 22;
-});
+function SensorDataEvent() {
+ var _self = {
+ data: 0,
+ accuracy: 0,
+ timestamp: 0,
+ reason: ''
+ };
-_self.__defineGetter__("IO_ERR", function () {
- return 100;
-});
+ // This type of event inherit from Event
+ Event.call(this);
-_self.__defineGetter__("NOT_AVAILABLE_ERR", function () {
- return 101;
-});
+ this.__defineGetter__("data", function () {
+ return _self.data;
+ });
-function _setMessage(_self) {
- var c, g;
- for (c in _self) {
- g = _self.__lookupGetter__(c);
- if (g) {
- _self.message[g()] = c;
+ this.__defineGetter__("accuracy", function () {
+ return _self.accuracy;
+ });
+
+ this.__defineGetter__("timestamp", function () {
+ return _self.timestamp;
+ });
+
+ this.__defineGetter__("reason", function () {
+ return _self.reason;
+ });
+
+ this.initSensorDataEvent = function (type, bubbles, cancelable, reason, timestamp, accuracy, data) {
+ this.initEvent(type, bubbles, cancelable);
+
+ _self.reason = reason;
+ _self.timestamp = timestamp;
+ _self.accuracy = accuracy;
+
+ // If the data has only one part, just return the value, not the data object
+ if (utils.count(data) === 1) {
+ utils.forEach(data, function (section, key) {
+ _self.data = data[key];
+ });
}
- }
+ else {
+ _self.data = utils.copy(data);
+ }
+ };
}
-_setMessage(_self);
+// As only one sensor will be used during the simulation with a SensorConnection object,
+// we can get that sensor object first and then the following read or write operations will be simplified
+function _getSensorObj(type, name) {
+ var settings = platform.current().sensor, _sensor;
-module.exports = _self;
+ utils.forEach(settings, function (settingSection, settingType) {
+ if (settingSection.type === type) {
+ if (settingSection.name && settingSection.name !== name) {
+ return;
+ }
-});
-define('ripple/platform/wac/2.0/filesystem', function (require, exports, module) {
-/*
- * Copyright 2011 Intel Corporation.
- *
- * 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.
- */
+ _sensor = utils.copy(settingSection);
+ }
+ });
-var errorcode = require('ripple/platform/wac/2.0/errorcode'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- utils = require('ripple/utils'),
- dbfs = require('ripple/platform/wac/2.0/dbfs'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- _console = require('ripple/console'),
- _maxPathLength = 256,
- _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
- _realRoots = dbfs.roots,
- _r2vmap = {},
- _v2rmap = {},
- _initialized = false,
- _readOnly = false,
- _writeOnly = false,
- _defaultMode = "rw",
- File,
- FileStream;
+ return _sensor;
+}
-function _isValidChar(c) {
- return (c >= '0' && c <= '9') ||
- (c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z') ||
- (c === ' ') ||
- (c === '_') ||
- (c === '-') ||
- (c === '.');
+function _getAccelerometerData(dataType) {
+ var accelerometerData, data = {};
+
+ switch (dataType) {
+ case "Accelerometer":
+ accelerometerData = accelerometer.getInfo();
+ data = {
+ x: accelerometerData.acceleration.x,
+ y: accelerometerData.acceleration.y,
+ z: accelerometerData.acceleration.z
+ };
+ break;
+ case "Rotation":
+ accelerometerData = accelerometer.getInfo();
+ data = {
+ x: accelerometerData.orientation.alpha,
+ y: accelerometerData.orientation.beta,
+ z: accelerometerData.orientation.gamma
+ };
+ break;
+ case "Orientation":
+ accelerometerData = accelerometer.getInfo();
+ data = {
+ alpha: accelerometerData.orientation.alpha,
+ beta: accelerometerData.orientation.beta,
+ gamma: accelerometerData.orientation.gamma
+ };
+ break;
+ default:
+ break;
+ }
+
+ return data;
}
-function _isValidFileName(name) {
- var _valid = true,
- _c;
+// The parameter of event callback is an object that contains the latest value, not the value itself,
+// so we need a function to create such object.
+function _getSensorData(sensorType, sensor, onerror) {
+ var data = {}, value;
- if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
- _valid = false;
- } else {
- for (_c = 0; _c < name.length; _c++) {
- if (!_isValidChar(name[_c])) {
- _valid = false;
- break;
+ if (sensorType === "Accelerometer" || sensorType === "Rotation" || sensorType === "Orientation") {
+ return _getAccelerometerData(sensorType);
+ }
+
+ utils.forEach(sensor, function (sensorSection, key) {
+ try {
+ value = sensorSettings.retrieve(sensorType + "." + key);
+ }
+ catch (e) {
+ if (onerror) {
+ onerror(e);
}
}
- }
+
+ if (value) {
+ data[key] = value;
+ }
+ });
- return _valid;
+ return data;
}
-function _initialize() {
- var _i;
+// As the event type in sensor.js file are named in this way, so we can get it with this function.
+function _getSensorEventTypes(type, sensor) {
+ var types = [];
- dbfs.initialize();
-
- // set up the map between real path and virtual path
- for (_i = 0; _i < _virtualRoots.length; _i++) {
- _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
+ if (type === "Accelerometer" || type === "Rotation" || type === "Orientation") {
+ return ["AccelerometerInfoChangedEvent"];
}
- utils.forEach(_r2vmap, function (value, key) {
- _v2rmap[value] = key;
+ utils.forEach(sensor, function (sensorSection, sensorType) {
+ if (typeof sensorSection === "object") {
+ types.push(type + "-" + sensorType + "Changed");
+ }
});
+
+ return types;
}
-function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
- var _parts = srcLocation.replace(/\/$/, '').split("/"),
- _header, _fullPath,
- _i;
+function _onEventCallback(type, options, currentSensor, length, eventCallback, onerror) {
+ return function (values) {
+ var sensorEvent = new SensorDataEvent();
- // TODO: Initialize at bootstrap and emulatorBridge.link
- if (!_initialized) {
- _initialize();
- _initialized = true;
- }
+ // Only the sensor that has one attribute could be compared with the threshold
+ if (options && options.threshold && length === 1 && values[0] < options.threshold) {
+ return;
+ }
+
+ if (eventCallback) {
+ sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(),
+ currentSensor.resolution, _getSensorData(type, currentSensor, onerror));
+
+ eventCallback(sensorEvent);
+ }
+ };
+}
+
+function _bind(name, obj) {
+ var callback = null;
+
+ obj.__defineGetter__(name, function () {
+ return callback;
+ });
+
+ obj.__defineSetter__(name, function (cb) {
+ callback = cb;
+ });
+
+ return {
+ get: function () {
+ return callback;
+ },
+ set: function (value) {
+ callback = value;
+ },
+ exec: function (arg) {
+ return callback && callback(arg);
+ },
+ unbind: function (cb) {
+ callback = cb === callback ? null : callback;
+ }
+ };
+}
+
+function SensorConnection(type, name) {
+ var _self,
+ currentSensor = _getSensorObj(type, name),
+ sensorEvent = new SensorDataEvent(),
+ sensorEventTypes = _getSensorEventTypes(type, currentSensor),
+ watches = [],
+ _errorCode = new ErrorCode(),
+ _errorMsg = new ErrorMsg(),
+ sensorListener;
+
+ if (currentSensor) {
+ _self = {
+ sensor: {
+ resolution: currentSensor.resolution,
+ minDelay: currentSensor.minDelay,
+ range: currentSensor.range,
+ name: currentSensor.name,
+ type: currentSensor.type
+ },
+ status: "open",
+ error: null,
+ read: function () {
+
+ if (_self.status !== "open" && _self.status !== "watching") {
+ exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
+ return;
+ }
+
+ setTimeout(function () {
+ if (sensorListener.get()) {
+ sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(),
+ currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));
+
+ sensorListener.exec(sensorEvent);
+ }
+ }, 1);
+
+ return;
+ },
+
+ startWatch: function (options) {
+ var index, watchId, watchObj = {};
+
+ if (_self.status !== "open") {
+ exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
+ return;
+ }
+
+ if (typeof options !== "object") {
+ if (_self.onerror) {
+ _self.onerror(new SensorError(_errorCode.TYPE_MISMATCH_ERROR, _errorMsg.TYPE_MISMATCH_ERROR));
+ }
+ }
+
+ setTimeout(function () {
+ watchId = (new Date()).getTime();
+
+ // As there will be many attributes for some sensor, each of them is needed to be watched.
+ for (index = 0; index < sensorEventTypes.length; index++) {
+ watchObj = {
+ eventType: sensorEventTypes[index],
+ onEvent: _onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror),
+ };
+
+ watches.push(watchObj);
+ if (watchObj.eventType) {
+ event.on(watchObj.eventType, watchObj.onEvent);
+ }
+ }
+
+
+ if (options && options.interval) {
+ watchObj.intervalId = setInterval(_onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror),
+ options.interval);
+ }
+
+ _self.status = "watching";
+ if (_self.onstatuschange) {
+ _self.onstatuschange();
+ }
+
+ }, 1);
+
+ return;
+ },
+
+ endWatch: function () {
+ var index, watchObj;
+
+ if (_self.status !== "watching") {
+ exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
+ return;
+ }
+
+ for (index = 0; index < watches.length; index++) {
+ watchObj = watches[index];
+
+ try {
+ event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);
+ }
+ catch (e) {
+ if (_self.onerror) {
+ _self.onerror(e);
+ }
+ }
+
+ if (watchObj.intervalId) {
+ clearInterval(watchObj.intervalId);
+ }
+ }
+
+ watches = [];
+
+ _self.status = "open";
+ if (_self.onstatuschange) {
+ _self.onstatuschange();
+ }
+ },
+
+ // These functions are inherited from the EventTarget object
+ addEventListener: function (eventType, callback, useCapture) {
+ var sensorEvent;
+
+ if (eventType === "sensordata") {
+ sensorListener.set(callback);
+
+ event.on("sensordata", function (data) {
+ sensorEvent = new SensorDataEvent();
+ sensorEvent.initSensorDataEvent("sensordata", false, false, "read", (new Date()).getTime(),
+ currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));
+
+ sensorListener.exec(sensorEvent);
+ });
+ }
+ },
+
+ removeEventListener: function (eventType, callback) {
+ event.clear(eventType, callback);
+ sensorListener.unbind(callback);
+ },
+
+ dispatchEvent: function (evt) {
+ event.trigger("sensordata", evt);
+ }
+ };
+
+ sensorListener = _bind("onsensordata", _self);
+ }
+
+ return _self;
+}
+
+module.exports = function (option) {
+
+ var connectionObj,
+ _errorCode = new ErrorCode(),
+ _errorMsg = new ErrorMsg();
- for (_i = 0; _i < _parts.length; _i++) {
- if (!_isValidFileName(_parts[_i])) {
- if (onError) {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }
- return;
- }
+ if (option === null || option === undefined) {
+ return null;
}
- _header = _v2rmap[_parts[0]];
- if (_header === undefined) {
- if (onError) {
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ // There are two ways to construct an object
+ if (typeof option === "object") {
+ if ((option.type === null || option.type === undefined) &&
+ (option.name === null || option.name === undefined)) {
+ // Spec: If none of the dictionary members are defined then raise an instantiation exception
+ exception.raise(exception.types.Argument, "type illegal", new SensorError(_errorCode.ILLEGAL_TYPE, _errorMsg.ILLEGAL_TYPE));
}
- return;
- }
- if (_parts.length === 1) {
- _fullPath = _header;
- } else {
- _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
+ connectionObj = new SensorConnection(option.type, option.name);
+ }
+ else if (typeof option === "string") {
+ connectionObj = new SensorConnection(option, option);
}
- dbfs.stat(_fullPath,
- function (entry) {
- onSuccess(new File(entry, accessMode));
- },
- function () {
- if (onError) {
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
- }
- });
-}
+ return connectionObj;
+};
-function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
- _resolveSync(srcLocation,
- function (file) {
- setTimeout(function () {
- onSuccess(file);
- }, 1);
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- accessMode);
+});
+define('ripple/platform/w3c/1.0/geolocation', function (require, exports, module) {
+/*
+ * Copyright 2011 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 geo = require('ripple/geo'),
+ Position = require('ripple/platform/w3c/1.0/Position'),
+ PositionError = require('ripple/platform/w3c/1.0/PositionError'),
+ _watches = {},
+ _self;
+
+function createPosition() {
+ var position = new Position(),
+ positionInfo = geo.getPositionInfo();
+
+ position.coords.latitude = positionInfo.latitude;
+ position.coords.longitude = positionInfo.longitude;
+ position.coords.altitude = positionInfo.altitude;
+ position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
+ position.coords.accuracy = positionInfo.accuracy;
+ position.coords.heading = positionInfo.heading;
+ position.coords.speed = positionInfo.speed;
+ position.timestamp = positionInfo.timeStamp.getTime();
+
+ return position;
}
-File = function (entry, mode) {
- var _entry = entry,
- _mode = mode,
- _parent,
- _self;
+_self = {
+ getCurrentPosition: function (onSuccess, onError) {
+ var delay = ((geo.delay || 0) * 1000) || 1,
+ timeout = geo.timeout;
- function _r2v(rpath) {
- var i, v, r, regExp;
+ window.setTimeout(function () {
+ if (timeout) {
+ var error = new PositionError();
+ error.code = PositionError.TIMEOUT;
+ error.message = "postion timed out";
- for (i = 0; i < _virtualRoots.length; i++) {
- v = _virtualRoots[i];
- r = _v2rmap[v];
- if (rpath.match("^" + r)) {
- regExp = new RegExp("^" + r);
- return rpath.replace(regExp, v);
+ onError(error);
}
- }
+ else {
+ // TODO: build facility to trigger onError() from emulator
+ // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
+ _self.lastPosition = createPosition();
+ onSuccess(_self.lastPosition);
+ }
+ }, delay);
+ },
- return "";
- }
+ watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
+ var watchId = (new Date()).getTime().toString(),
+ watchObj = {},
+ timeout;
- function _v2r(vpath) {
- var i, v, r, regExp;
+ if (geolocationOptions) {
+ timeout = geolocationOptions.timeout || 10000;
- for (i = 0; i < _virtualRoots.length; i++) {
- v = _virtualRoots[i];
- r = _v2rmap[v];
- if (vpath.match("^" + v)) {
- regExp = new RegExp("^" + v);
- return vpath.replace(regExp, r);
- }
- }
+ watchObj = {
+ onSuccess: geolocationSuccess,
+ onError: geolocationError,
+ interval: timeout
+ };
- return "";
- }
+ _watches[watchId] = watchObj;
- function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
- var _srcName = String(src),
- _dstName = String(dst),
- _src = null,
- _dst = null,
- _error = false,
- _dstParent = null,
- _dstParts = _dstName.split("/"),
- _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");
+ _watches[watchId].intervalId = window.setInterval(function () {
+ _self.getCurrentPosition(_watches[watchId].onSuccess, _watches[watchId].onError);
+ }, timeout);
- if (!_entry.isDirectory) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
+ }
+ else {
+ if (typeof geolocationError === "function") {
+ window.setTimeout(function () {
+ geolocationError();
}, 1);
}
- return undefined;
}
- _resolveSync(_srcName,
- function (file) {
- _src = file;
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- _mode);
-
- if (_src) {
- if (_src.parent.fullPath === _self.fullPath) {
- if (!_readOnly && _mode !== "r") {
- _resolveSync(_dstParentName,
- function (file) {
- _dstParent = file;
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- _mode);
-
- if (_dstParent === null) {
- return undefined;
- }
+ return watchId;
+ },
- _resolveSync(_dstName,
- function (file) {
- _dst = file;
- },
- function (e) {
- if (e.code !== errorcode.NOT_FOUND_ERR) {
- setTimeout(function () {
- onError(e);
- }, 1);
- _error = true;
- }
- },
- _mode);
+ lastPosition: null,
- if (_error) {
- return undefined;
- }
+ clearWatch: function (watchId) {
+ window.clearInterval(_watches[watchId].intervalId);
+ delete _watches[watchId];
+ }
+};
- if (_src.isFile) {
- if (_dst === null) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
- } else {
- if (_dst === null) {
- func(_v2r(_srcName), _v2r(_dstName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
+module.exports = _self;
- return undefined;
- }
+});
+define('ripple/platform/w3c/1.0/Coordinates', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function (latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed) {
+ return {
+ latitude: latitude || 0, //Latitude in decimal degrees. (Number)
+ longitude: longitude || 0, //Longitude in decimal degrees. (Number)
+ altitude: altitude || 0, //Height of the position in meters above the ellipsoid. (Number)
+ accuracy: accuracy || 0, //Accuracy level of the latitude and longitude coordinates in meters. (Number)
+ altitudeAccuracy: altitudeAccuracy || 0, //Accuracy level of the altitude coordinate in meters. (Number)
+ heading: heading || 0, //Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
+ speed: speed || 0 //Current ground speed of the device, specified in meters per second. (Number)
+ };
+};
- _self = {
- toURI: function () {
- return "file://" + _entry.fullPath;
- },
- listFiles: function (onSuccess, onError, filter) {
- var _filter = Object(filter),
- _filterName = _filter.name,
- _startModified = _filter.startModified,
- _endModified = _filter.endModified;
+});
+define('ripple/platform/w3c/1.0/Position', function (require, exports, module) {
+/*
+ * Copyright 2011 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 Coordinates = require('ripple/platform/w3c/1.0/Coordinates');
- function _matchName(fileName) {
- var _matched = true,
- _name1 = String(_filterName).toLowerCase(),
- _name2 = fileName.toLowerCase(),
- _pattern;
+module.exports = function () {
+ return {
+ coords: new Coordinates(),
+ timestamp: new Date().getTime()
+ };
+};
- if (_filterName !== undefined && _filterName !== null) {
- if (!_name1.match("\\\\%")) {
- if (_name1.match("%")) {
- _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
- _matched = _name2.match(_pattern) ? true : false;
- } else {
- _matched = (_name1 === _name2);
- }
- } else {
- // % is not allowed as a part of file name
- _matched = false;
- }
- }
-
- return _matched;
- }
+});
+define('ripple/platform/w3c/1.0/Acceleration', function (require, exports, module) {
+module.exports = function (x, y, z) {
+ return {
+ x: x || 0, //Acceleration in the 'x' expressed in m/s^2. (Number)
+ y: y || 0, //Acceleration in the 'y' expressed in m/s^2. (Number)
+ z: z || 0 //Acceleration in the 'z' expressed in m/s^2. (Number)
+ };
+};
- function _matchDate(date) {
- var _matched = true;
+});
+define('ripple/platform/w3c/1.0/PositionError', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _self = function () {
+ return {
+ code: undefined,
+ message: undefined
+ };
+};
- if (_startModified !== undefined && _startModified !== null) {
- _matched = (date.getTime() >= _startModified.getTime());
- }
+_self.PERMISSION_DENIED = "PERMISSION_DENIED";
+_self.POSITION_UNAVAILABLE = "POSITION_UNAVAILABLE";
+_self.TIMEOUT = "TIMEOUT";
- if (_matched && (_endModified !== undefined && _endModified !== null)) {
- _matched = (date.getTime() <= _endModified.getTime());
- }
+module.exports = _self;
- return _matched;
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/XMLHttpRequest', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _matchFilter(entry) {
- return _matchName(entry.name) && _matchDate(entry.lastModifiedDate);
- }
+var xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
+module.exports = xhr.create("ripple/platform/webworks.tablet/2.0.0/server");
- function _listFiles() {
- var _files = [];
+});
+define('ripple/platform/webworks.tablet/2.0.0/spec', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
- if ((_startModified !== undefined && !wac2_utils.isValidDate(_startModified)) ||
- (_endModified !== undefined && !wac2_utils.isValidDate(_endModified))) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+ id: "webworks.tablet",
+ version: "2.0.0",
+ name: "WebWorks-TabletOS",
- if (!_entry.isDirectory) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- return undefined;
- }
+ persistencePrefix: "rim-tablet-",
- utils.forEach(_entry.children, function (child) {
- if (_matchFilter(child)) {
- _files.push(new File(child, _mode));
- }
- });
+ ui: require('ripple/platform/webworks.tablet/2.0.0/spec/ui'),
+ device: require('ripple/platform/webworks.tablet/2.0.0/spec/device'),
+ config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
+ events: require('ripple/platform/webworks.tablet/2.0.0/spec/events'),
- setTimeout(function () {
- onSuccess(_files);
- }, 1);
+ initialize: function () {},
- return null;
+ objects: {
+ XMLHttpRequest: {
+ path: "webworks.tablet/2.0.0/XMLHttpRequest"
+ },
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ navigator: {
+ path: "w3c/1.0/navigator",
+ children: {
+ geolocation: {
+ path: "w3c/1.0/geolocation"
+ }
}
-
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
},
- openStream: function (onSuccess, onError, mode, encoding) {
- function _openStream() {
- var _openMode = String(mode),
- _encoding = encoding ? String(encoding) : "UTF-8";
-
- if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
+ blackberry: {
+ children: {
+ transport: {
+ path: "webworks.core/2.0.0/client/transport"
+ },
+ events: {
+ path: "webworks.core/2.0.0/client/events"
+ },
+ app: {
+ path: "webworks.tablet/2.0.0/client/app",
+ feature: "blackberry.app",
+ children: {
+ event: {
+ path: "webworks.tablet/2.0.0/client/appEvent",
+ feature: "blackberry.app.event"
+ }
}
- return undefined;
- }
- if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
+ },
+ invoke: {
+ path: "webworks.tablet/2.0.0/client/invoke",
+ feature: "blackberry.invoke",
+ children: {
+ BrowserArguments: {
+ path: "webworks.tablet/2.0.0/client/BrowserArguments",
+ feature: "blackberry.invoke.BrowserArguments"
+ },
+ CameraArguments: {
+ path: "webworks.tablet/2.0.0/client/CameraArguments",
+ feature: "blackberry.invoke.CameraArguments"
+ }
}
- return undefined;
- }
-
- if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
- (_writeOnly && _openMode === "r")) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
+ },
+ identity: {
+ path: "webworks.tablet/2.0.0/client/identity",
+ feature: "blackberry.identity"
+ },
+ system: {
+ path: "webworks.tablet/2.0.0/client/system",
+ children: {
+ event: {
+ path: "webworks.tablet/2.0.0/client/systemEvent"
+ }
+ }
+ },
+ ui: {
+ children: {
+ dialog: {
+ path: "webworks.core/2.0.0/client/dialog",
+ feature: "blackberry.ui.dialog"
+ }
+ }
+ },
+ utils: {
+ path: "webworks.core/2.0.0/client/utils",
+ feature: "blackberry.utils"
+ },
+ io: {
+ children: {
+ dir: {
+ path: "webworks.tablet/2.0.0/client/io/dir",
+ feature: "blackberry.io.dir"
+ },
+ file: {
+ path: "webworks.core/2.0.0/client/io/file",
+ feature: "blackberry.io.file"
+ }
}
- return undefined;
}
-
- setTimeout(function () {
- onSuccess(new FileStream(_entry, _openMode, _encoding));
- }, 1);
-
- return null;
}
+ }
+ }
+};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
- },
- readAsText: function (onSuccess, onError, encoding) {
- function _readAsText() {
- var _encoding = encoding ? String(encoding) : "UTF-8";
- if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/CameraArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.CameraArguments ( )
+var _self = function () {
+ return {
+ //readwrite property Number view
+ view: 0
+ };
+};
- if (_writeOnly) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+//const Number VIEW_CAMERA = 0
+_self.__defineGetter__("VIEW_CAMERA", function () {
+ return 0;
+});
+//const Number VIEW_RECORDER = 1
+_self.__defineGetter__("VIEW_RECORDER", function () {
+ return 1;
+});
- if (_self.isFile) {
- dbfs.read(_entry.fullPath,
- function (data) {
- setTimeout(function () {
- onSuccess(data);
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
+module.exports = _self;
- return undefined;
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/io/dir', function (require, exports, module) {
+/*
+ * Copyright 2011 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 dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
+ utils = require('ripple/utils'),
+ _self = {};
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
- },
- copyTo: function (onSuccess, onError, src, dst, overwrite) {
- function _copyTo() {
- return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
+utils.mixin({
+ appDirs: {
+ "app": {
+ "storage" : {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/data"
}
-
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
},
- moveTo: function (onSuccess, onError, src, dst, overwrite) {
- function _moveTo() {
- return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
+ "shared": {
+ "bookmarks": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/bookmarks"
+ },
+ "books": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/books"
+ },
+ "camera": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/camera"
+ },
+ "documents": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/documents"
+ },
+ "downloads": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/downloads"
+ },
+ "misc": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/misc"
+ },
+ "music": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/music"
+ },
+ "photos": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/photos"
+ },
+ "print": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/print"
+ },
+ "videos": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/videos"
+ },
+ "voice": {
+ "path" : "file:///accounts/1000/appdata/emulatedapp/shared/voice"
}
+ }
+ }
+}, _self);
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
- },
- createDirectory: function (dirPath) {
- var _path = String(dirPath),
- _parts = _path.replace(/\/$/, "").split("/"),
- _dir = null,
- _exist = null,
- _current = _entry.fullPath,
- _i;
-
- function onSuccess(entry) {
- _dir = entry;
- }
+utils.mixin(dir, _self);
- for (_i = 0; _i < _parts.length; _i++) {
- if (!_isValidFileName(_parts[_i])) {
- throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
- }
- }
-
- if (!entry.isDirectory) {
- throw new DeviceApiError(errorcode.IO_ERR);
- }
+module.exports = _self;
- _exist = _parts.reduce(function (obj, token) {
- return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
- }, _entry);
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/BrowserArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.BrowserArguments ( url : String , [transport : blackberry.identity.Transport ] )
+module.exports = function (url, transport) {
+ return {
+ url: url
+ };
+};
- if (_exist) {
- throw new DeviceApiError(errorcode.IO_ERR);
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/identity', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/identity/",
+ _self = {};
- if (_readOnly || _mode === "r") {
- throw new DeviceApiError(errorcode.SECURITY_ERR);
- }
+_self.__defineGetter__("PIN", function () {
+ return transport.call(_uri + "PIN");
+});
- for (_i = 0; _i < _parts.length; _i++) {
- _current = _current + "/" + _parts[_i];
- dbfs.mkdir(_current, onSuccess);
- }
-
- return new File(_dir, _mode);
- },
- createFile: function (filePath) {
- var _name = String(filePath),
- _file = null;
+module.exports = _self;
- if (!_isValidFileName(_name)) {
- throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/system', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ system = require('ripple/platform/webworks.core/2.0.0/client/system'),
+ _uri = "blackberry/system/";
- if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
- throw new DeviceApiError(errorcode.IO_ERR);
- }
+system.__defineGetter__("scriptApiVersion", function () {
+ return transport.call(_uri + "softwareVersion");
+});
- if (_readOnly || _mode === "r") {
- throw new DeviceApiError(errorcode.SECURITY_ERR);
- }
- dbfs.touch(_entry.fullPath + "/" + _name,
- function (entry) {
- _file = new File(entry, _mode);
- },
- function () {});
-
- return _file;
- },
- resolve: function (filePath) {
- var _fullPath = _self.fullPath + "/" + String(filePath),
- _file = null;
-
- if (!_entry.isDirectory) {
- throw new DeviceApiError(errorcode.IO_ERR);
- }
+module.exports = system;
- _resolveSync(_fullPath,
- function (file) {
- _file = file;
- },
- function (e) {
- throw (e);
- },
- _mode);
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/app', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/app/",
+ _self;
- return _file;
- },
- deleteDirectory: function (onSuccess, onError, directory, recursive) {
- function _deleteDirectory() {
- var _dir = null,
- _dirName = String(directory);
- _resolveSync(_dirName,
- function (file) {
- _dir = file;
- },
- function (e) {
- setTimeout(function () {
- onError(e);
- }, 1);
- },
- _mode);
+_self = {
+ exit: function () {
+ transport.call(_uri + "exit", {async: true});
+ }
+};
- if (_dir) {
- if (_dir.isDirectory &&
- _dir.parent.fullPath === _self.fullPath &&
- (!recursive && _dir.length === 0)) {
- if (!_readOnly && _mode !== "r") {
- dbfs.rmdir(_v2r(_dirName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
+_self.__defineGetter__("author", function () {
+ return transport.call(_uri + "author");
+});
- return undefined;
- }
+_self.__defineGetter__("authorEmail", function () {
+ return transport.call(_uri + "authorEmail");
+});
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
- },
- deleteFile: function (onSuccess, onError, fileName) {
- function _deleteFile() {
- var _file = null;
- _resolveSync(String(fileName),
- function (file) {
- _file = file;
- },
- function (e) {
- if (onError) {
- setTimeout(function () {
- onError(e);
- }, 1);
- }
- },
- _mode);
+_self.__defineGetter__("authorURL", function () {
+ return transport.call(_uri + "authorURL");
+});
- if (_file) {
- if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
- if (!_readOnly && _mode !== "r") {
- dbfs.rm(_v2r(fileName),
- function () {
- setTimeout(function () {
- onSuccess();
- }, 1);
- },
- function () {});
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- }
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.IO_ERR));
- }, 1);
- }
- }
- }
+_self.__defineGetter__("copyright", function () {
+ return transport.call(_uri + "copyright");
+});
- return undefined;
- }
+_self.__defineGetter__("description", function () {
+ return transport.call(_uri + "description");
+});
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
- }
- };
+_self.__defineGetter__("id", function () {
+ return transport.call(_uri + "id");
+});
- _self.__defineGetter__("parent", function () {
- var _parts = _self.fullPath.split("/");
+_self.__defineGetter__("license", function () {
+ return transport.call(_uri + "license");
+});
- if (_parent === undefined) {
- if (_parts.length === 1) {
- // virtual root's parent is null
- _parent = null;
- } else {
- _resolveSync(_parts.splice(0, _parts.length - 1).join("/"),
- function (file) {
- _parent = file;
- },
- function () {},
- _mode);
- }
- return _parent;
- } else {
- return _parent;
- }
- });
+_self.__defineGetter__("licenseURL", function () {
+ return transport.call(_uri + "licenseURL");
+});
- _self.__defineGetter__("readOnly", function () {
- return false;
- });
+_self.__defineGetter__("name", function () {
+ return transport.call(_uri + "name");
+});
- _self.__defineGetter__("isFile", function () {
- return !_entry.isDirectory;
- });
+_self.__defineGetter__("version", function () {
+ return transport.call(_uri + "version");
+});
- _self.__defineGetter__("isDirectory", function () {
- return _entry.isDirectory;
- });
+module.exports = _self;
- _self.__defineGetter__("created", function () {
- return undefined;
- });
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/invoke', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var _uri = "blackberry/invoke/invoke",\r
+ APP_TYPE = "appType",\r
+ APP_URL_CAMERA = "camera://",\r
+ APP_URL_CAMERA_VIDEO = "camera://video",\r
+ APP_URL_MAP = "map://",\r
+ APP_URL_MUSIC = "music://",\r
+ APP_URL_PHOTOS = "photos://",\r
+ APP_URL_VIDEOS = "videos://",\r
+ APP_URL_APPWORLD = "appworld://",\r
+ APP_URL_UPDATE = "update://",\r
+ APP_TYPE_ERROR = "appType not supported",\r
+ APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",\r
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
+ _self;\r
+\r
+_self = {\r
+ invoke: function (appType, args) {\r
+ var get = {};\r
+\r
+ switch (appType) {\r
+\r
+ //Camera\r
+ case 4:\r
+ if (!args || args.view === 1) {\r
+ get.appType = APP_URL_CAMERA_VIDEO;\r
+ } else {\r
+ get.appType = APP_URL_CAMERA;\r
+ }\r
+ break;\r
+\r
+ //Maps\r
+ case 5:\r
+ get.appType = APP_URL_MAP;\r
+ break;\r
+\r
+ //Browser\r
+ case 11:\r
+\r
+ if (!args) {\r
+ get.appType = "http://";\r
+ }\r
+ else {\r
+ get.appType = args.url.split("://");\r
+\r
+ if (get.appType.length === 1) {\r
+ get.appType = "http://" + get.appType[0];\r
+ }\r
+ else if (get.appType.length === 2) {\r
+ if (get.appType[0].indexOf("http") !== 0) {\r
+ throw APP_BROWSER_ERROR;\r
+ }\r
+ else {\r
+ get.appType = args.url;\r
+ }\r
+ }\r
+ }\r
+ break;\r
+\r
+ //Music\r
+ case 13:\r
+ get.appType = APP_URL_MUSIC;\r
+ break;\r
+\r
+ //Photos\r
+ case 14:\r
+ get.appType = APP_URL_PHOTOS;\r
+ break;\r
+\r
+ //Videos\r
+ case 15:\r
+ get.appType = APP_URL_VIDEOS;\r
+ break;\r
+\r
+ //AppWorld\r
+ case 16:\r
+ get.appType = APP_URL_APPWORLD;\r
+ break;\r
+\r
+ //Update\r
+ case 17:\r
+ get.appType = APP_URL_UPDATE;\r
+ break;\r
+\r
+ default:\r
+ throw APP_TYPE_ERROR;\r
+ }\r
+\r
+ transport.call(_uri, {\r
+ get: get,\r
+ async: true\r
+ });\r
+ }\r
+};\r
+\r
+_self.__defineGetter__("APP_CAMERA", function () {\r
+ return 4;\r
+});\r
+_self.__defineGetter__("APP_MAPS", function () {\r
+ return 5;\r
+});\r
+_self.__defineGetter__("APP_BROWSER", function () {\r
+ return 11;\r
+});\r
+_self.__defineGetter__("APP_MUSIC", function () {\r
+ return 13;\r
+});\r
+_self.__defineGetter__("APP_PHOTOS", function () {\r
+ return 14;\r
+});\r
+_self.__defineGetter__("APP_VIDEOS", function () {\r
+ return 15;\r
+});\r
+_self.__defineGetter__("APP_APPWORLD", function () {\r
+ return 16;\r
+});\r
+\r
+module.exports = _self;\r
- _self.__defineGetter__("modified", function () {
- if (_entry.isDirectory) {
- return undefined;
- } else {
- return _entry.lastModifiedDate;
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/systemEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ api = "blackberry/system/event/";
+
+function _poll(evt, handler) {
+ transport.poll(api + evt, {}, function (data, response) {
+ if (handler) {
+ handler(data);
}
+ return !!handler;
});
+}
- _self.__defineGetter__("path", function () {
- var _parts = _self.fullPath.split("/");
+module.exports = {
+ deviceBatteryLevelChange: function (handler) {
+ _poll("deviceBatteryLevelChange", handler);
+ },
+ deviceBatteryStateChange: function (handler) {
+ _poll("deviceBatteryStateChange", handler);
+ }
+};
- if (_parts.length === 1) {
- // virtual root
- return _parts.join("");
- } else {
- return _parts.splice(0, _parts.length - 1).join("/") + "/";
- }
- });
+});
+define('ripple/platform/webworks.tablet/2.0.0/client/appEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _callbacks = {},
+ _self;
- _self.__defineGetter__("name", function () {
- return _entry.name;
- });
+function _poll(evt, handler) {
+ _callbacks[evt] = handler;
- _self.__defineGetter__("fullPath", function () {
- return _r2v(_entry.fullPath);
- });
+ transport.poll("blackberry/app/event/" + evt, {}, function () {
+ var func = _callbacks[evt];
- _self.__defineGetter__("fileSize", function () {
- if (_entry.isDirectory) {
- return undefined;
- } else {
- return _entry.data.length;
+ if (func) {
+ func();
}
- });
- _self.__defineGetter__("length", function () {
- var _l = 0;
- if (_entry.isDirectory) {
- utils.forEach(_entry.children, function () {
- _l++;
- });
- return _l;
- } else {
- return undefined;
- }
+ return !!func;
});
+}
- return _self;
+_self = {
+ onBackground: function (handler) {
+ _poll("onBackground", handler);
+ },
+
+ onForeground: function (handler) {
+ _poll("onForeground", handler);
+ },
+
+ onSwipeDown: function (handler) {
+ _poll("onSwipeDown", handler);
+ },
+
+ onSwipeStart: function (handler) {
+ _poll("onSwipeStart", handler);
+ }
};
-FileStream = function (entry, mode, encoding) {
- var _entry = entry,
- _data = entry.data,
- _mode = mode,
- _position = (_mode === "a" ? _data.length : 0),
- _self;
+module.exports = _self;
- _self = {
- close: function () {
- var _element;
- if (mode === "a" || mode === "w") {
- dbfs.write(_entry.fullPath, _data, function () {}, function () {});
- }
- for (_element in _self) {
- delete _self[_element];
+});
+define('ripple/platform/webworks.tablet/2.0.0/spec/device', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event');
+
+module.exports = {
+ "transports": {
+ "TCPCellular": {
+ "name": "Cellular TCP",
+ "control": {
+ "type": "checkbox",
+ "value": true
}
},
- read: function (charCount) {
- var _count = charCount | 0,
- _substr = _data.substring(_position, _position + _count);
-
- if (_position + _count > _data.length) {
- _position = _data.length;
- } else {
- _position += _count;
+ "WAP": {
+ "name": "WAP",
+ "control": {
+ "type": "checkbox",
+ "value": false
}
-
- return _substr;
},
- readBytes: function (byteCount) {
- var _substr = _self.read(byteCount),
- _bytes = [],
- _i;
-
- for (_i = 0; _i < _substr.length; _i++) {
- _bytes.push(_substr.charCodeAt(_i));
+ "WAP2": {
+ "name": "WAP 2.0",
+ "control": {
+ "type": "checkbox",
+ "value": false
}
-
- return _bytes;
},
- readBase64: function (byteCount) {
- var _substr = _self.read(byteCount);
-
- return window.atob(_substr);
+ "MDS": {
+ "name": "MDS",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
},
- write: function (stringData) {
- var _stringData = String(stringData),
- _substr = _data.substring(0, _position);
-
- _data = _substr.concat(_stringData);
- _position = _data.length;
+ "BISB": {
+ "name": "BIS B",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
},
- writeBytes: function (byteData) {
- _self.write(String.fromCharCode.apply(String, byteData));
+ "Unite": {
+ "name": "Unite!",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
},
- writeBase64: function (base64Data) {
- _self.write(window.btoa(String(base64Data)));
+ "TCPWifi": {
+ "name": "Wifi TCP",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
}
- };
+ },
+ "identity": {
+ "PIN": {
+ "name": "PIN",
+ "control": {
+ "type": "text",
+ "value": "43A8C489"
+ }
+ }
+ },
+ "battery": {
+ "state": {
+ "name": "Handset is Charging",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryStateChanged", [setting]);
+ }
+ },
+ "level": {
+ "name": "Charge Level (% remaining)",
+ "control": {
+ "type": "select",
+ "value": 100
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- _self.__defineGetter__("eof", function () {
- return _position === _data.length;
- });
+ for (i = 0; i <= 100; i++) {
+ optionList[i] = i;
+ }
- _self.__defineGetter__("position", function () {
- return _position;
- });
+ return optionList;
+ }()),
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryLevelChanged", [setting]);
+ }
+ }
+ },
+ "system": {
+ "isMassStorageActive": {
+ "name": "Mass Storage Is Connected",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "hasDataCoverage": {
+ "name": "Has Data Coverage",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("CoverageChange");
+ require('ripple/bus').send("network", setting);
+ }
+ },
+ "lag": {
+ "name": "Lag the network",
+ "control": {
+ type: "checkbox",
+ value: false
+ },
+ "callback": function (setting) {
+ require('ripple/bus').send("lag", setting);
+ }
+ },
+ "network": {
+ "name": "Data Network",
+ "control": {
+ "type": "select",
+ "value": "3GPP"
+ },
+ "options": {
+ "3GPP" : "3GPP",
+ "CDMA": "CDMA",
+ "iDEN": "iDEN",
+ "Wi-Fi": "Wi-Fi"
+ },
+ "callback": function (setting) {
+ event.trigger("CoverageChange");
+ }
+ }
+ }
+};
- _self.__defineSetter__("position", function (value) {
- var _value = value | 0;
+});
+define('ripple/platform/webworks.tablet/2.0.0/spec/events', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _self,
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ events = require('ripple/platform/webworks.core/2.0.0/spec/events');
- if (_value >= 0 && _value <= _data.length) {
- _position = _value;
- } else {
- throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
+_self = {
+ "app.event.onSwipeDown": {
+ callback: function () {
+ event.trigger("AppSwipeDown");
}
- });
+ },
+ "app.event.onSwipeStart": {
+ callback: function () {
+ event.trigger("AppSwipeStart");
+ }
+ }
+};
- _self.__defineGetter__("bytesAvailable", function () {
- return (_data.length - _position) || -1;
- });
+utils.mixin(events, _self);
- return _self;
+module.exports = _self;
+
+});
+define('ripple/platform/webworks.tablet/2.0.0/spec/ui', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ plugins: [
+ "accelerometer",
+ "deviceSettings",
+ "geoView",
+ "platformEvents",
+ "widgetConfig",
+ "build"
+ ]
};
-module.exports = function () {
- return {
- maxPathLength: _maxPathLength,
- resolve: function (onSuccess, onError, srcLocation, accessMode) {
- function _resolve() {
- var _mode = accessMode ? String(accessMode) : _defaultMode;
+});
+define('ripple/platform/webworks.tablet/2.0.0/server', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ platform = "ripple/platform/webworks.tablet/2.0.0/server/",
+ core = "ripple/platform/webworks.core/2.0.0/server/",
+ systemEvent = require(platform + 'systemEvent'),
+ system = {};
- if (_mode === "r" || _mode === "rw") {
- _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
- return null;
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- }
- return undefined;
- }
+// ugh, thanks to the spec...
+system.event = systemEvent;
+utils.mixin(require(core + "system"), system);
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
+module.exports = {
+ blackberry: {
+ identity: require(platform + "identity"),
+ app: require(platform + "app"),
+ invoke: require(platform + "invoke"),
+ system: system,
+ ui: {
+ dialog: require(core + "dialog")
},
- handleSubFeatures: function (subFeatures) {
- if (wac2_utils.isEmptyObject(subFeatures) ||
- subFeatures["http://wacapps.net/api/filesystem"] ||
- (subFeatures["http://wacapps.net/api/filesystem.read"] &&
- subFeatures["http://wacapps.net/api/filesystem.write"])) {
- return;
- }
- if (subFeatures["http://wacapps.net/api/filesystem.read"]) {
- _readOnly = true;
- return;
- }
- if (subFeatures["http://wacapps.net/api/filesystem.write"]) {
- _writeOnly = true;
- return;
- }
- _console.warn("WAC-2.0-Filesystem: something wrong in handleSubFeatures");
+ io: {
+ dir: require(core + "io/dir"),
+ file: require(core + "io/file")
}
- };
+ }
};
-
});
-define('ripple/platform/wac/2.0/geolocation', function (require, exports, module) {
+define('ripple/platform/webworks.tablet/2.0.0/server/identity', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var deviceSettings = require('ripple/deviceSettings');
-var geo = require('ripple/geo'),
- Position = require('ripple/platform/w3c/1.0/Position'),
- PositionError = require('ripple/platform/w3c/1.0/PositionError'),
- _lastPosition = null,
- _watches = {},
- _defaultInterval = 100,
- _defaultDelay = 50,
+module.exports = {
+ PIN: function () {
+ return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
+ }
+};
+
+});
+define('ripple/platform/webworks.tablet/2.0.0/server/app', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ app = require('ripple/app'),
_self;
-function _createPosition() {
- var position = new Position(),
- positionInfo = geo.getPositionInfo();
+_self = {
+ event: require('ripple/platform/webworks.tablet/2.0.0/server/appEvent'),
- position.coords.latitude = positionInfo.latitude;
- position.coords.longitude = positionInfo.longitude;
- position.coords.altitude = positionInfo.altitude;
- position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
- position.coords.accuracy = positionInfo.accuracy;
- position.coords.heading = positionInfo.heading;
- position.coords.speed = positionInfo.speed;
- position.timestamp = positionInfo.timeStamp.getTime();
+ exit: function () {
+ event.trigger("AppExit");
+ return {code: 1};
+ },
- return position;
-}
+ author: function () {
+ return {code: 1, data: app.getInfo().author};
+ },
-function _isValid(onSuccess, onError, options, argLength) {
- if (argLength < 1 || argLength > 3)
- return false;
+ authorEmail: function () {
+ return {code: 1, data: app.getInfo().authorEmail};
+ },
- if (typeof onSuccess !== "function") // imply onSuccess == null
- return false;
+ authorURL: function () {
+ return {code: 1, data: app.getInfo().authorURL};
+ },
- if (onError && (typeof onError !== "function"))
- return false;
+ copyright: function () {
+ return {code: 1, data: app.getInfo().copyright};
+ },
- if ((options !== undefined) &&
- ((typeof options !== "object") ||
- (options.enableHighAccuracy !== undefined) && (typeof options.enableHighAccuracy !== "boolean") ||
- (options.timeout !== undefined) && (typeof options.timeout !== "number") ||
- (options.maximumAge !== undefined) && (typeof options.maximumAge !== "number")))
- return false;
+ description: function () {
+ return {code: 1, data: app.getInfo().description};
+ },
- return true;
-}
+ id: function () {
+ return {code: 1, data: app.getInfo().id};
+ },
-function _processOptions(options) {
- var validOptions = {
- enableHighAccuracy: false,
- timeout: 0,
- maximumAge: 0
- };
+ license: function () {
+ return {code: 1, data: app.getInfo().license};
+ },
- if (options !== undefined &&
- options.maximumAge !== undefined &&
- options.maximumAge === Math.floor(options.maximumAge) &&
- options.maximumAge >= 0) {
- validOptions.maximumAge = options.maximumAge | 0;
- } else {
- validOptions.maximumAge = 0;
- }
+ licenseURL: function () {
+ return {code: 1, data: app.getInfo().licenseURL};
+ },
- if (options !== undefined &&
- options.timeout !== undefined &&
- options.timeout === Math.floor(options.timeout)) {
- validOptions.timeout = (options.timeout >= 0) ? (options.timeout | 0) : 0;
- } else {
- validOptions.timeout = Infinity;
- }
+ name: function () {
+ return {code: 1, data: app.getInfo().name};
+ },
- if (options !== undefined && options.enableHighAccuracy !== undefined) {
- validOptions.enableHighAccuracy = options.enableHighAccuracy;
- } else {
- validOptions.enableHighAccuracy = false;
+ version: function () {
+ return {code: 1, data: app.getInfo().version};
}
+};
- validOptions.delay = geo.delay * 1000 || _defaultDelay;
-
- return validOptions;
-}
-
-function _errorOccur(code, onError) {
- if (!onError)
- return;
+module.exports = _self;
- var error = new PositionError();
+});
+define('ripple/platform/webworks.tablet/2.0.0/server/invoke', function (require, exports, module) {
+/*
+ * Copyright 2011 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 notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ type = "normal",
+ name = {
+ "camera://": "Camera",
+ "camera://video": "Video Camera",
+ "map://": "Maps",
+ "http://": "Browser",
+ "music://": "Music",
+ "photos://": "Photos",
+ "videos://": "Videos",
+ "appworld://": "App World",
+ "update://": "Update"
+ };
- error.code = code;
- switch (code) {
- case PositionError.POSITION_UNAVAILABLE:
- error.message = "Position unavailable";
- break;
+module.exports = {
+ invoke: function (opts) {
+ var app = name[opts.appType];
+ if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
+ app = "Browser";
+ }
- case PositionError.TIMEOUT:
- error.message = "Position timed out";
- break;
+ notifications.openNotification(type,
+ "Requested to launch: " + app + " application.");
+ return {code: 1};
}
+};
- onError(error);
-}
-
-function _execute(data) {
- return function () {
- if (_lastPosition !== null &&
- ((new Date()).getTime() - _lastPosition.timestamp <= data.maximumAge)) {
- window.setTimeout(function () {
- data.onSuccess(_lastPosition);
- }, 1);
- } else if (data.timeout === 0) {
- _errorOccur(PositionError.TIMEOUT, data.onError);
- } else {
- window.setTimeout(function () {
- if (data.delay <= data.timeout) {
- _lastPosition = _createPosition();
-
- if (_lastPosition !== null) {
- data.onSuccess(_lastPosition);
- } else {
- _errorOccur(PositionError.POSITION_UNAVAILABLE, data.onError);
- }
- } else {
- _errorOccur(PositionError.TIMEOUT, data.onError);
- }
- }, Math.min(data.delay, data.timeout));
- }
+});
+define('ripple/platform/webworks.tablet/2.0.0/server/systemEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ _onBatteryStateChange,
+ _onBatteryLevelChange,
+ _states = {
+ UNKNOWN: 0,
+ FULL: 1,
+ CHARGING: 2,
+ UNPLUGGED: 3
+ },
+ _battery = {
+ state: _states.UNKNOWN,
+ charging: null,
+ level: null
};
+
+function _getState() {
+ return _battery.level === 100 ? _states.FULL :
+ _battery.charging ? _states.CHARGING : _states.UNPLUGGED;
}
-function _interval(k, n) {
- return k * Math.floor((n + k - 1) / k) || k;
+function _pass(baton, data) {
+ if (baton) {
+ baton.pass({code: 1, data: data});
+ }
}
-_self = {
- getCurrentPosition: function (onSuccess, onError, options) {
- if (!_isValid(onSuccess, onError, options, arguments.length))
- return;
+event.on("DeviceBatteryStateChanged", function (charging) {
+ _battery.charging = charging;
+ _battery.state = _getState();
+ _pass(_onBatteryStateChange, _battery.state);
+});
- var validData = _processOptions(options);
+event.on("DeviceBatteryLevelChanged", function (level) {
+ level = parseInt(level, 10);
- validData.onSuccess = onSuccess;
- validData.onError = onError;
+ _battery.level = level;
+ _pass(_onBatteryLevelChange, level);
- _execute(validData)();
+ if (level === 100) {
+ _battery.state = _getState();
+ _pass(_onBatteryStateChange, _battery.state);
+ }
+});
+
+module.exports = {
+ deviceBatteryLevelChange: function (get, post, baton) {
+ baton.take();
+ _onBatteryLevelChange = baton;
},
+ deviceBatteryStateChange: function (get, post, baton) {
+ baton.take();
+ _onBatteryStateChange = baton;
+ }
+};
- watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
- if (!_isValid(geolocationSuccess, geolocationError, geolocationOptions, arguments.length))
- return undefined;
+});
+define('ripple/platform/webworks.tablet/2.0.0/server/appEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ notifications = require('ripple/notifications'),
+ _bg,
+ _fg,
+ _swipeDown,
+ _swipeStart,
+ _exit;
- var validData = _processOptions(geolocationOptions),
- watchId = (new Date()).getTime() | 0,
- watchObj = {
- onSuccess: geolocationSuccess,
- onError: geolocationError,
- enableHighAccuracy: validData.enableHighAccuracy,
- timeout: validData.timeout,
- maximumAge: validData.maximumAge,
- delay: validData.delay,
- interval: _interval(validData.maximumAge || _defaultInterval,
- Math.min(validData.delay, validData.timeout)),
- };
+event.on("AppExit", function () {
+ var baton = _exit;
+ _exit = null;
+ notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
+ return baton && baton.pass({code: 1});
+});
- _watches[watchId] = watchObj;
+event.on("AppRequestBackground", function () {
+ var baton = _bg;
+ _bg = null;
+ return baton && baton.pass({code: 1});
+});
- _watches[watchId].intervalId = window.setInterval(_execute(_watches[watchId]),
- _watches[watchId].interval);
+event.on("AppRequestForeground", function () {
+ var baton = _fg;
+ _fg = null;
+ return baton && baton.pass({code: 1});
+});
- return watchId;
- },
+event.on("AppSwipeDown", function () {
+ var baton = _swipeDown;
+ _swipeDown = null;
+ return baton && baton.pass({code: 1});
+});
- clearWatch: function (watchId) {
- if (arguments.length !== 1)
- return undefined;
+event.on("AppSwipeStart", function () {
+ var baton = _swipeStart;
+ _swipeStart = null;
+ return baton && baton.pass({code: 1});
+});
- var id = watchId | 0;
+module.exports = {
+ onBackground: function (get, post, baton) {
+ baton.take();
+ _bg = baton;
+ return {code: 1};
+ },
- if (_watches[id]) {
- window.clearInterval(_watches[id].intervalId);
- delete _watches[id];
+ onForeground: function (get, post, baton) {
+ baton.take();
+ _fg = baton;
+ return {code: 1};
+ },
- return null;
- }
+ onSwipeDown: function (get, post, baton) {
+ baton.take();
+ _swipeDown = baton;
+ return {code: 1};
+ },
- return undefined;
+ onSwipeStart: function (get, post, baton) {
+ baton.take();
+ _swipeStart = baton;
+ return {code: 1};
}
};
-module.exports = _self;
-
});
-define('ripple/platform/wac/2.0/messagefilter', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/XMLHttpRequest', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* limitations under the License.
*/
-var _self;
+var xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
+module.exports = xhr.create("ripple/platform/webworks.handset/2.0.0/server");
-_self = function (criteria) {
- var pattern,
- messageFilter;
+});
+define('ripple/platform/webworks.handset/2.0.0/spec', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
- messageFilter = {
- match: function (target) {
- var result = false, index;
+ id: "webworks.handset",
+ version: "2.0.0",
+ name: "WebWorks",
- if (Object.prototype.toString.call(criteria) === "[object Array]") {
- for (index in criteria) {
- if (_self(criteria[index]).match(target))
- return true;
- }
- return false;
- }
+ persistencePrefix: "rim-handset-",
- switch (Object.prototype.toString.call(target)) {
- case "[object Number]":
- result = (criteria === target);
- break;
+ ui: require('ripple/platform/webworks.handset/2.0.0/spec/ui'),
+ device: require('ripple/platform/webworks.handset/2.0.0/spec/device'),
+ config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
+ events: require('ripple/platform/webworks.handset/2.0.0/spec/events'),
- case "[object String]":
- result = pattern.test(target);
- break;
+ initialize: function () {},
- case "[object Array]":
- for (index in target) {
- if (messageFilter.match(target[index]))
- return true;
+ objects: {
+ XMLHttpRequest: {
+ path: "webworks.handset/2.0.0/XMLHttpRequest"
+ },
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ navigator: {
+ path: "w3c/1.0/navigator",
+ children: {
+ geolocation: {
+ path: "w3c/1.0/geolocation"
+ }
+ }
+ },
+ blackberry: {
+ path: "webworks.handset/2.0.0/client/blackberry",
+ children: {
+ pim: {
+ path: "webworks.handset/2.0.0/client/pim",
+ feature: "blackberry.pim.category|blackberry.pim.Task|blackberry.pim.Recurrence|blackberry.pim.Reminder|blackberry.pim.Appointment|blackberry.pim.Address|blackberry.pim.Attendee|blackberry.pim.Memo|blackberry.pim.Contact",
+ children: {
+ category: {
+ path: "webworks.handset/2.0.0/client/category",
+ feature: "blackberry.pim.category"
+ },
+ Task: {
+ path: "webworks.handset/2.0.0/client/Task",
+ feature: "blackberry.pim.Task"
+ },
+ Recurrence: {
+ path: "webworks.handset/2.0.0/client/Recurrence",
+ feature: "blackberry.pim.Recurrence"
+ },
+ Reminder: {
+ path: "webworks.handset/2.0.0/client/Reminder",
+ feature: "blackberry.pim.Reminder"
+ },
+ Appointment: {
+ path: "webworks.handset/2.0.0/client/Appointment",
+ feature: "blackberry.pim.Appointment"
+ },
+ Address: {
+ path: "webworks.handset/2.0.0/client/Address",
+ feature: "blackberry.pim.Address"
+ },
+ Attendee: {
+ path: "webworks.handset/2.0.0/client/Attendee",
+ feature: "blackberry.pim.Attendee"
+ },
+ Memo: {
+ path: "webworks.handset/2.0.0/client/Memo",
+ feature: "blackberry.pim.Memo"
+ },
+ Contact: {
+ path: "webworks.handset/2.0.0/client/Contact",
+ feature: "blackberry.pim.Contact"
+ }
+ }
+ },
+ phone: {
+ children: {
+ Phone: {
+ path: "webworks.handset/2.0.0/client/Phone",
+ feature: "blackberry.phone.Phone"
+ },
+ PhoneLogs: {
+ path: "webworks.handset/2.0.0/client/PhoneLogs",
+ feature: "blackberry.phone.PhoneLogs|blackberry.phone.Find",
+ children: {
+ CallLog: {
+ path: "webworks.handset/2.0.0/client/CallLog"
+ }
+ }
+ },
+ Find: {
+ children: {
+ FilterExpression: {
+ path: "webworks.handset/2.0.0/client/FilterExpression",
+ feature: "blackberry.phone.Find"
+ }
+ }
+ }
+ }
+ },
+ message: {
+ path: "webworks.handset/2.0.0/client/messaging",
+ feature: "blackberry.message.sms|blackberry.message",
+ children: {
+ sms: {
+ path: "webworks.handset/2.0.0/client/sms",
+ feature: "blackberry.message.sms"
+ },
+ Message: {
+ path: "webworks.handset/2.0.0/client/Message",
+ feature: "blackberry.message"
+ }
+ }
+ },
+ transport: {
+ path: "webworks.core/2.0.0/client/transport"
+ },
+ events: {
+ path: "webworks.core/2.0.0/client/events"
+ },
+ app: {
+ path: "webworks.handset/2.0.0/client/app",
+ feature: "blackberry.app",
+ children: {
+ event: {
+ path: "webworks.handset/2.0.0/client/appEvent",
+ feature: "blackberry.app.event"
+ }
+ }
+ },
+ invoke: {
+ path: "webworks.handset/2.0.0/client/invoke",
+ feature: "blackberry.invoke",
+ children: {
+ AddressBookArguments: {
+ path: "webworks.handset/2.0.0/client/AddressBookArguments",
+ feature: "blackberry.invoke.AddressBookArguments"
+ },
+ BrowserArguments: {
+ path: "webworks.handset/2.0.0/client/BrowserArguments",
+ feature: "blackberry.invoke.BrowserArguments"
+ },
+ CameraArguments: {
+ path: "webworks.handset/2.0.0/client/CameraArguments",
+ feature: "blackberry.invoke.CameraArguments"
+ },
+ CalendarArguments: {
+ path: "webworks.handset/2.0.0/client/CalendarArguments",
+ feature: "blackberry.invoke.CalendarArguments"
+ },
+ JavaArguments: {
+ path: "webworks.handset/2.0.0/client/JavaArguments",
+ feature: "blackberry.invoke.JavaArguments"
+ },
+ MapsArguments: {
+ path: "webworks.handset/2.0.0/client/MapsArguments",
+ feature: "blackberry.invoke.MapsArguments"
+ },
+ MemoArguments: {
+ path: "webworks.handset/2.0.0/client/MemoArguments",
+ feature: "blackberry.invoke.MemoArguments"
+ },
+ MessageArguments: {
+ path: "webworks.handset/2.0.0/client/MessageArguments",
+ feature: "blackberry.invoke.MessageArguments"
+ },
+ PhoneArguments: {
+ path: "webworks.handset/2.0.0/client/PhoneArguments",
+ feature: "blackberry.invoke.PhoneArguments"
+ },
+ SearchArguments: {
+ path: "webworks.handset/2.0.0/client/SearchArguments",
+ feature: "blackberry.invoke.SearchArguments"
+ },
+ TaskArguments: {
+ path: "webworks.handset/2.0.0/client/TaskArguments",
+ feature: "blackberry.invoke.TaskArguments"
+ }
+ }
+ },
+ identity: {
+ path: "webworks.handset/2.0.0/client/identity",
+ feature: "blackberry.identity",
+ children: {
+ Transport: {
+ path: "webworks.handset/2.0.0/client/identity/Transport",
+ feature: "blackberry.identity"
+ },
+ Service: {
+ path: "webworks.handset/2.0.0/client/identity/Service",
+ feature: "blackberry.identity"
+ },
+ phone: {
+ path: "webworks.handset/2.0.0/client/identity/phone",
+ feature: "blackberry.identity.phone"
+ }
+ }
+ },
+ system: {
+ path: "webworks.handset/2.0.0/client/system",
+ feature: "blackberry.system",
+ children: {
+ event: {
+ path: "webworks.handset/2.0.0/client/systemEvent",
+ feature: "blackberry.system.event"
+ }
+ }
+ },
+ ui: {
+ children: {
+ dialog: {
+ path: "webworks.core/2.0.0/client/dialog",
+ feature: "blackberry.ui.dialog"
+ },
+ menu: {
+ path: "webworks.handset/2.0.0/client/menu",
+ children: {
+ MenuItem: {
+ path: "webworks.handset/2.0.0/client/MenuItem"
+ }
+ }
+ }
+ }
+ },
+ utils: {
+ path: "webworks.core/2.0.0/client/utils",
+ feature: "blackberry.utils"
+ },
+ find: {
+ feature: "blackberry.find",
+ children: {
+ FilterExpression: {
+ path: "webworks.handset/2.0.0/client/FilterExpression",
+ feature: "blackberry.find"
+ }
+ }
+ },
+ push: {
+ path: "webworks.handset/2.0.0/client/push",
+ feature: "blackberry.push"
+ },
+ audio: {
+ path: "webworks.handset/2.0.0/client/audio",
+ feature: "blackberry.audio",
+ children: {
+ Player: {
+ path: "webworks.handset/2.0.0/client/AudioPlayer",
+ feature: "blackberry.audio.Player"
+ }
+ }
+ },
+ io: {
+ children: {
+ dir: {
+ path: "webworks.handset/2.0.0/client/io/dir",
+ feature: "blackberry.io.dir"
+ },
+ file: {
+ path: "webworks.core/2.0.0/client/io/file",
+ feature: "blackberry.io.file"
+ }
+ }
}
- break;
}
-
- return result;
}
- };
-
- if (typeof criteria === "string")
- pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");
-
- return messageFilter;
+ }
};
-module.exports = _self;
-
});
-define('ripple/platform/wac/2.0/messaging', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/CalendarArguments', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var utils = require('ripple/utils'),
- event = require('ripple/event'),
- db = require('ripple/db'),
- exception = require('ripple/exception'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
- Filter = require('ripple/platform/wac/2.0/messagefilter'),
- FileSystem = require('ripple/platform/wac/2.0/filesystem'),
- MessageSendCallback,
- Message,
- MessageFilter,
- Recipients,
- _KEY = "wac2-pim-messaging",
- _PENDING_TIME = 600,
- _messages = {},
- _subscriber = {
- onSMS: {},
- onMMS: {},
- onEmail: {}
- },
- _sentStatus = {},
- _security = {
- "http://wacapps.net/api/messaging": [],
- "http://wacapps.net/api/messaging.send": ["sendMessage"],
- "http://wacapps.net/api/messaging.find": ["findMessages"],
- "http://wacapps.net/api/messaging.subscribe": ["onSMS", "onMMS", "onEmail"],
- "http://wacapps.net/api/messaging.write": ["update"],
- all: true
- },
- _fileSystem,
- _initialized = false,
- _self;
-
-function _initialize() {
- _get();
- if (!_fileSystem) {
- _fileSystem = new FileSystem();
- }
- _initialized = true;
-}
-
-function _get() {
- _messages = db.retrieveObject(_KEY) || {1: [], 2: [], 3: [], 4: []};
- utils.forEach(_messages, function (folder) {
- utils.forEach(folder, function (messageItem) {
- if (messageItem.timestamp)
- messageItem.timestamp = new Date(messageItem.timestamp);
- });
- });
-}
-
-function _save() {
- db.saveObject(_KEY, _messages);
-}
-
-function _updateDB(message, duplicate) {
- _get();
- _messages[message.folder].push(message);
- if (duplicate)
- _messages[duplicate.folder].push(duplicate);
- _save();
-}
-
-function _processAttachments(message) {
- var attachmentsFileName = [],
- attachmentsContent = [];
-
- function _generateAttachmentFileName(attachment) {
- var lastDot = attachment.filename.lastIndexOf(".");
- return attachment.filename.substring(0, lastDot) + "_" + Math.uuid(8, 16) + attachment.filename.substring(lastDot);
- }
-
- function _onResolveSuccess(file) {
- var fileAttachment = file.createFile(attachmentsFileName[0]);
-
- fileAttachment.openStream(
- function (fs) {
- fs.write(attachmentsContent[0]);
- fs.close();
- }, null, "w");
- }
-
- function _onResolveError() {
- }
-
- if (message.attachments.length === 0)
- return;
-
- attachmentsFileName.push(_generateAttachmentFileName(message.attachments[0]));
- attachmentsContent.push(message.attachments[0].content);
-
- _fileSystem.resolve(_onResolveSuccess, _onResolveError, "attachments", "rw");
-
- message.attachments = utils.copy(attachmentsFileName);
-}
-
-function _errorOccurred(onError, code) {
- if (!onError)
- return;
-
- setTimeout(function () {
- onError(new DeviceApiError(code));
- }, 1);
-}
-
-function _pendingOperate(operate, scope) {
- var i, argumentVector = [];
-
- for (i = 0; i < arguments.length - 2; i++)
- argumentVector[i] = arguments[i + 2];
-
- return function () {
- var pendingObj, pendingOperation;
-
- pendingObj = new PendingObject();
- pendingObj.pendingID = window.setTimeout(function () {
- pendingObj.setCancelFlag(false);
- if (operate)
- operate.apply(scope, argumentVector);
- }, _PENDING_TIME);
-
- pendingOperation = new PendingOperation(pendingObj);
-
- return pendingOperation;
+//blackberry.invoke.CalendarArguments ( )
+//blackberry.invoke.CalendarArguments ( date : Date )
+//blackberry.invoke.CalendarArguments ( appointment : blackberry.pim.Appointment )
+var _self = function () {
+ //readonly property Appointment appointment
+ //readonly property Date date
+ //readwrite property Number view
+ return {
+ appointment: undefined,
+ date: undefined,
+ view: 0
};
-}
-
-function _onMessage(onMessage, messageHandler) {
- if (!messageHandler)
- exception.raise(exception.types.Argument,
- onMessage + " invalid messageHandler parameter",
- new DeviceApiError(errorcode.INVALID_VALUES_ERR));
-
- utils.validateArgumentType(messageHandler, "function", null,
- "messageHandler invalid function parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
-
- if (!_security.all && !_security[onMessage])
- exception.raise(exception.types.Argument,
- onMessage + " access denied", new DeviceApiError(errorcode.SECURITY_ERR));
-
- var idSubscribe = (new Date()).getTime() | 0;
- _subscriber[onMessage][idSubscribe] = messageHandler;
-
- return idSubscribe;
-}
-
-function _validateRecipients(message) {
- var i;
-
- for (i = 0; i < message.to.length;) {
- message.to[i] = message.to[i].replace(/^\s*(\S*)\s*$/, '$1');
- if (message.to[i] === "")
- message.to.splice(i, 1);
- else
- i++;
- }
- for (i = 0; i < message.cc.length;) {
- message.cc[i] = message.cc[i].replace(/^\s*(\S*)\s*$/, '$1');
- if (message.cc[i] === "")
- message.cc.splice(i, 1);
- else
- i++;
- }
- for (i = 0; i < message.bcc.length;) {
- message.bcc[i] = message.bcc[i].replace(/^\s*(\S*)\s*$/, '$1');
- if (message.bcc[i] === "")
- message.bcc.splice(i, 1);
- else
- i++;
- }
- if (message.to.length + message.cc.length + message.bcc.length === 0)
- exception.raise(exception.types.Argument,
- "sendMessage invalid message.to parameter",
- new DeviceApiError(errorcode.INVALID_VALUES_ERR));
-}
-
-function _isValid(onSuccess, onError, message) {
- if (onSuccess &&
- typeof onSuccess !== "function" &&
- typeof onSuccess !== "object") {
- exception.raise(exception.types.Argument,
- "sendMessage invalid successCallback parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
-
- if (onError) {
- utils.validateArgumentType(onError, "function", null,
- "sendMessage invalid errorCallback parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- }
-
- if (!onSuccess) {
- _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
- return false;
- }
-
- if (message) {
- utils.validateArgumentType(message, "object", null,
- "sendMessage invalid message parameter",
- new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- } else {
- _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
- return false;
- }
-
- if (message.type !== _self().TYPE_SMS &&
- message.type !== _self().TYPE_MMS &&
- message.type !== _self().TYPE_EMAIL)
- exception.raise(exception.types.Argument,
- "sendMessage invalid message.type parameter",
- new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+};
- if (!_security.all && !_security.sendMessage) {
- _errorOccurred(onError, errorcode.SECURITY_ERR);
- return false;
- }
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_NEW", function () {
+ return 0;
+});
+//const Number VIEW_VIEW = 1
+_self.__defineGetter__("VIEW_VIEW", function () {
+ return 1;
+});
+//const Number VIEW_AGENDA = 2
+_self.__defineGetter__("VIEW_AGENDA", function () {
+ return 2;
+});
+//const Number VIEW_DAY = 3
+_self.__defineGetter__("VIEW_DAY", function () {
+ return 3;
+});
+//const Number VIEW_DEFAULT = 4
+_self.__defineGetter__("VIEW_DEFAULT", function () {
+ return 4;
+});
+//const Number VIEW_MONTH = 5
+_self.__defineGetter__("VIEW_MONTH", function () {
+ return 5;
+});
+//const Number VIEW_WEEK = 6
+_self.__defineGetter__("VIEW_WEEK", function () {
+ return 6;
+});
- TypeCoerce(Message(0)).cast(message);
- _validateRecipients(message);
+module.exports = _self;
- return true;
-}
+});
+define('ripple/platform/webworks.handset/2.0.0/client/Appointment', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ utils = require('ripple/utils'),
+ _uri = "blackberry/pim/appointment/";
-function _getEachSentStatus(onMessageSentSuccess, onMessageSentError, message,
- sucRecipients, failRecipients, recType) {
- utils.forEach(message[recType], function (recipient) {
- if (_sentStatus[recipient]) {
- sucRecipients[recType].push(recipient);
- if (onMessageSentSuccess) {
- onMessageSentSuccess(recipient);
- }
- } else {
- failRecipients[recType].push(recipient);
- if (onMessageSentError) {
- onMessageSentError(new DeviceApiError(errorcode.UNKNOWN_ERR), recipient);
+function Appointment(service) {
+ var _self = {
+ allDay: false,
+ attendees: [],
+ end: null,
+ freeBusy: null,
+ location: null,
+ note: null,
+ recurrence: null,
+ reminder: null,
+ start: null,
+ summary: null,
+ uid: null,
+ remove: function () {
+ transport.call(_uri + "remove", {get: {uid: _self.uid}});
+ },
+ save: function () {
+ if (_self.uid === null) {
+ _self.uid = Number(Math.uuid(8, 10));
}
+ transport.call(_uri + "save", {post: {appointment: _self}});
}
- });
-}
-
-function _getSentStatus(onSuccess, onError, message, onMessageSentSuccess, onMessageSentError) {
- var allSentSuccess,
- sucRecipients = new Recipients(),
- failRecipients = new Recipients(),
- duplicate;
+ };
- _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
- message, sucRecipients, failRecipients, "to");
+ return _self;
+}
- if (message.type === _self().TYPE_EMAIL) {
- _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
- message, sucRecipients, failRecipients, "cc");
- _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
- message, sucRecipients, failRecipients, "bcc");
+function _massage(property, name) {
+ if (name === "recurrence" && property) {
+ if (property.end) {
+ property.end = new Date(property.end);
+ }
}
-
- allSentSuccess = (failRecipients.total() === 0);
-
- if (allSentSuccess) {
- message.folder = _self().FOLDER_SENTBOX;
- } else if (sucRecipients.total() === 0) {
- message.folder = _self().FOLDER_DRAFTS;
- } else {
- duplicate = utils.copy(message);
-
- message.to = sucRecipients.to;
- message.cc = sucRecipients.cc;
- message.bcc = sucRecipients.bcc;
- message.folder = _self().FOLDER_SENTBOX;
-
- duplicate.to = failRecipients.to;
- duplicate.cc = failRecipients.cc;
- duplicate.bcc = failRecipients.bcc;
- duplicate.folder = _self().FOLDER_DRAFTS;
+ if (name === "reminder" && property) {
+ if (property.date) {
+ property.date = new Date(property.date);
+ }
}
-
- _updateDB(message, duplicate);
-
- if (allSentSuccess) {
- onSuccess();
- } else if (onError) {
- onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ if ((name === "end" || name === "start") && property) {
+ property = new Date(property);
}
+ return property;
}
-_self = function () {
- var messaging = {
- createMessage: function (type) {
- type = type | 0;
-
- if (type < _self().TYPE_SMS || type > _self().TYPE_EMAIL)
- exception.raise(exception.types.Argument,
- "type invalid value", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
-
- var msg = new Message(type);
-
- return msg;
- },
-
- sendMessage: function (successCallback, errorCallback, message) {
- var ret;
-
- function _sendMessage() {
- event.trigger("OutsideMessageReceived", [message]);
-
- return _pendingOperate(_getSentStatus, undefined,
- successCallback, errorCallback, message)();
- }
-
- function _sendEachMessage() {
- utils.forEach(successCallback, function (value, key) {
- utils.validateArgumentType(value, "function", null,
- "sendMessage invalid successCallback." + key + " parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- });
-
- event.trigger("OutsideMessageReceived", [message]);
-
- return _pendingOperate(_getSentStatus, undefined,
- successCallback.onsuccess, errorCallback, message,
- successCallback.onmessagesendsuccess, successCallback.onmessagesenderror)();
- }
-
- if (!_isValid(successCallback, errorCallback, message))
- return null;
-
- switch (typeof successCallback) {
- case "function":
- ret = _sendMessage();
- break;
-
- case "object":
- ret = _sendEachMessage();
- break;
- }
-
- return ret;
- },
-
- findMessages: function (successCallback, errorCallback, filter) {
- function _findMessages() {
- var message, result = [];
-
- if (!_security.all && !_security.findMessages)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
-
- utils.forEach(_messages, function (folder) {
- utils.forEach(folder, function (messageItem) {
- if ((filter === undefined || filter === null) ||
- (filter.id === undefined || Filter(filter.id).match(messageItem.id)) &&
- (filter.type === undefined || Filter(filter.type).match(messageItem.type)) &&
- (filter.folder === undefined || Filter(filter.folder).match(messageItem.folder)) &&
- (filter.startTimestamp === undefined || (messageItem.timestamp >= filter.startTimestamp)) &&
- (filter.endTimestamp === undefined || (messageItem.timestamp <= filter.endTimestamp)) &&
- (filter.from === undefined || Filter(filter.from).match(messageItem.from)) &&
- (filter.to === undefined || Filter(filter.to).match(messageItem.to)) &&
- (filter.cc === undefined || Filter(filter.cc).match(messageItem.cc)) &&
- (filter.bcc === undefined || Filter(filter.bcc).match(messageItem.bcc)) &&
- (filter.body === undefined || Filter(filter.body).match(messageItem.body)) &&
- (filter.isRead === undefined || (messageItem.isRead === filter.isRead)) &&
- (filter.messagePriority === undefined || (messageItem.priority === filter.messagePriority)) &&
- (filter.subject === undefined || Filter(filter.subject).match(messageItem.subject))) {
- message = utils.copy(messageItem);
- result.push(message);
- }
- });
- });
- successCallback(result);
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findMessages", _pendingOperate(_findMessages));
- },
-
- onSMS: function (messageHandler) {
- return _onMessage("onSMS", messageHandler);
- },
-
- onMMS: function (messageHandler) {
- return _onMessage("onMMS", messageHandler);
- },
-
- onEmail: function (messageHandler) {
- return _onMessage("onEmail", messageHandler);
- },
-
- unsubscribe: function (subscriptionHandler) {
- var onMessage, idSubscribe;
-
- utils.validateArgumentType(subscriptionHandler, "integer",
- null, "subscriptionHandler invalid function parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
-
- for (onMessage in _subscriber) {
- for (idSubscribe in _subscriber[onMessage]) {
- if (idSubscribe == subscriptionHandler) {
- delete _subscriber[onMessage][idSubscribe];
- return;
- }
- }
- }
- },
-
- handleSubFeatures: function (subFeatures) {
- for (var subFeature in subFeatures) {
- if (_security[subFeature].length === 0) {
- _security.all = true;
- return;
- }
- _security.all = false;
- utils.forEach(_security[subFeature], function (method) {
- _security[method] = true;
- });
- }
+Appointment.find = function (filter, orderBy, maxReturn, service, isAscending) {
+ var opts = {
+ post: {
+ filter: filter,
+ orderBy: orderBy,
+ maxReturn: maxReturn,
+ service: service,
+ isAscending: isAscending
}
};
- messaging.__defineGetter__("TYPE_SMS", function () {
- return 1;
- });
-
- messaging.__defineGetter__("TYPE_MMS", function () {
- return 2;
- });
-
- messaging.__defineGetter__("TYPE_EMAIL", function () {
- return 3;
- });
-
- messaging.__defineGetter__("FOLDER_INBOX", function () {
- return 1;
- });
-
- messaging.__defineGetter__("FOLDER_OUTBOX", function () {
- return 2;
- });
-
- messaging.__defineGetter__("FOLDER_DRAFTS", function () {
- return 3;
- });
-
- messaging.__defineGetter__("FOLDER_SENTBOX", function () {
- return 4;
+ return transport.call(_uri + "find", opts).map(function (obj) {
+ var appt = new Appointment();
+ appt.allDay = obj.allDay;
+ appt.attendees = obj.attendees;
+ appt.end = _massage(obj.end, "end");
+ appt.freeBusy = obj.freeBusy;
+ appt.location = obj.location;
+ appt.note = obj.note;
+ appt.recurrence = _massage(obj.recurrence, "recurrence");
+ appt.reminder = _massage(obj.reminder, "reminder");
+ appt.start = _massage(obj.start, "start");
+ appt.summary = obj.summary;
+ appt.uid = obj.uid;
+ return appt;
});
-
- if (!_initialized)
- _initialize();
-
- return messaging;
-};
-
-MessageSendCallback = {
- onsuccess: function () {},
- onmessagesendsuccess: function (recipient) {},
- onmessagesenderror: function (error, recipient) {}
};
-Message = function (type) {
- this.id = Math.uuid(null, 16);
- this.type = type;
- this.folder = 0;
- this.timestamp = new Date();
- this.from = "";
- this.to = [""];
- this.cc = [""];
- this.bcc = [""];
- this.body = "";
- this.isRead = false;
- this.priority = false;
- this.subject = "";
- this.attachments = [""];
-
- this.update = function (successCallback, errorCallback) {
- function _update() {
- var isFound = false;
-
- if (!_security.all && !_security.update)
- return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
-
- TypeCoerce(new Message(0)).cast(this);
- _get();
- utils.forEach(_messages[this.folder], function (messageItem) {
- if (messageItem.id === this.id) {
- !this.isRead || (messageItem.isRead = this.isRead);
- if (this.folder === _self().FOLDER_DRAFTS) {
- !this.type || (messageItem.type = this.type);
- !this.to || (messageItem.to = utils.copy(this.to));
- !this.cc || (messageItem.cc = utils.copy(this.cc));
- !this.bcc || (messageItem.bcc = utils.copy(this.bcc));
- !this.body || (messageItem.body = this.body);
- !this.priority || (messageItem.priority = this.priority);
- !this.subject || (messageItem.subject = this.subject);
- !this.attachments || (messageItem.attachments = utils.copy(this.attachments));
- }
- isFound = true;
- }
- });
-
- if (isFound) {
- _save();
- successCallback();
- } else {
- _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
- }
- }
- return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "update", _pendingOperate(_update, this));
- };
-};
+Appointment.__defineGetter__("FREE", function () {
+ return 0;
+});
+Appointment.__defineGetter__("TENTATIVE", function () {
+ return 1;
+});
+Appointment.__defineGetter__("BUSY", function () {
+ return 2;
+});
+Appointment.__defineGetter__("OUT_OF_OFFICE", function () {
+ return 3;
+});
-MessageFilter = {
- id: "",
- type: [0],
- folder: [0],
- startTimestamp: new Date(),
- endTimestamp: new Date(),
- from: "",
- to: [""],
- cc: [""],
- bcc: [""],
- body: "",
- isRead: false,
- messagePriority: false,
- subject: ""
-};
+module.exports = Appointment;
-Recipients = function () {
- this.to = [];
- this.cc = [];
- this.bcc = [];
+});
+define('ripple/platform/webworks.handset/2.0.0/client/messaging', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {};
- this.total = function () {
- return (this.to.length + this.cc.length + this.bcc.length);
+});
+define('ripple/platform/webworks.handset/2.0.0/client/CameraArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.CameraArguments ( )
+var _self = function () {
+ return {
+ //readwrite property Number view
+ view: 0
};
};
-event.on("MessageReceived", function (message) {
- var onMessage;
+//const Number VIEW_CAMERA = 0
+_self.__defineGetter__("VIEW_CAMERA", function () {
+ return 0;
+});
+//const Number VIEW_RECORDER = 1
+_self.__defineGetter__("VIEW_RECORDER", function () {
+ return 1;
+});
- switch (message.type) {
- case "sms":
- message.type = _self().TYPE_SMS;
- onMessage = "onSMS";
- break;
+module.exports = _self;
- case "mms":
- message.type = _self().TYPE_MMS;
- onMessage = "onMMS";
- break;
+});
+define('ripple/platform/webworks.handset/2.0.0/client/io/dir', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
+ utils = require('ripple/utils'),
+ _uri = "blackberry/io/dir/",
+ FILE = "file://",
+ _self = {};
- case "email":
- message.type = _self().TYPE_EMAIL;
- onMessage = "onEmail";
- break;
+function _prunePrefix(path) {
+ return path.replace(new RegExp("^" + FILE), '');
+}
- default:
- break;
+utils.mixin({
+ getFreeSpaceForRoot: function (path) {
+ return transport.call(_uri + "getFreeSpaceForRoot", {
+ post: {path: _prunePrefix(path)}
+ });
+ },
+ getRootDirs: function () {
+ return transport.call(_uri + "getRootDirs", {}).map(function (dir) {
+ return FILE + dir;
+ });
}
+}, _self);
+
+utils.mixin(dir, _self);
+
+module.exports = _self;
- message.folder = _self().FOLDER_INBOX;
- _processAttachments(message);
- _updateDB(message);
- utils.forEach(_subscriber[onMessage], function (subscriberCallback) {
- subscriberCallback(message);
- });
});
+define('ripple/platform/webworks.handset/2.0.0/client/TaskArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.TaskArguments ( [task : blackberry.pim.Task ] )
+var _self = function (task) {
+ return {
+ view: 0,
+ task: task
+ };
+};
-event.on("MessageSent", function (sentStatus) {
- _sentStatus = sentStatus;
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_NEW", function () {
+ return 0;
+});
+//const Number VIEW_EDIT = 1
+_self.__defineGetter__("VIEW_EDIT", function () {
+ return 1;
});
module.exports = _self;
});
-define('ripple/platform/wac/2.0/orientation', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/identity/Service', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+function Service() {
+ return {
+ emailAddress: null,
+ isDefault: null,
+ name: null,
+ type: null
+ };
+}
-var utils = require('ripple/utils'),
- event = require('ripple/event'),
- Rotation = function (alpha, beta, gamma) {
- return {
- alpha: alpha || 0,
- beta: beta || 0,
- gamma: gamma || 0
- };
- },
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- _rotationInfo = new Rotation(),
- _defaultInterval = 100,
- _watches = {},
- _self;
-
-module.exports = _self = {
- getCurrentOrientation: function (onSuccess, onError) {
- function _getCurrentOrientation() {
- setTimeout(function () {
- onSuccess(utils.copy(_rotationInfo));
- }, 1);
- return null;
- }
-
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentOrientation", _getCurrentOrientation);
- },
+Service.__defineGetter__("TYPE_EMAIL", function () {
+ return 0;
+});
- watchOrientation: function (orientationSuccess, orientationError, options) {
- function _watchOrientation() {
- var watchId = (new Date()).getTime() | 0,
- watchObj = {},
- opt = Object(options),
- minNotificationInterval = opt.minNotificationInterval | 0,
- orientationInterval = _defaultInterval;
+Service.__defineGetter__("TYPE_CALENDAR", function () {
+ return 1;
+});
- if (minNotificationInterval > 0) {
- orientationInterval = minNotificationInterval;
- }
+Service.__defineGetter__("TYPE_CONTACT", function () {
+ return 2;
+});
- watchObj = {
- onSuccess: orientationSuccess,
- onError: orientationError,
- interval: orientationInterval
- };
+module.exports = Service;
- _watches[watchId] = watchObj;
+});
+define('ripple/platform/webworks.handset/2.0.0/client/identity/Transport', function (require, exports, module) {
+/*
+ * Copyright 2011 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 Transport(name, type) {
+ this.__defineGetter__("name", function () {
+ return name || "";
+ });
+ this.__defineGetter__("type", function () {
+ return type || "";
+ });
+}
- _watches[watchId].intervalId = setInterval(function () {
- _self.getCurrentOrientation(_watches[watchId].onSuccess, _watches[watchId].onError);
- }, _watches[watchId].interval);
+module.exports = Transport;
- return watchId;
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/identity/phone', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/identity/phone/",
+ _self;
- return wac2_utils.validateTypeMismatch(orientationSuccess, orientationError, "watchOrientation", _watchOrientation);
+_self = {
+ getLineIds: function () {
+ return transport.call(_uri + "getLineIds");
},
+ getLineLabel: function (id) {
+ return transport.call(_uri + "getLineLabel", {get: {id: id}});
+ },
+ getLineNumber: function (id) {
+ return transport.call(_uri + "getLineNumber", {get: {id: id}});
+ },
+ getLineType: function (id) {
+ return transport.call(_uri + "getLineType", {get: {id: id}});
+ }
+};
- clearWatch: function (watchId) {
-
- var id = watchId | 0;
- if (_watches[id]) {
- clearInterval(_watches[id].intervalId);
- delete(_watches[id]);
- return null;
- }
+module.exports = _self;
- return undefined;
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/PhoneArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.PhoneArguments ( [dialString : String ] , [smartDialing : Boolean ] , [lineId : Number ] )
+var _self = function (dialString, smartDialing, lineId) {
+ return {
+ dialString: dialString,
+ smartDialing: smartDialing,
+ lineId: (lineId ? lineId : -1),
+ view: 0
+ };
};
-event.on("AccelerometerInfoChangedEvent", function (orientationInfo) {
- _rotationInfo.alpha = orientationInfo.orientation.alpha;
- _rotationInfo.beta = orientationInfo.orientation.beta;
- _rotationInfo.gamma = orientationInfo.orientation.gamma;
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_CALL", function () {
+ return 0;
+});
+//const Number VIEW_DEFAULT = 1
+_self.__defineGetter__("VIEW_VOICEMAIL", function () {
+ return 1;
});
+module.exports = _self;
});
-define('ripple/platform/wac/2.0/pendingObject', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/BrowserArguments', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-module.exports = function (pendingObj) {
- var cancelFlag = true;
- this.setCancelFlag = function (flag) {
- cancelFlag = flag;
- };
- this.getCancelFlag = function () {
- return cancelFlag;
+//blackberry.invoke.BrowserArguments ( url : String , [transport : blackberry.identity.Transport ] )
+module.exports = function (url, transport) {
+ return {
+ url: url
};
- this.userCancel = null;
- this.pendingID = null;
};
});
-define('ripple/platform/wac/2.0/pendingoperation', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/audio/player/";
-module.exports = function (pendingObj) {
- var pending = true;
- this.cancel = function () {
- if (pending === true) {
- if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
- pending = false;
- // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
- clearTimeout(pendingObj.pendingID);
- return false;
+function Player(locator, type, async) {
+ //we can't use the async prop since we need the ID before we can do anything else.
+ var _id = transport.call(_uri + "create", {
+ get: {locator: locator, type: type},
+ async: false
+ }),
+ _listener,
+ _closed,
+ _self,
+ _poll = function (path) {
+ transport.poll(_uri + path, {
+ get: {id: _id}
+ }, function (response) {
+ if (_listener) {
+ _listener(_self, response.event, response.eventData);
+ }
+
+ return !!_listener;
+ });
+ };
+
+ _self = {
+ addPlayerListener: function (callback) {
+ if (!_closed && callback) {
+ _listener = callback;
+ _poll("onStart");
+ _poll("onStopped");
+ _poll("onBufferingStarted");
+ _poll("onBufferingStopped");
+ _poll("onDurationUpdated");
+ _poll("onEnd");
+ _poll("onError");
+ _poll("onVolumeChange");
+ _poll("onClose");
}
- if (typeof (pendingObj.userCancel) === "function") {
- pendingObj.userCancel();
+ else {
+ _listener = null;
}
- clearTimeout(pendingObj.pendingID);
- pending = false;
- return true;
- } else {
- return false;
+
+ return !_closed;
+ },
+
+ close: function () {
+ _listener = null;
+ _closed = true;
+ return transport.call(_uri + "close", {get: {id: _id}});
+ },
+
+ pause: function () {
+ return transport.call(_uri + "pause", {get: {id: _id}});
+ },
+
+ play: function () {
+ return transport.call(_uri + "play", {get: {id: _id}});
}
};
-};
+ _self.__defineGetter__("duration", function () {
+ return transport.call(_uri + "getDuration", {get: {id: _id}});
+ });
+
+ _self.__defineGetter__("mediaTime", function () {
+ return transport.call(_uri + "getMediaTime", {get: {id: _id}});
+ });
+
+ _self.__defineSetter__("mediaTime", function (val) {
+ transport.call(_uri + "setMediaTime", {get: {id: _id, value: val}});
+ });
+
+ _self.__defineGetter__("state", function () {
+ return transport.call(_uri + "getState", {get: {id: _id}});
+ });
+
+ _self.__defineGetter__("volumeLevel", function () {
+ return transport.call(_uri + "getVolumeLevel", {get: {id: _id}});
+ });
+
+ _self.__defineSetter__("volumeLevel", function (val) {
+ transport.call(_uri + "setVolumeLevel", {get: {id: _id, value: val}});
+ });
+
+ _self.__defineGetter__("EVENT_BUFFERING_STARTED", function () {
+ return "EVENT_BUFFERING_STARTED";
+ });
+ _self.__defineGetter__("EVENT_BUFFERING_STOPPED", function () {
+ return "EVENT_BUFFERING_STOPPED";
+ });
+ _self.__defineGetter__("EVENT_CLOSED", function () {
+ return "EVENT_CLOSED";
+ });
+ _self.__defineGetter__("EVENT_DEVICE_AVAILABLE", function () {
+ return "EVENT_DEVICE_AVAILABLE";
+ });
+ _self.__defineGetter__("EVENT_DEVICE_UNAVAILABLE", function () {
+ return "EVENT_DEVICE_UNAVAILABLE";
+ });
+ _self.__defineGetter__("EVENT_DURATION_UPDATED", function () {
+ return "EVENT_DURATION_UPDATED";
+ });
+ _self.__defineGetter__("EVENT_END_OF_MEDIA", function () {
+ return "EVENT_END_OF_MEDIA";
+ });
+ _self.__defineGetter__("EVENT_ERROR", function () {
+ return "EVENT_ERROR";
+ });
+ _self.__defineGetter__("EVENT_RECORD_ERROR", function () {
+ return "EVENT_ERROR";
+ });
+ _self.__defineGetter__("EVENT_RECORD_STARTED", function () {
+ return "EVENT_RECORD_STARTED";
+ });
+ _self.__defineGetter__("EVENT_RECORD_STOPPED", function () {
+ return "EVENT_RECORD_STOPPED";
+ });
+ _self.__defineGetter__("EVENT_SIZE_CHANGED", function () {
+ return "EVENT_SIZE_CHANGED";
+ });
+ _self.__defineGetter__("EVENT_STARTED", function () {
+ return "EVENT_STARTED";
+ });
+ _self.__defineGetter__("EVENT_STOPPED", function () {
+ return "EVENT_STOPPED";
+ });
+ _self.__defineGetter__("EVENT_STOPPED_AT_TIME", function () {
+ return "EVENT_STOPPED_AT_TIME";
+ });
+ _self.__defineGetter__("EVENT_VOLUME_CHANGED", function () {
+ return "EVENT_VOLUME_CHANGED";
+ });
+
+ return _self;
+}
+Player.__defineGetter__("TIME_UNKNOWN", function () {
+ return -1;
});
-define('ripple/platform/wac/2.0/spec/config', function (require, exports, module) {
+Player.__defineGetter__("CLOSED", function () {
+ return 0;
+});
+Player.__defineGetter__("UNREALIZED", function () {
+ return 100;
+});
+Player.__defineGetter__("REALIZED", function () {
+ return 200;
+});
+Player.__defineGetter__("PREFETCHED", function () {
+ return 300;
+});
+Player.__defineGetter__("STARTED", function () {
+ return 400;
+});
+
+module.exports = Player;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/category', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var platform = require('ripple/platform'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- constants = require('ripple/constants');
-
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (configValidationObject) {
- var valid = true;
- // no xmlns:JIL in wac 2.0 spec
- valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/pim/category/",
+ _self;
- return valid;
+_self = {
+ addCategory: function (categoryName) {
+ transport.call(_uri + "addCategory", {
+ get: {categoryName: categoryName}
+ });
},
- extractInfo: function (configValidationObject) {
- if (!configValidationObject) {
- return null;
- }
+ deleteCategory: function (categoryName) {
+ transport.call(_uri + "deleteCategory", {
+ get: {categoryName: categoryName}
+ });
+ },
+ getCategories: function () {
+ return transport.call(_uri + "getCategories");
+ }
+};
- var widgetInfo = {},
- configFeatures,
- configPreferences,
- preferenceName,
- platform;
+module.exports = _self;
- widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
- widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
- widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+});
+define('ripple/platform/webworks.handset/2.0.0/client/PushData', function (require, exports, module) {
+/*
+ * Copyright 2011 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 PushData(data, port) {
+ this.port = port;
+ this.data = data;
- widgetInfo.features = {};
+ this.getHeaderField = function (field) {
+ if (field === undefined || field === null) {
+ throw "no field specified";
+ }
+ else if (!(typeof field === 'number' && field >= 0) && typeof field !== 'string') {
+ throw "field is not valid";
+ }
- configFeatures = configValidationObject.widget.children.feature.validationResult;
- utils.forEach(configFeatures, function (f) {
- if (f.valid === true) {
- var feature = {id: f.attributes.name.value,
- required: f.attributes.required.valid};
- widgetInfo.features[feature.id] = feature;
- }
- });
+ return data.headerField[field];
+ };
- widgetInfo.preferences = {};
+ this.getRequestURI = function () {
+ return data.requestURI;
+ };
- configPreferences = configValidationObject.widget.children.preference.validationResult;
+ this.getSource = function () {
+ return data.source;
+ };
- platform = require('ripple/platform');
- utils.forEach(configPreferences, function (preference) {
- preferenceName = preference.attributes.name.value;
- if (preferenceName) {
- widgetInfo.preferences[preferenceName] = {
- "key": preferenceName,
- "value": preference.attributes.value.value || "",
- "readonly": preference.attributes.readonly.value === "true"
- };
+ this.isChannelEncrypted = data.isChannelEncrypted;
- db.save(preferenceName,
- widgetInfo.preferences[preferenceName].value,
- platform.getPersistencePrefix(widgetInfo.id));
- }
- });
+ this.payload = data.payload;
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,feature and preference. \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- viewmodes: {
- attributeName: "viewmodes",
- required: false,
- type: "list",
- listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
- },
- defaultlocale: {
- attributeName: "defaultlocale",
- required: false,
- type: "iso-language"
- },
- },
- children: {
- name: {
- nodeName: "name",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- "short": {
- attributeName: "short",
- required: false,
- type: "string"
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- required: false,
- type: "regex",
- regex: constants.REGEX.URL
- },
- email: {
- attributeName: "email",
- required: false,
- type: "regex",
- regex: constants.REGEX.EMAIL
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 0,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- href: {
- attributeName: "href",
- type: "regex",
- required: false,
- regex: constants.REGEX.URL
- }
- },
- children: {
- span: {
- nodeName: "span",
- required: false,
- type: "string",
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- }
- }
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- width: {
- attributeName: "width",
- required: false,
- type: "integer"
- },
- height: {
- attributeName: "height",
- required: false,
- type: "integer"
- }
- }
- },
- content: {
- nodeName: "content",
- required: false,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- unique: true
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- encoding: {
- attributeName: "encoding",
- required: false,
- type: "string"
- },
- type: {
- attributeName: "type",
- required: false,
- type: "string"
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/TR/geolocation-API/",
- "http://wacapps.net/api/deviceapis", "http://wacapps.net/api/accelerometer",
- "http://wacapps.net/api/orientation", "http://wacapps.net/api/camera",
- "http://wacapps.net/api/camera.show", "http://wacapps.net/api/camera.capture",
- "http://wacapps.net/api/devicestatus", "http://wacapps.net/api/devicestatus.deviceinfo",
- "http://wacapps.net/api/devicestatus.networkinfo", "http://wacapps.net/api/filesystem",
- "http://wacapps.net/api/filesystem.read", "http://wacapps.net/api/filesystem.write",
- "http://wacapps.net/api/messaging", "http://wacapps.net/api/messaging.send",
- "http://wacapps.net/api/messaging.find", "http://wacapps.net/api/messaging.subscribe",
- "http://wacapps.net/api/messaging.write", "http://wacapps.net/api/pim.contact",
- "http://wacapps.net/api/pim.contact.read", "http://wacapps.net/api/pim.contact.write",
- "http://wacapps.net/api/pim.calendar", "http://wacapps.net/api/pim.calendar.read",
- "http://wacapps.net/api/pim.calendar.write", "http://wacapps.net/api/pim.task",
- "http://wacapps.net/api/pim.task.read", "http://wacapps.net/api/pim.task.write",
- "http://wacapps.net/api/deviceinteraction"]
- },
- required: {
- attributeName: "required",
- type: "boolean",
- required: false
- }
- },
- children: {
- param: {
- nodeName: "param",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string",
- },
- value: {
- attributeName: "value",
- required: true,
- type: "string",
- }
- }
- }
- }
- },
- preference: {
- nodeName: "preference",
- required: false,
- occurrence: 0,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language",
- },
- dir: {
- attributeName: "dir",
- required: false,
- type: "list",
- listValues: ["ltr", "rtl", "lro", "rlo"]
- },
- name: {
- attributeName: "name",
- required: true,
- type: "string"
- },
- value: {
- type: "string",
- required: false,
- attributeName: "value"
- },
- readonly: {
- attributeName: "readonly",
- type: "boolean",
- required: false
- }
- }
- }
- }
- }
- }
-};
+ this.__defineGetter__("ACCEPT", function () {
+ return 0;
+ });
+ this.__defineGetter__("DECLINE_USERDCR", function () {
+ return 1;
+ });
+ this.__defineGetter__("DECLINE_USERDCU", function () {
+ return 2;
+ });
+ this.__defineGetter__("DECLINE_USERPND", function () {
+ return 3;
+ });
+ this.__defineGetter__("DECLINE_USERREQ", function () {
+ return 4;
+ });
+ this.__defineGetter__("DECLINE_USERRFS", function () {
+ return 5;
+ });
+}
+
+module.exports = PushData;
});
-define('ripple/platform/wac/2.0/spec/device', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/identity', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
-
-function deviceStatusEventTrigger(setting) {
- event.trigger("DeviceStatusChanged", [setting]);
-}
-
-module.exports = {
- "Config": {
- "vibratingMode": {
- "name": "Vibrator",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("VibratingModeChanged", [setting]);
- }
- },
- "soundVolume": {
- "name": "Sound Volume",
- "control": {
- "type": "range",
- "value": 100,
- "min": 0,
- "max": 100
- },
- "callback": function (setting) {
- event.trigger("VolumeChanged", [setting]);
- }
- },
- "backlight": {
- "name": "Backlight",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("BacklightChanged", [setting]);
- }
- }
- },
- "Battery": {
- "batteryLevel": {
- "name": "Battery Remaining %",
- "control": {
- "type": "select",
- "value": 100
- },
- "options": (function () {
- var i,
- optionList = {};
-
- for (i = 0; i <= 100; i += 10) {
- optionList[i] = i;
- }
-
- return optionList;
- }()),
- "event": "BatteryLevelChanged",
- "callback": function (setting) {
- event.trigger("BatteryLevelChanged", [setting]);
- }
- },
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/identity/",
+ _self;
- "batteryBeingCharged": {
- "name": "Battery Is Charging",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "BatteryBeingChargedChanged",
- "callback": function (setting) {
- event.trigger("BatteryBeingChargedChanged", [setting]);
- }
- },
+_self = {
+ getDefaultService: function () {
+ return transport.call(_uri + "getDefaultService");
},
- "CellularHardware": {
- "status": {
- "name": "status",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "CellularHardwareStatusChanged",
- "callback": function (setting) {
- event.trigger("CellularHardwareStatusChanged", [setting]);
- }
- }
+ getServiceList: function () {
+ return transport.call(_uri + "getServiceList");
},
- "CellularNetwork": {
- "isInRoaming": {
- "name": "Roaming",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "CellularNetworkIsInRoamingChanged",
- "callback": function (setting) {
- event.trigger("CellularNetworkIsInRoamingChanged", [setting]);
- }
- },
- "mcc": {
- "name": "mcc",
- "control": {
- "type": "text",
- "value": "460",
- "readonly": "readonly"
- }
- },
- "mnc": {
- "name": "mnc",
- "control": {
- "type": "text",
- "value": "0",
- "readonly": "readonly"
- }
- },
- "signalStrength": {
- "name": "Signal Strength",
- "control": {
- "type": "select",
- "value": 100
- },
- "options": (function () {
- var i,
- optionList = {};
-
- for (i = 0; i <= 100; i += 10) {
- optionList[i] = i;
- }
+ getTransportList: function () {
+ return transport.call(_uri + "getTransportList");
+ }
+};
- return optionList;
- }()),
- "event": "CellularNetworkSignalStrengthChanged",
- "callback": function (setting) {
- event.trigger("CellularNetworkSignalStrengthChanged", [setting]);
- }
- },
- "operatorName": {
- "name": "Operator Name",
- "control": {
- "type": "text",
- "value": "CMCC",
- "readonly": "readonly"
- }
- }
- },
- "Device": {
- "imei": {
- "name": "IMEI",
- "control": {
- "type": "text",
- "value": "860398001689659",
- "readonly": "readonly"
- }
- },
- "model": {
- "name": "Model",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- },
- "version": {
- "name": "Version",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- },
- "vendor": {
- "name": "Vendor.",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- }
- },
- "Display": {
- "resolutionHeight": {
- "name": "Resolution Height",
- "control": {
- "type": "number",
- "value": 0,
- "readonly": "readonly"
- }
- },
- "resolutionWidth": {
- "name": "Resolution Width",
- "control": {
- "type": "number",
- "value": 0,
- "readonly": "readonly"
- }
- },
- "pixelAspectRatio": {
- "name": "Pixel Aspectratio",
- "control": {
- "type": "number",
- "value": 0,
- "readonly": "readonly"
- }
- },
- "dpiY": {
- "name": "DPI-Y",
- "control": {
- "type": "number",
- "value": 0,
- "readonly": "readonly"
- }
- },
- "dpiX": {
- "name": "DPI-X",
- "control": {
- "type": "number",
- "value": 0,
- "readonly": "readonly"
- }
- },
- "colorDepth": {
- "name": "Color Depth",
- "control": {
- "type": "number",
- "value": 32,
- "readonly": "readonly"
- }
- }
- },
- "MemoryUnit": {
- "removable": {
- "name": "Removable",
- "control": {
- "type": "checkbox",
- "value": true,
- "readonly": "readonly"
- }
- },
- "size": {
- "name": "Total Memory",
- "control": {
- "type": "number",
- "value": 262144,
- "readonly": "readonly"
- }
- },
- "availableSize": {
- "name": "Available Size",
- "control": {
- "type": "range",
- "value": 16384,
- "min": 0,
- "max": 262144
- },
- "event": "MemoryUnitAvailableSizeChanged",
- "callback": function (setting) {
- event.trigger("MemoryUnitAvailableSizeChanged", [setting]);
- }
- }
- },
- "OperatingSystem": {
- "language": {
- "name": "Language",
- "control": {
- "type": "text",
- "value": "English",
- "readonly": "readonly"
- }
- },
- "version": {
- "name": "Version",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- },
- "name": {
- "name": "Name",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- },
- "vendor": {
- "name": "Vendor",
- "control": {
- "type": "text",
- "value": "",
- "readonly": "readonly"
- }
- }
- },
- "WebRuntime": {
- "wacVersion": {
- "name": "WAC Version",
- "control": {
- "type": "text",
- "value": "2.0",
- "readonly": "readonly"
- }
- },
- "supportedImageFormats": {
- "name": "Image Formats",
- "control": {
- "type": "text",
- "value": "gif87, gif89, png, jpeg",
- "readonly": "readonly"
- },
- "event": "WebRuntimeSupportedImageFormatsChanged",
- "callback": function (setting) {
- event.trigger("WebRuntimeSupportedImageFormatsChanged", [setting]);
- }
- },
- "version": {
- "name": "Web Runtime Version",
- "control": {
- "type": "text",
- "value": "1.0",
- "readonly": "readonly"
- }
- },
- "name": {
- "name": "Web Runtime Name",
- "control": {
- "type": "text",
- "value": "Tizen Web Simulator",
- "readonly": "readonly"
- }
- },
- "vendor": {
- "name": "Vendor Name",
- "control": {
- "type": "text",
- "value": "Tizen SDK team",
- "readonly": "readonly"
- }
- }
- },
- "WiFiHardware": {
- "status": {
- "name": "Status",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "WiFiHardwareStatusChanged",
- "callback": function (setting) {
- event.trigger("WiFiHardwareStatusChanged", [setting]);
- }
- }
- },
- "WiFiNetwork": {
- "ssid": {
- "name": "SSID",
- "control": {
- "type": "text",
- "value": "OfficeWLAN"
- },
- "event": "WiFiHardwareSsidChanged",
- "callback": function (setting) {
- event.trigger("WiFiHardwareSsidChanged", [setting]);
- }
- },
- "signalStrength": {
- "name": "Signal Strength",
- "control": {
- "type": "select",
- "value": 10
- },
- "options": (function () {
- var i,
- optionList = {};
+_self.__defineGetter__("IMEI", function () {
+ return transport.call(_uri + "IMEI");
+});
- for (i = 0; i <= 10; i++) {
- optionList[i] = i;
- }
+_self.__defineGetter__("IMSI", function () {
+ return transport.call(_uri + "IMSI");
+});
- return optionList;
- }()),
- "event": "WiFiHardwareSignalStrengthChanged",
- "callback": function (setting) {
- event.trigger("WiFiHardwareSignalStrengthChanged", [setting]);
- }
- },
- "networkStatus": {
- "name": "Network Status",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "event": "WiFiHardwareNetworkStatusChanged",
- "callback": function (setting) {
- event.trigger("WiFiHardwareNetworkStatusChanged", [setting]);
- }
- }
- }
-};
+_self.__defineGetter__("PIN", function () {
+ return transport.call(_uri + "PIN");
+});
+module.exports = _self;
});
-define('ripple/platform/wac/2.0/spec/ui', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/JavaArguments', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- plugins: [
- "accelerometer",
- "messaging",
- "geoView",
- "widgetConfig",
- "deviceSettings"
- ]
+//blackberry.invoke.JavaArguments ( uri : String , [params : String [ ] ] )
+var _self = function (uri, params) {
+ return {
+ uri: uri,
+ params: params,
+ args: arguments
+ };
};
+module.exports = _self;
+
});
-define('ripple/platform/wac/2.0/spec', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/FilterExpression', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+//blackberry.find.FilterExpression ( leftField : object , operator : object , rightField : object , [negate : Boolean ] )
+var FilterExpression = function (leftField, operator, rightField, negate) {
+ this.__defineGetter__("leftField", function () {
+ return leftField;
+ });
-module.exports = {
+ this.__defineGetter__("operator", function () {
+ return operator;
+ });
- id: "wac",
- version: "2.0",
- name: "WAC",
+ this.__defineGetter__("rightField", function () {
+ return rightField;
+ });
- persistencePrefix: "wac2-",
+ this.__defineGetter__("negate", function () {
+ return negate ? true : false;
+ });
+};
- config: require('ripple/platform/wac/2.0/spec/config'),
- ui: require('ripple/platform/wac/2.0/spec/ui'),
- device: require('ripple/platform/wac/2.0/spec/device'),
+module.exports = FilterExpression;
- objects: {
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- navigator: {
- path: "w3c/1.0/navigator",
- children: {
- geolocation: {
- path: "wac/2.0/geolocation",
- feature: "http://www.w3.org/TR/geolocation-API/"
- }
- }
- },
- deviceapis: {
- path: "wac/2.0/deviceapis",
- feature: "http://wacapps.net/api/deviceapis",
- /*
- * Before we inject those cloned objects into the simulated application
- * namespace, we will handle the feature requests from config.xml.
- * Especially for:
- * - camera.show, camera.capture
- * - devicestatus.deviceinfo, devicestatus.networkinfo
- * - filesystem.read, filesystem.write
- * - messaging.send, messaging.find, messaging.subscribe, messaging.write
- * - pim
- * - contact.read, contact.write
- * - calendar.read, calendar.write
- * - task.read, task.write
- */
- children: {
- accelerometer: {
- path: "wac/2.0/accelerometer",
- feature: "http://wacapps.net/api/accelerometer"
- },
- orientation: {
- path: "wac/2.0/orientation",
- feature: "http://wacapps.net/api/orientation"
- },
- camera: {
- path: "wac/2.0/camera",
- feature: "http://wacapps.net/api/camera|http://wacapps.net/api/camera.show|http://wacapps.net/api/camera.capture",
- handleSubfeatures: true
- },
- devicestatus: {
- path: "wac/2.0/devicestatus",
- feature: "http://wacapps.net/api/devicestatus|http://wacapps.net/api/devicestatus.deviceinfo|http://wacapps.net/api/devicestatus.networkinfo",
- handleSubfeatures: true
- },
- filesystem: {
- path: "wac/2.0/filesystem",
- feature: "http://wacapps.net/api/filesystem|http://wacapps.net/api/filesystem.read|http://wacapps.net/api/filesystem.write",
- handleSubfeatures: true
- },
- messaging: {
- path: "wac/2.0/messaging",
- feature: "http://wacapps.net/api/messaging|http://wacapps.net/api/messaging.send|http://wacapps.net/api/messaging.find|http://wacapps.net/api/messaging.subscribe|http://wacapps.net/api/messaging.write",
- handleSubfeatures: true
- },
- pim: {
- children: {
- contact: {
- path: "wac/2.0/contact",
- feature: "http://wacapps.net/api/pim.contact|http://wacapps.net/api/pim.contact.read|http://wacapps.net/api/pim.contact.write",
- handleSubfeatures: true
- },
- calendar: {
- path: "wac/2.0/calendar",
- feature: "http://wacapps.net/api/pim.calendar.write|http://wacapps.net/api/pim.calendar.read|http://wacapps.net/api/pim.calendar",
- handleSubfeatures: true
- },
- task: {
- path: "wac/2.0/task",
- feature: "http://wacapps.net/api/pim.task|http://wacapps.net/api/pim.task.read|http://wacapps.net/api/pim.task.write",
- handleSubfeatures: true
- }
- }
- },
- deviceinteraction: {
- path: "wac/2.0/deviceinteraction",
- feature: "http://wacapps.net/api/deviceinteraction"
- }
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/system', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ system = require('ripple/platform/webworks.core/2.0.0/client/system'),
+ _uri = "blackberry/system/",
+ _self;
+
+_self = {
+ setHomeScreenBackground: function (filePath) {
+ transport.call(_uri + "setHomeScreenBackground", {
+ get: {filePath: filePath},
+ async: true
+ });
+ },
+};
+
+(function () {
+ // HACK: can't type check if system[key] is a function, sets off getters
+ // also can't use utils.mixin or forEach for the same reason
+ function get(i) {
+ return function () {
+ return system[i];
+ };
+ }
+
+ for (var key in system) {
+ if (system.hasOwnProperty(key)) {
+ _self.__defineGetter__(key, get(key));
}
}
-};
+}());
+module.exports = _self;
});
-define('ripple/platform/wac/2.0/task', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/Recurrence', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+function Recurrence() {
+ return {
+ //readwrite property Number count
+ //readwrite property Number dayInMonth
+ //readwrite property Number dayInWeek
+ //readwrite property Number dayInYear
+ //readwrite property Date end
+ //readwrite property Number frequency
+ //readwrite property Number interval
+ //readwrite property Number monthInYear
+ //readwrite property Number weekInMonth
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- _console = require('ripple/console'),
- exception = require('ripple/exception'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
- PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
- PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
- Task, TaskList, _get,
- _ID_WITHOUT = 0, _ID_GEN_NEW = 1, _ID_FROM_PROP = 2,
- _SIM_TASK_LIST = 0, _DEVICE_TASK_LIST = 1,
- _HIGH_PRIORITY = 0, _MEDIUM_PRIORITY = 1, _LOW_PRIORITY = 2,
- _STATUS_COMPLETED = 0, _STATUS_NEEDS_ACTION = 1, _STATUS_IN_PROCESS = 2, _STATUS_CANCELLED = 3,
- _TASK_OBJECTS = "wac2.0-pim-task-objects",
- _addTaskAllowed = true, _deleteTaskAllowed = true,
- _updateTaskAllowed = true, _findTasksAllowed = true;
-
+ count: null,
+ dayInMonth: null,
+ dayInWeek: null,
+ dayInYear: null,
+ end: null,
+ frequency: null,
+ interval: null,
+ monthInYear: null,
+ weekInMonth: null
+ };
+}
-module.exports = function () {
- var _taskListArray = [],
- _PENDING_TIME = 10;
+Recurrence.__defineGetter__("NO_REPEAT", function () {
+ return 0;
+});
+Recurrence.__defineGetter__("DAILY", function () {
+ return 1;
+});
+Recurrence.__defineGetter__("WEEKLY", function () {
+ return 2;
+});
+Recurrence.__defineGetter__("MONTHLY", function () {
+ return 3;
+});
+Recurrence.__defineGetter__("YEARLY", function () {
+ return 4;
+});
+Recurrence.__defineGetter__("JANUARY", function () {
+ return 0x20000;
+});
+Recurrence.__defineGetter__("FEBRUARY", function () {
+ return 0x40000;
+});
+Recurrence.__defineGetter__("MARCH", function () {
+ return 0x80000;
+});
+Recurrence.__defineGetter__("APRIL", function () {
+ return 0x100000;
+});
+Recurrence.__defineGetter__("MAY", function () {
+ return 0x200000;
+});
+Recurrence.__defineGetter__("JUNE", function () {
+ return 0x400000;
+});
+Recurrence.__defineGetter__("JULY", function () {
+ return 0x800000;
+});
+Recurrence.__defineGetter__("AUGUST", function () {
+ return 0x1000000;
+});
+Recurrence.__defineGetter__("SEPTEMBER", function () {
+ return 0x2000000;
+});
+Recurrence.__defineGetter__("OCTOBER", function () {
+ return 0x4000000;
+});
+Recurrence.__defineGetter__("NOVEMBER", function () {
+ return 0x8000000;
+});
+Recurrence.__defineGetter__("DECEMBER", function () {
+ return 0x10000000;
+});
+Recurrence.__defineGetter__("FIRST", function () {
+ return 0x1;
+});
+Recurrence.__defineGetter__("SECOND", function () {
+ return 0x2;
+});
+Recurrence.__defineGetter__("THIRD", function () {
+ return 0x4;
+});
+Recurrence.__defineGetter__("FOURTH", function () {
+ return 0x8;
+});
+Recurrence.__defineGetter__("FIFTH", function () {
+ return 0x10;
+});
+Recurrence.__defineGetter__("LAST", function () {
+ return 0x20;
+});
+Recurrence.__defineGetter__("SECONDLAST", function () {
+ return 0x40;
+});
+Recurrence.__defineGetter__("THIRDLAST", function () {
+ return 0x80;
+});
+Recurrence.__defineGetter__("FOURTHLAST", function () {
+ return 0x100;
+});
+Recurrence.__defineGetter__("FIFTHLAST", function () {
+ return 0x200;
+});
+Recurrence.__defineGetter__("SUNDAY", function () {
+ return 0x10000;
+});
+Recurrence.__defineGetter__("MONDAY", function () {
+ return 0x8000;
+});
+Recurrence.__defineGetter__("TUESDAY", function () {
+ return 0x4000;
+});
+Recurrence.__defineGetter__("WEDNESDAY", function () {
+ return 0x2000;
+});
+Recurrence.__defineGetter__("THURSDAY", function () {
+ return 0x1000;
+});
+Recurrence.__defineGetter__("FRIDAY", function () {
+ return 0x800;
+});
+Recurrence.__defineGetter__("SATURDAY", function () {
+ return 0x400;
+});
- function _pendingOperate(operate) {
- var pendingObj, pendingOperation, i, argumentVector = [];
+module.exports = Recurrence;
- for (i = 0; i < arguments.length - 1; i++)
- argumentVector[i] = arguments[i + 1];
+});
+define('ripple/platform/webworks.handset/2.0.0/client/Message', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
+ identity = require('ripple/platform/webworks.handset/2.0.0/client/identity'),
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
+ select = require('ripple/platform/webworks.core/2.0.0/select'),
+ _uri = "blackberry/message/message/";
- pendingObj = new PendingObject();
+function Message(service) {
+ var _service = service,
+ _msg = {
+ uid: 0,
+ status: Message.STATUS_DRAFT,
+ from: "",
+ folder: Message.FOLDER_DRAFT,
+ replyTo: "",
+ bccRecipients: "",
+ body: "",
+ ccRecipients: "",
+ priority: Message.PRIORITY_MEDIUM, //default to med priority
+ subject: "",
+ toRecipients: "",
- pendingObj.pendingID = window.setTimeout(function () {
- pendingObj.setCancelFlag(false);
- operate.apply(this, argumentVector);
- }, _PENDING_TIME);
+ remove: function () {
+ _msg.folder = Message.FOLDER_DELETED;
+ transport.call(_uri + "remove", {
+ get: {uid: _msg.uid}
+ });
+ },
- pendingOperation = new PendingOperation(pendingObj);
+ save: function () {
+ if (_msg.uid === 0) {
+ _msg.uid = Number(Math.uuid(8, 10));
+ }
- return pendingOperation;
- }
+ _msg.replyTo = _msg.from = _service.emailAddress;
+ _msg.status = Message.STATUS_SAVED;
+ transport.call(_uri + "save", {
+ post: {message: _msg}
+ });
+ },
- /* taskProperties attribute check & paste */
- function _checkAndPasteProperties(p, dst) {
+ send: function () {
+ if (_msg.toRecipients) {
+ if (_msg.uid === 0) {
+ _msg.uid = Number(Math.uuid(8, 10));
+ }
- if (p.summary !== null && p.summary !== undefined)
- dst.summary = String(p.summary);
+ _msg.folder = Message.FOLDER_DRAFT;
+ _msg.status = Message.STATUS_UNKNOWN;
+ transport.call(_uri + "send", {
+ get: {message: _msg}
+ });
+ } else {
+ throw "message has no recipients";
+ }
+ }
+ };
- if (p.description !== null && p.description !== undefined)
- dst.description = String(p.description);
+ if (!_service) {
+ _service = identity.getDefaultService().reduce(function (email, service) {
+ return service.type === Service.TYPE_EMAIL ? service : email;
+ }, null);
+ }
- if (p.status !== null && p.status !== undefined) {
- if (p.status === _STATUS_COMPLETED ||
- p.status === _STATUS_NEEDS_ACTION ||
- p.status === _STATUS_IN_PROCESS ||
- p.status === _STATUS_CANCELLED) {
- dst.status = p.status;
- } else
- return false;
- }
+ return _msg;
+}
- if (p.priority !== null && p.priority !== undefined) {
- if (p.priority === _HIGH_PRIORITY ||
- p.priority === _MEDIUM_PRIORITY ||
- p.priority === _LOW_PRIORITY) {
- dst.priority = p.priority;
- } else
- return false;
+Message.find = function (filter, maxReturn, service) {
+ var opts = {
+ post: {
+ filter: filter,
+ maxReturn: maxReturn,
+ service: service
}
+ };
- if (p.dueDate !== null && p.dueDate !== undefined) {
- if (!wac2_utils.isValidDate(p.dueDate))
- return false;
- dst.dueDate = new Date(p.dueDate);
- }
+ return transport.call(_uri + "find", opts).map(function (obj) {
+ var msg = new Message();
- /* dueDate is a option properties.
- "The default value is undefined.
- If no value is provided, the task has no due date."
- If p.dueDate is set its default value 'undefined',
- we assign default value to dst.dueDate */
- if (p.dueDate === undefined) {
- dst.dueDate = undefined;
- }
+ msg.uid = obj.uid;
+ msg.status = obj.status;
+ msg.from = obj.from;
+ msg.folder = obj.folder;
+ msg.replyTo = obj.replyTo;
+ msg.bccRecipients = obj.bccRecipients;
+ msg.body = obj.body;
+ msg.ccRecipients = obj.ccRecipients;
+ msg.priority = obj.priority;
+ msg.subject = obj.subject;
+ msg.toRecipients = obj.toRecipients;
- return true;
- }
+ return msg;
+ });
+};
- function _taskFilterCheck(filter) {
- var i;
- if (filter.id !== undefined && filter.id !== null) {
- filter.id = String(filter.id);
- } else {
- filter.id = undefined;
- }
- if (filter.summary !== undefined && filter.summary !== null) {
- filter.summary = String(filter.summary);
- } else {
- filter.summary = undefined;
- }
- if (filter.description !== undefined && filter.description !== null) {
- filter.description = String(filter.description);
- } else {
- filter.description = undefined;
- }
- if (filter.status !== undefined && filter.status !== null) {
- if (!wac2_utils.isValidArray(filter.status)) {
- return false;
- }
- for (i = 0; i < filter.status.length; i++) {
- filter.status[i] = filter.status[i] | 0;
- if (filter.status[i] !== _STATUS_COMPLETED &&
- filter.status[i] !== _STATUS_NEEDS_ACTION &&
- filter.status[i] !== _STATUS_IN_PROCESS &&
- filter.status[i] !== _STATUS_CANCELLED) {
- return false;
- }
- }
- } else {
- filter.status = undefined;
- }
- if (filter.priority !== undefined && filter.priority !== null) {
- if (!wac2_utils.isValidArray(filter.priority)) {
- return false;
- }
- for (i = 0; i < filter.priority.length; i++) {
- filter.priority[i] = filter.priority[i] | 0;
- if (filter.priority[i] !== _HIGH_PRIORITY &&
- filter.priority[i] !== _MEDIUM_PRIORITY &&
- filter.priority[i] !== _LOW_PRIORITY) {
- return false;
- }
- }
- } else {
- filter.priority = undefined;
- }
- if (filter.dueDate !== undefined && filter.dueDate !== null) {
- if (!wac2_utils.isValidDate(filter.dueDate)) {
- return false;
- }
- filter.dueDate = new Date(filter.dueDate);
- } else {
- filter.dueDate = undefined;
- }
- return true;
- }
- function TaskProperties(prop) {
- var _self;
- _self = {
- priority : _LOW_PRIORITY,
- description : "",
- summary : "",
- dueDate : undefined,
- status : _STATUS_NEEDS_ACTION
- };
- if (prop) {
- if (_checkAndPasteProperties(prop, _self) === false)
- return undefined;
- }
- return _self;
- }
+Message.__defineGetter__("STATUS_UNKNOWN", function () {
+ return -1;
+});
+Message.__defineGetter__("STATUS_SAVED", function () {
+ return 0;
+});
+Message.__defineGetter__("STATUS_DRAFT", function () {
+ return 1;
+});
+Message.__defineGetter__("STATUS_SENT", function () {
+ return 2;
+});
+Message.__defineGetter__("STATUS_ERROR_OCCURED", function () {
+ return 3;
+});
+Message.__defineGetter__("PRIORITY_HIGH", function () {
+ return 0;
+});
+Message.__defineGetter__("PRIORITY_MEDIUM", function () {
+ return 1;
+});
+Message.__defineGetter__("PRIORITY_LOW", function () {
+ return 2;
+});
+Message.__defineGetter__("FOLDER_INBOX", function () {
+ return 0;
+});
+Message.__defineGetter__("FOLDER_SENT", function () {
+ return 1;
+});
+Message.__defineGetter__("FOLDER_DRAFT", function () {
+ return 2;
+});
+Message.__defineGetter__("FOLDER_OUTBOX", function () {
+ return 3;
+});
+Message.__defineGetter__("FOLDER_DELETED", function () {
+ return 4;
+});
+Message.__defineGetter__("FOLDER_OTHER", function () {
+ return 5;
+});
- function Task(prop, idChoice) {
- var id, _self = new TaskProperties(prop);
- /* if error occurs during checking, _self is an empty object.
- so i randomly pick description to check if property check fails */
- if (_self.description === undefined)
- return undefined;
+module.exports = Message;
- switch (idChoice) {
- case _ID_WITHOUT:
- // do nothing
- break;
- case _ID_GEN_NEW:
- id = Math.uuid(undefined, 16);
- _self.__defineGetter__("id", function () {
- return id;
- });
- break;
- case _ID_FROM_PROP:
- id = String(prop.id);
- _self.__defineGetter__("id", function () {
- return id;
- });
- break;
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/menu', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ MenuItem = require('ripple/platform/webworks.handset/2.0.0/client/MenuItem'),
+ utils = require('ripple/utils'),
+ onSelect,
+ _items = {},
+ _uri = "blackberry/ui/menu/",
+ _self;
- return _self;
- }
+_self = {
+ addMenuItem: function (menuItem) {
+ _items[menuItem.id] = menuItem;
- function _get() {
- var taskListArray = [],
- data = db.retrieveObject(_TASK_OBJECTS);
- utils.forEach(data, function (taskList) {
- for (var t in taskList._list) {
- if (taskList._list[t].dueDate !== undefined &&
- taskList._list[t].dueDate !== null)
- taskList._list[t].dueDate = new Date(taskList._list[t].dueDate);
- }
- taskListArray.push(new TaskList(taskList._list, taskList.type, taskList.name));
+ transport.call(_uri + "addMenuItem", {
+ get: {"item": menuItem}
});
- /* add default taskList if taskListArray is empty */
- if (taskListArray.length === 0) {
- taskListArray = [new TaskList({}, 0, "Office tasks"), new TaskList({}, 1, "Home tasks")];
- }
+ if (utils.count(_items) === 1) {
+ transport.poll(_uri + "onSelect", {}, function (response) {
+ var item = _items[response];
- return taskListArray;
- }
+ if (item && item.callback) {
+ item.callback();
+ }
- function _save() {
- db.saveObject(_TASK_OBJECTS, _taskListArray);
- }
+ return !!utils.count(_items);
+ });
+ }
+ },
- function TaskList(taskList, type, name) {
- var task;
- this._list = taskList;
- this.type = type;
- this.name = name;
+ clearMenuItems: function () {
+ _items = {};
+ transport.call(_uri + "clearMenuItems");
+ },
- this.createTask = function (properties) {
- task = new Task(properties, _ID_WITHOUT);
- /* if error occurs during checking, task is an empty object.
- so i randomly pick summary to check if property check fails */
- if (task.summary === undefined) {
- exception.raise(exception.types.Argument,
- "EventProperties: input parameter contains invalid values",
- new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- return undefined;
- }
- return task;
- };
+ getMenuItems: function () {
+ return utils.map(_items, function (item) {
+ var menuItem = new MenuItem(item.isSeparator, item.ordinal, item.caption, item.callback);
+ menuItem.id = item.id;
+ menuItem.isDefault = item.isDefault;
+ return menuItem;
+ });
+ },
- this.addTask = function (onSuccess, onError, task) {
- var inner = this,
- newTask, _task = Object(task);
- function _addTask() {
- var ret;
- if (!_addTaskAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- newTask = new Task(_task, _ID_GEN_NEW);
- /* if error occurs during checking, newTask is an empty object.
- so i randomly pick id to check if property check fails */
- if (newTask.id === undefined) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- ret = _pendingOperate(function () {
- inner._list[newTask.id] = newTask;
- _save();
- onSuccess(new Task(newTask, _ID_FROM_PROP));
- });
- }
+ hasMenuItem: function (menuItem) {
+ return !!_items[menuItem.id];
+ },
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "addTask", _addTask);
- };
+ open: function () {
+ transport.call(_uri + "open", {async: true});
+ },
- this.updateTask = function (onSuccess, onError, task) {
- var inner = this,
- newTask, _task = Object(task);
- function _updateTask() {
- var ret;
- if (!_updateTaskAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
+ removeMenuItem: function (menuItem) {
+ delete _items[menuItem.id];
+ transport.call(_uri + "removeMenuItem", {
+ get: {item: menuItem}
+ });
+ },
- if (_checkAndPasteProperties(_task, _task) === false) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
+ setDefaultMenuItem: function (menuItem) {
+ utils.forEach(_items, function (item) {
+ item.isDefault = false;
+ });
- ret = _pendingOperate(function () {
- if (inner._list[_task.id]) {
- newTask = new Task(inner._list[_task.id], _ID_FROM_PROP);
- /* Don't need to double check the return of _checkAndPasteProperties
- _task has been checked & pasted already */
- _checkAndPasteProperties(_task, newTask);
- inner._list[newTask.id] = newTask;
- _save();
- onSuccess();
- } else {
- if (onError) {
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
- }
- }
- });
- return ret;
- }
+ _items[menuItem.id].isDefault = true;
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "updateTask", _updateTask);
- };
+ transport.call(_uri + "setDefaultMenuItem", {
+ get: {id: menuItem.id}
+ });
+ }
+};
- this.deleteTask = function (onSuccess, onError, id) {
- var inner = this;
- function _deleteTask() {
- var ret;
- /* according to spec "If any of the input parameters are not
- compatible with the expected type for that parameter,
- a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be
- synchronously thrown." so an error is raised synchronously */
- utils.validateArgumentType(id, "string", null,
- "Task:deleteTask: " + " invalid id parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- if (!_deleteTaskAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- ret = _pendingOperate(function () {
- if (inner._list[id]) {
- delete inner._list[id];
- _save();
- onSuccess();
- } else {
- if (onError)
- onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
- }
- });
- return ret;
- }
+module.exports = _self;
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteTask", _deleteTask);
- };
+});
+define('ripple/platform/webworks.handset/2.0.0/client/MessageArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.MessageArguments ( )
+//blackberry.invoke.MessageArguments ( message : blackberry.message.Message )
+//blackberry.invoke.MessageArguments ( to : String , subject : String , body : String )
+var _self = function () {
+ return {
+ view: 1
+ };
+};
- this.findTasks = function (onSuccess, onError, filter) {
- var inner = this, _filter = Object(filter), tmp = [], rst = [], valid_tmp = false;
- function _findTasks() {
- var ret;
- if (!_taskFilterCheck(_filter)) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
- return undefined;
- }
- if (!_findTasksAllowed) {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.SECURITY_ERR));
- }, 1);
- }
- return undefined;
- }
- ret = _pendingOperate(function () {
- var i, e;
- if (_filter.id !== undefined) {
- tmp = wac2_utils.matchOptionString(inner._list, "id", _filter.id);
- valid_tmp = true;
- }
- if (_filter.summary !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionString(tmp, "summary", _filter.summary);
- } else {
- tmp = wac2_utils.matchOptionString(inner._list, "summary", _filter.summary);
- valid_tmp = true;
- }
- }
- if (_filter.description !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionString(tmp, "description", _filter.description);
- } else {
- tmp = wac2_utils.matchOptionString(inner._list, "description", _filter.description);
- valid_tmp = true;
- }
- }
- if (_filter.status !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionShortArray(tmp, "status", _filter.status);
- } else {
- tmp = wac2_utils.matchOptionShortArray(inner._list, "status", _filter.status);
- valid_tmp = true;
- }
- }
- if (_filter.priority !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionShortArray(tmp, "priority", _filter.priority);
- } else {
- tmp = wac2_utils.matchOptionShortArray(inner._list, "priority", _filter.priority);
- valid_tmp = true;
- }
- }
- if (_filter.initialDueDate !== undefined ||
- _filter.endDueDate !== undefined) {
- if (valid_tmp) {
- tmp = wac2_utils.matchOptionDate(tmp, "dueDate", _filter.initialDueDate, _filter.endDueDate);
- } else {
- tmp = wac2_utils.matchOptionDate(inner._list, "dueDate", _filter.initialDueDate, _filter.endDueDate);
- valid_tmp = true;
- }
- }
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_NEW", function () {
+ return 0;
+});
+//const Number VIEW_DEFAULT = 1
+_self.__defineGetter__("VIEW_DEFAULT", function () {
+ return 1;
+});
+//const Number VIEW_SAVED = 2
+_self.__defineGetter__("VIEW_SAVED", function () {
+ return 2;
+});
+//const Number VIEW_SEARCH = 3
+_self.__defineGetter__("VIEW_SEARCH", function () {
+ return 3;
+});
- if (valid_tmp) {
- for (i = 0; i < tmp.length; i++) {
- rst.push(new Task(tmp[i], _ID_FROM_PROP));
- }
- } else {
- for (e in inner._list) {
- rst.push(new Task(inner._list[e], _ID_FROM_PROP));
- }
- }
- onSuccess(rst);
- });
- return ret;
- }
+module.exports = _self;
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "findTasks", _findTasks);
- };
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/app', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
+ _uri = "blackberry/app/",\r
+ _self;\r
+\r
+_self = {\r
+ exit: function () {\r
+ transport.call(_uri + "exit", {async: true});\r
+ },\r
+\r
+ setHomeScreenIcon: function (uri, hover) {\r
+ transport.call(_uri + "setHomeScreenIcon", {\r
+ get: {\r
+ uri: uri,\r
+ hover: hover\r
+ },\r
+ async: true\r
+ });\r
+\r
+ return true;\r
+ },\r
+\r
+ setHomeScreenName: function (text) {\r
+ transport.call(_uri + "setHomeScreenName", {\r
+ get: {text: text},\r
+ async: true\r
+ });\r
+\r
+ return true;\r
+ },\r
+\r
+ requestForeground: function () {\r
+ transport.call(_uri + "requestForeground", {async: true});\r
+ },\r
+\r
+ requestBackground: function () {\r
+ transport.call(_uri + "requestBackground", {async: true});\r
+ },\r
+\r
+ removeBannerIndicator: function () {\r
+ transport.call(_uri + "removeBannerIndicator", {async: true});\r
+ },\r
+\r
+ showBannerIndicator: function (icon, count) {\r
+ transport.call(_uri + "showBannerIndicator", {\r
+ get: {\r
+ icon: icon,\r
+ count: count\r
+ },\r
+ async: true\r
+ });\r
+ },\r
+};\r
+\r
+_self.__defineGetter__("author", function () {\r
+ return transport.call(_uri + "author");\r
+});\r
+\r
+_self.__defineGetter__("authorEmail", function () {\r
+ return transport.call(_uri + "authorEmail");\r
+});\r
+\r
+_self.__defineGetter__("authorURL", function () {\r
+ return transport.call(_uri + "authorURL");\r
+});\r
+\r
+_self.__defineGetter__("copyright", function () {\r
+ return transport.call(_uri + "copyright");\r
+});\r
+\r
+_self.__defineGetter__("description", function () {\r
+ return transport.call(_uri + "description");\r
+});\r
+\r
+_self.__defineGetter__("id", function () {\r
+ return transport.call(_uri + "id");\r
+});\r
+\r
+_self.__defineGetter__("isForeground", function () {\r
+ return transport.call(_uri + "isForeground");\r
+});\r
+\r
+_self.__defineGetter__("license", function () {\r
+ return transport.call(_uri + "license");\r
+});\r
+\r
+_self.__defineGetter__("licenseURL", function () {\r
+ return transport.call(_uri + "licenseURL");\r
+});\r
+\r
+_self.__defineGetter__("name", function () {\r
+ return transport.call(_uri + "name");\r
+});\r
+\r
+_self.__defineGetter__("version", function () {\r
+ return transport.call(_uri + "version");\r
+});\r
+\r
+module.exports = _self;\r
- this.getTaskLists = function (onSuccess, onError) {
- function _getTaskLists() {
- var ret;
- ret = _pendingOperate(function () {
- if (_taskListArray.length === 0) {
- _taskListArray = _get();
- }
- onSuccess(_taskListArray);
- }, 1);
- return ret;
- }
+});
+define('ripple/platform/webworks.handset/2.0.0/client/Reminder', function (require, exports, module) {
+/*
+ * Copyright 2011 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 Reminder = function () {
- return wac2_utils.validateTypeMismatch(onSuccess, onError, "getTaskLists", _getTaskLists);
- };
+ return {
+ //readwrite property Date date
+ //readwrite property Number relativeHours
+ //readwrite property Number type
- this.__defineGetter__("SIM_TASK_LIST", function () {
- return 0;
- });
- this.__defineGetter__("DEVICE_TASK_LIST", function () {
- return 1;
- });
- this.__defineGetter__("HIGH_PRIORITY", function () {
- return 0;
- });
- this.__defineGetter__("MEDIUM_PRIORITY", function () {
- return 1;
- });
- this.__defineGetter__("LOW_PRIORITY", function () {
- return 2;
- });
- this.__defineGetter__("STATUS_COMPLETED", function () {
- return 0;
- });
- this.__defineGetter__("STATUS_NEEDS_ACTION", function () {
- return 1;
- });
- this.__defineGetter__("STATUS_IN_PROCESS", function () {
- return 2;
- });
- this.__defineGetter__("STATUS_CANCELLED", function () {
- return 3;
- });
+ date: null,
+ relativeHours: null,
+ type: null
- this.handleSubFeatures = function (subFeatures) {
- if (wac2_utils.isEmptyObject(subFeatures) ||
- subFeatures["http://wacapps.net/api/pim.task"] ||
- (subFeatures["http://wacapps.net/api/pim.task.read"] &&
- subFeatures["http://wacapps.net/api/pim.task.write"])) {
- return;
- }
- if (subFeatures["http://wacapps.net/api/pim.task.read"] &&
- !subFeatures["http://wacapps.net/api/pim.task.write"]) {
- _addTaskAllowed = false;
- _deleteTaskAllowed = false;
- _updateTaskAllowed = false;
- return;
- }
- if (subFeatures["http://wacapps.net/api/pim.task.write"] &&
- !subFeatures["http://wacapps.net/api/pim.task.read"]) {
- _findTasksAllowed = false;
- return;
- }
- _console.warn("WAC-2.0-Task-handleSubFeatures: something wrong");
};
};
+Reminder.__defineGetter__("DATE", function () {
+ return 0;
+});
+Reminder.__defineGetter__("RELATIVE", function () {
+ return 1;
});
-define('ripple/platform/wac/2.0/typecoerce', function (require, exports, module) {
+
+module.exports = Reminder;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/invoke', function (require, exports, module) {
/*\r
- * Copyright 2011 Intel Corporation.\r
+ * Copyright 2011 Research In Motion Limited.\r
*\r
* Licensed under the Apache License, Version 2.0 (the "License");\r
* you may not use this file except in compliance with the License.\r
* See the License for the specific language governing permissions and\r
* limitations under the License.\r
*/\r
-\r
-var utils = require('ripple/utils'),\r
+var _uri = "blackberry/invoke/invoke",\r
+ APP_URL_CAMERA = "camera://",\r
+ APP_URL_CAMERA_VIDEO = "camera://video",\r
+ APP_URL_MAP = "map://",\r
+ APP_URL_MUSIC = "music://",\r
+ APP_URL_PHOTOS = "photos://",\r
+ APP_URL_VIDEOS = "videos://",\r
+ APP_URL_APPWORLD = "appworld://",\r
+ APP_URL_UPDATE = "update://",\r
+ APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",\r
+ APP_ADDRESSBOOK_ERROR = "Invalid arguments specified",\r
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
_self;\r
\r
-_self = function (pattern) {\r
- var typeCoerce,\r
- typeOfPattern = Object.prototype.toString.call(pattern);\r
+_self = {\r
+ invoke: function (appType, args) {\r
+ var get = {};\r
\r
- typeCoerce = {\r
- cast: function (obj) {\r
- var validObj,\r
- validValue,\r
- elementType,\r
- typeOfObj = Object.prototype.toString.call(obj);\r
+ switch (appType) {\r
\r
- switch (typeOfPattern) {\r
- case "[object String]":\r
- validObj = (typeOfObj !== typeOfPattern) ? String(obj) : obj;\r
- break;\r
+ //AddressBook\r
+ case 0:\r
+ if (args) {\r
+ if (args.view === 1 && args.contact) {\r
+ throw APP_ADDRESSBOOK_ERROR; //contact cannot be used with this view\r
+ }\r
+ else if (args.view === 2 && !args.contact) {\r
+ throw APP_ADDRESSBOOK_ERROR; //need contact for this view\r
+ }\r
+ }\r
\r
- case "[object Number]":\r
- validObj = (typeOfObj !== typeOfPattern) ? (Number(obj) | 0) : obj;\r
- break;\r
+ get.appType = appType;\r
+ break;\r
\r
- case "[object Object]":\r
- if (typeOfObj !== typeOfPattern) {\r
- validObj = {};\r
- } else {\r
- validObj = obj;\r
- utils.forEach(validObj, function (value, key) {\r
- if (pattern[key] === undefined) {\r
- delete validObj[key];\r
- } else {\r
- validValue = _self(pattern[key]).cast(value);\r
- if (validObj[key] !== validValue)\r
- validObj[key] = validValue;\r
- }\r
- });\r
- }\r
- break;\r
+ //Bluetooth Config\r
+ case 1:\r
+ get.appType = appType;\r
+ break;\r
\r
- case "[object Array]":\r
- if (typeOfObj !== typeOfPattern) {\r
- validObj = [];\r
- } else {\r
- validObj = obj;\r
- elementType = _self(pattern[0]);\r
- utils.forEach(validObj, function (element, index) {\r
- validObj[index] = elementType.cast(element);\r
- });\r
+ //Calculator\r
+ case 2:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Calendar\r
+ case 3:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Camera\r
+ case 4:\r
+ if (!args || args.view === 1) {\r
+ get.appType = APP_URL_CAMERA_VIDEO;\r
+ } else {\r
+ get.appType = APP_URL_CAMERA;\r
+ }\r
+ break;\r
+\r
+ //Maps\r
+ case 5:\r
+ get.appType = APP_URL_MAP;\r
+ break;\r
+\r
+ //Memopad\r
+ case 6:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Messages\r
+ case 7:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Phone\r
+ case 8:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Search\r
+ case 9:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Tasks\r
+ case 10:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ //Browser\r
+ case 11:\r
+\r
+ if (!args) {\r
+ get.appType = "http://";\r
+ } else {\r
+ if (args.url && !args.url.match(/^https?:\/\//)) {\r
+ throw APP_BROWSER_ERROR;\r
}\r
- break;\r
+ get.appType = args.url;\r
}\r
\r
- return validObj;\r
+ break;\r
+\r
+ //Java\r
+ case 12:\r
+ get.appType = appType;\r
+ break;\r
+\r
+ default:\r
+ throw "appType not supported";\r
}\r
- };\r
\r
- return typeCoerce;\r
+ transport.call(_uri, {\r
+ get: get,\r
+ async: true\r
+ });\r
+ }\r
};\r
\r
+_self.__defineGetter__("APP_ADDRESSBOOK", function () {\r
+ return 0;\r
+});\r
+_self.__defineGetter__("APP_BLUETOOTH_CONFIG", function () {\r
+ return 1;\r
+});\r
+_self.__defineGetter__("APP_CALCULATOR", function () {\r
+ return 2;\r
+});\r
+_self.__defineGetter__("APP_CALENDAR", function () {\r
+ return 3;\r
+});\r
+_self.__defineGetter__("APP_CAMERA", function () {\r
+ return 4;\r
+});\r
+_self.__defineGetter__("APP_MAPS", function () {\r
+ return 5;\r
+});\r
+_self.__defineGetter__("APP_MEMOPAD", function () {\r
+ return 6;\r
+});\r
+_self.__defineGetter__("APP_MESSAGES", function () {\r
+ return 7;\r
+});\r
+_self.__defineGetter__("APP_PHONE", function () {\r
+ return 8;\r
+});\r
+_self.__defineGetter__("APP_SEARCH", function () {\r
+ return 9;\r
+});\r
+_self.__defineGetter__("APP_TASKS", function () {\r
+ return 10;\r
+});\r
+_self.__defineGetter__("APP_BROWSER", function () {\r
+ return 11;\r
+});\r
+_self.__defineGetter__("APP_JAVA", function () {\r
+ return 12;\r
+});\r
+\r
module.exports = _self;\r
});
-define('ripple/platform/wac/2.0/wac2_utils', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/AddressBookArguments', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
+//blackberry.invoke.AddressBookArguments ( [contact : blackberry.pim.Contact ] )
+var _self = function (contact) {
+ return {
+ contact: contact,
+ //readwrite property Number view
+ view: 0
+ };
+};
+
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_NEW", function () {
+ return 0;
+});
+//const Number VIEW_COMPOSE = 1
+_self.__defineGetter__("VIEW_COMPOSE", function () {
+ return 1;
+});
+//const Number VIEW_DISPLAY = 2
+_self.__defineGetter__("VIEW_DISPLAY", function () {
+ return 2;
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/Phone', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/phone/",
+ _listeners = {},
+ _self;
+
+_self = {
+ activeCalls: function () {
+ return transport.call(_uri + "activeCalls");
+ },
+
+ addPhoneListener: function (callback, eventType) {
+ var assigned = false;
+
+ if (callback && typeof eventType === "number") {
+ _listeners[eventType] = callback;
+ assigned = true;
+ } else if (eventType && callback === null) {
+ delete _listeners[eventType];
+ } else {
+ _listeners = {};
+ }
+
+ transport.poll(_uri + "onPhoneEvent", {
+ get: {eventType: eventType}
+ }, function (response) {
+ var func = _listeners[eventType];
+
+ if (func) {
+ func(response.callId, response.error);
+ }
+
+ return !!func;
+ });
+
+ // hackish (return true that event was assigned, this is a disconnect between transport poll api and server)
+ return assigned;
+ },
+
+ inActiveCall: function () {
+ return transport.call(_uri + "inActiveCall");
+ }
+};
+
+_self.__defineGetter__("CB_CALL_INITIATED", function () {
+ return 0;
+});
+_self.__defineGetter__("CB_CALL_WAITING", function () {
+ return 1;
+});
+_self.__defineGetter__("CB_CALL_INCOMING", function () {
+ return 2;
+});
+_self.__defineGetter__("CB_CALL_ANSWERED", function () {
+ return 3;
+});
+_self.__defineGetter__("CB_CALL_CONNECTED", function () {
+ return 4;
+});
+_self.__defineGetter__("CB_CALL_CONFERENCECALL_ESTABLISHED", function () {
+ return 5;
+});
+_self.__defineGetter__("CB_CONFERENCECALL_DISCONNECTED", function () {
+ return 6;
+});
+_self.__defineGetter__("CB_CALL_DISCONNECTED", function () {
+ return 7;
+});
+_self.__defineGetter__("CB_CALL_DIRECTCONNECT_CONNECTED", function () {
+ return 8;
+});
+_self.__defineGetter__("CB_CALL_DIRECTCONNECT_DISCONNECTED", function () {
+ return 9;
+});
+_self.__defineGetter__("CB_CALL_ENDED_BYUSER", function () {
+ return 10;
+});
+_self.__defineGetter__("CB_CALL_FAILED", function () {
+ return 11;
+});
+_self.__defineGetter__("CB_CALL_RESUMED", function () {
+ return 12;
+});
+_self.__defineGetter__("CB_CALL_HELD", function () {
+ return 13;
+});
+_self.__defineGetter__("CB_CALL_ADDED", function () {
+ return 14;
+});
+_self.__defineGetter__("CB_CALL_REMOVED", function () {
+ return 15;
+});
+_self.__defineGetter__("CALL_ERROR_SUBSCRIBER_BUSY", function () {
+ return 1;
+});
+_self.__defineGetter__("CALL_ERROR_CONGESTION", function () {
+ return 2;
+});
+_self.__defineGetter__("CALL_ERROR_RADIO_PATH_UNAVAILABLE", function () {
+ return 3;
+});
+_self.__defineGetter__("CALL_ERROR_NUMBER_UNOBTAINABLE", function () {
+ return 4;
+});
+_self.__defineGetter__("CALL_ERROR_AUTHORIZATION_FAILURE", function () {
+ return 5;
+});
+_self.__defineGetter__("CALL_ERROR_EMERGENCY_CALLS_ONLY", function () {
+ return 6;
+});
+_self.__defineGetter__("CALL_ERROR_HOLD_ERROR", function () {
+ return 7;
+});
+_self.__defineGetter__("CALL_ERROR_OUTGOING_CALLS_BARRED", function () {
+ return 8;
+});
+_self.__defineGetter__("CALL_ERROR_GENERAL", function () {
+ return 9;
+});
+_self.__defineGetter__("CALL_ERROR_MAINTENANCE_REQUIRED", function () {
+ return 10;
+});
+_self.__defineGetter__("CALL_ERROR_SERVICE_NOT_AVAILABLE", function () {
+ return 11;
+});
+_self.__defineGetter__("CALL_ERROR_DUE_TO_FADING", function () {
+ return 12;
+});
+_self.__defineGetter__("CALL_ERROR_LOST_DUE_TO_FADING", function () {
+ return 13;
+});
+_self.__defineGetter__("CALL_ERROR_TRY_AGAIN", function () {
+ return 14;
+});
+_self.__defineGetter__("CALL_ERROR_FDN_MISMATCH", function () {
+ return 15;
+});
+_self.__defineGetter__("CALL_ERROR_CONNECTION_DENIED_BY_NETWORK", function () {
+ return 16;
+});
+_self.__defineGetter__("CALL_ERROR_NUMBER_NOT_IN_SERVICE", function () {
+ return 17;
+});
+_self.__defineGetter__("CALL_ERROR_PLEASE_TRY_LATER", function () {
+ return 18;
+});
+_self.__defineGetter__("CALL_ERROR_SERVICE_CONFLICT", function () {
+ return 19;
+});
+_self.__defineGetter__("CALL_ERROR_SYSTEM_BUSY_TRY_LATER", function () {
+ return 20;
+});
+_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_PRIVATE", function () {
+ return 21;
+});
+_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_DATA", function () {
+ return 22;
+});
+_self.__defineGetter__("CALL_ERROR_USER_NOT_AUTHORIZED", function () {
+ return 23;
+});
+_self.__defineGetter__("CALL_ERROR_USER_NOT_AVAILABLE", function () {
+ return 24;
+});
+_self.__defineGetter__("CALL_ERROR_USER_UNKNOWN", function () {
+ return 25;
+});
+_self.__defineGetter__("CALL_ERROR_USER_NOT_REACHABLE", function () {
+ return 26;
+});
+_self.__defineGetter__("CALL_ERROR_INCOMING_CALL_BARRED", function () {
+ return 27;
+});
+_self.__defineGetter__("CALL_ERROR_CALL_REPLACED_BY_STK", function () {
+ return 28;
+});
+_self.__defineGetter__("CALL_ERROR_STK_CALL_NOT_ALLOWED", function () {
+ return 29;
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/audio', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ supportedContentTypes: function (protocol) {
+ return protocol === 'rtsp' ?
+ ['audio/amr', 'audio/mp4', 'audio/aac'] :
+ ['audio/midi', 'mpeg', 'x-wav', 'amr', 'basic', 'x-gsm', 'mp4', 'aac', 'x-ms-wma', 'flac', 'ogg'];
+ },
+ supportedProtocols: function (contentType) {
+ return ['http', 'file', 'rtsp'];
+ }
+};
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/MapsArguments', function (require, exports, module) {
/*
- * Copyright 2011 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+//blackberry.invoke.MapsArguments ( )
+//blackberry.invoke.MapsArguments ( latitude : Number , longitude : Number )
+//blackberry.invoke.MapsArguments ( locationDocument : Document ) - Supported in 5.0.0 only
+//blackberry.invoke.MapsArguments ( locationDocument : String ) - Supported in 6.0.0 only
+//blackberry.invoke.MapsArguments ( address : blackberry.pim.Address )
+var _self = function () {
+ return {};
+};
-var utils = require('ripple/utils'),
- errorcode = require('ripple/platform/wac/2.0/errorcode'),
- DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror');
+module.exports = _self;
-module.exports = {
- _wac2_regexSanitize: function (regexString) {
- var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
- return regexString.replace("^", "\\^")
- .replace("$", "\\$")
- .replace("(", "\\(")
- .replace(")", "\\)")
- .replace("<", "\\<")
- .replace("[", "\\[")
- .replace("{", "\\{")
- .replace(/\\([^%])/, "\\\\$1") /* don't replace \\% */
- .replace("|", "\\|")
- .replace(">", "\\>")
- .replace(".", "\\.")
- .replace("*", "\\*")
- .replace("+", "\\+")
- .replace("?", "\\?")
- .replace(escapePattern, "$1.*") /* replace % with .* */
- .replace(percentPattern, "%"); /* strip excape of % */
- },
+});
+define('ripple/platform/webworks.handset/2.0.0/client/Address', function (require, exports, module) {
+/*
+ * Copyright 2011 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 Address() {
+ return {
+ //readwrite property String address1
+ //readwrite property String address2
+ //readwrite property String city
+ //readwrite property String country
+ //readwrite property String stateProvince
+ //readwrite property String zipPostal
- isValidDate: function (d) {
- if (Object.prototype.toString.call(d) !== "[object Date]")
- return false;
- return !isNaN(d.getTime());
- },
+ address1: null,
+ address2: null,
+ city: null,
+ country: null,
+ stateProvince: null,
+ zipPostal: null
+ };
+}
- isValidArray: function (a) {
- return (Object.prototype.toString.call(a) === "[object Array]");
- },
-
- matchOptionArrayString: function (src, attr, pattern) {
- /* src.obj[attr] is a StringArray */
- var _pattern, re, _stringMatch;
- _pattern = this._wac2_regexSanitize(pattern);
- re = new RegExp("^" + _pattern + "$", "i");
+module.exports = Address;
- _stringMatch = function (obj, index) {
- if (pattern.search(/^%*$/i) === 0)
- return true;
- if (obj[attr] === undefined || obj[attr] === null)
- return false;
- return obj[attr].some(function (f) {
- return f.search(re) !== -1;
- });
- };
- return utils.filter(src, _stringMatch);
+});
+define('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
+ utils = require('ripple/utils'),
+ _onCallLog = {
+ Added: null,
+ Removed: null,
+ Updated: null,
+ Reset: null,
},
+ _uri = "blackberry/phone/logs/",
+ _self;
- matchOptionString: function (src, attr, pattern) {
- /* src.obj[attr] is a string */
- var _stringMatch, _pattern, _re;
- _pattern = this._wac2_regexSanitize(pattern);
- _re = new RegExp("^" + _pattern + "$", "mi");
+function _massage(property, name) {
+ if (name === "date" && property) {
+ return new Date(property);
+ }
+ return property;
+}
- _stringMatch = function (obj, index) {
- return (obj[attr].search(_re) !== -1);
- };
- return utils.filter(src, _stringMatch);
- },
+function _toCallLog(log) {
+ var callLog = new CallLog(),
+ prop;
+ for (prop in log) {
+ if (log.hasOwnProperty(prop)) {
+ callLog[prop] = _massage(log[prop], prop);
+ }
+ }
+ return callLog;
+}
- matchOptionDate: function (src, attr, filterStart, filterEnd) {
- var _dateMatch;
- _dateMatch = function (obj, index) {
- var matched = true, valueDate = obj[attr];
-
- if (filterStart !== undefined && filterStart !== null) {
- matched = (valueDate.getTime() >= filterStart.getTime());
- }
- if (matched && (filterEnd !== undefined && filterEnd !== null)) {
- matched = (valueDate.getTime() <= filterEnd.getTime());
- }
- return matched;
- };
- return utils.filter(src, _dateMatch);
- },
+function handle(evt) {
+ return function (response) {
+ var func = _onCallLog[evt], args;
- matchOptionShortArray: function (src, attr, filterArray) {
- /* src.obj[attr] is a short, filterArray is an array
- i.e. find status is [CONFRIMED or TENTATIVE] */
- var arraySome = function (obj, index) {
- return filterArray.some(function (f) {
- return f === obj[attr];
+ if (func) {
+ args = utils.map(response, function (value) {
+ return _toCallLog(value);
});
- };
- return utils.filter(src, arraySome);
- },
+ func.apply(null, args);
+ }
- validateTypeMismatch: function (onSuccess, onError, name, callback) {
- if (onSuccess) {
- utils.validateArgumentType(onSuccess, "function", null,
- name + " invalid successCallback parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ return !!func;
+ };
+}
+
+function poll(path) {
+ transport.poll(_uri + path, {}, handle(path.replace("onCallLog", "")));
+}
+
+_self = {
+ addPhoneLogListener: function (onCallLogAdded, onCallLogRemoved, onCallLogUpdated, onCallLogReset) {
+ _onCallLog.Added = onCallLogAdded;
+ _onCallLog.Removed = onCallLogRemoved;
+ _onCallLog.Updated = onCallLogUpdated;
+ _onCallLog.Reset = onCallLogReset;
+
+ if (onCallLogAdded) {
+ poll("onCallLogAdded");
}
- if (onError) {
- utils.validateArgumentType(onError, "function", null,
- name + " invalid errorCallback parameter",
- new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ if (onCallLogRemoved) {
+ poll("onCallLogRemoved");
}
- if (onSuccess) {
- return callback && callback();
- } else {
- if (onError) {
- setTimeout(function () {
- onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- }, 1);
- }
+ if (onCallLogUpdated) {
+ poll("onCallLogUpdated");
}
- return undefined;
+
+ if (onCallLogReset) {
+ poll("onCallLogReset");
+ }
+
+ return !!(onCallLogAdded || onCallLogRemoved ||
+ onCallLogUpdated || onCallLogRemoved);
},
- isEmptyObject: function (obj) {
- var prop;
+ callAt: function (index, folderID) {
+ var log = transport.call(_uri + "callAt", {
+ get: {
+ index: index,
+ folderID: folderID
+ }
+ });
- for (prop in obj) {
- return false;
+ if (log && log.date) {
+ log.date = new Date(log.date);
}
- return true;
+
+ return log;
+ },
+
+ deleteCallAt: function (index, folderID) {
+ return transport.call(_uri + "deleteCallAt", {
+ get: {
+ index: index,
+ folderID: folderID
+ }
+ });
+ },
+
+ find: function (filter, folderID, orderBy, maxReturn, isAscending) {
+ return transport.call(_uri + "find", {
+ post: {
+ filter: filter,
+ folderID: folderID,
+ orderBy: orderBy,
+ maxReturn: maxReturn,
+ isAscending: isAscending
+ }
+ }).map(_toCallLog);
+ },
+
+ numberOfCalls: function (folderID) {
+ return transport.call(_uri + "numberOfCalls", {
+ get: {
+ folderID: folderID
+ }
+ });
}
};
+_self.__defineGetter__("FOLDER_MISSED_CALLS", function () {
+ return 0;
+});
+
+_self.__defineGetter__("FOLDER_NORMAL_CALLS", function () {
+ return 1;
+});
+
+module.exports = _self;
});
-define('ripple/platform/web/default/device', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/systemEvent', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-window.addEventListener("load", function () {
- var event = require('ripple/event');
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ utils = require('ripple/utils'),
+ _self,
+ _callbacks = {};
- event.on("HardwareKey", function (key) {
- event.trigger("HardwareKeyDefault", [key]);
+function _poll(evt, args, callback) {
+ _callbacks[evt + args.key] = callback;
+
+ transport.poll("blackberry/system/event/" + evt, {get: args}, function () {
+ var func = _callbacks[evt + args.key];
+
+ if (func) {
+ func();
+ }
+
+ return !!func;
});
+}
- //HACK: Remove this guy from namespace since we are just hacking this in as a bootstrapper
- delete window.device;
-});
+_self = {
+ onCoverageChange: function (callback) {
+ _poll("onCoverageChange", {}, callback);
+ },
-});
-define('ripple/platform/web/default/spec/ui', function (require, exports, module) {
-module.exports = {
- plugins: [
- "accelerometer",
- "geoView"
- ]
+ onHardwareKey: function (key, callback) {
+ _poll("onHardwareKey", {key: key}, callback);
+ }
};
+_self.__defineGetter__("KEY_BACK", function () {
+ return 0;
});
-define('ripple/platform/web/default/spec', function (require, exports, module) {
+_self.__defineGetter__("KEY_MENU", function () {
+ return 1;
+});
+_self.__defineGetter__("KEY_CONVENIENCE_1", function () {
+ return 2;
+});
+_self.__defineGetter__("KEY_CONVENIENCE_2", function () {
+ return 3;
+});
+_self.__defineGetter__("KEY_STARTCALL", function () {
+ return 4;
+});
+_self.__defineGetter__("KEY_ENDCALL", function () {
+ return 5;
+});
+_self.__defineGetter__("KEY_VOLUMEDOWN", function () {
+ return 6;
+});
+_self.__defineGetter__("KEY_VOLUMEUP", function () {
+ return 7;
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/client/SearchArguments', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+//blackberry.invoke.SearchArguments ( )
+//blackberry.invoke.SearchArguments ( text : String , name : String )
+var _self = function (text, name) {
-module.exports = {
-
- id: "web",
- version: "default",
- name: "Mobile Web",
-
- ui: require('ripple/platform/web/default/spec/ui'),
- device: {},
-
- persistencePrefix: "tinyhippos-",
-
- initialize: function () {},
+ return {
+ text: text,
+ name: name
+ };
- objects: {
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- navigator: {
- path: "w3c/1.0/navigator",
- children: {
- geolocation: {
- path: "w3c/1.0/geolocation"
- }
- }
- },
- device: {
- path: "web/default/device"
- }
- },
};
+module.exports = _self;
+
});
-define('ripple/platform/webworks.bb10/1.0.0/app', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/Memo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- app = require('ripple/app'),
- notifications = require('ripple/notifications'),
- _uri = "blackberry/app/",
- _self;
+ _uri = "blackberry/pim/memo/";
-_self = {
- exit: function () {
- notifications.openNotification("normal", "blackberry.app.exit() was called, in the real world your app will exit, here... you get this notification");
- }
-};
+function Memo() {
+ var _self = {
+ categories: [],
+ note: null,
+ title: null,
+ uid: null,
+ remove: function () {
+ transport.call(_uri + "remove", {
+ get: {uid: _self.uid}
+ });
+ },
+ save: function () {
+ if (_self.uid === null) {
+ _self.uid = Number(Math.uuid(8, 10));
+ }
+ transport.call(_uri + "save", {
+ post: {memo: _self}
+ });
+ }
+ };
-_self.__defineGetter__("author", function () {
- return app.getInfo().author;
-});
+ return _self;
+}
-_self.__defineGetter__("authorEmail", function () {
- return app.getInfo().authorEmail;
-});
+Memo.find = function (filter, orderBy, maxReturn, service, isAscending) {
+ var opts = {
+ post: {
+ filter: filter,
+ orderBy: orderBy,
+ maxReturn: maxReturn,
+ isAscending: isAscending,
+ service: service
+ }
+ };
-_self.__defineGetter__("authorURL", function () {
- return app.getInfo().authorURL;
-});
+ return transport.call(_uri + "find", opts).map(function (obj) {
+ var memo = new Memo();
+ memo.uid = obj.uid;
+ memo.categories = obj.categories || [];
+ memo.note = obj.note;
+ memo.title = obj.title;
+ return memo;
+ });
+};
-_self.__defineGetter__("copyright", function () {
- return app.getInfo().copyright;
-});
+module.exports = Memo;
-_self.__defineGetter__("description", function () {
- return app.getInfo().description;
});
+define('ripple/platform/webworks.handset/2.0.0/client/push', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _self,
+ _uri = "blackberry/push/onPush",
+ callbacks = {},
+ PushData = require('ripple/platform/webworks.handset/2.0.0/client/PushData');
-_self.__defineGetter__("id", function () {
- return app.getInfo().id;
-});
+_self = {
+ openPushListener: function (callback, port, bbTransport, maxQueueCap) {
+ callbacks["onPush" + port] = callback;
-_self.__defineGetter__("license", function () {
- return app.getInfo().license;
-});
+ transport.poll(_uri, {
+ get: {
+ port: port,
+ bbTransport: bbTransport,
+ maxQueueCap: maxQueueCap
+ }
+ }, function (response) {
+ var func = callbacks["onPush" + port];
-_self.__defineGetter__("licenseURL", function () {
- return app.getInfo().licenseURL;
-});
+ if (func) {
+ func(new PushData(response, port));
+ }
-_self.__defineGetter__("name", function () {
- return app.getInfo().name;
-});
+ return !!func;
+ });
+ },
-_self.__defineGetter__("version", function () {
- return app.getInfo().version;
-});
+ closePushListener: function (port) {
+ delete callbacks["onPush" + port];
+ }
+};
module.exports = _self;
});
-define('ripple/platform/webworks.bb10/1.0.0/connection', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/pim', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var deviceSettings = require('ripple/deviceSettings'),
- _self = {};
-
-_self.__defineGetter__("type", function () {
- return deviceSettings.retrieve("NetworkStatus.connectionType");
-});
-
-_self.__defineGetter__("UNKNOWN", function () { return "unknown"; });
-_self.__defineGetter__("ETHERNET", function () { return "ethernet"; });
-_self.__defineGetter__("WIFI", function () { return "wifi"; });
-_self.__defineGetter__("BLUETOOTH_DUN", function () { return "bluetooth_dun"; });
-_self.__defineGetter__("USB", function () { return "usb"; });
-_self.__defineGetter__("VPN", function () { return "vpn"; });
-_self.__defineGetter__("BB", function () { return "rim-bb"; });
-_self.__defineGetter__("CELL_2G", function () { return "2g"; });
-_self.__defineGetter__("CELL_3G", function () { return "3g"; });
-_self.__defineGetter__("CELL_4G", function () { return "4g"; });
-_self.__defineGetter__("NONE", function () { return "none"; });
-
-module.exports = _self;
+module.exports = {};
});
-define('ripple/platform/webworks.bb10/1.0.0/device', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/MemoArguments', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var devices = require('ripple/devices'),
- _self = {};
+//blackberry.invoke.MemoArguments ( [memo : blackberry.pim.Memo ] )
+var _self = function (memo) {
+ return {
+ memo: memo,
+ view: 0
+ };
+};
-_self.__defineGetter__("softwareVersion", function () {
- return devices.getCurrentDevice().osVersion;
+//const Number VIEW_NEW = 0
+_self.__defineGetter__("VIEW_NEW", function () {
+ return 0;
});
-
-_self.__defineGetter__("hardwareId", function () {
- return devices.getCurrentDevice().hardwareId;
+//const Number VIEW_EDIT = 1
+_self.__defineGetter__("VIEW_EDIT", function () {
+ return 1;
});
+
module.exports = _self;
});
-define('ripple/platform/webworks.bb10/1.0.0/dialog', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/Attendee', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self,
- ui = require('ripple/ui'),
- event = require('ripple/event'),
- isDialogVisible = false,
- visibleDialogArgs,
- utils = require('ripple/utils');
+function Attendee() {
+ return {
+ //readwrite property String address
+ //readwrite property Number type
-function getButtonsForDialogType(dialogType) {
- switch (dialogType) {
- case _self.D_OK:
- return ["Ok"];
- case _self.D_SAVE:
- return ["Save", "Discard"];
- case _self.D_DELETE:
- return ["Delete", "Cancel"];
- case _self.D_YES_NO:
- return ["Yes", "No"];
- case _self.D_OK_CANCEL:
- return ["Ok", "Cancel"];
- default:
- throw new Error("Invalid dialog type: " + dialogType);
- }
+ address: null,
+ type: null
+ };
}
-event.on("LayoutChanged", function () {
- if (isDialogVisible) {
- closeDialog();
- //Used to resize dialog on orientation change
- _self.ask(visibleDialogArgs);
- }
+Attendee.__defineGetter__("ORGANIZER", function () {
+ return 0;
});
-function closeDialog() {
- var buttonsDiv = document.getElementById("dialog-buttons"),
- messageDiv = document.getElementById("dialog-message");
+Attendee.__defineGetter__("INVITED", function () {
+ return 1;
+});
- ui.hideOverlay("dialog-window", function (dialog) {
- buttonsDiv.innerHTML = "";
- messageDiv.innerHTML = "";
- isDialogVisible = false;
- });
-}
+Attendee.__defineGetter__("ACCEPTED", function () {
+ return 2;
+});
-function ask(args, callback) {
- if (!args) {
- throw ("No arguments provided");
- } else if (!args.buttons || !args.message) {
- throw ("Invalid arguments");
- }
- visibleDialogArgs = args;
+Attendee.__defineGetter__("DECLINED", function () {
+ return 3;
+});
- ui.showOverlay("dialog-window", function (dialog) {
- var container = document.getElementById("viewport-container"),
- height = window.getComputedStyle(container, null).getPropertyValue("height"),
- width = window.getComputedStyle(container, null).getPropertyValue("width"),
- sizeDiv = document.getElementById("dialog-wrapper"),
- positionDiv = document.getElementById("dialog-window"),
- titleDiv = document.getElementById("dialog-title"),
- buttonsDiv = document.getElementById("dialog-buttons"),
- messageDiv = document.getElementById("dialog-message"),
- position, size;
+Attendee.__defineGetter__("TENTATIVE", function () {
+ return 4;
+});
- if (!messageDiv || !buttonsDiv) {
- return;
- }
+module.exports = Attendee;
- dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");
+});
+define('ripple/platform/webworks.handset/2.0.0/client/appEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _callbacks = {},
+ _self;
- position = "overlay-dialog";
- size = "overlay-dialog-wrapper";
+function _poll(evt, handler) {
+ _callbacks[evt] = handler;
- if (args.settings && args.settings.position) {
- position += " overlay-dialog-" + args.settings.position;
- }
+ transport.poll("blackberry/app/event/" + evt, {}, function () {
+ var func = _callbacks[evt];
- if (args.settings && args.settings.size) {
- size += " overlay-dialog-wrapper-" + args.settings.size;
+ if (func) {
+ func();
}
- positionDiv.setAttribute("class", position);
- sizeDiv.setAttribute("class", size);
-
- titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
- messageDiv.innerHTML = args.message;
- isDialogVisible = true;
-
- args.buttons.forEach(function (button) {
- var buttonElement = utils.createElement("input", {
- "type": "button",
- "value": button
- });
- buttonElement.addEventListener("click", function () {
- var buttonIndex = args.buttons.indexOf(button);
- closeDialog();
- callback(buttonIndex);
- });
- buttonsDiv.appendChild(buttonElement);
- });
- }, true);
+ return !!func;
+ });
}
_self = {
- customAskAsync: function (message, choices, callback, settings) {
- ask({
- message: message,
- buttons: choices,
- settings: settings
- }, function (response) {
- if (callback) {
- callback(response);
- }
- });
+ onBackground: function (handler) {
+ _poll("onBackground", handler);
},
- standardAskAsync: function (message, type, callback, settings) {
- var choices = getButtonsForDialogType(type);
- ask({
- message: message,
- buttons: choices,
- settings: settings
- }, function (response) {
- if (callback) {
- callback(response);
- }
- });
+ onForeground: function (handler) {
+ _poll("onForeground", handler);
+ },
+
+ onExit: function (handler) {
+ _poll("onExit", handler);
}
};
-_self.__defineGetter__("D_OK", function () {
- return 0;
-});
+module.exports = _self;
-_self.__defineGetter__("D_SAVE", function () {
- return 1;
});
+define('ripple/platform/webworks.handset/2.0.0/client/blackberry', function (require, exports, module) {
+/*
+ * Copyright 2011 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 blackberry = {},
+ transport = require('ripple/platform/webworks.core/2.0.0/client/transport');
-_self.__defineGetter__("D_DELETE", function () {
- return 2;
+blackberry.__defineGetter__("network", function () {
+ return transport.call("blackberry/system/network");
});
-_self.__defineGetter__("D_YES_NO", function () {
- return 3;
-});
+module.exports = blackberry;
-_self.__defineGetter__("D_OK_CANCEL", function () {
- return 4;
});
+define('ripple/platform/webworks.handset/2.0.0/client/CallLog', function (require, exports, module) {
+/*
+ * Copyright 2011 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 CallLog() {
+ // readwrite property String addressBookNumber
+ // readwrite property String addressBookType
+ // readwrite property Date date
+ // readwrite property Number duration
+ // readwrite property String name
+ // readwrite property String notes
+ // readwrite property String number
+ // readwrite property Number status
+ // readwrite property Number type
+ this.addressBookNumber = null;
+ this.addressBookType = null;
+ this.date = null;
+ this.duration = null;
+ this.name = null;
+ this.notes = null;
+ this.number = null;
+ this.status = null;
+ this.type = null;
+}
-_self.__defineGetter__("BOTTOM", function () {
- return "bottomCenter";
-});
+function _get(val) {
+ return function () {
+ return val;
+ };
+}
-_self.__defineGetter__("CENTER", function () {
- return "middleCenter";
-});
+CallLog.__defineGetter__("STATUS_NORMAL", _get(0));
+CallLog.__defineGetter__("STATUS_BUSY", _get(1));
+CallLog.__defineGetter__("STATUS_CONGESTION", _get(2));
+CallLog.__defineGetter__("STATUS_PATH_UNAVAILABLE", _get(3));
+CallLog.__defineGetter__("STATUS_NUMBER_UNOBTAINABLE", _get(4));
+CallLog.__defineGetter__("STATUS_AUTHENTICATION_FAILURE", _get(5));
+CallLog.__defineGetter__("STATUS_EMERGENCY_CALLS_ONLY", _get(6));
+CallLog.__defineGetter__("STATUS_HOLD_ERROR", _get(7));
+CallLog.__defineGetter__("STATUS_OUTGOING_CALLS_BARRED", _get(8));
+CallLog.__defineGetter__("STATUS_GENERAL_ERROR", _get(9));
+CallLog.__defineGetter__("STATUS_MAINTENANCE_REQUIRED", _get(10));
+CallLog.__defineGetter__("STATUS_SERVICE_NOT_AVAILABLE", _get(11));
+CallLog.__defineGetter__("STATUS_CALL_FAIL_DUE_TO_FADING", _get(12));
+CallLog.__defineGetter__("STATUS_CALL_LOST_DUE_TO_FADING", _get(13));
+CallLog.__defineGetter__("STATUS_CALL_FAILED_TRY_AGAIN", _get(14));
+CallLog.__defineGetter__("STATUS_FDN_MISMATCH", _get(15));
+CallLog.__defineGetter__("STATUS_CONNECTION_DENIED", _get(16));
+CallLog.__defineGetter__("STATUS_INCOMING_CALL_BARRED", _get(17));
+CallLog.__defineGetter__("TYPE_RECEIVED_CALL", _get(0));
+CallLog.__defineGetter__("TYPE_PLACED_CALL", _get(1));
+CallLog.__defineGetter__("TYPE_MISSED_CALL_UNOPENED", _get(2));
+CallLog.__defineGetter__("TYPE_MISSED_CALL_OPENED", _get(3));
-_self.__defineGetter__("TOP", function () {
- return "topCenter";
-});
+module.exports = CallLog;
-_self.__defineGetter__("SIZE_FULL", function () {
- return "full";
});
+define('ripple/platform/webworks.handset/2.0.0/client/sms', function (require, exports, module) {
+/*
+ * Copyright 2011 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/message/sms/",
+ onReceive,
+ _self;
-_self.__defineGetter__("SIZE_LARGE", function () {
- return "large";
-});
+_self = {
+ addReceiveListener: function (callback) {
+ onReceive = callback;
+ transport.poll(_uri + "onReceive", {}, function (response) {
+ if (onReceive) {
+ onReceive(response.body, response.from, response.time);
+ }
+ return !!onReceive;
+ });
+ },
-_self.__defineGetter__("SIZE_MEDIUM", function () {
- return "medium";
-});
+ removeReceiveListener: function () {
+ if (onReceive) {
+ onReceive = null;
+ return true;
+ }
-_self.__defineGetter__("SIZE_SMALL", function () {
- return "small";
+ return false;
+ },
+
+ send: function (message, address) {
+ transport.call(_uri + "send", {
+ get: {
+ message: message,
+ address: address
+ },
+ async: true
+ });
+ }
+};
+
+_self.__defineGetter__("isListeningForMessage", function () {
+ return transport.call(_uri + "isListeningForMessage", {async: false});
});
-_self.__defineGetter__("SIZE_TALL", function () {
- return "tall";
+_self.__defineSetter__("isListeningForMessage", function (value) {
+ transport.call(_uri + "isListeningForMessage", {
+ async: false,
+ get: {isListeningForMessage: value}
+ });
});
module.exports = _self;
});
-define('ripple/platform/webworks.bb10/1.0.0/event', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/MenuItem', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ event = require('ripple/event');
-var event = require('ripple/event'),
- settings = require('ripple/deviceSettings'),
- app = require('ripple/app'),
- cons = require('ripple/console'),
- utils = require('ripple/utils'),
- events = {
- batterystatus: {
- callbacks: [],
- feature: 'blackberry.system'
- },
- batterylow: {
- callbacks: [],
- feature: 'blackberry.system'
- },
- batterycritical: {
- callbacks: [],
- feature: 'blackberry.system'
- },
- connectionchange: {
- callbacks: [],
- feature: 'blackberry.connection'
- },
- invoked: {
- callbacks: [],
- feature: 'blackberry.invoked'
- },
- swipedown: {
- callbacks: [],
- feature: 'blackberry.app'
- },
- resume: {
- callbacks: [],
- feature: 'blackberry.app'
- },
- pause: {
- callbacks: [],
- feature: 'blackberry.app'
- },
- languagechange: {
- callbacks: [],
- feature: "blackberry.system"
- },
- regionchange: {
- callbacks: [],
- feature: "blackberry.system"
- }
- };
-
-function _apply(eventName, args) {
- events[eventName].callbacks.forEach(function (cb) {
- cb.apply(null, args);
- });
-}
-
-event.on('DeviceBatteryStateChanged', function (charging) {
- var info = {
- isPlugged: charging,
- level: parseInt(settings.retrieve('battery.level'), 10)
- };
-
- _apply('batterystatus', [info]);
-});
-
-event.on('DeviceBatteryLevelChanged', function (level) {
- var info = {
- isPlugged: settings.retrieve('battery.state'),
- level: parseInt(level, 10)
- };
-
- _apply('batterystatus', [info]);
-
- if (level === '14') {
- _apply('batterylow', [info]);
- }
+function MenuItem(isSeparator, ordinal, caption, callback) {
+ var _isDefault = false,
+ id = Math.uuid();
- if (level === '4') {
- _apply('batterycritical', [info]);
+ if (ordinal < 0) {
+ throw "Ordinal cannot be less than 0";
+ } else if (isSeparator) {
+ if (caption !== undefined) {
+ throw "caption must not be supplied";
+ } else if (callback !== undefined) {
+ throw "callback must not be supplied";
+ }
+ } else if (!isSeparator) {
+ if (caption === undefined) {
+ throw "caption must be supplied";
+ }
}
-});
-event.on('DeviceConnectionChanged', function (info) {
- _apply('connectionchange', [info]);
-});
+ this.callback = callback;
-event.on("LanguageChanged", function (lang) {
- _apply("languagechange", [lang]);
-});
+ this.__defineSetter__("id", function (i) {
+ id = i;
+ });
-event.on("RegionChanged", function (lang) {
- _apply("regionchange", [lang]);
-});
+ this.__defineGetter__("id", function () {
+ return id;
+ });
-event.on("AppInvoke", function (invokeInfo) {
- var invokeTargets = app.getInfo().invokeTargets;
+ this.__defineSetter__("caption", function (c) {
+ caption = c;
+ event.trigger("MenuItemChanged", [this]);
+ });
- if (!invokeTargets) {
- cons.log("The application cannot be invoked, please add a rim:invoke-target node in config.xml");
- return;
- }
+ this.__defineGetter__("caption", function () {
+ return caption;
+ });
- if (invokeTargets.some(function (target) {
- return target.filter.some(function (filter) {
- return (
- (!filter.property ||
- (filter.property && filter.property[0]["@attributes"].var === "exts" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
- return invokeInfo.extension.match(value);
- })) ||
- (filter.property && filter.property[0]["@attributes"].var === "uris" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
- return invokeInfo.uri.match(value);
- }))) &&
- filter.action.some(function (action) {
- return invokeInfo.action.match(action["#text"][0].replace("*", ""));
- }) &&
- filter["mime-type"].some(function (type) {
- return invokeInfo.type.match(type["#text"][0].replace("*", ""));
- })
- );
- });
- })) {
- _apply('invoked', [invokeInfo]);
- }
- else {
- cons.log("Cannot invoke application, values enter to not match values in rim:invoke-target in config.xml");
- }
-});
+ this.__defineSetter__("ordinal", function (o) {
+ ordinal = o;
+ event.trigger("MenuItemChanged", [this]);
+ });
-event.on('AppSwipeDown', function () {
- _apply('swipedown');
-});
+ this.__defineGetter__("ordinal", function () {
+ return ordinal;
+ });
-event.on('AppResume', function () {
- _apply('resume');
-});
+ this.__defineGetter__("isSeparator", function () {
+ return isSeparator;
+ });
-event.on('AppPause', function () {
- _apply('pause');
-});
+ this.__defineSetter__("isDefault", function (d) {
+ _isDefault = d;
+ event.trigger("MenuItemChanged", [this]);
+ });
-module.exports = {
- addEventListener: function (type, func) {
- this.removeEventListener(type, func);
+ this.__defineGetter__("isDefault", function () {
+ return _isDefault;
+ });
- if (!app.getInfo().features || app.getInfo().features[events[type].feature]) {
- events[type].callbacks.push(func);
- }
- else {
- throw ("Cannot register a hanlder for the " + type + " event. Please add the '" +
- events[type].feature + "' to your config.xml.");
- }
- },
+ this.__defineGetter__("id", function () {
+ return id;
+ });
+}
- removeEventListener: function (type, func) {
- var idx = events[type].callbacks.indexOf(func);
- if (idx >= 0) {
- delete events[type].callbacks[idx];
- }
- }
-};
+module.exports = MenuItem;
});
-define('ripple/platform/webworks.bb10/1.0.0/identity', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/Contact', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var deviceSettings = require('ripple/deviceSettings'),
- _self = {};
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/pim/contact/";
-_self.__defineGetter__("uuid", function () {
- return deviceSettings.retrieve("identity.uuid");
-});
+function Contact(service) {
+ var _self = {
+ anniversary: null,
+ birthday: null,
+ categories: [],
+ company: null,
+ email1: "",
+ email2: "",
+ email3: "",
+ faxPhone: null,
+ firstName: null,
+ homeAddress: null,
+ homePhone: null,
+ homePhone2: null,
+ jobTitle: null,
+ lastName: null,
+ mobilePhone: null,
+ note: null,
+ otherPhone: null,
+ pagerPhone: null,
+ picture: null,
+ pin: null,
+ title: null,
+ uid: null,
+ user1: null,
+ user2: null,
+ user3: null,
+ user4: null,
+ webpage: null,
+ workAddress: null,
+ workPhone: null,
+ workPhone2: null,
+ remove: function () {
+ if (!_self.uid) {
+ throw "task has not yet been saved (has no uid)";
+ }
+ transport.call(_uri + "remove", {
+ get: { id: _self.uid }
+ });
+ },
+ save: function () {
+ if (!_self.uid) {
+ _self.uid = Math.uuid(null, 16);
+ }
+ transport.call(_uri + "save", {
+ post: { contact: _self }
+ });
+ },
+ setPicture: function (picture) {
+ throw "not implemented";
+ }
+ };
-module.exports = _self;
+ return _self;
+}
-});
-define('ripple/platform/webworks.bb10/1.0.0/invoke', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-var notifications = require('ripple/notifications'),\r
- utils = require('ripple/utils'),\r
- _self = {};\r
-\r
-function _fail(onError) {\r
- if (onError && typeof onError === "function") {\r
- onError("invalid invocation request");\r
- }\r
-}\r
-\r
-_self.invoke = function (request, onSuccess, onError) {\r
- var argsString = "";\r
-\r
- if (!request) { // is this check even needed?\r
- _fail(onError);\r
- return;\r
- } else {\r
- if (request) {\r
- utils.forEach(request, function (arg, key) {\r
- argsString += key + " = " + arg + "</br>";\r
- });\r
-\r
- notifications.openNotification("normal", "Requested to invoke external application with the following arguments:</br> " +\r
- argsString + "</br>");\r
- }\r
- else {\r
- _fail(onError);\r
- return;\r
- }\r
- }\r
-};\r
-\r
-_self.__defineGetter__("ACTION_OPEN", function () {\r
- return "bb.action.OPEN";\r
-});\r
-_self.__defineGetter__("ACTION_VIEW", function () { \r
- return "bb.action.VIEW"; \r
-});\r
-_self.__defineGetter__("ACTION_SHARE", function () {\r
- return "bb.action.SHARE";\r
-});\r
-\r
-module.exports = _self;\r
+function _massage(property, name) {
+ if ((name === "anniversary" || name === "birthday") && property) {
+ return new Date(property);
+ }
+ return property;
+}
+
+Contact.find = function (fieldFilter, orderBy, maxReturn, service, isAscending) {
+ return transport.call(_uri + "find", {
+ post: {
+ fieldFilter: fieldFilter,
+ orderBy: orderBy,
+ maxReturn: maxReturn,
+ service: service,
+ isAscending: isAscending
+ }
+ }).map(function (properties) {
+ var contact = new Contact(),
+ key;
+ for (key in properties) {
+ if (contact.hasOwnProperty(key)) {
+ contact[key] = _massage(properties[key], key);
+ }
+ }
+ return contact;
+ });
+};
+
+module.exports = Contact;
});
-define('ripple/platform/webworks.bb10/1.0.0/navigator', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/PhoneCall', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var nav = require('ripple/platform/w3c/1.0/navigator'),
- utils = require('ripple/utils'),
- deviceSettings = require('ripple/deviceSettings'),
- _self = {};
+function PhoneCall(onhold) {
+ return {
+ //Boolean isOnHold ( )
+ //readonly property Boolean outgoing
+ //readonly property String recipientName
+ //readonly property String recipientNumber
-utils.mixin(nav, _self);
+ outgoing: false,
+ recipientName: null,
+ recipientNumber: null,
-_self.__defineGetter__("language", function () {
- return deviceSettings.retrieve("system.language");
-});
+ isOnHold: function () {
+ return onhold;
+ }
+ };
+}
-module.exports = _self;
+module.exports = PhoneCall;
});
-define('ripple/platform/webworks.bb10/1.0.0/spec/config', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/client/Task', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils');
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/pim/Task/";
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (config) {
- return true;
- },
- extractInfo: function (config) {
- if (!config) {
- return null;
- }
+function Task() {
+ var _self = {
+ save: function () {
+ if (!_self.uid) {
+ _self.uid = Math.uuid(null, 16);
+ }
+ transport.call(_uri + "save", {
+ post: {
+ task: _self
+ }
+ });
+ },
+ remove: function () {
+ if (!_self.uid) {
+ throw "task has not yet been saved (has no uid)";
+ }
+ transport.call(_uri + "remove", {
+ get: {
+ id: _self.uid
+ }
+ });
+ },
+ uid: null,
+ categories: [],
+ due: null,
+ note: "",
+ priority: Task.PRIORITY_NORMAL,
+ recurrence: null,
+ reminder: null,
+ status: Task.NOT_STARTED,
+ summary: ""
+ };
- var widgetInfo = {},
- widgetFeatures = config.widget.children.feature.validationResult,
- accessUrls = config.widget.children.access.validationResult,
- invokeTargets = config.rawJSON.widget[0]["rim:invoke-target"],
- accessFeatures = config.widget.children.access.children.feature.validationResult,
- toFeature = function (validationResult) {
- return {
- id: validationResult.attributes.id.value,
- required: !validationResult.attributes.required || validationResult.attributes.required.value,
- URIs: []
- };
- };
+ return _self;
+}
- widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
- widgetInfo.name = config.widget.children.name.validationResult[0].value;
- widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
- widgetInfo.author = config.widget.children.author.validationResult[0].value;
- widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
- widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
- widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
- widgetInfo.description = config.widget.children.description.validationResult[0].value;
- widgetInfo.invokeTargets = invokeTargets;
- if (config.widget.children.license.validationResult[0]) {
- widgetInfo.license = config.widget.children.license.validationResult[0].value;
- widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
+function _massage(property, name) {
+ if (name === "recurrence" && property) {
+ if (property.end) {
+ property.end = new Date(property.end);
}
+ }
+ if (name === "reminder" && property) {
+ if (property.date) {
+ property.date = new Date(property.date);
+ }
+ }
+ if (name === "due" && property) {
+ property = new Date(property);
+ }
+ return property;
+}
- widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
- if (validationResult.valid) {
- var feature = toFeature(validationResult);
- feature.URIs.push({
- value: utils.location().href,
- subdomains: true
- });
- features = features || {};
- features[feature.id] = feature;
- }
- return features;
- }, {});
-
- widgetInfo.features = accessUrls.map(function (access) {
- return {
- uri: access.attributes.uri.value,
- subdomains: access.attributes.subdomains.value,
- features: accessFeatures ? accessFeatures.filter(function (f) {
- return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
- }) : null
- };
- }).reduce(function (result, access) {
- return access.features ? access.features.reduce(function (features, validationResult) {
- var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
- feature.URIs.push({
- value: access.uri,
- subdomains: access.subdomains
- });
- features[feature.id] = feature;
- return features;
- }, result) : result;
- }, widgetInfo.features);
-
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:rim": {
- attributeName: "xmlns:rim",
- required: true,
- type: "list",
- listValues: ["http://www.blackberry.com/ns/widgets"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- "rim:header": {
- attributeName: "rim:header",
- required: false,
- type: "string"
- },
- "rim:backButton": {
- attributeName: "rim:backButton",
- required: false,
- type: "string"
- }
- },
- children: {
- name: {
- nodeName: "name",
- required: true,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- "rim:hover": {
- attributeName: "rim:hover",
- type: "boolean",
- required: false
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 1,
- attributes: {
- href: {
- attributeName: "href",
- type: "string",
- required: false
- },
- "rim:copyright": {
- attributeName: "rim:copyright",
- type: "string",
- required: false
- },
- email: {
- attributeName: "email",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 1,
- attributes : {
- href: {
- attributeName: "href",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- "rim:cache": {
- nodeName: "rim:cache",
- required: false,
- occurrence: 1,
- attributes: {
- disableAllCache: {
- attributeName: "disableAllCache",
- required: false,
- type: "boolean"
- },
- aggressiveCacheAge: {
- attributeName: "aggressiveCacheAge",
- required: false,
- type: "number"
- },
- maxCacheSizeTotal: {
- attributeName: "maxCacheSizeTotal",
- required: false,
- type: "number"
- },
- maxCacheSizeItem: {
- attributeName: "maxCacheSizeItem",
- required: false,
- type: "number"
- }
- }
- },
- access: {
- nodeName: "access",
- required: false,
- occurrence: 0,
- attributes: {
- uri: {
- attributeName: "uri",
- required: true,
- type: "string"
- },
- subdomains: {
- attributeName: "subdomains",
- required: false,
- type: "boolean"
- }
- },
- children: {
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- //TODO: this should be a list
- type: "string"
- },
- required: {
- attributeName: "required",
- required: false,
- type: "boolean"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- }
- }
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- //TODO: this should be a list
- type: "string"
- },
- required: {
- attributeName: "required",
- required: false,
- type: "boolean"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- }
- }
- },
- "rim:loadingScreen": {
- nodeName: "rim:loadingScreen",
- required: false,
- occurrence: 1,
- attributes: {
- backgroundColor: {
- attributeName: "backgroundColor",
- required: false,
- type: "string"
- },
- backgroundImage: {
- attributeName: "backgroundImage",
- required: false,
- type: "string"
- },
- foregroundImage: {
- attributeName: "foregroundImage",
- required: false,
- type: "string"
- },
- onRemotePageLoad: {
- attributeName: "onRemotePageLoad",
- required: false,
- type: "boolean"
- },
- onLocalPageLoad: {
- attributeName: "onLocalPageLoad",
- required : false,
- type: "boolean"
- },
- onFirstLaunch: {
- attributeName: "onFirstLaunch",
- required: false,
- type: "boolean"
- }
- },
- children: {
- "rim:transitionEffect": {
- nodeName: "rim:transitionEffect",
- required: false,
- occurrence: 1,
- attributes: {
- "type": {
- attributeName: "type",
- required: true,
- type: "list",
- listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
- },
- duration: {
- attributeName: "duration",
- required: false,
- type: "number"
- },
- direction: {
- attributeName: "direction",
- required: false,
- type: "list",
- listValues: ["left", "right", "up", "down"]
- }
- }
- }
- }
- },
- "rim:invoke-target": {
- nodeName: "rim:invoke-target",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- type: "string"
- }
- },
- children: {
- "type": {
- nodeName: "type",
- required: true,
- occurrence: 1
- },
- "require-source-permissions": {
- nodeName: "require-source-permissions",
- required: false,
- occurence: 0
- },
- "filter": {
- nodeName: "filter",
- required: false,
- occurence: 0,
- children: {
- "action": {
- nodeName: "action",
- required: true,
- occurence: 0
- },
- "mime-type": {
- nodeName: "mime-type",
- required: true,
- occurence: 0
- },
- "property": {
- nodeName: "property",
- required: false,
- occurenc: 0,
- attributes: {
- "var": {
- attributeName: "var",
- required: false,
- type: "string"
- },
- "value": {
- attributeName: "value",
- required: false,
- type: "string"
- }
- }
- }
- },
- }
- }
- },
- "rim:connection": {
- nodeName: "rim:connection",
- required: false,
- occurrence: 1,
- attributes: {
- timeout: {
- attributeName: "timeout",
- required: false,
- type: "number"
- }
- },
- children: {
- id: {
- nodeName: "id",
- required: false,
- occurrence: 0
- }
- }
- },
- "rim:navigation": {
- nodeName: "rim:navigation",
- required: false,
- occurrence: 1,
- attributes: {
- mode: {
- attributeName: "mode",
- required: false,
- type: "list",
- listValues: ["focus"]
- }
- }
- },
- "content": {
- nodeName: "content",
- required: true,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- type: {
- attributeName: "type",
- required: false,
- type: "string"
- },
- charset: {
- attributeName: "charset",
- required: false,
- type: "string"
- }
- }
- }
+Task.find = function (filter, orderBy, maxReturn, isAscending) {
+ return transport.call(_uri + "find", {
+ post: {
+ filter: filter,
+ orderBy: orderBy,
+ maxReturn: maxReturn,
+ isAscending: isAscending
+ }
+ }).map(function (properties) {
+ var task = new Task(),
+ key;
+ for (key in properties) {
+ if (task.hasOwnProperty(key)) {
+ task[key] = _massage(properties[key], key);
}
}
- }
+ return task;
+ });
};
+Task.__defineGetter__("NOT_STARTED", function () {
+ return 0;
});
-define('ripple/platform/webworks.bb10/1.0.0/spec/device', function (require, exports, module) {
+
+Task.__defineGetter__("IN_PROGRESS", function () {
+ return 1;
+});
+
+Task.__defineGetter__("COMPLETED", function () {
+ return 2;
+});
+
+Task.__defineGetter__("WAITING", function () {
+ return 3;
+});
+
+Task.__defineGetter__("DEFERRED", function () {
+ return 4;
+});
+
+Task.__defineGetter__("PRIORITY_HIGH", function () {
+ return 0;
+});
+
+Task.__defineGetter__("PRIORITY_NORMAL", function () {
+ return 1;
+});
+
+Task.__defineGetter__("PRIORITY_LOW", function () {
+ return 2;
+});
+
+module.exports = Task;
+
+});
+define('ripple/platform/webworks.handset/2.0.0/spec/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
var event = require('ripple/event');
module.exports = {
- "NetworkStatus": {
- "connectionType": {
- "name": "Connection Type",
+ "transports": {
+ "TCP Cellular": {
+ "name": "Cellular TCP",
"control": {
- "type": "select",
- "value": "ethernet"
- },
- "options": {
- "unknown": "UNKNOWN",
- "ethernet": "ETHERNET",
- "wifi": "WIFI",
- "bluetooth_dun": "BLUETOOTH_DUN",
- "usb": "USB",
- "vpn": "VPN",
- "rim-bb": "BB",
- "2g": "CELL_2G",
- "3g": "CELL_3G",
- "4g": "CELL_4G",
- "none": "NONE"
- },
- "callback": function (setting, oldSetting) {
- event.trigger("DeviceConnectionChanged", [{oldType: oldSetting, newType: setting}]);
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "Wap": {
+ "name": "WAP",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ },
+ "Wap 2.0": {
+ "name": "WAP 2.0",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ },
+ "MDS": {
+ "name": "MDS",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "Bis B": {
+ "name": "BIS B",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "Unite!": {
+ "name": "Unite",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ },
+ "TCP Wifi": {
+ "name": "Wifi TCP",
+ "control": {
+ "type": "checkbox",
+ "value": true
}
}
},
"identity": {
- "uuid": {
- "name": "uuid",
+ "IMEI": {
+ "name": "IMEI",
"control": {
"type": "text",
- "value": "43A8C489"
+ "value": "123456786543210"
}
- }
- },
- "system": {
- "language": {
- "name": "language",
+ },
+ "IMSI": {
+ "name": "IMSI",
"control": {
"type": "text",
- "value": "en_US"
- },
- "callback": function (setting) {
- event.trigger("LanguageChanged", [setting]);
+ "value": "310150123456789"
}
},
- "region": {
- "name": "region",
+ "PIN": {
+ "name": "PIN",
"control": {
"type": "text",
- "value": "en_CA"
- },
- "callback": function (setting) {
- event.trigger("RegionChanged", [setting]);
+ "value": "43A8C489"
}
}
},
- "battery": {
- "state": {
- "name": "Handset is Charging",
+ "system": {
+ "isMassStorageActive": {
+ "name": "Mass Storage Is Connected",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "hasDataCoverage": {
+ "name": "Has Data Coverage",
"control": {
"type": "checkbox",
"value": true
},
"callback": function (setting) {
- event.trigger("DeviceBatteryStateChanged", [setting]);
+ event.trigger("CoverageChange");
+ require('ripple/bus').send("network", setting);
}
},
- "level": {
- "name": "Charge Level (% remaining)",
+ "lag": {
+ "name": "Lag the network",
"control": {
- "type": "select",
- "value": 100
+ type: "checkbox",
+ value: false
},
- "options": (function () {
- var i,
- optionList = {};
-
- for (i = 0; i <= 100; i++) {
- optionList[i] = i;
- }
-
- return optionList;
- }()),
"callback": function (setting) {
- event.trigger("DeviceBatteryLevelChanged", [setting]);
+ require('ripple/bus').send("lag", setting);
}
- }
- },
- "Perimeters": {
- "perimeter": {
- "name": "Perimeter",
+ },
+ "network": {
+ "name": "Data Network",
"control": {
"type": "select",
- "value": "Consumer"
+ "value": "3GPP"
},
"options": {
- "Enterprise": "Enterprise",
- "Consumer": "Consumer"
+ "3GPP" : "3GPP",
+ "CDMA": "CDMA",
+ "iDEN": "iDEN",
+ "Wi-Fi": "Wi-Fi"
+ },
+ "callback": function (setting) {
+ event.trigger("CoverageChange");
}
}
}
};
});
-define('ripple/platform/webworks.bb10/1.0.0/spec/events', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/spec/events', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var _self,
- event = require('ripple/event');
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ events = require('ripple/platform/webworks.core/2.0.0/spec/events');
-module.exports = {
- "blackberry.event.swipedown": {
+_self = {
+ "system.event.onExit": {
callback: function () {
- event.trigger("AppSwipeDown");
+ event.trigger("AppExit");
}
},
- "blackberry.event.resume": {
+ "system.event.onCoverageChange": {
callback: function () {
- event.trigger("AppResume");
+ event.trigger("CoverageChange");
}
},
- "blackberry.event.pause": {
- callback: function () {
- event.trigger("AppPause");
+ "system.event.onHardwareKey": {
+ args: [
+ "Back",
+ "Menu",
+ "Convenience 1",
+ "Convenience 2",
+ "Start Call",
+ "End Call",
+ "Volume Down",
+ "Volume Up"
+ ],
+ callback: function (key) {
+ event.trigger("HardwareKey", [key]);
}
}
};
+utils.mixin(events, _self);
+
+module.exports = _self;
+
});
-define('ripple/platform/webworks.bb10/1.0.0/spec/ui', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/spec/ui', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
"geoView",
"platformEvents",
"widgetConfig",
- "build",
- "invoke"
+ "messaging",
+ "push",
+ "phone",
+ "build"
]
};
});
-define('ripple/platform/webworks.bb10/1.0.0/spec', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
-
- id: "webworks.bb10",
- version: "1.0.0",
- name: "BlackBerry 10 WebWorks",
-
- persistencePrefix: "rim-bb10-",
-
- ui: require('ripple/platform/webworks.bb10/1.0.0/spec/ui'),
- device: require('ripple/platform/webworks.bb10/1.0.0/spec/device'),
- config: require('ripple/platform/webworks.bb10/1.0.0/spec/config'),
- events: require('ripple/platform/webworks.bb10/1.0.0/spec/events'),
-
- initialize: function () {
- var event = require('ripple/event'),
- _console = require('ripple/console'),
- emulatorBridge = require('ripple/emulatorBridge');
+var utils = require('ripple/utils'),
+ platform = "ripple/platform/webworks.handset/2.0.0/server/",
+ core = "ripple/platform/webworks.core/2.0.0/server/",
+ systemEvent = require(platform + 'systemEvent'),
+ system = {};
- event.on("TinyHipposLoaded", function () {
- var doc = emulatorBridge.document(),
- evt = doc.createEvent("Events");
- evt.initEvent("webworksready", true, true);
- doc.dispatchEvent(evt);
- _console.log("fired webworksready event!");
- });
- },
+// ugh, thanks to the spec...
+system.event = systemEvent;
+utils.mixin(require(core + "system"), system);
- objects: {
- Coordinates: {
- path: "w3c/1.0/Coordinates"
+module.exports = {
+ blackberry: {
+ invoke: require(platform + "invoke"),
+ system: system,
+ app: require(platform + "app"),
+ identity: require(platform + "identity"),
+ message: {
+ sms: require(platform + "sms"),
+ message: require(platform + "message")
},
- Position: {
- path: "w3c/1.0/Position"
+ push: require(platform + "push"),
+ pim: {
+ Task: require(platform + "Task"),
+ category: require(platform + "category"),
+ memo: require(platform + "memo"),
+ appointment: require(platform + "appointment"),
+ contact: require(platform + "contact")
},
- PositionError: {
- path: "w3c/1.0/PositionError"
+ audio: {
+ player: require(platform + "audioPlayer")
},
- navigator: {
- path: "webworks.bb10/1.0.0/navigator",
- children: {
- geolocation: {
- path: "w3c/1.0/geolocation"
- }
- }
+ ui: {
+ menu: require(platform + "menu"),
+ dialog: require(core + "dialog")
},
- blackberry: {
- children: {
- event: {
- path: "webworks.bb10/1.0.0/event"
- },
- app: {
- path: "webworks.bb10/1.0.0/app",
- feature: "blackberry.app"
- },
- invoke: {
- path: "webworks.bb10/1.0.0/invoke",
- feature: "blackberry.invoke"
- },
- identity: {
- path: "webworks.bb10/1.0.0/identity",
- feature: "blackberry.identity"
- },
- system: {
- path: "webworks.bb10/1.0.0/system"
- },
- connection: {
- path: "webworks.bb10/1.0.0/connection"
- },
- ui: {
- children: {
- dialog: {
- path: "webworks.bb10/1.0.0/dialog",
- feature: "blackberry.ui.dialog"
- }
- }
- },
- }
+ phone: require(platform + "phone"),
+ io: {
+ dir: require(platform + "io/dir"),
+ file: require(core + "io/file")
}
}
};
});
-define('ripple/platform/webworks.bb10/1.0.0/system', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var deviceSettings = require('ripple/deviceSettings'),\r
- devices = require('ripple/devices'),\r
- app = require('ripple/app'),\r
- utils = require('ripple/utils'),\r
- _self;\r
-\r
-function _is(feature) {\r
- return {\r
- allowedFor: function (location) {\r
- return feature && feature.URIs.some(function (uri) {\r
- return uri.value === location ||\r
- (location.indexOf(uri.value) >= 0 && uri.subdomains);\r
- });\r
- }\r
- };\r
-}\r
-\r
-_self = {\r
- hasCapability: function (capability) {\r
- var capabilities = devices.getCurrentDevice().capabilities;\r
- return capabilities ? capabilities.some(function (type) {\r
- return type === capability;\r
- }) : false;\r
- },\r
- hasPermission: function (desiredModule) {\r
- var info = app.getInfo(),\r
- feature = info.features ? info.features[desiredModule] : null;\r
-\r
- return feature === null || _is(feature).allowedFor(utils.location().href) ? _self.ALLOW : _self.DENY;\r
- }\r
-};\r
-\r
-_self.__defineGetter__("ALLOW", function () {\r
- return 0;\r
-});\r
-\r
-_self.__defineGetter__("DENY", function () {\r
- return 1;\r
-});\r
-\r
-_self.__defineGetter__("softwareVersion", function () {\r
- return devices.getCurrentDevice().osVersion;\r
-});\r
-\r
-_self.__defineGetter__("hardwareId", function () {\r
- return devices.getCurrentDevice().hardwareId;\r
-});\r
-\r
-_self.__defineGetter__("language", function () {\r
- return deviceSettings.retrieve("system.language");\r
-});\r
-\r
-_self.__defineGetter__("region", function () {\r
- return deviceSettings.retrieve("system.region");\r
-});\r
-\r
-module.exports = _self;\r
-
-});
-define('ripple/platform/webworks.core/2.0.0/XMLHttpRequest', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/audioPlayer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+//create my dom collection node in UI
+
+var utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ notifications = require('ripple/notifications'),
+ Player = require('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer'),
+ _handlers = {
+ loadstart: {},
+ canplaythrough: {},
+ durationchange: {},
+ ended: {},
+ error: {},
+ play: {},
+ pause: {},
+ volumechange: {},
+ close: {}
+ },
+ extract = {
+ time: function (audio) {
+ return audio.currentTime;
+ },
+ duration: function (audio) {
+ return audio.duration;
+ },
+ error: function (audio) {
+ return audio.error;
+ },
+ nothing: function (audio) {
+ return null;
+ }
+ },
+ container;
+
+container = utils.createElement("section", {
+ id: "webworks-audio-players"
+});
+
+document.getElementById("ui").appendChild(container);
+
+function _errClosed(method) {
+ notifications.openNotification("error",
+ "attempted to call " + method + " on a player that is already closed. This is a very bad thing to do :)");
+ return false;
+}
+
+function _removeHandler(type, id) {
+ var audio = document.getElementById(id);
+
+ if (audio && _handlers[type][id]) {
+ audio.removeEventListener(type, _handlers[type][id]);
+ delete _handlers[type][id];
+ }
+}
+
+function _addHandler(type, id, callback) {
+ var audio = document.getElementById(id);
+
+ if (audio) {
+ _removeHandler(type, id);
+ audio.addEventListener(type, callback);
+ _handlers[type][id] = callback;
+ }
+}
+
+function proxyEvent(from, map) {
+ var audio = document.getElementById(map.id);
+
+ if (audio) {
+ map.baton.take();
+ _addHandler(from, map.id, function () {
+ _removeHandler(from, map.id);
+ map.baton.pass({code: 1, data: {
+ event: map.target,
+ eventData: map.data(this)
+ }});
+ });
+ }
+ else {
+ return {code: -1, data: {event: "EVENT_ERROR", eventData: 5}};
+ }
+}
+
module.exports = {
- create: function (server) {
- var XHR = window.XMLHttpRequest,
- webworks = require(server);
- return function () {
- var _url,
- _async,
- xhr = new XHR(),
- origMethods = {
- open: xhr.open,
- send: xhr.send,
- setRequestHeader: xhr.setRequestHeader
- };
+ create: function (args) {
+ var id = Math.uuid(),
+ audio = utils.createElement("audio", {
+ id: id
+ });
- function onreadystatechange() {
- if (typeof xhr.onreadystatechange === "function") {
- xhr.onreadystatechange();
- }
- }
+ audio.setAttribute("src", args.locator);
- function statemachine(getResult) {
- var state = 0,
- incState = function (prev, baton) {
- state++;
- if (_async) {
- baton.take();
- window.setTimeout(baton.pass, 1);
- }
- },
- setResponse = function (result) {
- xhr.__defineGetter__("status", function () {
- return 200;
- });
+ if (args.type) {
+ audio.setAttribute("type", args.type);
+ }
- xhr.__defineGetter__("responseText", function () {
- return result !== null && result !== undefined ?
- JSON.stringify(result) : null;
- });
- };
+ container.appendChild(audio);
+ audio.load();
- xhr.__defineGetter__("readyState", function () {
- return state;
- });
+ if (audio.error) {
+ throw "there was a problem opening the audio file";
+ }
- jWorkflow.order(incState)
- .andThen(onreadystatechange)
- .andThen(incState)
- .andThen(onreadystatechange)
- .andThen(incState)
- .andThen(onreadystatechange)
- .andThen(getResult)
- .andThen(setResponse)
- .andThen(incState)
- .andThen(onreadystatechange)
- .start();
+ return {code: 1, data: id};
+ },
+
+ play: function (args) {
+ var audio = document.getElementById(args.id),
+ playing;
+
+ if (audio) {
+ audio.play();
+ audio.rimState = Player.STARTED;
+ playing = !!!audio.error;
+ }
+ else {
+ playing = _errClosed("play");
+ }
+
+ return {code: 1, data: playing};
+ },
+
+ pause: function (args) {
+ var audio = document.getElementById(args.id),
+ paused;
+
+ if (audio) {
+ audio.pause();
+ paused = !!!audio.error;
+ } else {
+ paused = _errClosed("pause");
+ }
+
+ return {code: 1, data: paused};
+ },
+
+ close: function (args) {
+ var audio = document.getElementById(args.id),
+ callback = _handlers["close"][args.id],
+ closed = true;
+
+ if (audio) {
+ if (callback) {
+ callback();
}
+ container.removeChild(audio);
+ }
+ else {
+ closed = _errClosed("close");
+ }
- xhr.setRequestHeader = function (header, value) {
- if (!_url.match(/^webworks:\/\//)) {
- origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
- }
- };
+ return {code: 1, data: closed};
+ },
- xhr.open = function (method, url, async, user, password) {
- _url = url;
- _async = async;
+ onStart: function (args, post, baton) {
+ return proxyEvent("play", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_START",
+ data: extract.time
+ });
+ },
- if (!_url.match(/^webworks:\/\//)) {
- origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
- }
- };
+ onStopped: function (args, post, baton) {
+ return proxyEvent("pause", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_STOPPED",
+ data: extract.time
+ });
+ },
- xhr.send = function (post) {
- if (!_url.match(/^webworks:\/\//)) {
- origMethods.send.apply(xhr, Array.prototype.slice.call(arguments));
- return;
- }
+ onBufferingStarted: function (args, post, baton) {
+ return proxyEvent("loadstart", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_BUFFERING_STARTED",
+ data: extract.time
+ });
+ },
- var params = _url.match(/\?(.*)$/),
- objPath = _url.match(/^webworks:\/\/([^\?]*)/)[1].split("/"),
- apiMethod = objPath.reduce(function (obj, name) {
- return obj[name];
- }, webworks),
- postParams = {},
- get = {};
+ onBufferingStopped: function (args, post, baton) {
+ return proxyEvent("canplaythrough", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_BUFFERING_STOPPED",
+ data: extract.time
+ });
+ },
- if (params) {
- params[1].split("&").forEach(function (param) {
- var pair = param.split("="),
- key = decodeURIComponent(pair[0]),
- value = decodeURIComponent(pair[1]);
- // parsing undefied with JSON throws exception
- get[key] = value === "undefined" ? undefined : JSON.parse(value);
- });
- }
+ onDurationUpdated: function (args, post, baton) {
+ return proxyEvent("durationchange", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_DURATION_UPDATED",
+ data: extract.duration
+ });
+ },
- if (post) {
- post.split("&").forEach(function (param) {
- var pair = param.split("="),
- value;
- try {
- value = JSON.parse(decodeURIComponent(pair[1]));
- } catch (e) {
- value = pair[1] === "undefined" ? undefined : pair[1];
- }
+ onEnd: function (args, post, baton) {
+ return proxyEvent("ended", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_END_OF_MEDIA",
+ data: extract.duration
+ });
+ },
- postParams[pair[0]] = value;
- });
- }
+ onError: function (args, post, baton) {
+ return proxyEvent("error", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_ERROR",
+ data: extract.error
+ });
+ },
- statemachine(function (prev, baton) {
- return apiMethod(get, postParams, baton);
- });
- };
+ onVolumeChange: function (args, post, baton) {
+ return proxyEvent("volumechange", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_VOLUME_CHANGED",
+ data: extract.nothing
+ });
+ },
- return xhr;
- };
- }
-};
+ onClose: function (args, post, baton) {
+ return proxyEvent("close", {
+ id: args.id,
+ baton: baton,
+ target: "EVENT_CLOSED",
+ data: extract.nothing
+ });
+ },
-});
-define('ripple/platform/webworks.core/2.0.0/client/FileProperties', function (require, exports, module) {
-/*
- * Copyright 2011 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 FileProperties(props) {
- props = props || {};
+ getDuration: function (args) {
+ var audio = document.getElementById(args.id),
+ duration;
- function _get(val) {
- return function () {
- return props[val];
- };
- }
+ if (audio) {
+ duration = audio.duration;
+ }
+ else {
+ _errClosed("getDuration");
+ duration = -1;
+ }
- this.__defineGetter__("dateCreated", _get("dateCreated")); //tablet only
- this.__defineGetter__("dateModified", _get("dateModified"));
- this.__defineGetter__("directory", _get("directory"));
- this.__defineGetter__("fileExtension", _get("fileExtension"));
- this.__defineGetter__("isHidden", _get("isHidden"));
- this.__defineGetter__("isReadonly", _get("isReadonly")); //handset only
- this.__defineGetter__("mimeType", _get("mimeType")); //handset only
- this.__defineGetter__("size", _get("size"));
-}
+ return {code: 1, data: duration};
+ },
-module.exports = FileProperties;
+ getMediaTime: function (args) {
+ var audio = document.getElementById(args.id),
+ time;
-});
-define('ripple/platform/webworks.core/2.0.0/client/dialog', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
- _uri = "blackberry/ui/dialog/",\r
- _self;\r
-\r
-function getButtonsForDialogType(dialogType) {\r
- switch (dialogType) {\r
- case _self.D_OK:\r
- return ["Ok"];\r
- case _self.D_SAVE:\r
- return ["Save", "Discard"];\r
- case _self.D_DELETE:\r
- return ["Delete", "Cancel"];\r
- case _self.D_YES_NO:\r
- return ["Yes", "No"];\r
- case _self.D_OK_CANCEL:\r
- return ["Ok", "Cancel"];\r
- default:\r
- throw new Error("Invalid dialog type: " + dialogType);\r
- }\r
-}\r
-\r
-_self = {\r
- customAskAsync: function (message, choices, callback, settings) {\r
- return transport.call(_uri + "ask", {\r
- async: true,\r
- get: {\r
- message: message,\r
- buttons: choices,\r
- settings: settings\r
- }\r
- }, function (response) {\r
- if (callback) {\r
- callback(response);\r
- }\r
- });\r
- },\r
-\r
- standardAskAsync: function (message, type, callback, settings) {\r
- var choices = getButtonsForDialogType(type);\r
- return transport.call(_uri + "ask", {\r
- async: true,\r
- get: {\r
- message: message,\r
- buttons: choices,\r
- settings: settings\r
- }\r
- }, function (response) {\r
- if (callback) {\r
- callback(response);\r
- }\r
- });\r
- }\r
-};\r
-\r
-_self.__defineGetter__("D_OK", function () {\r
- return 0;\r
-});\r
-\r
-_self.__defineGetter__("D_SAVE", function () {\r
- return 1;\r
-});\r
-\r
-_self.__defineGetter__("D_DELETE", function () {\r
- return 2;\r
-});\r
-\r
-_self.__defineGetter__("D_YES_NO", function () {\r
- return 3;\r
-});\r
-\r
-_self.__defineGetter__("D_OK_CANCEL", function () {\r
- return 4;\r
-});\r
-\r
-_self.__defineGetter__("BOTTOM", function () {\r
- return "bottomCenter";\r
-});\r
-\r
-_self.__defineGetter__("CENTER", function () {\r
- return "middleCenter";\r
-});\r
-\r
-_self.__defineGetter__("TOP", function () {\r
- return "topCenter";\r
-});\r
-\r
-_self.__defineGetter__("SIZE_FULL", function () {\r
- return "full";\r
-});\r
-\r
-_self.__defineGetter__("SIZE_LARGE", function () {\r
- return "large";\r
-});\r
-\r
-_self.__defineGetter__("SIZE_MEDIUM", function () {\r
- return "medium";\r
-});\r
-\r
-_self.__defineGetter__("SIZE_SMALL", function () {\r
- return "small";\r
-});\r
-\r
-_self.__defineGetter__("SIZE_TALL", function () {\r
- return "tall";\r
-});\r
-\r
-module.exports = _self;\r
+ if (audio) {
+ time = audio.currentTime;
+ }
+ else {
+ _errClosed("getMediaTime");
+ time = -1;
+ }
-});
-define('ripple/platform/webworks.core/2.0.0/client/events', function (require, exports, module) {
-/*
- * Copyright 2011 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 _handlers = [],
- _self;
+ return {code: 1, data: time};
+ },
-_self = {
- eventsMap: {
- getHandlerById: function (handlerId) {
- return _handlers[handlerId];
- },
- addHandler: function (handler) {
- _handlers.push(handler);
- return _handlers.length - 1;
- },
- removeHandler: function (handlerId) {
- if (handlerId > -1 && handlerId < _handlers.length) {
- delete _handlers[handlerId]; //cannot splice because all published IDs would refer to the wrong handler
- }
+ setMediaTime: function (args) {
+ var audio = document.getElementById(args.id);
+
+ if (audio) {
+ audio.currentTime = args.value;
}
+ else {
+ _errClosed("setMediaTime");
+ }
+
+ return {code: 1};
},
- registerEventHandler : function (eventName, eventCallback, eventParams) {
- return _self.eventsMap.addHandler(eventCallback);
+ getVolumeLevel: function (args) {
+ var audio = document.getElementById(args.id),
+ level;
+
+ if (audio) {
+ level = audio.volume * 100;
+ }
+ else {
+ _errClosed("getVolumeLevel");
+ level = -1;
+ }
+
+ return {code: 1, data: level};
},
- getEventHandler : function (handlerId) {
- return _self.eventsMap.getHandlerById(handlerId);
+ setVolumeLevel: function (args) {
+ var audio = document.getElementById(args.id);
+
+ if (audio) {
+ audio.volume = args.value / 100;
+ }
+ else {
+ _errClosed("setVolumeLevel");
+ }
+
+ return {code: 1};
+ },
+
+ getState: function (args) {
+ var audio = document.getElementById(args.id),
+ state = audio ? audio.rimState || Player.PREFETCHED : Player.CLOSED;
+ return {code: 1, data: state};
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.core/2.0.0/client/io/dir', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/io/dir', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/io/dir/",
- FILE = "file://";
-
-function _prunePrefix(path) {
- return path.replace(new RegExp("^" + FILE), '');
-}
+var cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
+ dir = require('ripple/platform/webworks.core/2.0.0/server/io/dir'),
+ utils = require('ripple/utils'),
+ _self = {};
-function _addPrefix(path) {
- return FILE + path;
+function _packet(data) {
+ return {
+ code: 1,
+ data: data
+ };
}
-module.exports = {
- createNewDir: function (path) {
- transport.call(_uri + "createNewDir", {
- post: {path: _prunePrefix(path)}
- });
- },
- deleteDirectory: function (path, recursive) {
- transport.call(_uri + "deleteDirectory", {
- post: {path: _prunePrefix(path), recursive: recursive}
- });
- },
- exists: function (path) {
- return transport.call(_uri + "exists", {
- post: {path: _prunePrefix(path)}
- });
- },
- getParentDirectory: function (path) {
- return _addPrefix(transport.call(_uri + "getParentDirectory", {
- post: {path: _prunePrefix(path)}
- }));
- },
- listDirectories: function (path) {
- return transport.call(_uri + "listDirectories", {
- post: {path: _prunePrefix(path)}
- });
- },
- listFiles: function (path) {
- return transport.call(_uri + "listFiles", {
- post: {path: _prunePrefix(path)}
- });
+utils.mixin({
+ getFreeSpaceForRoot: function (get, post, baton) {
+ return _packet(cache.dir.getFreeSpaceForRoot(post.path));
},
- rename: function (path, newName) {
- transport.call(_uri + "rename", {
- post: {path: _prunePrefix(path), newName: newName}
- });
+ getRootDirs: function (get, post, baton) {
+ return _packet(cache.dir.getRootDirs());
}
-};
+}, _self);
+
+utils.mixin(dir, _self);
+
+module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/client/io/file', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/identity/phone', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/io/file/",
- FILE = "file://",
- _onFileOpened;
+var _lines = [
+ {id: 1, number: 12345678910, label: "rogers", type: 1},
+ {id: 2, number: 10987654321, label: "mystery", type: 0}
+ ],
+ _self;
-function _prunePrefix(path) {
- return path.replace(new RegExp("^" + FILE), '');
-}
+function _filterLines(args) {
-module.exports = {
- copy: function (from, to) {
- transport.call(_uri + "copy", {
- post: {from: _prunePrefix(from), to: _prunePrefix(to)}
- });
- },
- deleteFile: function (path) {
- transport.call(_uri + "deleteFile", {
- post: {path: _prunePrefix(path)}
- });
- },
- exists: function (path) {
- return transport.call(_uri + "exists", {
- post: {path: _prunePrefix(path)}
- });
- },
- getFileProperties: function (path) {
- var properties = transport.call(_uri + "getFileProperties", {
- post: {path: _prunePrefix(path)}
- });
- properties.directory = FILE + properties.directory;
- return properties;
- },
- open: function (path, newName) {
- transport.call(_uri + "open", {
- post: {path: _prunePrefix(path)}
+ var result = _lines;
+
+ if (args && typeof args.id === "number") {
+ result = _lines.filter(function (line) {
+ return line.id === args.id;
});
- },
- readFile: function (path, onFileOpened, async) {
- async = async === false ? false : true;
- var uri = _uri + "readFile",
- args = {
- post: {path: _prunePrefix(path), async: async}
- },
- callResult;
+ if (result.length === 0) {
+ throw "invalid line id: " + args.id;
+ }
+ }
- _onFileOpened = onFileOpened;
+ return result;
+}
- if (async) {
- transport.poll(uri, args, function (data, res) {
- if (_onFileOpened) {
- _onFileOpened(FILE + data.fullPath, data.blobData);
- }
- return false;
- });
- } else {
- callResult = transport.call(uri, args);
- _onFileOpened(FILE + callResult.fullPath, callResult.blobData);
- }
- },
- rename: function (path, newName) {
- transport.call(_uri + "rename", {
- post: {path: _prunePrefix(path), newName: newName}
+_self = {
+ getLineIds: function () {
+ var lines = _lines.map(function (line) {
+ return line.id;
});
+ return {
+ code: 1,
+ data: lines
+ };
},
- saveFile: function (path, blob) {
- transport.call(_uri + "saveFile", {
- post: {path: _prunePrefix(path), blob: blob}
- });
- }
-};
-
-});
-define('ripple/platform/webworks.core/2.0.0/client/system', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
- _uri = "blackberry/system/",\r
- _self;\r
-\r
-_self = {\r
- hasCapability: function (capability) {\r
- return transport.call(_uri + "hasCapability", {\r
- get: {capability: capability}\r
- });\r
- },\r
-\r
- hasDataCoverage: function () {\r
- return transport.call(_uri + "hasDataCoverage");\r
- },\r
-\r
- hasPermission: function (desiredModule) {\r
- return transport.call(_uri + "hasPermission", {\r
- get: {desiredModule: desiredModule}\r
- });\r
- },\r
-\r
- isMassStorageActive: function () {\r
- return transport.call(_uri + "isMassStorageActive");\r
- }\r
-};\r
-\r
-_self.__defineGetter__("model", function () {\r
- return transport.call(_uri + "model");\r
-});\r
-_self.__defineGetter__("scriptApiVersion", function () {\r
- return transport.call(_uri + "scriptApiVersion");\r
-});\r
-_self.__defineGetter__("softwareVersion", function () {\r
- return transport.call(_uri + "softwareVersion");\r
-});\r
-\r
-_self.__defineGetter__("ALLOW", function () {\r
- return 0;\r
-});\r
-_self.__defineGetter__("DENY", function () {\r
- return 1;\r
-});\r
-_self.__defineGetter__("PROMPT", function () {\r
- return 2;\r
-});\r
-_self.__defineGetter__("NOT_SET", function () {\r
- return 3;\r
-});\r
-\r
-module.exports = _self;\r
+ getLineLabel: function (args) {
+ return {
+ code: 1,
+ data: _filterLines(args)[0].label
+ };
+ },
+ getLineNumber: function (args) {
+ return {
+ code: 1,
+ data: _filterLines(args)[0].number
+ };
+ },
+ getLineType: function (args) {
+ return {
+ code: 1,
+ data: _filterLines(args)[0].type
+ };
+ }
+};
+
+module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/client/transport', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/category', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self;
-
-function RemoteFunctionCall(functionUri) {
- var params = {},
- postString = "",
- postParams = {};
-
- function composeUri() {
- var uri = "webworks://" + functionUri,
- paramCount = 1,
- param;
-
- for (param in params) {
- if (params.hasOwnProperty(param)) {
- if (paramCount === 1) {
- uri += "?";
- } else {
- uri += "&";
- }
- uri += param + "=" + params[param];
- paramCount++;
- }
+var db = require('ripple/db'),
+ _KEY = "blackberry-pim-category",
+ _self;
- uri = uri.replace(/\&$/, "");
- }
+function _get() {
+ return db.retrieveObject(_KEY) || [];
+}
- return uri;
+function _save(category) {
+ var categories = _get();
+ if (!categories.some(function (item) {
+ return item === category;
+ })) {
+ categories.push(category);
+ db.saveObject(_KEY, categories);
}
+}
- function createXhrRequest(uri, isAsync) {
- var request = new XMLHttpRequest(),
- paramCount = 1,
- param;
-
- for (param in postParams) {
- if (postParams.hasOwnProperty(param)) {
- postString += param + "=" + postParams[param] + "&";
- paramCount++;
- }
- }
-
- postString = postString.replace(/\&$/, "");
-
- // TODO: make get/post
- request.open("POST", uri, isAsync);
- request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+function _remove(category) {
+ var categories = _get(),
+ index = categories.indexOf(category);
- return request;
+ if (index >= 0) {
+ categories.splice(index, 1);
+ db.saveObject(_KEY, categories);
}
-
- this.addParam = function (name, value) {
- params[name] = encodeURIComponent(JSON.stringify(value));
- };
-
- this.addPostParam = function (name, value) {
- postParams[name] = encodeURIComponent(JSON.stringify(value));
- };
-
- this.makeSyncCall = function (success, error) {
- var requestUri = composeUri(),
- request = createXhrRequest(requestUri, false),
- response, errored, cb, data;
-
- request.send(postString);
-
- response = JSON.parse(request.responseText || "null");
- errored = response.code < 0;
- cb = errored ? error : success;
- data = errored ? response.msg : response.data;
-
- if (cb) {
- cb(data, response);
- }
- else if (errored) {
- throw data;
- }
-
- return data;
- };
-
- this.makeAsyncCall = function (success, error) {
- var requestUri = composeUri(),
- request = createXhrRequest(requestUri, true);
-
- request.onreadystatechange = function () {
- if (request.readyState === 4 && request.status === 200) {
- var response = JSON.parse(request.responseText || "null"),
- cb = response.code < 0 ? error : success,
- data = response.code < 0 ? response.msg : response.data;
-
- return cb && cb(data, response);
- }
- };
-
- request.send(postString);
- };
}
_self = {
- call: function (url, opts, success, error) {
- var request = new RemoteFunctionCall(url),
- name;
-
- opts = opts || {};
-
- if (opts.get) {
- for (name in opts.get) {
- if (Object.hasOwnProperty.call(opts.get, name)) {
- request.addParam(name, opts.get[name]);
- }
- }
- }
-
- if (opts.post) {
- for (name in opts.post) {
- if (Object.hasOwnProperty.call(opts.post, name)) {
- request.addPostParam(name, opts.post[name]);
- }
- }
- }
-
- return opts.async ? request.makeAsyncCall(success, error) : request.makeSyncCall(success, error);
+ addCategory: function (args) {
+ _save(args.categoryName);
+ return {code: 1};
},
-
- poll: function (url, opts, callback) {
- opts = opts || {};
- opts.async = true;
-
- _self.call(url, opts, function (data, response) {
- if (callback(data, response)) {
- _self.poll(url, opts, callback);
- }
- });
+ deleteCategory: function (args) {
+ _remove(args.categoryName);
+ return {code: 1};
+ },
+ getCategories: function () {
+ return {code: 1, data: _get()};
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/client/utils', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/identity', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _blobs = {};
+var _self,
+ Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
+ Transport = require('ripple/platform/webworks.handset/2.0.0/client/identity/Transport'),
+ utils = require('ripple/utils'),
+ platform = require('ripple/platform'),
+ deviceSettings = require('ripple/deviceSettings'),
+ _transportTypes = [
+ {name: "TCP Cellular", type: "TCP Cellular"},
+ {name: "Wap", type: "Wap"},
+ {name: "Wap 2.0", type: "Wap 2.0"},
+ {name: "MDS", type: "MDS"},
+ {name: "BIS B", type: "Bis B"},
+ {name: "Unite!", type: "Unite!"},
+ {name: "TCP Wifi", type: "TCP Wifi"},
+ ],
+ _services = [
+ new Service(),
+ new Service()
+ ];
-function _blobBuilder() {
- var BlobBuilder = BlobBuilder || WebKitBlobBuilder;
- return new BlobBuilder();
+function _isTransportAvailable(transport) {
+ return deviceSettings.retrieveAsBoolean("transports." + transport.type);
}
-module.exports = {
- parseURL: function (theUrl) {
- /********START IDEA BORROWING*******/
- // parseUri 1.2.2
- // (c) Steven Levithan <stevenlevithan.com>
- // MIT License
-
- function parseUri(str) {
- var o = parseUri.options,
- m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
- uri = {},
- i = 14;
-
- while (i--) {
- uri[o.key[i]] = m[i] || "";
- }
-
- uri[o.q.name] = {};
- uri[o.q.arrayName] = [];
- uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
- if ($1) {
- uri[o.q.name][$1] = $2;
- uri[o.q.arrayName].push($2);
- }
- });
-
- return uri;
- }
-
- parseUri.options = {
- strictMode: false,
- key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
- q: {
- name: "queryKey",
- arrayName: "queryArray",
- parser: /(?:^|&)([^&=]*)=?([^&]*)/g
- },
- parser: {
- strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
- loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
- }
- };
- /********END IDEA BORROWING*******/
-
- parseUri.strictMode = "strict";
- var uri = parseUri(theUrl),
- retVal = {
- getURLParameter : function (key) {
- return uri.queryKey[key];
- },
-
- getURLParameterByIndex : function (index) {
- return uri.queryArray[index];
- }
- };
+utils.mixin({
+ name: "Super Dave Osborne",
+ emailAddress: "dave@stunt.com",
+ isDefault: true,
+ type: Service.TYPE_EMAIL
+}, _services[0]);
- //Add default values for the http/https port if they weren't specified in the URL. The above parser returns undefined. We need the values
- //to be compatible with the BB version of API.
- if (uri["port"] === "") {
- if (uri["protocol"] === "http") {
- uri["port"] = "80";
- }
- else if (uri["protocol"] === "https") {
- uri["port"] = "443";
- }
- else {
- uri["port"] = "0";
- }
- }
+utils.mixin({
+ name: "Fred Penner",
+ emailAddress: "fred@fredpenner.com",
+ isDefault: false,
+ type: Service.TYPE_CONTACT
+}, _services[1]);
- retVal.__defineGetter__("host", function () {
- return uri["host"];
+_self = {
+ getDefaultService: function () {
+ var serices = _services.filter(function (service) {
+ return service.isDefault === true;
});
- retVal.__defineGetter__("port", function () {
- return parseInt(uri["port"], 10);
+ return {code: 1, data: serices};
+ },
+ getServiceList: function () {
+ return {code: 1, data: _services};
+ },
+ getTransportList: function () {
+ var transports = _transportTypes.filter(function (transport) {
+ return _isTransportAvailable(transport);
+ }).map(function (transport) {
+ return new Transport(transport.name, transport.type);
});
-
- return retVal;
+ return {code: 1, data: transports};
},
-
- generateUniqueId: function () {
- return Math.floor(Math.random() * Number.MAX_VALUE);
+ IMEI: function () {
+ return {code: 1, data: deviceSettings.retrieve("identity.IMEI")};
},
-
- blobToString: function (blob, encoding) {
- return _blobs[blob.id];
+ IMSI: function () {
+ return {code: 1, data: deviceSettings.retrieve("identity.IMSI")};
},
-
- stringToBlob: function (string, encoding) {
- var id = Math.uuid(undefined, 16),
- blob = _blobBuilder(),
- finalBlob;
-
- _blobs[id] = string;
- blob.append(string);
-
- finalBlob = blob.getBlob();
- finalBlob.id = id;
- finalBlob.length = finalBlob.size;
-
- return finalBlob;
- }
+ PIN: function () {
+ return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
+ },
+ phone: require('ripple/platform/webworks.handset/2.0.0/server/identity/phone')
};
+module.exports = _self;
+
});
-define('ripple/platform/webworks.core/2.0.0/fsCache', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/menu', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var fs = require('ripple/dbfs'),
- utils = require('ripple/utils'),
- _console = require('ripple/console'),
- constants = require('ripple/constants'),
+var _menuItems = {},
event = require('ripple/event'),
- bbUtils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
- FileProperties = require('ripple/platform/webworks.core/2.0.0/client/FileProperties'),
- _cache = {},
- _self;
-
-function _createPath(path) {
- var parts = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
- workflow = jWorkflow.order();
-
- parts.forEach(function (part, index) {
- var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+ events = require('ripple/platform/webworks.core/2.0.0/client/events'),
+ ui = require('ripple/ui'),
+ devices = require('ripple/devices'),
+ utils = require('ripple/utils'),
+ tooltip = require('ripple/ui/plugins/tooltip'),
+ _self,
+ isMenuOpen = false,
+ _baton,
+ menuWindow = document ? document.getElementById("menu-window") : undefined;
- workflow.andThen(function (prev, baton) {
- baton.take();
- fs.mkdir(dir, baton.pass, baton.pass);
- });
+if (menuWindow) {
+ menuWindow.addEventListener("click", function () {
+ _self.close();
});
-
- workflow.start(_self.refresh);
}
-event.on("FileSystemInitialized", function () {
- _createPath("/SDCard");
- _createPath("/store/home/user/music");
- _createPath("/store/home/user/pictures");
- _createPath("/store/home/user/videos");
- _createPath("/store/home/user/videos");
- _createPath("/accounts/1000/appdata/emulatedapp/data");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/bookmarks");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/books");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/camera");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/documents");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/downloads");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/misc");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/music");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/photos");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/print");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/videos");
- _createPath("/accounts/1000/appdata/emulatedapp/shared/voice");
+
+event.on("LayoutChanged", function () {
+ if (isMenuOpen) {
+ _self.close();
+ //Used to resize menu on orientation change
+ _self.open();
+ }
});
-function _fsError(e) {
- _self.refresh();
- if (e.code !== 1) { // suppress file not found error
- _console.error("FileSystem error (code " + e.code + ")");
+event.on("HardwareKeyDefault", function (key) {
+ if (key === 1 || key === "1") { //menu button key
+ if (isMenuOpen) {
+ _self.close();
+ }
+ else {
+ _self.open();
+ }
}
-}
+});
-function _walk(path, parent) {
- fs.ls(path, function (entries) {
- parent.children = parent.children || {};
+event.on("MenuItemSelected", function (menuItem) {
+ var baton = _baton;
+ _baton = null;
+ return baton && baton.pass({code: 1, data: menuItem});
+});
- entries.forEach(function (entry) {
- parent.children[entry.name] = entry;
- parent.children[entry.name].properties = {};
+event.on("MenuItemChanged", function (menuItem) {
+ _menuItems[menuItem.id] = menuItem;
+});
- if (entry.isDirectory) {
- _walk(entry.fullPath, entry);
- } else {
- entry.file(function (file) {
- utils.mixin(file, parent.children[entry.name].properties);
- });
- fs.read(entry.fullPath, function (data) {
- parent.children[entry.name].data = data;
- }, function (e) {
- console.error(e);
- });
- }
- });
- }, function (e) {
- console.error(e);
- });
-}
+_self = {
-function _get(path) {
- return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
- return token === "" ? obj : (obj && obj.children ? obj.children[token] || null : null);
- }, _cache);
-}
+ onSelect : function (args, post, baton) {
+ baton.take();
+ _baton = baton;
+ },
-function _getInfo(path) {
- var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
- name = parent.splice(parent.length - 1, 1).join(""),
- ext = name.split(".");
+ addMenuItem: function (args) {
+ if (!args) {
+ throw "item not found";
+ }
+ _menuItems[args.item.id] = args.item;
+ event.trigger("MenuChanged", [_menuItems]);
+ return {code: 1};
+ },
- return {
- name: name,
- extension: ext.length > 1 ? ext[ext.length - 1] : "",
- hidden: (name.length > 0 && name[0] === ".") || false,
- parent: parent.join("/") || "/"
- };
-}
+ clearMenuItems: function () {
+ _menuItems = {};
+ event.trigger("MenuChanged", [utils.copy(_menuItems)]);
+ return {code: 1};
+ },
-function _set(path, obj) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ open: function () {
+ function _return() {
+ return {code: 1};
+ }
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ if (utils.count(_menuItems) === 0) {
+ _return();
+ }
- parent.children = parent.children || {};
- obj.properties = obj.properties || {};
- parent.children[child] = obj;
-}
+ ui.showOverlay("menu-window", function (menu) {
+ var container = document.getElementById("viewport-container"),
+ height = window.getComputedStyle(container, null).getPropertyValue("height"),
+ width = window.getComputedStyle(container, null).getPropertyValue("width"),
+ menuButtons = document.getElementById("menu-buttons"),
+ sorted,
+ menuItem;
-function _delete(path) {
- var parent = _cache,
- tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
- child = tokens.splice(tokens.length - 1, 1).join("");
+ if (!menuButtons) {
+ _return();
+ }
- tokens.forEach(function (token) {
- parent = parent.children[token];
- });
+ menu.setAttribute("style", "display:block;height:" + height + "; width:" + width + ";");
+ isMenuOpen = true;
- delete parent.children[child];
-}
+ sorted = utils.map(_menuItems, function (item) {
+ return item;
+ }).sort(function (a, b) {
+ return a.ordinal - b.ordinal;
+ });
-// TODO: handle exceptions so that any respective fs command can error out
-// TODO: dateCreated is always dateModified
+ menuButtons.innerHTML = "";
+ sorted.forEach(function (item) {
+ if (!item.isSeparator) {
+ if (item.isDefault) {
+ menuItem = utils.createElement("div", {
+ "class": "overlay-menu-item-default",
+ "id": "default-menu-item"
+ });
+ }
+ else {
+ menuItem = utils.createElement("div", {
+ "class": "overlay-menu-item"
+ });
+ }
+ menuItem.innerHTML = item.caption;
-_self = {
- refresh: function () {
- _cache = {};
- _walk("/", _cache);
- },
- file: {
- exists: function (path) {
- var entry = _get(path);
- return !!(entry && !entry.isDirectory);
- },
+ menuItem.addEventListener("click", function () {
+ _baton.pass({code: 1, data: item.id});
+ });
+ }
+ else {
+ menuItem = utils.createElement("hr", {});
+ }
+ menuButtons.appendChild(menuItem);
+ tooltip.create("#default-menu-item", "Default Item");
+ });
+ }, true);
- deleteFile: function (path) {
- _delete(path);
- fs.rm(path, function () {}, _fsError);
- },
+ event.trigger("MenuOpened", []);
- copy: function (from, to) {
- var fromEntry = _get(from);
+ _return();
+ },
- _set(to, {
- fullPath: to,
- properties: fromEntry.properties,
- data: fromEntry.data
- });
+ close: function () {
+ ui.hideOverlay("menu-window", function (menu) {
+ var menuButtons = document.getElementById("menu-buttons");
+ menuButtons.innerHTML = "";
+ isMenuOpen = false;
+ menu.setAttribute("style", "display:none;");
- fs.cp(from, to, function (entry) {
- entry.file(function (file) {
- entry.properties = entry.properties || {};
- utils.mixin(file, entry.properties);
- _set(to, entry);
- });
- }, _fsError);
- },
+ });
+ return {code: 1};
+ },
- getFileProperties: function (path) {
- var entry = _get(path),
- info = _getInfo(path);
+ removeMenuItem: function (args) {
+ delete _menuItems[args.item.id];
+ event.trigger("MenuChanged", [_menuItems]);
+ return {code: 1};
+ },
- fs.stat(path, function () {}, _fsError);
+ setDefaultMenuItem: function (args) {
- return new FileProperties({
- //HACK: not sure where these should come from so check both for now.
- dateCreated: entry.properties.lastModifiedDate || entry.lastModifiedDate,
- dateModified: entry.properties.lastModifiedDate || entry.lastModifiedDate,
- directory: info.parent,
- fileExtension: info.extension,
- isHidden: info.hidden,
- isReadonly: false,
- mimeType: entry.properties.type,
- size: entry.properties.size
- });
- },
+ utils.forEach(_menuItems, function (item) {
+ item.isDefault = false;
+ });
- rename: function (path, newName) {
- _self.dir.rename(path, newName);
- },
+ _menuItems[args.id].isDefault = true;
- readFile: function (path, success, async) {
- var entry = _get(path);
+ event.trigger("DefaultItemChanged", [_menuItems[args.id]]);
+ return {code: 1};
+ }
+};
- async = async === false ? async : true;
+module.exports = _self;
- if (!async) {
- success(bbUtils.stringToBlob(entry.data));
- }
- else {
- fs.read(path, function (data) {
- var blob = bbUtils.stringToBlob(data);
- if (async) {
- success(blob);
- }
- entry.data = data;
- _set(path, entry);
- }, _fsError);
- }
- },
+});
+define('ripple/platform/webworks.handset/2.0.0/server/app', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ app = require('ripple/app'),
+ notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ ui = require('ripple/ui'),
+ _isForeground = true,
+ _self;
- saveFile: function (path, blob) {
- var data = bbUtils.blobToString(blob);
+_self = {
+ event: require('ripple/platform/webworks.handset/2.0.0/server/appEvent'),
- _set(path, {
- lastModifiedDate: new Date(),
- fullPath: path,
- isDirectory: false,
- properties: {
- type: "",
- size: blob.size
- },
- data: data
- });
+ exit: function () {
+ event.trigger("AppExit");
+ return {code: 1};
+ },
- fs.write(path, data, function (entry) {
- entry.data = data;
- entry.file(function (file) {
- entry.properties = entry.properties || {};
- utils.mixin(file, entry.properties);
- _set(path, entry);
- });
- }, _fsError);
- }
+ author: function () {
+ return {code: 1, data: app.getInfo().author};
},
- dir: {
- createNewDir: function (path) {
- var entry = _get(path),
- info = _getInfo(path);
- if (!entry) {
- _set(path, {
- name: info.name,
- isDirectory: true,
- fullPath: path
- });
- }
+ authorEmail: function () {
+ return {code: 1, data: app.getInfo().authorEmail};
+ },
- fs.mkdir(path, function (entry) {
- _set(path, entry);
- }, _fsError);
- },
+ authorURL: function () {
+ return {code: 1, data: app.getInfo().authorURL};
+ },
- deleteDirectory: function (path, recursive) {
- _delete(path);
- if (recursive) {
- fs.rm(path, function () {}, _fsError, {recursive: recursive});
- } else {
- fs.rmdir(path, function () {}, _fsError);
- }
- },
+ copyright: function () {
+ return {code: 1, data: app.getInfo().copyright};
+ },
- exists: function (path) {
- var entry = _get(path);
- return !!(entry && entry.isDirectory);
- },
+ description: function () {
+ return {code: 1, data: app.getInfo().description};
+ },
- getFreeSpaceForRoot: function (path) {
- function _du(obj, size) {
- utils.forEach(obj, function (child, key) {
- if (child.isDirectory && child.children) {
- size += _du(child.children, size);
- } else if (child.properties && child.properties.size) {
- size += child.properties.size;
- }
- });
- return size;
- }
+ isForeground: function () {
+ return {code: 1, data: _isForeground};
+ },
- return constants.FS_SIZE - _du(_cache.children, 0);
- },
+ id: function () {
+ return {code: 1, data: app.getInfo().id};
+ },
- getParentDirectory: function (path) {
- path = "/" + path.replace(/^\//, '').replace(/\/$/, '');
+ license: function () {
+ return {code: 1, data: app.getInfo().license};
+ },
- var entry = _get(path),
- array = path.split("/");
+ licenseURL: function () {
+ return {code: 1, data: app.getInfo().licenseURL};
+ },
- return entry ? array.splice(0, array.length - 1).join("/") || "/" : null;
- },
+ name: function () {
+ return {code: 1, data: app.getInfo().name};
+ },
- listDirectories: function (path) {
- var dir = _get(path),
- directories = [];
+ version: function () {
+ return {code: 1, data: app.getInfo().version};
+ },
- utils.forEach(dir.children, function (item) {
- if (item.isDirectory) {
- directories.push(item.name);
- }
- });
+ requestBackground: function () {
+ ui.showOverlay("background-window", function (background) {
+ var button = background.children["background-return"];
- fs.ls(path, function () {}, _fsError);
+ if (button) {
+ button.addEventListener("click", _self.requestForeground);
+ }
+ _isForeground = false;
+ event.trigger("AppRequestBackground");
+ });
- return directories;
- },
+ return {code: 1};
+ },
- listFiles: function (path) {
- var dir = _get(path),
- files = [];
+ requestForeground: function () {
+ ui.hideOverlay("background-window", function (background) {
+ var button = background.children["background-return"];
- if (dir) {
- utils.forEach(dir.children, function (item) {
- if (!item.isDirectory) {
- files.push(item.name);
- }
- });
+ if (button) {
+ button.removeEventListener("click", _self.requestForeground);
}
+ _isForeground = true;
+ event.trigger("AppRequestForeground");
+ });
- fs.ls(path, function () {}, _fsError);
+ return {code: 1};
+ },
- return files;
- },
+ setHomeScreenIcon: function (args) {
+ if (args.uri) {
+ var msg = "The application set the home screen" +
+ (args.hover ? " hover " : " ") +
+ "icon to " + args.uri;
- rename: function (path, newName) {
- var info = _getInfo(path),
- parent = info.parent,
- oldName = info.name,
- from = (parent === "/" ? "" : parent) + "/" + oldName,
- to = (parent === "/" ? "" : parent) + "/" + newName;
+ notifications.openNotification("normal", msg);
+ return {code: 1};
+ }
+ else {
+ return {code: 0};
+ }
+ },
- _delete(from);
- _set(to, {
- name: info.name,
- fullPath: path
- });
+ setHomeScreenName: function (args) {
+ if (args.text) {
+ var msg = "The application set the home screen name to " + args.text;
+ notifications.openNotification("normal", msg);
+ return {code: 1};
+ }
+ else {
+ return {code: 1};
+ }
+ },
- fs.mv(from, to, function (entry) {
- _set(to, entry);
- }, _fsError);
- },
+ removeBannerIndicator: function () {
+ event.trigger("BannerUpdated", ["", 0]);
+ return {code: 1};
+ },
+
+ showBannerIndicator: function (args) {
+ event.trigger("BannerUpdated", [args.icon, args.count]);
+ return {code: 1};
+ },
- getRootDirs: function () {
- return _self.dir.listDirectories("/");
- }
- }
};
module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/select', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/invoke', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- _select,
- _predicates = {
- "==": function (left, right) {
- return left === right;
- },
- "!=": function (left, right) {
- return left !== right;
- },
- "<": function (left, right) {
- return left < right;
- },
- ">": function (left, right) {
- return left > right;
- },
- "<=": function (left, right) {
- return left <= right;
- },
- ">=": function (left, right) {
- return left >= right;
- },
- "REGEX": function (left, right) {
- return left && left.match(new RegExp(right));
- },
- "CONTAINS": function (left, right) {
- return left.indexOf(right) >= 0;
- }
+var notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ type = "normal",
+ name = {
+ "0": "Address Book",
+ "1": "Bluetooth Config",
+ "2": "Calculator",
+ "3": "Calendar",
+ "camera://": "Camera",
+ "camera://video": "Video Camera",
+ "map://": "Maps",
+ "6": "Memopad",
+ "7": "Messages",
+ "8": "Phone",
+ "9": "Search",
+ "10": "Tasks",
+ "11": "Browser",
+ "http://": "Browser",
+ "12": "Java",
};
-function isFilter(field) {
- return field && field.operator !== undefined && field.operator !== null;
-}
+module.exports = {
+ invoke: function (opts) {
+ var app = name[opts.appType];
+ if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
+ app = "Browser";
+ }
-function extractValue(item, field) {
- return field.split(".").reduce(function (value, prop) {
- return value[prop];
- }, item);
-}
+ notifications.openNotification(type,
+ "Requested to launch: " + app + " application.");
+ return {code: 1};
+ }
+};
-function copy(items) {
- //use a reduce to ensure that we always just return an array
- //not the most performant but will whitewash the result
- return utils.reduce(items, function (array, item) {
- array.push(item);
- return array;
- }, []);
-}
+});
+define('ripple/platform/webworks.handset/2.0.0/server/contact', function (require, exports, module) {
+/*
+ * Copyright 2011 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 select = require('ripple/platform/webworks.core/2.0.0/select'),
+ db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _KEY = "blackberry-pim-contacts",
+ _self;
-_select = {
- ops: {
- find: {
- 0: "!=",
- 1: "==",
- 2: "<",
- 3: "<=",
- 4: ">",
- 5: ">=",
- 8: "REGEX",
- 16: "AND",
- 32: "OR",
- 64: "CONTAINS"
- },
- phone: {
- 0: "!=",
- 1: "==",
- 2: "<",
- 3: "<=",
- 4: ">",
- 5: ">=",
- 8: "AND",
- 16: "OR",
- 32: "CONTAINS"
- }
- },
- from: function (items) {
- var _getPredicate = function (filter, operators) {
+function _defaultContacts() {
+ var id1 = Math.uuid(null, 16),
+ id2 = Math.uuid(null, 16),
+ id3 = Math.uuid(null, 16),
+ id4 = Math.uuid(null, 16),
+ contacts = {};
+
+ contacts[id1] = {
+ uuid: id1,
+ firstName: "Leonardo",
+ homePhone: "4567892345",
+ email1: "leo@underground.com"
+ };
+ contacts[id2] = {
+ uuid: id2,
+ firstName: "Raphael",
+ homePhone: "4563457890",
+ email1: "raph@underground.com"
+ };
+ contacts[id3] = {
+ uuid: id3,
+ firstName: "Michelangelo",
+ homePhone: "4563453425",
+ email1: "mike@underground.com"
+ };
+ contacts[id4] = {
+ uuid: id4,
+ firstName: "Donatello",
+ homePhone: "4563453425",
+ email1: "don@undergound.com"
+ };
- var noOp = function () {
- return false;
- },
- operator = (function () {
- var result = operators[filter.operator] || filter.operator,
- exists = function (op) {
- return result === op;
- };
+ return contacts;
+}
- return utils.some(operators, exists) ? result : "";
- }());
+function _get() {
+ return db.retrieveObject(_KEY) || _defaultContacts();
+}
- return function (item) {
- var left = extractValue(item, filter.leftField),
- right = filter.rightField,
- predicate = _predicates[operator] || noOp;
+function _save(contacts) {
+ db.saveObject(_KEY, contacts);
+}
- return filter.negate ? !predicate(left, right) : predicate(left, right);
- };
+_self = {
+ save: function (get, post) {
+ var contacts = _get();
- },
- _applyFilter = function (filter, operators) {
- var result = [],
- left,
- right,
- op;
+ contacts[post.contact.uid] = post.contact;
+ _save(contacts);
+ return {code: 1};
+ },
+ remove: function (get, post) {
+ var contacts = _get(),
+ id = get.id;
- if (isFilter(filter.leftField) && isFilter(filter.rightField)) {
+ delete contacts[id];
+ _save(contacts);
+ return {code: 1};
+ },
+ find: function (get, post) {
+ var contacts = _get(),
+ match = select.from(contacts);
- left = _select.from(items).where(filter.leftField);
- right = _select.from(items).where(filter.rightField);
- op = operators[filter.operator] || filter.operator;
+ if (post.orderBy) {
+ match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
+ }
- switch (op) {
- case "AND":
- result = left.filter(function (item) {
- return right.indexOf(item) >= 0;
- });
- break;
- case "OR":
- result = left.concat(right.filter(function (item) {
- return left.indexOf(item) < 0;
- }));
- break;
- }
+ if (post.maxReturn) {
+ match.max(post.maxReturn);
+ }
- if (filter.negate) {
- //reverse the result set.
- result = utils.filter(items, function (item) {
- return result.indexOf(item) < 0;
- });
- }
- }
- else {
- result = utils.filter(items, _getPredicate(filter, operators));
- }
+ return {code: 1, data: match.where(post.fieldFilter)};
+ }
+};
- return result;
- },
- _orderBy,
- _max,
- _direction,
- _self = {
- orderBy: function (prop, dir) {
- _orderBy = prop;
- _direction = dir || "asc";
- return _self;
- },
- max: function (max) {
- _max = max;
- return _self;
- },
- where: function (filter, ops) {
- var result = isFilter(filter) ? _applyFilter(filter, ops || _select.ops.find) : copy(items);
+module.exports = _self;
- result.sort(function (a, b) {
- if (a[_orderBy] < b[_orderBy]) {
- return _direction === "asc" ? -1 : 1;
- }
- else if (a[_orderBy] > b[_orderBy]) {
- return _direction === "asc" ? 1: -1;
- }
- return 0;
- });
+});
+define('ripple/platform/webworks.handset/2.0.0/server/systemEvent', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ _onCoverageChange,
+ _onHardwareKey = {};
- return result.slice(0, _max === null || _max === -1 ? undefined : _max); // slice in V8 returns empty array if null
- }
- };
+event.on("CoverageChange", function () {
+ var baton = _onCoverageChange;
+ _onCoverageChange = null;
+ return baton && baton.pass({code: 1});
+});
- return _self;
+event.on("HardwareKey", function (key) {
+ var baton = _onHardwareKey["key_" + key];
+ delete _onHardwareKey["key_" + key];
+
+ if (baton) {
+ baton.pass({code: 1});
}
-};
+ else {
+ event.trigger("HardwareKeyDefault", [key]);
+ }
+});
-module.exports = _select;
+module.exports = {
+ onCoverageChange: function (args, post, baton) {
+ baton.take();
+ _onCoverageChange = baton;
+ },
+
+ onHardwareKey: function (args, post, baton) {
+ baton.take();
+ _onHardwareKey["key_" + args.key] = baton;
+ }
+};
});
-define('ripple/platform/webworks.core/2.0.0/server/dialog', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/push', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var event = require('ripple/event'),
- devices = require('ripple/devices'),
- ui = require('ripple/ui'),
utils = require('ripple/utils'),
- isDialogVisible = false,
- visibleDialogArgs,
+ _handlers = {},
_self;
-function closeDialog() {
- var buttonsDiv = document.getElementById("dialog-buttons"),
- messageDiv = document.getElementById("dialog-message");
-
- ui.hideOverlay("dialog-window", function (dialog) {
- buttonsDiv.innerHTML = "";
- messageDiv.innerHTML = "";
- isDialogVisible = false;
+function listenersChanged() {
+ var ports = utils.map(_handlers, function (handler) {
+ return handler.port;
});
+ event.trigger("PushListenersChanged", [ports]);
}
-event.on("LayoutChanged", function () {
- if (isDialogVisible) {
- closeDialog();
- //Used to resize dialog on orientation change
- _self.ask(visibleDialogArgs);
- }
+event.on("Push", function (data, port) {
+ var handler = _handlers["port_" + port];
+ delete _handlers["port_" + port];
+ window.setTimeout(function () {
+ if (!_handlers["port_" + port]) {
+ //doesn't look like they are coming back ;)
+ listenersChanged();
+ }
+ }, 100);
+ return handler && handler.baton.pass({code: 1, data: data});
});
_self = {
- ask: function (args, post, baton) {
- if (!args) {
- throw ("No arguments provided");
- } else if (!args.buttons || !args.message) {
- throw ("Invalid arguments");
+ onPush: function (args, post, baton) {
+ if (!args.port) {
+ throw "no port specified";
+ }
+ else if (typeof args.port !== 'number') {
+ throw "port is not a number";
}
baton.take();
- visibleDialogArgs = args;
-
- ui.showOverlay("dialog-window", function (dialog) {
- var container = document.getElementById("viewport-container"),
- height = window.getComputedStyle(container, null).getPropertyValue("height"),
- width = window.getComputedStyle(container, null).getPropertyValue("width"),
- sizeDiv = document.getElementById("dialog-wrapper"),
- positionDiv = document.getElementById("dialog-window"),
- titleDiv = document.getElementById("dialog-title"),
- buttonsDiv = document.getElementById("dialog-buttons"),
- messageDiv = document.getElementById("dialog-message"),
- position, size;
+ _handlers["port_" + args.port] = {
+ port: args.port,
+ baton: baton
+ };
+ listenersChanged();
+ }
+};
- if (!messageDiv || !buttonsDiv) {
- return;
- }
+module.exports = _self;
- dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");
+});
+define('ripple/platform/webworks.handset/2.0.0/server/memo', function (require, exports, module) {
+/*
+ * Copyright 2011 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 db = require('ripple/db'),
+ select = require('ripple/platform/webworks.core/2.0.0/select'),
+ _self;
- position = "overlay-dialog";
- size = "overlay-dialog-wrapper";
+function _get() {
+ return db.retrieveObject("webworks-pim-memo-list") || {};
+}
- if (args.settings && args.settings.position) {
- position += " overlay-dialog-" + args.settings.position;
- }
+function _do(func) {
+ var memos = _get();
+ func(memos);
+ db.saveObject("webworks-pim-memo-list", memos);
+}
- if (args.settings && args.settings.size) {
- size += " overlay-dialog-wrapper-" + args.settings.size;
+_self = {
+ find: function (get, post) {
+ var memos = select.from(_get())
+ .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
+ .max(post.maxReturn)
+ .where(post.filter);
+ return {code: 1, data: memos};
+ },
+ remove: function (get, post) {
+ _do(function (memos) {
+ if (!memos[get.uid]) {
+ throw "attempting to delete a non existant memo with uid: " + get.uid;
}
-
- positionDiv.setAttribute("class", position);
- sizeDiv.setAttribute("class", size);
-
- titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
- messageDiv.innerHTML = args.message;
- isDialogVisible = true;
-
- args.buttons.forEach(function (button) {
- var buttonElement = utils.createElement("input", {
- "type": "button",
- "value": button
- });
- buttonElement.addEventListener("click", function () {
- var buttonIndex = args.buttons.indexOf(button);
- closeDialog();
- baton.pass({code: 1, data: buttonIndex});
- });
- buttonsDiv.appendChild(buttonElement);
- });
- }, true);
+ delete memos[get.uid];
+ });
+ return {code: 1};
+ },
+ save: function (get, post) {
+ _do(function (memos) {
+ memos[post.memo.uid] = post.memo;
+ });
+ return {code: 1};
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/server/io/dir', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/appEvent', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var cache = require('ripple/platform/webworks.core/2.0.0/fsCache');
+var event = require('ripple/event'),
+ notifications = require('ripple/notifications'),
+ _bg,
+ _fg,
+ _exit;
-function _packet(data) {
- return {
- code: 1,
- data: data
- };
-}
+event.on("AppRequestBackground", function () {
+ var baton = _bg;
+ _bg = null;
+ return baton && baton.pass({code: 1});
+});
+
+event.on("AppRequestForeground", function () {
+ var baton = _fg;
+ _fg = null;
+ return baton && baton.pass({code: 1});
+});
+
+event.on("AppExit", function () {
+ var baton = _exit;
+ _exit = null;
+ notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
+ return baton && baton.pass({code: 1});
+});
module.exports = {
- createNewDir: function (get, post, baton) {
- cache.dir.createNewDir(post.path);
- return _packet();
- },
- deleteDirectory: function (get, post, baton) {
- cache.dir.deleteDirectory(post.path, post.recursive);
- return _packet();
- },
- exists: function (get, post, baton) {
- return _packet(cache.dir.exists(post.path));
- },
- getParentDirectory: function (get, post, baton) {
- return _packet(cache.dir.getParentDirectory(post.path));
- },
- listDirectories: function (get, post, baton) {
- return _packet(cache.dir.listDirectories(post.path));
+ onBackground: function (get, post, baton) {
+ baton.take();
+ _bg = baton;
+ return {code: 1};
},
- listFiles: function (get, post, baton) {
- return _packet(cache.dir.listFiles(post.path));
+
+ onForeground: function (get, post, baton) {
+ baton.take();
+ _fg = baton;
+ return {code: 1};
},
- rename: function (get, post, baton) {
- cache.dir.rename(post.path, post.newName);
- return _packet();
+
+ onExit: function (get, post, baton) {
+ baton.take();
+ _exit = baton;
+ return {code: 1};
}
};
});
-define('ripple/platform/webworks.core/2.0.0/server/io/file', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/appointment', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
- constants = require('ripple/constants'),
- notifications = require('ripple/notifications');
+var db = require('ripple/db'),
+ select = require('ripple/platform/webworks.core/2.0.0/select'),
+ _self;
-function _packet(data) {
- return {
- code: 1,
- data: data
- };
+function _get() {
+ return db.retrieveObject("webworks-pim-appointment-list") || {};
}
-module.exports = {
- copy: function (get, post, baton) {
- cache.file.copy(post.from, post.to);
- return _packet();
- },
- deleteFile: function (get, post, baton) {
- cache.file.deleteFile(post.path);
- return _packet();
- },
- exists: function (get, post, baton) {
- return _packet(cache.file.exists(post.path));
- },
- getFileProperties: function (get, post, baton) {
- return _packet(cache.file.getFileProperties(post.path));
- },
- open: function (get, post, baton) {
- var msg = "Attempting to open file: " + post.path;
- notifications.openNotification("normal", msg);
- return _packet(cache.file.exists(post.path));
- },
- readFile: function (get, post, baton) {
- var val;
+function _do(func) {
+ var appointments = _get();
+ func(appointments);
+ db.saveObject("webworks-pim-appointment-list", appointments);
+}
- if (post.async) {
- baton.take();
- }
+_self = {
+ find: function (get, post) {
+ var appointments = _get(),
+ data = select.from(appointments)
+ .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
+ .max(post.maxReturn)
+ .where(post.filter);
- cache.file.readFile(post.path, function (data) {
- if (post.async) {
- baton.pass(_packet({
- fullPath: post.path,
- blobData: data
- }));
- } else {
- val = data;
+ return {code: 1, data: data};
+ },
+
+ remove: function (get) {
+ _do(function (appointments) {
+ if (!appointments[get.uid]) {
+ throw "attempting to delete a non existant appointment with uid: " + get.uid;
}
- }, post.async);
+ delete appointments[get.uid];
+ });
- if (!post.async) {
- return _packet({
- fullPath: post.path,
- blobData: val
- });
- }
- },
- rename: function (get, post, baton) {
- cache.file.rename(post.path, post.newName);
- return _packet();
+ return {code: 1};
},
- saveFile: function (get, post, baton) {
- cache.file.saveFile(post.path, post.blob);
- return _packet();
+
+ save: function (get, post) {
+ _do(function (appointments) {
+ appointments[post.appointment.uid] = post.appointment;
+ });
+
+ return {code: 1};
}
};
+module.exports = _self;
+
});
-define('ripple/platform/webworks.core/2.0.0/server/system', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/sms', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var deviceSettings = require('ripple/deviceSettings'),
- devices = require('ripple/devices'),
- app = require('ripple/app'),
- client = require('ripple/platform/webworks.core/2.0.0/client/system'),
- utils = require('ripple/utils'),
+var _listener,
+ _isListening = false,
notifications = require('ripple/notifications'),
constants = require('ripple/constants'),
- platform = require('ripple/platform'),
+ event = require('ripple/event'),
+ _console = require('ripple/console'),
+ _onReceive,
_self;
-function _is(feature) {
- return {
- allowedFor: function (location) {
- return feature && feature.URIs.some(function (uri) {
- return uri.value === location ||
- (location.indexOf(uri.value) >= 0 && uri.subdomains);
- });
- }
- };
-}
+event.on("MessageReceived", function (message) {
+ if (!_isListening || message.type !== 'sms') {
+ return;
+ }
+
+ var baton = _onReceive;
+ _onReceive = null;
+ _isListening = false;
+ return baton && baton.pass({code: 1, data: message});
+});
_self = {
- hasCapability: function (args) {
- var capabilities = devices.getCurrentDevice().capabilities;
- return {
- code: 1,
- data: capabilities ? capabilities.some(function (type) {
- return type === args.capability;
- }) : false
- };
- },
- isMassStorageActive: function () {
- return {code: 1, data: deviceSettings.retrieveAsBoolean("system.isMassStorageActive")};
- },
- hasDataCoverage: function () {
- return {code: 1, data: deviceSettings.retrieveAsBoolean("system.hasDataCoverage")};
- },
- softwareVersion: function () {
- return {code: 1, data: devices.getCurrentDevice().osVersion};
- },
- model: function () {
- return {code: 1, data: devices.getCurrentDevice().model};
- },
- scriptApiVersion: function () {
- return {code: 1, data: platform.current().version};
+ onReceive: function (args, post, baton) {
+ baton.take();
+ _onReceive = baton;
+ _isListening = !!_onReceive;
},
- setHomeScreenBackground: function (args) {
- var path = args.filePath,
- msg = "Set home screen background to " + path + ".";
+
+ send: function (args) {
+ var msg = "To " + args.address + ": " + args.message;
notifications.openNotification("normal", msg);
+ _console.log(msg);
return {code: 1};
},
- hasPermission: function (args) {
- var info = app.getInfo(),
- feature = info.features ? info.features[args.desiredModule] : null;
- return {code: 1, data: feature === null || _is(feature).allowedFor(utils.location().href) ? client.ALLOW : client.DENY};
- },
- network: function () {
- return {code: 1, data: deviceSettings.retrieve("system.network")};
+ isListeningForMessage: function (get, post, baton) {
+ if (get && typeof get.isListeningForMessage === "boolean") {
+ _isListening = get.isListeningForMessage;
+ }
+
+ return {code: 1, data: _isListening};
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.core/2.0.0/spec/config', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/phone', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils');
+var PhoneCall = require('ripple/platform/webworks.handset/2.0.0/client/PhoneCall'),
+ PhoneLogs = require('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs'),
+ CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
+ select = require('ripple/platform/webworks.core/2.0.0/select'),
+ event = require('ripple/event'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ _KEY = "blackberry-phone-logs",
+ _onPhoneEventListeners = {},
+ _activeCalls = {},
+ _onCallLogAdded,
+ _onCallLogRemoved,
+ _onCallLogUpdated,
+ _onCallLogReset,
+ _self;
-module.exports = {
- fileName: "config.xml",
- validateVersion: function (config) {
- return true;
- },
- extractInfo: function (config) {
- if (!config) {
- return null;
- }
+function _defaultLogs() {
+ var n1 = new CallLog(),
+ n2 = new CallLog(),
+ m1 = new CallLog(),
+ m2 = new CallLog();
- var widgetInfo = {},
- widgetFeatures = config.widget.children.feature.validationResult,
- accessUrls = config.widget.children.access.validationResult,
- accessFeatures = config.widget.children.access.children.feature.validationResult,
- toFeature = function (validationResult) {
- return {
- id: validationResult.attributes.id.value,
- required: !validationResult.attributes.required || validationResult.attributes.required.value,
- URIs: []
- };
- };
+ n1.number = "12344567";
+ n1.name = "larry";
+ n1.type = CallLog.TYPE_PLACED_CALL;
+ n1.status = CallLog.STATUS_NORMAL;
- widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
- widgetInfo.name = config.widget.children.name.validationResult[0].value;
- widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
- widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
- widgetInfo.author = config.widget.children.author.validationResult[0].value;
- widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
- widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
- widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
- widgetInfo.description = config.widget.children.description.validationResult[0].value;
- if (config.widget.children.license.validationResult[0]) {
- widgetInfo.license = config.widget.children.license.validationResult[0].value;
- widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
- }
+ n2.number = "14567890";
+ n2.name = "curly";
+ n2.type = CallLog.TYPE_RECEIVED_CALL;
+ n2.status = CallLog.STATUS_NORMAL;
- widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
- if (validationResult.valid) {
- var feature = toFeature(validationResult);
- feature.URIs.push({
- value: utils.location().href,
- subdomains: true
- });
- features = features || {};
- features[feature.id] = feature;
- }
- return features;
- }, {});
+ m1.number = "17659800";
+ m1.name = "moe";
+ m1.type = CallLog.TYPE_MISSED_CALL_UNOPENED;
+ m1.status = CallLog.STATUS_NORMAL;
- widgetInfo.features = accessUrls.map(function (access) {
- return {
- uri: access.attributes.uri.value,
- subdomains: access.attributes.subdomains.value,
- features: accessFeatures ? accessFeatures.filter(function (f) {
- return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
- }) : null
- };
- }).reduce(function (result, access) {
- return access.features ? access.features.reduce(function (features, validationResult) {
- var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
- feature.URIs.push({
- value: access.uri,
- subdomains: access.subdomains
- });
- features[feature.id] = feature;
- return features;
- }, result) : result;
- }, widgetInfo.features);
+ m2.number = "14567896";
+ m2.name = "snarf";
+ m2.type = CallLog.TYPE_MISSED_CALL_OPENED;
+ m2.status = CallLog.STATUS_NORMAL;
- return widgetInfo;
- },
- schema: {
- rootElement: "widget",
- widget: {
- nodeName: "widget",
- required: true,
- occurrence: 1,
- attributes: {
- xmlns: {
- attributeName: "xmlns",
- required: true,
- type: "list",
- listValues: ["http://www.w3.org/ns/widgets"]
- },
- "xmlns:rim": {
- attributeName: "xmlns:rim",
- required: true,
- type: "list",
- listValues: ["http://www.blackberry.com/ns/widgets"]
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- id: {
- attributeName: "id",
- required: false,
- type: "string"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- },
- "rim:header": {
- attributeName: "rim:header",
- required: false,
- type: "string"
- },
- "rim:backButton": {
- attributeName: "rim:backButton",
- required: false,
- type: "string"
- }
- },
- children: {
- name: {
- nodeName: "name",
- required: true,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- description: {
- nodeName: "description",
- required: false,
- occurrence: 1,
- attributes: {
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- icon: {
- nodeName: "icon",
- required: false,
- occurrence: 0,
- attributes: {
- src: {
- attributeName: "src",
- type: "string",
- required: true
- },
- "rim:hover": {
- attributeName: "rim:hover",
- type: "boolean",
- required: false
- }
- }
- },
- author: {
- nodeName: "author",
- required: false,
- occurrence: 1,
- attributes: {
- href: {
- attributeName: "href",
- type: "string",
- required: false
- },
- "rim:copyright": {
- attributeName: "rim:copyright",
- type: "string",
- required: false
- },
- email: {
- attributeName: "email",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- license: {
- nodeName: "license",
- required: false,
- occurrence: 1,
- attributes : {
- href: {
- attributeName: "href",
- type: "string",
- required: false
- },
- "xml:lang": {
- attributeName: "xml:lang",
- required: false,
- type: "iso-language"
- },
- "its:dir": {
- attributeName: "its:dir",
- required: false,
- type: "list",
- listValues: ["rtl", "ltr", "lro", "rlo"]
- }
- }
- },
- "rim:cache": {
- nodeName: "rim:cache",
- required: false,
- occurrence: 1,
- attributes: {
- disableAllCache: {
- attributeName: "disableAllCache",
- required: false,
- type: "boolean"
- },
- aggressiveCacheAge: {
- attributeName: "aggressiveCacheAge",
- required: false,
- type: "number"
- },
- maxCacheSizeTotal: {
- attributeName: "maxCacheSizeTotal",
- required: false,
- type: "number"
- },
- maxCacheSizeItem: {
- attributeName: "maxCacheSizeItem",
- required: false,
- type: "number"
- }
- }
- },
- access: {
- nodeName: "access",
- required: false,
- occurrence: 0,
- attributes: {
- uri: {
- attributeName: "uri",
- required: true,
- type: "string"
- },
- subdomains: {
- attributeName: "subdomains",
- required: false,
- type: "boolean"
- }
- },
- children: {
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- //TODO: this should be a list
- type: "string"
- },
- required: {
- attributeName: "required",
- required: false,
- type: "boolean"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- }
- }
- }
- }
- },
- feature: {
- nodeName: "feature",
- required: false,
- occurrence: 0,
- attributes: {
- id: {
- attributeName: "id",
- required: true,
- //TODO: this should be a list
- type: "string"
- },
- required: {
- attributeName: "required",
- required: false,
- type: "boolean"
- },
- version: {
- attributeName: "version",
- required: false,
- type: "string"
- }
- }
- },
- "rim:loadingScreen": {
- nodeName: "rim:loadingScreen",
- required: false,
- occurrence: 1,
- attributes: {
- backgroundColor: {
- attributeName: "backgroundColor",
- required: false,
- type: "string"
- },
- backgroundImage: {
- attributeName: "backgroundImage",
- required: false,
- type: "string"
- },
- foregroundImage: {
- attributeName: "foregroundImage",
- required: false,
- type: "string"
- },
- onRemotePageLoad: {
- attributeName: "onRemotePageLoad",
- required: false,
- type: "boolean"
- },
- onLocalPageLoad: {
- attributeName: "onLocalPageLoad",
- required : false,
- type: "boolean"
- },
- onFirstLaunch: {
- attributeName: "onFirstLaunch",
- required: false,
- type: "boolean"
- }
- },
- children: {
- "rim:transitionEffect": {
- nodeName: "rim:transitionEffect",
- required: false,
- occurrence: 1,
- attributes: {
- "type": {
- attributeName: "type",
- required: true,
- type: "list",
- listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
- },
- duration: {
- attributeName: "duration",
- required: false,
- type: "number"
- },
- direction: {
- attributeName: "direction",
- required: false,
- type: "list",
- listValues: ["left", "right", "up", "down"]
- }
- }
- }
- }
- },
- "rim:connection": {
- nodeName: "rim:connection",
- required: false,
- occurrence: 1,
- attributes: {
- timeout: {
- attributeName: "timeout",
- required: false,
- type: "number"
- }
- },
- children: {
- id: {
- nodeName: "id",
- required: false,
- occurrence: 0
- }
- }
- },
- "rim:navigation": {
- nodeName: "rim:navigation",
- required: false,
- occurrence: 1,
- attributes: {
- mode: {
- attributeName: "mode",
- required: false,
- type: "list",
- listValues: ["focus"]
- }
- }
- },
- "content": {
- nodeName: "content",
- required: true,
- occurrence: 1,
- attributes: {
- src: {
- attributeName: "src",
- required: true,
- type: "string"
- },
- type: {
- attributeName: "type",
- required: false,
- type: "string"
- },
- charset: {
- attributeName: "charset",
- required: false,
- type: "string"
- }
- }
- }
+ return {
+ normal: [n1, n2],
+ missed: [m1, m2]
+ };
+}
+
+function _getLogs(folderID) {
+ var logs = db.retrieveObject(_KEY) || _defaultLogs();
+ return folderID === undefined || folderID === null ?
+ logs : logs[folderID !== PhoneLogs.FOLDER_NORMAL_CALLS ? "missed" : "normal"];
+}
+
+function _saveLogs(logs) {
+ db.saveObject(_KEY, logs);
+}
+
+function _isMissedCall(log) {
+ return (log.type === CallLog.TYPE_MISSED_CALL_UNOPENED ||
+ log.type === CallLog.TYPE_MISSED_CALL_OPENED) ? true : false;
+}
+
+function _isNormalCall(log) {
+ return (log.type === CallLog.TYPE_RECEIVED_CALL ||
+ log.type === CallLog.TYPE_PLACED_CALL) ? true : false;
+}
+
+event.on("PhoneEvent", function (type, callId, error) {
+ var baton = _onPhoneEventListeners[type];
+ delete _onPhoneEventListeners[type];
+
+ return baton && baton.pass({code: 1, data: {callId: callId, error: error}});
+});
+
+event.on("PhoneCallLogAdded", function (log) {
+ var logs = _getLogs(),
+ baton = _onCallLogAdded;
+
+ logs[_isMissedCall(log) ? "missed" : "normal"].push(log);
+ _saveLogs(logs);
+
+ _onCallLogAdded = null;
+ return baton && baton.pass({code: 1, data: {log: log}});
+});
+
+event.on("PhoneCallLogRemoved", function (log) {
+ // TODO: make this be the only one responsible for deletion (instead of triggering internally)
+ var baton = _onCallLogRemoved;
+ _onCallLogRemoved = null;
+ return baton && baton.pass({code: 1, data: {log: log}});
+});
+
+event.on("PhoneCallLogUpdated", function (newLog, oldLog) {
+ // TODO: implement way to update with just this event
+ var baton = _onCallLogUpdated;
+ _onCallLogUpdated = null;
+ return baton && baton.pass({code: 1, data: {
+ newLog: newLog,
+ oldLog: oldLog
+ }});
+});
+
+event.on("PhoneCallLogReset", function () {
+ _saveLogs(_defaultLogs());
+ var baton = _onCallLogReset;
+ _onCallLogReset = null;
+ return baton && baton.pass({code: 1});
+});
+
+event.on("PhoneCallInitiated", function (call) {
+ _activeCalls[call.id] = call;
+});
+
+event.on("PhoneCallEnded", function (call) {
+ delete _activeCalls[call.id];
+});
+
+_self = {
+ logs: {
+ onCallLogAdded: function (get, post, baton) {
+ baton.take();
+ _onCallLogAdded = baton;
+ },
+
+ onCallLogRemoved: function (get, post, baton) {
+ baton.take();
+ _onCallLogRemoved = baton;
+ },
+
+ onCallLogUpdated: function (get, post, baton) {
+ baton.take();
+ _onCallLogUpdated = baton;
+ },
+
+ onCallLogReset: function (get, post, baton) {
+ baton.take();
+ _onCallLogReset = baton;
+ },
+
+ callAt: function (get) {
+ var logs = _getLogs(get.folderID !== null && get.folderID !== undefined ?
+ get.folderID : PhoneLogs.FOLDER_MISSED_CALLS);
+ return {code: 1, data: logs.length > get.index ? logs[get.index] : null};
+ },
+
+ deleteCallAt: function (get) {
+ var logs = _getLogs(),
+ subLog = _getLogs(get.folderID),
+ deleted = false,
+ type, log;
+
+ if (subLog.length > get.index &&
+ (type = _isNormalCall(subLog[get.index]) ? "normal" : "missed") &&
+ (log = logs[type].splice(get.index, 1))) {
+ event.trigger("PhoneCallLogRemoved", [log]);
+ _saveLogs(logs);
+ deleted = true;
}
+
+ return {code: 1, data: deleted};
+ },
+
+ find: function (get, post) {
+ var data = select.from(_getLogs(post.folderID !== null && post.folderID !== undefined ?
+ post.folderID : PhoneLogs.FOLDER_MISSED_CALLS))
+ .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
+ .max(post.maxReturn)
+ .where(post.filter, select.ops.phone);
+ return {code: 1, data: data};
+ },
+
+ numberOfCalls: function (get) {
+ return {code: 1, data: _getLogs(get.folderID !== null && get.folderID !== undefined ?
+ get.folderID : PhoneLogs.FOLDER_MISSED_CALLS).length};
}
+ },
+
+ onPhoneEvent: function (get, post, baton) {
+ baton.take();
+ _onPhoneEventListeners[get.eventType] = baton;
+ },
+
+ activeCalls: function () {
+ var data = utils.map(_activeCalls, function (callItem) {
+ var call = new PhoneCall(callItem.onhold);
+ call.outgoing = callItem.outgoing;
+ call.recipientName = callItem.recipient.name;
+ call.recipientNumber = callItem.recipient.number;
+ return call;
+ });
+ return {code: 1, data: data};
+ },
+
+ inActiveCall: function () {
+ return {code: 1, data: utils.count(_activeCalls) > 0 ? true : false};
}
};
+module.exports = _self;
+
});
-define('ripple/platform/webworks.core/2.0.0/spec/events', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/message', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ select = require('ripple/platform/webworks.core/2.0.0/select'),
+ Message = require('ripple/platform/webworks.handset/2.0.0/client/Message'),
+ _self;
-module.exports = {
- "app.event.onBackground": {
- callback: function () {
- event.trigger("AppRequestBackground");
- }
+function _get() {
+ return db.retrieveObject("webworks-message-list") || {};
+}
+
+function _do(func) {
+ var messages = _get();
+ func(messages);
+ db.saveObject("webworks-message-list", messages);
+}
+
+_self = {
+ find: function (get, post) {
+ var data = select
+ .from(_get())
+ .max(post.maxReturn)
+ .where(post.filter);
+ return {code: 1, data: data};
},
- "app.event.onForeground": {
- callback: function () {
- event.trigger("AppRequestForeground");
- }
+
+ remove: function (get, post) {
+ _do(function (messages) {
+ if (!messages[get.uid]) {
+ throw "attempting to delete a non existant message with uid: " + get.uid;
+ }
+ delete messages[get.uid];
+ });
+ return {code: 1};
+ },
+
+ save: function (get, post) {
+ _do(function (messages) {
+ var orig = messages[post.message.uid],
+ updated = utils.copy(post.message);
+
+ updated.folder = orig ? orig.folder : Message.FOLDER_DRAFT;
+ updated.status = orig ? orig.status : Message.STATUS_DRAFT;
+
+ messages[post.message.uid] = updated;
+ });
+ return {code: 1};
+ },
+
+ send: function (get, post) {
+ _do(function (messages) {
+ var updated = utils.copy(get.message);
+
+ updated.folder = Message.FOLDER_SENT;
+ updated.status = Message.STATUS_SENT;
+
+ messages[updated.uid] = updated;
+ });
+ return {code: 1};
}
};
+module.exports = _self;
+
});
-define('ripple/platform/webworks.handset/2.0.0/XMLHttpRequest', function (require, exports, module) {
+define('ripple/platform/webworks.handset/2.0.0/server/Task', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var select = require('ripple/platform/webworks.core/2.0.0/select'),
+ db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _KEY = "blackberry-pim-task",
+ _self;
-var xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
-module.exports = xhr.create("ripple/platform/webworks.handset/2.0.0/server");
+function _get() {
+ return db.retrieveObject(_KEY) || {};
+}
+
+function _save(tasks) {
+ db.saveObject(_KEY, tasks);
+}
+
+_self = {
+ save: function (get, post) {
+ var tasks = _get(),
+ properties = post.task,
+ id = properties.uid;
+
+ if (tasks[id]) {
+ utils.mixin(properties, tasks[id]);
+ } else {
+ tasks[id] = properties;
+ }
+
+ _save(tasks);
+
+ return {code: 1};
+ },
+
+ remove: function (get, post) {
+ var tasks = _get(),
+ id = get.id;
+
+ delete tasks[id];
+
+ _save(tasks);
+
+ return {code: 1};
+ },
+
+ find: function (get, post) {
+ var tasks = _get(),
+ match = select.from(tasks);
+
+ if (post.orderBy) {
+ match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
+ }
+
+ if (post.maxReturn) {
+ match.max(post.maxReturn);
+ }
+
+ return {code: 1, data: match.where(post.filter)};
+ }
+};
+
+module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/client/Address', function (require, exports, module) {
+define('ripple/platform/web/default/spec', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function Address() {
- return {
- //readwrite property String address1
- //readwrite property String address2
- //readwrite property String city
- //readwrite property String country
- //readwrite property String stateProvince
- //readwrite property String zipPostal
- address1: null,
- address2: null,
- city: null,
- country: null,
- stateProvince: null,
- zipPostal: null
- };
-}
+module.exports = {
-module.exports = Address;
+ id: "web",
+ version: "default",
+ name: "Mobile Web",
+
+ ui: require('ripple/platform/web/default/spec/ui'),
+ device: {},
+
+ persistencePrefix: "tinyhippos-",
+
+ initialize: function () {},
+
+ objects: {
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ navigator: {
+ path: "w3c/1.0/navigator",
+ children: {
+ geolocation: {
+ path: "w3c/1.0/geolocation"
+ }
+ }
+ },
+ device: {
+ path: "web/default/device"
+ }
+ },
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/AddressBookArguments', function (require, exports, module) {
+define('ripple/platform/web/default/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.AddressBookArguments ( [contact : blackberry.pim.Contact ] )
-var _self = function (contact) {
- return {
- contact: contact,
- //readwrite property Number view
- view: 0
- };
-};
+window.addEventListener("load", function () {
+ var event = require('ripple/event');
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_NEW", function () {
- return 0;
-});
-//const Number VIEW_COMPOSE = 1
-_self.__defineGetter__("VIEW_COMPOSE", function () {
- return 1;
-});
-//const Number VIEW_DISPLAY = 2
-_self.__defineGetter__("VIEW_DISPLAY", function () {
- return 2;
+ event.on("HardwareKey", function (key) {
+ event.trigger("HardwareKeyDefault", [key]);
+ });
+
+ //HACK: Remove this guy from namespace since we are just hacking this in as a bootstrapper
+ delete window.device;
});
-module.exports = _self;
+});
+define('ripple/platform/web/default/spec/ui', function (require, exports, module) {
+module.exports = {
+ plugins: [
+ "accelerometer",
+ "geoView"
+ ]
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/Appointment', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/CameraAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- utils = require('ripple/utils'),
- _uri = "blackberry/pim/appointment/";
-
-function Appointment(service) {
- var _self = {
- allDay: false,
- attendees: [],
- end: null,
- freeBusy: null,
- location: null,
- note: null,
- recurrence: null,
- reminder: null,
- start: null,
- summary: null,
- uid: null,
- remove: function () {
- transport.call(_uri + "remove", {get: {uid: _self.uid}});
- },
- save: function () {
- if (_self.uid === null) {
- _self.uid = Number(Math.uuid(8, 10));
- }
- transport.call(_uri + "save", {post: {appointment: _self}});
- }
- };
-
- return _self;
-}
-
-function _massage(property, name) {
- if (name === "recurrence" && property) {
- if (property.end) {
- property.end = new Date(property.end);
- }
- }
- if (name === "reminder" && property) {
- if (property.date) {
- property.date = new Date(property.date);
- }
- }
- if ((name === "end" || name === "start") && property) {
- property = new Date(property);
- }
- return property;
-}
-
-Appointment.find = function (filter, orderBy, maxReturn, service, isAscending) {
- var opts = {
- post: {
- filter: filter,
- orderBy: orderBy,
- maxReturn: maxReturn,
- service: service,
- isAscending: isAscending
- }
+module.exports = function (supportsVideo, hasFlash, sensorPixels, maxZoomFactor) {
+ return {
+ supportsVideo: supportsVideo,
+ hasFlash: hasFlash,
+ sensorPixels: sensorPixels,
+ maxZoomFactor: maxZoomFactor
};
- return transport.call(_uri + "find", opts).map(function (obj) {
- var appt = new Appointment();
- appt.allDay = obj.allDay;
- appt.attendees = obj.attendees;
- appt.end = _massage(obj.end, "end");
- appt.freeBusy = obj.freeBusy;
- appt.location = obj.location;
- appt.note = obj.note;
- appt.recurrence = _massage(obj.recurrence, "recurrence");
- appt.reminder = _massage(obj.reminder, "reminder");
- appt.start = _massage(obj.start, "start");
- appt.summary = obj.summary;
- appt.uid = obj.uid;
- return appt;
- });
};
-Appointment.__defineGetter__("FREE", function () {
- return 0;
-});
-Appointment.__defineGetter__("TENTATIVE", function () {
- return 1;
-});
-Appointment.__defineGetter__("BUSY", function () {
- return 2;
});
-Appointment.__defineGetter__("OUT_OF_OFFICE", function () {
- return 3;
-});
-
-module.exports = Appointment;
+define('ripple/platform/phonegap/1.0.0/map', function (require, exports, module) {
+/*
+ * Copyright 2011 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 () {
+ throw "not implemented";
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/Attendee', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/NetworkAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function Attendee() {
+module.exports = function (info, id, activeConnections) {
return {
- //readwrite property String address
- //readwrite property Number type
-
- address: null,
- type: null
+ info: info,
+ id: id,
+ activeConnections: activeConnections || []
};
-}
-
-Attendee.__defineGetter__("ORGANIZER", function () {
- return 0;
-});
-
-Attendee.__defineGetter__("INVITED", function () {
- return 1;
-});
+};
-Attendee.__defineGetter__("ACCEPTED", function () {
- return 2;
});
+define('ripple/platform/phonegap/1.0.0/AVCodecsAttributes', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function (info, id, audioCodecs, videoCodecs) {
+ return {
+ info: info,
+ id: id,
+ audioCodecs: audioCodecs,
+ videoCodecs: videoCodecs
+ };
+};
-Attendee.__defineGetter__("DECLINED", function () {
- return 3;
});
+define('ripple/platform/phonegap/1.0.0/ContactField', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function (type, value, pref) {
+ return {
+ type: type,
+ value: value,
+ pref: pref || false
+ };
+};
-Attendee.__defineGetter__("TENTATIVE", function () {
- return 4;
});
-
-module.exports = Attendee;
+define('ripple/platform/phonegap/1.0.0/ContactAccount', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function (domain, username, userid) {
+ return {
+ domain: domain,
+ username: username,
+ userid: userid
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/NetworkStatus', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/audio/player/";
+module.exports = {
+ NOT_REACHABLE: 0,
+ REACHABLE_VIA_CARRIER_DATA_NETWORK: 1,
+ REACHABLE_VIA_WIFI_NETWORK: 2
+};
-function Player(locator, type, async) {
- //we can't use the async prop since we need the ID before we can do anything else.
- var _id = transport.call(_uri + "create", {
- get: {locator: locator, type: type},
- async: false
- }),
- _listener,
- _closed,
- _self,
- _poll = function (path) {
- transport.poll(_uri + path, {
- get: {id: _id}
- }, function (response) {
- if (_listener) {
- _listener(_self, response.event, response.eventData);
- }
+});
+define('ripple/platform/phonegap/1.0.0/spec', function (require, exports, module) {
+module.exports = {
+ id: "phonegap",
+ version: "1.0.0",
+ name: "PhoneGap",
+ type: "platform",
- return !!_listener;
- });
- };
+ persistencePrefix: "phonegap-",
- _self = {
- addPlayerListener: function (callback) {
- if (!_closed && callback) {
- _listener = callback;
- _poll("onStart");
- _poll("onStopped");
- _poll("onBufferingStarted");
- _poll("onBufferingStopped");
- _poll("onDurationUpdated");
- _poll("onEnd");
- _poll("onError");
- _poll("onVolumeChange");
- _poll("onClose");
- }
- else {
- _listener = null;
- }
+ config: require('ripple/platform/phonegap/1.0.0/spec/config'),
+ device: require('ripple/platform/phonegap/1.0.0/spec/device'),
+ ui: require('ripple/platform/phonegap/1.0.0/spec/ui'),
+ events: require('ripple/platform/phonegap/1.0.0/spec/events'),
- return !_closed;
- },
+ initialize: function () { },
- close: function () {
- _listener = null;
- _closed = true;
- return transport.call(_uri + "close", {get: {id: _id}});
+ objects: {
+ PhoneGap: {
+ path: "phonegap/1.0.0/PhoneGap"
},
-
- pause: function () {
- return transport.call(_uri + "pause", {get: {id: _id}});
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
},
-
- play: function () {
- return transport.call(_uri + "play", {get: {id: _id}});
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ Acceleration: {
+ path: "phonegap/1.0.0/Acceleration"
+ },
+ navigator: {
+ path: "phonegap/1.0.0/navigator",
+ children: {
+ accelerometer: {
+ path: "phonegap/1.0.0/accelerometer"
+ },
+ geolocation: {
+ path: "w3c/1.0/geolocation"
+ },
+ notification: {
+ path: "phonegap/1.0.0/notification"
+ },
+ contacts: {
+ path: "phonegap/1.0.0/contacts"
+ },
+ network: {
+ path: "phonegap/1.0.0/network"
+ },
+ camera: {
+ path: "phonegap/1.0.0/camera"
+ },
+ sms: {
+ path: "phonegap/1.0.0/sms"
+ },
+ telephony: {
+ path: "phonegap/1.0.0/telephony"
+ },
+ map: {
+ path: "phonegap/1.0.0/map"
+ },
+ orientation: {
+ path: "phonegap/1.0.0/orientation"
+ },
+ system: {
+ path: "phonegap/1.0.0/system"
+ },
+ compass: {
+ path: "phonegap/1.0.0/compass"
+ }
+ }
+ },
+ ContactError: {
+ path: "phonegap/1.0.0/ContactError"
+ },
+ Contact: {
+ path: "phonegap/1.0.0/Contact"
+ },
+ ContactName: {
+ path: "phonegap/1.0.0/ContactName"
+ },
+ ContactAccount: {
+ path: "phonegap/1.0.0/ContactAccount"
+ },
+ ContactAddress: {
+ path: "phonegap/1.0.0/ContactAddress"
+ },
+ ContactOrganization: {
+ path: "phonegap/1.0.0/ContactOrganization"
+ },
+ ContactFindOptions: {
+ path: "phonegap/1.0.0/ContactFindOptions"
+ },
+ ContactField: {
+ path: "phonegap/1.0.0/ContactField"
+ },
+ NetworkStatus: {
+ path: "phonegap/1.0.0/NetworkStatus"
+ },
+ device: {
+ path: "phonegap/1.0.0/device"
+ },
+ SystemInfoOptions: {
+ path: "phonegap/1.0.0/SystemInfoOptions"
+ },
+ PowerAttributes: {
+ path: "phonegap/1.0.0/PowerAttributes"
+ },
+ CPUAttributes: {
+ path: "phonegap/1.0.0/CPUAttributes"
+ },
+ ThermalAttributes: {
+ path: "phonegap/1.0.0/ThermalAttributes"
+ },
+ NetworkAttributes: {
+ path: "phonegap/1.0.0/NetworkAttributes"
+ },
+ Connection: {
+ path: "phonegap/1.0.0/Connection"
+ },
+ ConnectionAttributes: {
+ path: "phonegap/1.0.0/ConnectionAttributes"
+ },
+ SensorAttributes: {
+ path: "phonegap/1.0.0/SensorAttributes"
+ },
+ AVCodecsAttributes: {
+ path: "phonegap/1.0.0/AVCodecsAttributes"
+ },
+ AudioCodecAttributes: {
+ path: "phonegap/1.0.0/AudioCodecAttributes"
+ },
+ VideoCodecAttributes: {
+ path: "phonegap/1.0.0/VideoCodecAttributes"
+ },
+ StorageUnitAttributes: {
+ path: "phonegap/1.0.0/StorageUnitAttributes"
+ },
+ InputDevicesAttributes: {
+ path: "phonegap/1.0.0/InputDevicesAttributes"
+ },
+ OutputDevicesAttributes: {
+ path: "phonegap/1.0.0/OutputDevicesAttributes"
+ },
+ DisplayDeviceAttributes: {
+ path: "phonegap/1.0.0/DisplayDeviceAttributes"
+ },
+ AudioDeviceAttributes: {
+ path: "phonegap/1.0.0/AudioDeviceAttributes"
+ },
+ PrintingDeviceAttributes: {
+ path: "phonegap/1.0.0/PrintingDeviceAttributes"
+ },
+ BrailleDeviceAttributes: {
+ path: "phonegap/1.0.0/BrailleDeviceAttributes"
+ },
+ PointerAttributes: {
+ path: "phonegap/1.0.0/PointerAttributes"
+ },
+ KeyboardAttributes: {
+ path: "phonegap/1.0.0/KeyboardAttributes"
+ },
+ CameraAttributes: {
+ path: "phonegap/1.0.0/CameraAttributes"
+ },
+ MicrophoneAttributes: {
+ path: "phonegap/1.0.0/MicrophoneAttributes"
}
- };
-
- _self.__defineGetter__("duration", function () {
- return transport.call(_uri + "getDuration", {get: {id: _id}});
- });
-
- _self.__defineGetter__("mediaTime", function () {
- return transport.call(_uri + "getMediaTime", {get: {id: _id}});
- });
-
- _self.__defineSetter__("mediaTime", function (val) {
- transport.call(_uri + "setMediaTime", {get: {id: _id, value: val}});
- });
-
- _self.__defineGetter__("state", function () {
- return transport.call(_uri + "getState", {get: {id: _id}});
- });
-
- _self.__defineGetter__("volumeLevel", function () {
- return transport.call(_uri + "getVolumeLevel", {get: {id: _id}});
- });
-
- _self.__defineSetter__("volumeLevel", function (val) {
- transport.call(_uri + "setVolumeLevel", {get: {id: _id, value: val}});
- });
-
- _self.__defineGetter__("EVENT_BUFFERING_STARTED", function () {
- return "EVENT_BUFFERING_STARTED";
- });
- _self.__defineGetter__("EVENT_BUFFERING_STOPPED", function () {
- return "EVENT_BUFFERING_STOPPED";
- });
- _self.__defineGetter__("EVENT_CLOSED", function () {
- return "EVENT_CLOSED";
- });
- _self.__defineGetter__("EVENT_DEVICE_AVAILABLE", function () {
- return "EVENT_DEVICE_AVAILABLE";
- });
- _self.__defineGetter__("EVENT_DEVICE_UNAVAILABLE", function () {
- return "EVENT_DEVICE_UNAVAILABLE";
- });
- _self.__defineGetter__("EVENT_DURATION_UPDATED", function () {
- return "EVENT_DURATION_UPDATED";
- });
- _self.__defineGetter__("EVENT_END_OF_MEDIA", function () {
- return "EVENT_END_OF_MEDIA";
- });
- _self.__defineGetter__("EVENT_ERROR", function () {
- return "EVENT_ERROR";
- });
- _self.__defineGetter__("EVENT_RECORD_ERROR", function () {
- return "EVENT_ERROR";
- });
- _self.__defineGetter__("EVENT_RECORD_STARTED", function () {
- return "EVENT_RECORD_STARTED";
- });
- _self.__defineGetter__("EVENT_RECORD_STOPPED", function () {
- return "EVENT_RECORD_STOPPED";
- });
- _self.__defineGetter__("EVENT_SIZE_CHANGED", function () {
- return "EVENT_SIZE_CHANGED";
- });
- _self.__defineGetter__("EVENT_STARTED", function () {
- return "EVENT_STARTED";
- });
- _self.__defineGetter__("EVENT_STOPPED", function () {
- return "EVENT_STOPPED";
- });
- _self.__defineGetter__("EVENT_STOPPED_AT_TIME", function () {
- return "EVENT_STOPPED_AT_TIME";
- });
- _self.__defineGetter__("EVENT_VOLUME_CHANGED", function () {
- return "EVENT_VOLUME_CHANGED";
- });
-
- return _self;
-}
-
-Player.__defineGetter__("TIME_UNKNOWN", function () {
- return -1;
-});
-Player.__defineGetter__("CLOSED", function () {
- return 0;
-});
-Player.__defineGetter__("UNREALIZED", function () {
- return 100;
-});
-Player.__defineGetter__("REALIZED", function () {
- return 200;
-});
-Player.__defineGetter__("PREFETCHED", function () {
- return 300;
-});
-Player.__defineGetter__("STARTED", function () {
- return 400;
-});
+ }
-module.exports = Player;
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/BrowserArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ContactFindOptions', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.BrowserArguments ( url : String , [transport : blackberry.identity.Transport ] )
-module.exports = function (url, transport) {
+module.exports = function (filter, multiple, updatedSince) {
return {
- url: url
+ filter: filter || "",
+ multiple: multiple || false,
+ updatedSince: updatedSince || ""
};
};
});
-define('ripple/platform/webworks.handset/2.0.0/client/CalendarArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/SensorAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.CalendarArguments ( )
-//blackberry.invoke.CalendarArguments ( date : Date )
-//blackberry.invoke.CalendarArguments ( appointment : blackberry.pim.Appointment )
-var _self = function () {
- //readonly property Appointment appointment
- //readonly property Date date
- //readwrite property Number view
+module.exports = function (value, min, max, normalizedValue) {
return {
- appointment: undefined,
- date: undefined,
- view: 0
+ value: value,
+ min: min,
+ max: max,
+ normalizedValue: normalizedValue
};
};
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_NEW", function () {
- return 0;
-});
-//const Number VIEW_VIEW = 1
-_self.__defineGetter__("VIEW_VIEW", function () {
- return 1;
-});
-//const Number VIEW_AGENDA = 2
-_self.__defineGetter__("VIEW_AGENDA", function () {
- return 2;
-});
-//const Number VIEW_DAY = 3
-_self.__defineGetter__("VIEW_DAY", function () {
- return 3;
});
-//const Number VIEW_DEFAULT = 4
-_self.__defineGetter__("VIEW_DEFAULT", function () {
- return 4;
+define('ripple/platform/phonegap/1.0.0/PhoneGap', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ available: true
+};
+
});
-//const Number VIEW_MONTH = 5
-_self.__defineGetter__("VIEW_MONTH", function () {
- return 5;
+define('ripple/platform/phonegap/1.0.0/SystemInfoOptions', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function (highThreshold, lowThreshold, thresholdTarget, timeout, id) {
+ return {
+ highThreshold: highThreshold,
+ lowThreshold: lowThreshold,
+ thresholdTarget: thresholdTarget,
+ timeout: timeout,
+ id: id
+ };
+};
+
});
-//const Number VIEW_WEEK = 6
-_self.__defineGetter__("VIEW_WEEK", function () {
- return 6;
+define('ripple/platform/phonegap/1.0.0/navigator', function (require, exports, module) {
+/*
+ * Copyright 2011 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 nav = require('ripple/platform/w3c/1.0/navigator'),
+ event = require('ripple/event'),
+ _console = require('ripple/console'),
+ utils = require('ripple/utils'),
+ emulatorBridge = require('ripple/emulatorBridge'),
+ _self = {};
+
+event.on("TinyHipposLoaded", function () {
+ var doc = emulatorBridge.document(),
+ evt = doc.createEvent("Events");
+ evt.initEvent("deviceready", true, true);
+ doc.dispatchEvent(evt);
+ _console.log("fired deviceready event!");
});
+utils.mixin(nav, _self);
+
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/client/CallLog', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function CallLog() {
- // readwrite property String addressBookNumber
- // readwrite property String addressBookType
- // readwrite property Date date
- // readwrite property Number duration
- // readwrite property String name
- // readwrite property String notes
- // readwrite property String number
- // readwrite property Number status
- // readwrite property Number type
- this.addressBookNumber = null;
- this.addressBookType = null;
- this.date = null;
- this.duration = null;
- this.name = null;
- this.notes = null;
- this.number = null;
- this.status = null;
- this.type = null;
-}
+var _self = {},
+ event = require('ripple/event'),
+ devices = require('ripple/devices');
-function _get(val) {
- return function () {
- return val;
- };
-}
-CallLog.__defineGetter__("STATUS_NORMAL", _get(0));
-CallLog.__defineGetter__("STATUS_BUSY", _get(1));
-CallLog.__defineGetter__("STATUS_CONGESTION", _get(2));
-CallLog.__defineGetter__("STATUS_PATH_UNAVAILABLE", _get(3));
-CallLog.__defineGetter__("STATUS_NUMBER_UNOBTAINABLE", _get(4));
-CallLog.__defineGetter__("STATUS_AUTHENTICATION_FAILURE", _get(5));
-CallLog.__defineGetter__("STATUS_EMERGENCY_CALLS_ONLY", _get(6));
-CallLog.__defineGetter__("STATUS_HOLD_ERROR", _get(7));
-CallLog.__defineGetter__("STATUS_OUTGOING_CALLS_BARRED", _get(8));
-CallLog.__defineGetter__("STATUS_GENERAL_ERROR", _get(9));
-CallLog.__defineGetter__("STATUS_MAINTENANCE_REQUIRED", _get(10));
-CallLog.__defineGetter__("STATUS_SERVICE_NOT_AVAILABLE", _get(11));
-CallLog.__defineGetter__("STATUS_CALL_FAIL_DUE_TO_FADING", _get(12));
-CallLog.__defineGetter__("STATUS_CALL_LOST_DUE_TO_FADING", _get(13));
-CallLog.__defineGetter__("STATUS_CALL_FAILED_TRY_AGAIN", _get(14));
-CallLog.__defineGetter__("STATUS_FDN_MISMATCH", _get(15));
-CallLog.__defineGetter__("STATUS_CONNECTION_DENIED", _get(16));
-CallLog.__defineGetter__("STATUS_INCOMING_CALL_BARRED", _get(17));
-CallLog.__defineGetter__("TYPE_RECEIVED_CALL", _get(0));
-CallLog.__defineGetter__("TYPE_PLACED_CALL", _get(1));
-CallLog.__defineGetter__("TYPE_MISSED_CALL_UNOPENED", _get(2));
-CallLog.__defineGetter__("TYPE_MISSED_CALL_OPENED", _get(3));
+event.on("HardwareKey", function (key) {
+ event.trigger("HardwareKeyDefault", [key]);
+});
-module.exports = CallLog;
+_self.__defineGetter__("name", function () {
+ return devices.getCurrentDevice().name;
+});
+
+_self.__defineGetter__("platform", function () {
+ return devices.getCurrentDevice().osName;
+});
+_self.__defineGetter__("uuid", function () {
+ return devices.getCurrentDevice().uuid;
});
-define('ripple/platform/webworks.handset/2.0.0/client/CameraArguments', function (require, exports, module) {
+
+_self.__defineGetter__("version", function () {
+ return devices.getCurrentDevice().osVersion;
+});
+
+_self.phonegap = "placeholder string";
+
+module.exports = _self;
+
+});
+define('ripple/platform/phonegap/1.0.0/AudioCodecAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.CameraArguments ( )
-var _self = function () {
+module.exports = function (info, id, compFormats, encode, decode) {
return {
- //readwrite property Number view
- view: 0
+ info: info,
+ id: id,
+ compFormats: compFormats,
+ encode: encode,
+ decode: decode
};
};
-//const Number VIEW_CAMERA = 0
-_self.__defineGetter__("VIEW_CAMERA", function () {
- return 0;
-});
-//const Number VIEW_RECORDER = 1
-_self.__defineGetter__("VIEW_RECORDER", function () {
- return 1;
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/Contact', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/spec/config', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/pim/contact/";
+var constants = require('ripple/constants');
-function Contact(service) {
- var _self = {
- anniversary: null,
- birthday: null,
- categories: [],
- company: null,
- email1: "",
- email2: "",
- email3: "",
- faxPhone: null,
- firstName: null,
- homeAddress: null,
- homePhone: null,
- homePhone2: null,
- jobTitle: null,
- lastName: null,
- mobilePhone: null,
- note: null,
- otherPhone: null,
- pagerPhone: null,
- picture: null,
- pin: null,
- title: null,
- uid: null,
- user1: null,
- user2: null,
- user3: null,
- user4: null,
- webpage: null,
- workAddress: null,
- workPhone: null,
- workPhone2: null,
- remove: function () {
- if (!_self.uid) {
- throw "task has not yet been saved (has no uid)";
- }
- transport.call(_uri + "remove", {
- get: { id: _self.uid }
- });
- },
- save: function () {
- if (!_self.uid) {
- _self.uid = Math.uuid(null, 16);
- }
- transport.call(_uri + "save", {
- post: { contact: _self }
- });
- },
- setPicture: function (picture) {
- throw "not implemented";
+module.exports = {
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
+ (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));
+
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
}
- };
- return _self;
-}
+ var widgetInfo = {};
-function _massage(property, name) {
- if ((name === "anniversary" || name === "birthday") && property) {
- return new Date(property);
- }
- return property;
-}
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
-Contact.find = function (fieldFilter, orderBy, maxReturn, service, isAscending) {
- return transport.call(_uri + "find", {
- post: {
- fieldFilter: fieldFilter,
- orderBy: orderBy,
- maxReturn: maxReturn,
- service: service,
- isAscending: isAscending
- }
- }).map(function (properties) {
- var contact = new Contact(),
- key;
- for (key in properties) {
- if (contact.hasOwnProperty(key)) {
- contact[key] = _massage(properties[key], key);
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:gap": {
+ attributeName: "xmlns:gap",
+ required: true,
+ type: "list",
+ listValues: ["http://phonegap.com/ns/1.0"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["floating", "fullscreen"]
+ }
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "short": {
+ attributeName: "short",
+ type: "string",
+ required: false
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ email: {
+ attributeName: "email",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.EMAIL
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ encoding: {
+ attributeName: "encoding",
+ type: "string",
+ required: false
+ },
+ type: {
+ attributeName: "type",
+ type: "string",
+ required: false
+ }
+ }
+ },
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "list",
+ required: true,
+ listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
+ "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
+ "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
+ "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
+ "http://api.phonegap.com/1.0/storage"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "string",
+ required: true
+ },
+ value: {
+ type: "string",
+ attributeName: "value",
+ required: false
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
+ }
+ }
+ }
}
}
- return contact;
- });
+ }
};
-module.exports = Contact;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/FilterExpression', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/spec/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.find.FilterExpression ( leftField : object , operator : object , rightField : object , [negate : Boolean ] )
-var FilterExpression = function (leftField, operator, rightField, negate) {
- this.__defineGetter__("leftField", function () {
- return leftField;
- });
+var event = require('ripple/event');
- this.__defineGetter__("operator", function () {
- return operator;
- });
+module.exports = {
+ "NetworkStatus": {
+ "connectionType": {
+ "name": "Connection Type",
+ "control": {
+ "type": "select",
+ "value": "ethernet"
+ },
+ "options": {
+ "unknown": "UNKNOWN",
+ "ethernet": "ETHERNET",
+ "wifi": "WIFI",
+ "2g": "CELL_2G",
+ "3g": "CELL_3G",
+ "4g": "CELL_4G",
+ "none": "none"
+ },
+ "callback": function (setting) {
+ var connected = setting !== "none";
+ require('ripple/bus').send("network", connected);
+ }
+ },
+ "lag": {
+ "name": "Lag the network",
+ "control": {
+ type: "checkbox",
+ value: false
+ },
+ "callback": function (setting) {
+ require('ripple/bus').send("lag", setting);
+ }
+ },
+ }
+};
- this.__defineGetter__("rightField", function () {
- return rightField;
- });
+});
+define('ripple/platform/phonegap/1.0.0/spec/events', function (require, exports, module) {
+function _fires(name, data) {
+ return function () {
+ var doc = require("ripple/emulatorBridge").document(),
+ evt = doc.createEvent("Events");
- this.__defineGetter__("negate", function () {
- return negate ? true : false;
- });
-};
+ evt.initEvent(name, true, false);
+ doc.dispatchEvent(evt);
+ };
+}
-module.exports = FilterExpression;
+module.exports = {
+ "deviceready": {
+ callback: _fires("deviceready")
+ },
+ "backbutton": {
+ callback: _fires("backbutton")
+ },
+ "menubutton": {
+ callback: _fires("menubutton")
+ },
+ "pause": {
+ callback: _fires("pause")
+ },
+ "resume": {
+ callback: _fires("resume")
+ },
+ "searchbutton": {
+ callback: _fires("searchbutton")
+ },
+ "online": {
+ callback: _fires("online")
+ },
+ "offline": {
+ callback: _fires("offline")
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/JavaArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/spec/ui', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.JavaArguments ( uri : String , [params : String [ ] ] )
-var _self = function (uri, params) {
- return {
- uri: uri,
- params: params,
- args: arguments
- };
+module.exports = {
+ plugins: [
+ "accelerometer",
+ "deviceSettings",
+ "geoView",
+ "widgetConfig",
+ "platformEvents"
+ ]
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/MapsArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/VideoCodecAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.MapsArguments ( )
-//blackberry.invoke.MapsArguments ( latitude : Number , longitude : Number )
-//blackberry.invoke.MapsArguments ( locationDocument : Document ) - Supported in 5.0.0 only
-//blackberry.invoke.MapsArguments ( locationDocument : String ) - Supported in 6.0.0 only
-//blackberry.invoke.MapsArguments ( address : blackberry.pim.Address )
-var _self = function () {
- return {};
+module.exports = function (info, id, compFormats, containerFormats, hwAccel, profiles, frameTypes, rateTypes) {
+ return {
+ info: info,
+ id: id,
+ compFormats: compFormats,
+ containerFormats: containerFormats,
+ hwAccel: hwAccel,
+ profiles: profiles,
+ frameTypes: frameTypes,
+ rateTypes: rateTypes
+ };
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/Memo', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/Connection', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/pim/memo/";
-
-function Memo() {
- var _self = {
- categories: [],
- note: null,
- title: null,
- uid: null,
- remove: function () {
- transport.call(_uri + "remove", {
- get: {uid: _self.uid}
- });
- },
- save: function () {
- if (_self.uid === null) {
- _self.uid = Number(Math.uuid(8, 10));
- }
- transport.call(_uri + "save", {
- post: {memo: _self}
- });
- }
- };
-
- return _self;
-}
-
-Memo.find = function (filter, orderBy, maxReturn, service, isAscending) {
- var opts = {
- post: {
- filter: filter,
- orderBy: orderBy,
- maxReturn: maxReturn,
- isAscending: isAscending,
- service: service
- }
- };
-
- return transport.call(_uri + "find", opts).map(function (obj) {
- var memo = new Memo();
- memo.uid = obj.uid;
- memo.categories = obj.categories || [];
- memo.note = obj.note;
- memo.title = obj.title;
- return memo;
- });
+module.exports = {
+ UNKNOWN: "unknown",
+ ETHERNET: "ethernet",
+ WIFI: "wifi",
+ CELL_2G: "2g",
+ CELL_3G: "3g",
+ CELL_4G: "4g",
+ NONE: "none"
};
-module.exports = Memo;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/MemoArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/notification', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.MemoArguments ( [memo : blackberry.pim.Memo ] )
-var _self = function (memo) {
- return {
- memo: memo,
- view: 0
- };
-};
+var notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ _console = require('ripple/console'),
+ ui = require('ripple/ui'),
+ goodVibrations = require('ripple/ui/plugins/goodVibrations');
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_NEW", function () {
- return 0;
-});
-//const Number VIEW_EDIT = 1
-_self.__defineGetter__("VIEW_EDIT", function () {
- return 1;
-});
+module.exports = {
+ alert: function (message, title, buttonName) {
+ notifications.openNotification("normal", message);
+ },
-module.exports = _self;
+ beep: function (times) {
+ for (var i = times; i > 0; i--) {
+ _console.log("beep!");
+ }
+ notifications.openNotification("normal", "BEEP x " + times);
+ },
+
+ vibrate: function (milliseconds) {
+ milliseconds = milliseconds || 500;
+ goodVibrations.vibrateDevice(milliseconds);
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/MenuItem', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/telephony', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- event = require('ripple/event');
-
-function MenuItem(isSeparator, ordinal, caption, callback) {
- var _isDefault = false,
- id = Math.uuid();
-
- if (ordinal < 0) {
- throw "Ordinal cannot be less than 0";
- } else if (isSeparator) {
- if (caption !== undefined) {
- throw "caption must not be supplied";
- } else if (callback !== undefined) {
- throw "callback must not be supplied";
- }
- } else if (!isSeparator) {
- if (caption === undefined) {
- throw "caption must be supplied";
- }
+module.exports = {
+ send: function () {
+ throw "not implemented";
}
+};
- this.callback = callback;
-
- this.__defineSetter__("id", function (i) {
- id = i;
- });
-
- this.__defineGetter__("id", function () {
- return id;
- });
-
- this.__defineSetter__("caption", function (c) {
- caption = c;
- event.trigger("MenuItemChanged", [this]);
- });
-
- this.__defineGetter__("caption", function () {
- return caption;
- });
-
- this.__defineSetter__("ordinal", function (o) {
- ordinal = o;
- event.trigger("MenuItemChanged", [this]);
- });
-
- this.__defineGetter__("ordinal", function () {
- return ordinal;
- });
-
- this.__defineGetter__("isSeparator", function () {
- return isSeparator;
- });
-
- this.__defineSetter__("isDefault", function (d) {
- _isDefault = d;
- event.trigger("MenuItemChanged", [this]);
- });
-
- this.__defineGetter__("isDefault", function () {
- return _isDefault;
- });
-
- this.__defineGetter__("id", function () {
- return id;
- });
-}
-
-module.exports = MenuItem;
+});
+define('ripple/platform/phonegap/1.0.0/system', function (require, exports, module) {
+module.exports = {
+ get: function () {
+ throw "not implemented";
+ },
+ has: function () {
+ throw "not implemented";
+ },
+ monitor: function () {
+ throw "not implemented";
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/Message', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/contacts', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
- identity = require('ripple/platform/webworks.handset/2.0.0/client/identity'),
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
- select = require('ripple/platform/webworks.core/2.0.0/select'),
- _uri = "blackberry/message/message/";
+var Contact = require('./Contact'),
+ ContactName = require('./ContactName'),
+ ContactError = require('./ContactError'),
+ ContactField = require('./ContactField'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ event = require('ripple/event'),
+ _defaultContacts =
+ [{
+ "id": Math.uuid(undefined, 16),
+ "name": new ContactName("Brent Lintner"),
+ "displayName": "Brent Lintner",
+ "emails": [new ContactField("work", "brent@tinyhippos.com", false)]
+ }, {
+ "id": Math.uuid(undefined, 16),
+ "name": new ContactName("PJ Lowe"),
+ "displayName": "PJ Lowe",
+ "emails": [new ContactField("work", "pj@tinyhippos.com", false)]
+ }, {
+ "id": Math.uuid(undefined, 16),
+ "name": new ContactName("Dan Silivestru"),
+ "displayName": "Dan Silivestru",
+ "emails": [new ContactField("work", "dan@tinyhippos.com", false)]
+ }, {
+ "id": Math.uuid(undefined, 16),
+ "name": new ContactName("Gord Tanner"),
+ "displayName": "Gord Tanner",
+ "emails": [new ContactField("work", "gord@tinyhippos.com", true)]
+ }, {
+ "id": Math.uuid(undefined, 16),
+ "name": new ContactName("Mark McArdle"),
+ "displayName": "Mark McArdle",
+ "emails": [new ContactField("work", "mark@tinyhippos.com", false)]
+ }],
+ self;
-function Message(service) {
- var _service = service,
- _msg = {
- uid: 0,
- status: Message.STATUS_DRAFT,
- from: "",
- folder: Message.FOLDER_DRAFT,
- replyTo: "",
- bccRecipients: "",
- body: "",
- ccRecipients: "",
- priority: Message.PRIORITY_MEDIUM, //default to med priority
- subject: "",
- toRecipients: "",
+function _error(callback, code, msg) {
+ var e = new ContactError();
+ e.code = code;
+ e.message = msg;
+ window.setTimeout(function () {
+ callback(e);
+ }, 1);
+}
- remove: function () {
- _msg.folder = Message.FOLDER_DELETED;
- transport.call(_uri + "remove", {
- get: {uid: _msg.uid}
- });
- },
- save: function () {
- if (_msg.uid === 0) {
- _msg.uid = Number(Math.uuid(8, 10));
- }
+function _getContacts() {
+ return db.retrieveObject("phonegap-contacts") ||
+ _defaultContacts.map(function (person) {
+ var contact = new Contact();
+ contact.updated = new Date();
+ utils.forEach(person, function (value, prop) {
+ contact[prop] = value;
+ });
- _msg.replyTo = _msg.from = _service.emailAddress;
- _msg.status = Message.STATUS_SAVED;
- transport.call(_uri + "save", {
- post: {message: _msg}
- });
- },
+ return contact;
+ });
+}
- send: function () {
- if (_msg.toRecipients) {
- if (_msg.uid === 0) {
- _msg.uid = Number(Math.uuid(8, 10));
- }
+function _saveContacts(contacts) {
+ db.saveObject("phonegap-contacts", contacts);
+}
- _msg.folder = Message.FOLDER_DRAFT;
- _msg.status = Message.STATUS_UNKNOWN;
- transport.call(_uri + "send", {
- get: {message: _msg}
- });
- } else {
- throw "message has no recipients";
- }
+function _filtered(compare, options) {
+ // this could be done a lot better..
+ var found = false;
+ if (!options.filter || options.filter === "") {
+ found = true;
+ } else if (typeof compare === "string" &&
+ compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
+ found = true;
+ } else if (typeof compare === "object" || compare instanceof Array) {
+ utils.forEach(compare, function (value) {
+ if (!found) {
+ found = _filtered(value, options);
}
- };
+ });
+ }
+ return found;
+}
- if (!_service) {
- _service = identity.getDefaultService().reduce(function (email, service) {
- return service.type === Service.TYPE_EMAIL ? service : email;
- }, null);
+event.on("phonegap-contact-save", function (contactProperties, success, error) {
+ var contacts = _getContacts(),
+ existsIndex = contacts.reduce(function (result, value, index) {
+ return value.id === contactProperties.id ? index : result;
+ }, -1),
+ contact = existsIndex >= 0 ? contacts[existsIndex] : new Contact();
+
+ utils.mixin(contactProperties, contact);
+ if (existsIndex < 0) {
+ contacts.push(contact);
}
+ _saveContacts(contacts);
+ success(contact);
+});
- return _msg;
-}
+event.on("phonegap-contact-remove", function (id, success, error) {
+ if (!id) {
+ _error(error, ContactError.NOT_FOUND_ERROR, "id is falsy (" + id + ")");
+ } else {
+ var contacts = _getContacts(),
+ toDelete = contacts.reduce(function (result, current, index) {
+ return current.id === id ? index : result;
+ }, -1);
-Message.find = function (filter, maxReturn, service) {
- var opts = {
- post: {
- filter: filter,
- maxReturn: maxReturn,
- service: service
+ if (toDelete >= 0) {
+ contacts.splice(toDelete, 1);
+ _saveContacts(contacts);
+ success();
+ } else {
+ _error(error, ContactError.NOT_FOUND_ERROR, "could not find contact with id (" + id + ")");
}
- };
+ }
+});
- return transport.call(_uri + "find", opts).map(function (obj) {
- var msg = new Message();
+self = module.exports = {
+ create: function (properties) {
+ var contact = new Contact();
+ utils.forEach(properties, function (value, key) {
+ contact[key] = value;
+ });
+ return contact;
+ },
+ find: function (fields, success, error, options) {
+ var foundContacts = [],
+ tempContact = self.create(),
+ contacts = _getContacts(),
+ errorFlag = false;
- msg.uid = obj.uid;
- msg.status = obj.status;
- msg.from = obj.from;
- msg.folder = obj.folder;
- msg.replyTo = obj.replyTo;
- msg.bccRecipients = obj.bccRecipients;
- msg.body = obj.body;
- msg.ccRecipients = obj.ccRecipients;
- msg.priority = obj.priority;
- msg.subject = obj.subject;
- msg.toRecipients = obj.toRecipients;
+ options = options || {};
- return msg;
- });
-};
+ // not a fan of error handling at the moment
+ if (!fields || !("forEach" in fields)) {
+ errorFlag = true;
+ _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing contact fields array");
+ return;
+ }
+ // handle special case of ["*"] to return all fields
+ if (fields.length === 1 && fields[0] === "*") {
+ fields = utils.map(tempContact, function (v, k) {
+ return k;
+ });
+ }
-Message.__defineGetter__("STATUS_UNKNOWN", function () {
- return -1;
-});
-Message.__defineGetter__("STATUS_SAVED", function () {
- return 0;
-});
-Message.__defineGetter__("STATUS_DRAFT", function () {
- return 1;
-});
-Message.__defineGetter__("STATUS_SENT", function () {
- return 2;
-});
-Message.__defineGetter__("STATUS_ERROR_OCCURED", function () {
- return 3;
-});
-Message.__defineGetter__("PRIORITY_HIGH", function () {
- return 0;
-});
-Message.__defineGetter__("PRIORITY_MEDIUM", function () {
- return 1;
-});
-Message.__defineGetter__("PRIORITY_LOW", function () {
- return 2;
-});
-Message.__defineGetter__("FOLDER_INBOX", function () {
- return 0;
-});
-Message.__defineGetter__("FOLDER_SENT", function () {
- return 1;
-});
-Message.__defineGetter__("FOLDER_DRAFT", function () {
- return 2;
-});
-Message.__defineGetter__("FOLDER_OUTBOX", function () {
- return 3;
-});
-Message.__defineGetter__("FOLDER_DELETED", function () {
- return 4;
-});
-Message.__defineGetter__("FOLDER_OTHER", function () {
- return 5;
-});
+ fields.forEach(function (prop) {
+ if (!(tempContact.hasOwnProperty(prop))) {
+ errorFlag = true;
+ _error(error, ContactError.INVALID_ARGUMENT_ERROR, "invalid contact field (" + prop + ")");
+ }
+ });
+
+ if (typeof success !== "function" && !errorFlag) {
+ errorFlag = true;
+ _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing success callback");
+ }
+
+ if (errorFlag) {
+ return;
+ }
+
+ if (fields.length > 0) {
+ contacts.forEach(function (contact, index) {
+ var newContact = utils.copy(contact);
+
+ if (options && (!_filtered(contact, options) ||
+ options.updatedSince && contact.updated && contact.updated.getTime() < options.updatedSince.getTime())) {
+ return;
+ }
+
+ utils.forEach(newContact, function (value, prop) {
+ if (typeof newContact[prop] !== "function" && prop !== "id" &&
+ !fields.some(function (field) {
+ return field === prop;
+ })) {
+ delete newContact[prop];
+ }
+ });
-module.exports = Message;
+ foundContacts.push(newContact);
+ });
+ }
+
+ window.setTimeout(function () {
+ // TODO: don't loop over entire db just to slice the array
+ if (options.multiple === false) {
+ foundContacts = foundContacts.splice(0, 1);
+ }
+ success(foundContacts);
+ }, 1);
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/MessageArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/PointerAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.MessageArguments ( )
-//blackberry.invoke.MessageArguments ( message : blackberry.message.Message )
-//blackberry.invoke.MessageArguments ( to : String , subject : String , body : String )
-var _self = function () {
+module.exports = function (type, supportsMultiTouch, info) {
return {
- view: 1
+ type: type,
+ supportsMultiTouch: supportsMultiTouch,
+ info: info
};
};
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_NEW", function () {
- return 0;
-});
-//const Number VIEW_DEFAULT = 1
-_self.__defineGetter__("VIEW_DEFAULT", function () {
- return 1;
-});
-//const Number VIEW_SAVED = 2
-_self.__defineGetter__("VIEW_SAVED", function () {
- return 2;
-});
-//const Number VIEW_SEARCH = 3
-_self.__defineGetter__("VIEW_SEARCH", function () {
- return 3;
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/Phone', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/AudioDeviceAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/phone/",
- _listeners = {},
- _self;
-
-_self = {
- activeCalls: function () {
- return transport.call(_uri + "activeCalls");
- },
-
- addPhoneListener: function (callback, eventType) {
- var assigned = false;
-
- if (callback && typeof eventType === "number") {
- _listeners[eventType] = callback;
- assigned = true;
- } else if (eventType && callback === null) {
- delete _listeners[eventType];
- } else {
- _listeners = {};
- }
-
- transport.poll(_uri + "onPhoneEvent", {
- get: {eventType: eventType}
- }, function (response) {
- var func = _listeners[eventType];
-
- if (func) {
- func(response.callId, response.error);
- }
-
- return !!func;
- });
-
- // hackish (return true that event was assigned, this is a disconnect between transport poll api and server)
- return assigned;
- },
+module.exports = function (type, freqRangeLow, freqRangeHigh, volumeLevel, info) {
+ return {
+ type: type,
+ freqRangeLow: freqRangeLow,
+ freqRangeHigh: freqRangeHigh,
+ volumeLevel: volumeLevel,
+ info: info
+ };
- inActiveCall: function () {
- return transport.call(_uri + "inActiveCall");
- }
};
-_self.__defineGetter__("CB_CALL_INITIATED", function () {
- return 0;
-});
-_self.__defineGetter__("CB_CALL_WAITING", function () {
- return 1;
-});
-_self.__defineGetter__("CB_CALL_INCOMING", function () {
- return 2;
-});
-_self.__defineGetter__("CB_CALL_ANSWERED", function () {
- return 3;
-});
-_self.__defineGetter__("CB_CALL_CONNECTED", function () {
- return 4;
-});
-_self.__defineGetter__("CB_CALL_CONFERENCECALL_ESTABLISHED", function () {
- return 5;
-});
-_self.__defineGetter__("CB_CONFERENCECALL_DISCONNECTED", function () {
- return 6;
-});
-_self.__defineGetter__("CB_CALL_DISCONNECTED", function () {
- return 7;
-});
-_self.__defineGetter__("CB_CALL_DIRECTCONNECT_CONNECTED", function () {
- return 8;
-});
-_self.__defineGetter__("CB_CALL_DIRECTCONNECT_DISCONNECTED", function () {
- return 9;
-});
-_self.__defineGetter__("CB_CALL_ENDED_BYUSER", function () {
- return 10;
-});
-_self.__defineGetter__("CB_CALL_FAILED", function () {
- return 11;
-});
-_self.__defineGetter__("CB_CALL_RESUMED", function () {
- return 12;
-});
-_self.__defineGetter__("CB_CALL_HELD", function () {
- return 13;
-});
-_self.__defineGetter__("CB_CALL_ADDED", function () {
- return 14;
-});
-_self.__defineGetter__("CB_CALL_REMOVED", function () {
- return 15;
-});
-_self.__defineGetter__("CALL_ERROR_SUBSCRIBER_BUSY", function () {
- return 1;
-});
-_self.__defineGetter__("CALL_ERROR_CONGESTION", function () {
- return 2;
-});
-_self.__defineGetter__("CALL_ERROR_RADIO_PATH_UNAVAILABLE", function () {
- return 3;
-});
-_self.__defineGetter__("CALL_ERROR_NUMBER_UNOBTAINABLE", function () {
- return 4;
-});
-_self.__defineGetter__("CALL_ERROR_AUTHORIZATION_FAILURE", function () {
- return 5;
-});
-_self.__defineGetter__("CALL_ERROR_EMERGENCY_CALLS_ONLY", function () {
- return 6;
-});
-_self.__defineGetter__("CALL_ERROR_HOLD_ERROR", function () {
- return 7;
-});
-_self.__defineGetter__("CALL_ERROR_OUTGOING_CALLS_BARRED", function () {
- return 8;
-});
-_self.__defineGetter__("CALL_ERROR_GENERAL", function () {
- return 9;
-});
-_self.__defineGetter__("CALL_ERROR_MAINTENANCE_REQUIRED", function () {
- return 10;
-});
-_self.__defineGetter__("CALL_ERROR_SERVICE_NOT_AVAILABLE", function () {
- return 11;
-});
-_self.__defineGetter__("CALL_ERROR_DUE_TO_FADING", function () {
- return 12;
-});
-_self.__defineGetter__("CALL_ERROR_LOST_DUE_TO_FADING", function () {
- return 13;
-});
-_self.__defineGetter__("CALL_ERROR_TRY_AGAIN", function () {
- return 14;
-});
-_self.__defineGetter__("CALL_ERROR_FDN_MISMATCH", function () {
- return 15;
-});
-_self.__defineGetter__("CALL_ERROR_CONNECTION_DENIED_BY_NETWORK", function () {
- return 16;
-});
-_self.__defineGetter__("CALL_ERROR_NUMBER_NOT_IN_SERVICE", function () {
- return 17;
-});
-_self.__defineGetter__("CALL_ERROR_PLEASE_TRY_LATER", function () {
- return 18;
-});
-_self.__defineGetter__("CALL_ERROR_SERVICE_CONFLICT", function () {
- return 19;
-});
-_self.__defineGetter__("CALL_ERROR_SYSTEM_BUSY_TRY_LATER", function () {
- return 20;
-});
-_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_PRIVATE", function () {
- return 21;
-});
-_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_DATA", function () {
- return 22;
-});
-_self.__defineGetter__("CALL_ERROR_USER_NOT_AUTHORIZED", function () {
- return 23;
-});
-_self.__defineGetter__("CALL_ERROR_USER_NOT_AVAILABLE", function () {
- return 24;
-});
-_self.__defineGetter__("CALL_ERROR_USER_UNKNOWN", function () {
- return 25;
-});
-_self.__defineGetter__("CALL_ERROR_USER_NOT_REACHABLE", function () {
- return 26;
-});
-_self.__defineGetter__("CALL_ERROR_INCOMING_CALL_BARRED", function () {
- return 27;
-});
-_self.__defineGetter__("CALL_ERROR_CALL_REPLACED_BY_STK", function () {
- return 28;
-});
-_self.__defineGetter__("CALL_ERROR_STK_CALL_NOT_ALLOWED", function () {
- return 29;
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/PhoneArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/DisplayDeviceAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.PhoneArguments ( [dialString : String ] , [smartDialing : Boolean ] , [lineId : Number ] )
-var _self = function (dialString, smartDialing, lineId) {
+module.exports = function (orientation, brightness, contrast, blanked, dotsPerInchW, dotsPerInchH, physicalWidth, physicalHeight, info) {
return {
- dialString: dialString,
- smartDialing: smartDialing,
- lineId: (lineId ? lineId : -1),
- view: 0
+ orientation: orientation,
+ brightness: brightness,
+ contrast: contrast,
+ blanked: blanked,
+ dotsPerInchW: dotsPerInchW,
+ dotsPerInchH: dotsPerInchH,
+ physicalWidth: physicalWidth,
+ physicalHeight: physicalHeight,
+ info: info
};
};
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_CALL", function () {
- return 0;
-});
-//const Number VIEW_DEFAULT = 1
-_self.__defineGetter__("VIEW_VOICEMAIL", function () {
- return 1;
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/PhoneCall', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/InputDevicesAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function PhoneCall(onhold) {
+module.exports = function (info, id, pointingDevices, activePointingDevices, keyboards, activeKeyboards, cameras, activeCameras, microphones, activeMicrophones) {
return {
- //Boolean isOnHold ( )
- //readonly property Boolean outgoing
- //readonly property String recipientName
- //readonly property String recipientNumber
-
- outgoing: false,
- recipientName: null,
- recipientNumber: null,
-
- isOnHold: function () {
- return onhold;
- }
+ info: info,
+ id: id,
+ pointingDevices: pointingDevices,
+ activePointingDevices: activePointingDevices,
+ keyboards: keyboards,
+ activeKeyboards: activeKeyboards,
+ cameras: cameras,
+ activeCameras: activeCameras,
+ microphones: microphones,
+ activeMicrophones: activeMicrophones
};
-}
-module.exports = PhoneCall;
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/camera', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
- utils = require('ripple/utils'),
- _onCallLog = {
- Added: null,
- Removed: null,
- Updated: null,
- Reset: null,
- },
- _uri = "blackberry/phone/logs/",
- _self;
-
-function _massage(property, name) {
- if (name === "date" && property) {
- return new Date(property);
- }
- return property;
-}
-
-function _toCallLog(log) {
- var callLog = new CallLog(),
- prop;
- for (prop in log) {
- if (log.hasOwnProperty(prop)) {
- callLog[prop] = _massage(log[prop], prop);
- }
- }
- return callLog;
-}
-
-function handle(evt) {
- return function (response) {
- var func = _onCallLog[evt], args;
-
- if (func) {
- args = utils.map(response, function (value) {
- return _toCallLog(value);
- });
- func.apply(null, args);
- }
-
- return !!func;
- };
-}
-
-function poll(path) {
- transport.poll(_uri + path, {}, handle(path.replace("onCallLog", "")));
-}
-
-_self = {
- addPhoneLogListener: function (onCallLogAdded, onCallLogRemoved, onCallLogUpdated, onCallLogReset) {
- _onCallLog.Added = onCallLogAdded;
- _onCallLog.Removed = onCallLogRemoved;
- _onCallLog.Updated = onCallLogUpdated;
- _onCallLog.Reset = onCallLogReset;
-
- if (onCallLogAdded) {
- poll("onCallLogAdded");
- }
-
- if (onCallLogRemoved) {
- poll("onCallLogRemoved");
- }
-
- if (onCallLogUpdated) {
- poll("onCallLogUpdated");
- }
-
- if (onCallLogReset) {
- poll("onCallLogReset");
+module.exports = {
+ getPicture: function (cameraSuccess, cameraError, cameraOptions) {
+ if (cameraError) {
+ cameraError.apply(null, ["not implemented"]);
}
-
- return !!(onCallLogAdded || onCallLogRemoved ||
- onCallLogUpdated || onCallLogRemoved);
- },
-
- callAt: function (index, folderID) {
- var log = transport.call(_uri + "callAt", {
- get: {
- index: index,
- folderID: folderID
- }
- });
-
- if (log && log.date) {
- log.date = new Date(log.date);
+ else {
+ throw "not implemented";
}
-
- return log;
- },
-
- deleteCallAt: function (index, folderID) {
- return transport.call(_uri + "deleteCallAt", {
- get: {
- index: index,
- folderID: folderID
- }
- });
- },
-
- find: function (filter, folderID, orderBy, maxReturn, isAscending) {
- return transport.call(_uri + "find", {
- post: {
- filter: filter,
- folderID: folderID,
- orderBy: orderBy,
- maxReturn: maxReturn,
- isAscending: isAscending
- }
- }).map(_toCallLog);
- },
-
- numberOfCalls: function (folderID) {
- return transport.call(_uri + "numberOfCalls", {
- get: {
- folderID: folderID
- }
- });
}
};
-_self.__defineGetter__("FOLDER_MISSED_CALLS", function () {
- return 0;
-});
-
-_self.__defineGetter__("FOLDER_NORMAL_CALLS", function () {
- return 1;
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/PushData', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/network', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function PushData(data, port) {
- this.port = port;
- this.data = data;
-
- this.getHeaderField = function (field) {
- if (field === undefined || field === null) {
- throw "no field specified";
- }
- else if (!(typeof field === 'number' && field >= 0) && typeof field !== 'string') {
- throw "field is not valid";
+var deviceSettings = require('ripple/deviceSettings'),
+ _self = {
+ connection: {
}
-
- return data.headerField[field];
- };
-
- this.getRequestURI = function () {
- return data.requestURI;
- };
-
- this.getSource = function () {
- return data.source;
};
- this.isChannelEncrypted = data.isChannelEncrypted;
-
- this.payload = data.payload;
-
- this.__defineGetter__("ACCEPT", function () {
- return 0;
- });
- this.__defineGetter__("DECLINE_USERDCR", function () {
- return 1;
- });
- this.__defineGetter__("DECLINE_USERDCU", function () {
- return 2;
- });
- this.__defineGetter__("DECLINE_USERPND", function () {
- return 3;
- });
- this.__defineGetter__("DECLINE_USERREQ", function () {
- return 4;
- });
- this.__defineGetter__("DECLINE_USERRFS", function () {
- return 5;
- });
-}
+_self.connection.__defineGetter__("type", function () {
+ return deviceSettings.retrieve("NetworkStatus.connectionType");
+});
-module.exports = PushData;
+module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/client/Recurrence', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/KeyboardAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function Recurrence() {
+module.exports = function (type, isHardware, info) {
return {
- //readwrite property Number count
- //readwrite property Number dayInMonth
- //readwrite property Number dayInWeek
- //readwrite property Number dayInYear
- //readwrite property Date end
- //readwrite property Number frequency
- //readwrite property Number interval
- //readwrite property Number monthInYear
- //readwrite property Number weekInMonth
-
- count: null,
- dayInMonth: null,
- dayInWeek: null,
- dayInYear: null,
- end: null,
- frequency: null,
- interval: null,
- monthInYear: null,
- weekInMonth: null
+ type: type,
+ isHardware: isHardware,
+ info: info
};
-}
-
-Recurrence.__defineGetter__("NO_REPEAT", function () {
- return 0;
-});
-Recurrence.__defineGetter__("DAILY", function () {
- return 1;
-});
-Recurrence.__defineGetter__("WEEKLY", function () {
- return 2;
-});
-Recurrence.__defineGetter__("MONTHLY", function () {
- return 3;
-});
-Recurrence.__defineGetter__("YEARLY", function () {
- return 4;
-});
-Recurrence.__defineGetter__("JANUARY", function () {
- return 0x20000;
-});
-Recurrence.__defineGetter__("FEBRUARY", function () {
- return 0x40000;
-});
-Recurrence.__defineGetter__("MARCH", function () {
- return 0x80000;
-});
-Recurrence.__defineGetter__("APRIL", function () {
- return 0x100000;
-});
-Recurrence.__defineGetter__("MAY", function () {
- return 0x200000;
-});
-Recurrence.__defineGetter__("JUNE", function () {
- return 0x400000;
-});
-Recurrence.__defineGetter__("JULY", function () {
- return 0x800000;
-});
-Recurrence.__defineGetter__("AUGUST", function () {
- return 0x1000000;
-});
-Recurrence.__defineGetter__("SEPTEMBER", function () {
- return 0x2000000;
-});
-Recurrence.__defineGetter__("OCTOBER", function () {
- return 0x4000000;
-});
-Recurrence.__defineGetter__("NOVEMBER", function () {
- return 0x8000000;
-});
-Recurrence.__defineGetter__("DECEMBER", function () {
- return 0x10000000;
-});
-Recurrence.__defineGetter__("FIRST", function () {
- return 0x1;
-});
-Recurrence.__defineGetter__("SECOND", function () {
- return 0x2;
-});
-Recurrence.__defineGetter__("THIRD", function () {
- return 0x4;
-});
-Recurrence.__defineGetter__("FOURTH", function () {
- return 0x8;
-});
-Recurrence.__defineGetter__("FIFTH", function () {
- return 0x10;
-});
-Recurrence.__defineGetter__("LAST", function () {
- return 0x20;
-});
-Recurrence.__defineGetter__("SECONDLAST", function () {
- return 0x40;
-});
-Recurrence.__defineGetter__("THIRDLAST", function () {
- return 0x80;
-});
-Recurrence.__defineGetter__("FOURTHLAST", function () {
- return 0x100;
-});
-Recurrence.__defineGetter__("FIFTHLAST", function () {
- return 0x200;
-});
-Recurrence.__defineGetter__("SUNDAY", function () {
- return 0x10000;
-});
-Recurrence.__defineGetter__("MONDAY", function () {
- return 0x8000;
-});
-Recurrence.__defineGetter__("TUESDAY", function () {
- return 0x4000;
-});
-Recurrence.__defineGetter__("WEDNESDAY", function () {
- return 0x2000;
-});
-Recurrence.__defineGetter__("THURSDAY", function () {
- return 0x1000;
-});
-Recurrence.__defineGetter__("FRIDAY", function () {
- return 0x800;
-});
-Recurrence.__defineGetter__("SATURDAY", function () {
- return 0x400;
-});
-
-module.exports = Recurrence;
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/Reminder', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ContactAddress', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var Reminder = function () {
-
+module.exports = function (pref, type, formatted, streetAddress, locality, region, postalCode, country, id) {
return {
- //readwrite property Date date
- //readwrite property Number relativeHours
- //readwrite property Number type
-
- date: null,
- relativeHours: null,
- type: null
-
+ pref: pref || null,
+ type: type || null,
+ formatted: formatted || null,
+ streetAddress: streetAddress || null,
+ locality: locality || null,
+ region: region || null,
+ postalCode: postalCode || null,
+ country: country || null,
+ id: id || null
};
-
};
-Reminder.__defineGetter__("DATE", function () {
- return 0;
-});
-
-Reminder.__defineGetter__("RELATIVE", function () {
- return 1;
-});
-
-module.exports = Reminder;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/SearchArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/BrailleDeviceAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.SearchArguments ( )
-//blackberry.invoke.SearchArguments ( text : String , name : String )
-var _self = function (text, name) {
-
+module.exports = function (nbCells, info) {
return {
- text: text,
- name: name
+ nbCells: nbCells,
+ info: info
};
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/Task', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/CPUAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/pim/Task/";
-
-function Task() {
- var _self = {
- save: function () {
- if (!_self.uid) {
- _self.uid = Math.uuid(null, 16);
- }
- transport.call(_uri + "save", {
- post: {
- task: _self
- }
- });
- },
- remove: function () {
- if (!_self.uid) {
- throw "task has not yet been saved (has no uid)";
- }
- transport.call(_uri + "remove", {
- get: {
- id: _self.uid
- }
- });
- },
- uid: null,
- categories: [],
- due: null,
- note: "",
- priority: Task.PRIORITY_NORMAL,
- recurrence: null,
- reminder: null,
- status: Task.NOT_STARTED,
- summary: ""
+module.exports = function (info, id, usage) {
+ return {
+ info: info,
+ id: id,
+ usage: usage
};
-
- return _self;
-}
-
-function _massage(property, name) {
- if (name === "recurrence" && property) {
- if (property.end) {
- property.end = new Date(property.end);
- }
- }
- if (name === "reminder" && property) {
- if (property.date) {
- property.date = new Date(property.date);
- }
- }
- if (name === "due" && property) {
- property = new Date(property);
- }
- return property;
-}
-
-Task.find = function (filter, orderBy, maxReturn, isAscending) {
- return transport.call(_uri + "find", {
- post: {
- filter: filter,
- orderBy: orderBy,
- maxReturn: maxReturn,
- isAscending: isAscending
- }
- }).map(function (properties) {
- var task = new Task(),
- key;
- for (key in properties) {
- if (task.hasOwnProperty(key)) {
- task[key] = _massage(properties[key], key);
- }
- }
- return task;
- });
};
-Task.__defineGetter__("NOT_STARTED", function () {
- return 0;
-});
-
-Task.__defineGetter__("IN_PROGRESS", function () {
- return 1;
-});
-
-Task.__defineGetter__("COMPLETED", function () {
- return 2;
-});
-
-Task.__defineGetter__("WAITING", function () {
- return 3;
-});
-
-Task.__defineGetter__("DEFERRED", function () {
- return 4;
-});
-
-Task.__defineGetter__("PRIORITY_HIGH", function () {
- return 0;
-});
-
-Task.__defineGetter__("PRIORITY_NORMAL", function () {
- return 1;
-});
-
-Task.__defineGetter__("PRIORITY_LOW", function () {
- return 2;
-});
-
-module.exports = Task;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/TaskArguments', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ThermalAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.TaskArguments ( [task : blackberry.pim.Task ] )
-var _self = function (task) {
+module.exports = function (info, id, state) {
return {
- view: 0,
- task: task
+ info: info,
+ id: id,
+ state: state
};
};
-//const Number VIEW_NEW = 0
-_self.__defineGetter__("VIEW_NEW", function () {
- return 0;
-});
-//const Number VIEW_EDIT = 1
-_self.__defineGetter__("VIEW_EDIT", function () {
- return 1;
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/webworks.handset/2.0.0/client/app', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
- _uri = "blackberry/app/",\r
- _self;\r
-\r
-_self = {\r
- exit: function () {\r
- transport.call(_uri + "exit", {async: true});\r
- },\r
-\r
- setHomeScreenIcon: function (uri, hover) {\r
- transport.call(_uri + "setHomeScreenIcon", {\r
- get: {\r
- uri: uri,\r
- hover: hover\r
- },\r
- async: true\r
- });\r
-\r
- return true;\r
- },\r
-\r
- setHomeScreenName: function (text) {\r
- transport.call(_uri + "setHomeScreenName", {\r
- get: {text: text},\r
- async: true\r
- });\r
-\r
- return true;\r
- },\r
-\r
- requestForeground: function () {\r
- transport.call(_uri + "requestForeground", {async: true});\r
- },\r
-\r
- requestBackground: function () {\r
- transport.call(_uri + "requestBackground", {async: true});\r
- },\r
-\r
- removeBannerIndicator: function () {\r
- transport.call(_uri + "removeBannerIndicator", {async: true});\r
- },\r
-\r
- showBannerIndicator: function (icon, count) {\r
- transport.call(_uri + "showBannerIndicator", {\r
- get: {\r
- icon: icon,\r
- count: count\r
- },\r
- async: true\r
- });\r
- },\r
-};\r
-\r
-_self.__defineGetter__("author", function () {\r
- return transport.call(_uri + "author");\r
-});\r
-\r
-_self.__defineGetter__("authorEmail", function () {\r
- return transport.call(_uri + "authorEmail");\r
-});\r
-\r
-_self.__defineGetter__("authorURL", function () {\r
- return transport.call(_uri + "authorURL");\r
-});\r
-\r
-_self.__defineGetter__("copyright", function () {\r
- return transport.call(_uri + "copyright");\r
-});\r
-\r
-_self.__defineGetter__("description", function () {\r
- return transport.call(_uri + "description");\r
-});\r
-\r
-_self.__defineGetter__("id", function () {\r
- return transport.call(_uri + "id");\r
-});\r
-\r
-_self.__defineGetter__("isForeground", function () {\r
- return transport.call(_uri + "isForeground");\r
-});\r
-\r
-_self.__defineGetter__("license", function () {\r
- return transport.call(_uri + "license");\r
-});\r
-\r
-_self.__defineGetter__("licenseURL", function () {\r
- return transport.call(_uri + "licenseURL");\r
-});\r
-\r
-_self.__defineGetter__("name", function () {\r
- return transport.call(_uri + "name");\r
-});\r
-\r
-_self.__defineGetter__("version", function () {\r
- return transport.call(_uri + "version");\r
-});\r
-\r
-module.exports = _self;\r
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/appEvent', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ContactOrganization', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _callbacks = {},
- _self;
-
-function _poll(evt, handler) {
- _callbacks[evt] = handler;
-
- transport.poll("blackberry/app/event/" + evt, {}, function () {
- var func = _callbacks[evt];
-
- if (func) {
- func();
- }
-
- return !!func;
- });
-}
-
-_self = {
- onBackground: function (handler) {
- _poll("onBackground", handler);
- },
-
- onForeground: function (handler) {
- _poll("onForeground", handler);
- },
-
- onExit: function (handler) {
- _poll("onExit", handler);
- }
+module.exports = function (pref, type, name, dept, title) {
+ return {
+ pref: pref || null,
+ type: type || null,
+ name: name || null,
+ department: dept || null,
+ title: title || null
+ };
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/audio', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/orientation', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- supportedContentTypes: function (protocol) {
- return protocol === 'rtsp' ?
- ['audio/amr', 'audio/mp4', 'audio/aac'] :
- ['audio/midi', 'mpeg', 'x-wav', 'amr', 'basic', 'x-gsm', 'mp4', 'aac', 'x-ms-wma', 'flac', 'ogg'];
+ currentOrientation: null,
+ getCurrentOrientation: function (onSuccess, onFail) {
+ throw "not implemented";
},
- supportedProtocols: function (contentType) {
- return ['http', 'file', 'rtsp'];
+ watchOrientation: function () {
+ throw "not implemented";
}
};
});
-define('ripple/platform/webworks.handset/2.0.0/client/blackberry', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/compass', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var blackberry = {},
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport');
+var geo = require('ripple/geo');
-blackberry.__defineGetter__("network", function () {
- return transport.call("blackberry/system/network");
-});
+function _getHeading() {
+ return geo.getPositionInfo().heading;
+}
-module.exports = blackberry;
+module.exports = {
+ getCurrentHeading: function (compassSuccess, compassError, compassOptions) {
+ setTimeout(function () {
+ compassSuccess(_getHeading());
+ }, 1);
+ },
+ watchHeading: function (compassSuccess, compassError, compassOptions) {
+ compassOptions = compassOptions || {};
+ return setInterval(function () {
+ compassSuccess(_getHeading());
+ }, compassOptions.frequency || 100);
+ },
+ clearWatch: function (watchId) {
+ clearInterval(watchId);
+ }
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/category', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ContactError', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/pim/category/",
- _self;
+function ContactError(code) {
+ this.code = code || null;
+}
-_self = {
- addCategory: function (categoryName) {
- transport.call(_uri + "addCategory", {
- get: {categoryName: categoryName}
- });
- },
- deleteCategory: function (categoryName) {
- transport.call(_uri + "deleteCategory", {
- get: {categoryName: categoryName}
- });
- },
- getCategories: function () {
- return transport.call(_uri + "getCategories");
- }
-};
+ContactError.UNKNOWN_ERROR = 0;
+ContactError.INVALID_ARGUMENT_ERROR = 1;
+ContactError.NOT_FOUND_ERROR = 2;
+ContactError.TIMEOUT_ERROR = 3;
+ContactError.PENDING_OPERATION_ERROR = 4;
+ContactError.IO_ERROR = 5;
+ContactError.NOT_SUPPORTED_ERROR = 6;
+ContactError.PERMISSION_DENIED_ERROR = 20;
-module.exports = _self;
+module.exports = ContactError;
});
-define('ripple/platform/webworks.handset/2.0.0/client/identity/Service', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/OutputDevicesAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function Service() {
+module.exports = function (info, id, displayDevices, activeDisplayDevices, printingDevices, activePrintingDevice, brailleDevices, activeBrailleDevice, audioDevices, activeAudioDevices) {
return {
- emailAddress: null,
- isDefault: null,
- name: null,
- type: null
+ info: info,
+ id: id,
+ displayDevices: displayDevices,
+ activeDisplayDevices: activeDisplayDevices,
+ printingDevices: printingDevices,
+ activePrintingDevice: activePrintingDevice,
+ brailleDevices: brailleDevices,
+ activeBrailleDevice: activeBrailleDevice,
+ audioDevices: audioDevices,
+ activeAudioDevices: activeAudioDevices
};
-}
-
-Service.__defineGetter__("TYPE_EMAIL", function () {
- return 0;
-});
-
-Service.__defineGetter__("TYPE_CALENDAR", function () {
- return 1;
-});
-
-Service.__defineGetter__("TYPE_CONTACT", function () {
- return 2;
-});
-
-module.exports = Service;
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/identity/Transport', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/MicrophoneAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-function Transport(name, type) {
- this.__defineGetter__("name", function () {
- return name || "";
- });
- this.__defineGetter__("type", function () {
- return type || "";
- });
-}
-
-module.exports = Transport;
+module.exports = function (type, freqRangeLow, freqRangeHigh, info, name, types) {
+ return {
+ type: type,
+ freqRangeLow: freqRangeLow,
+ freqRangeHigh: freqRangeHigh,
+ info: info,
+ name: name,
+ types: types
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/identity/phone', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ContactName', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/identity/phone/",
- _self;
-
-_self = {
- getLineIds: function () {
- return transport.call(_uri + "getLineIds");
- },
- getLineLabel: function (id) {
- return transport.call(_uri + "getLineLabel", {get: {id: id}});
- },
- getLineNumber: function (id) {
- return transport.call(_uri + "getLineNumber", {get: {id: id}});
- },
- getLineType: function (id) {
- return transport.call(_uri + "getLineType", {get: {id: id}});
- }
+module.exports = function (formatted, familyName, givenName, middleName, honorificPrefix, honorificSuffix) {
+ return {
+ formatted: formatted,
+ familyName: familyName,
+ givenName: givenName,
+ middleName: middleName,
+ honorificPrefix: honorificPrefix,
+ honorificSuffix: honorificSuffix
+ };
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/identity', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/StorageUnitAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/identity/",
- _self;
-
-_self = {
- getDefaultService: function () {
- return transport.call(_uri + "getDefaultService");
- },
- getServiceList: function () {
- return transport.call(_uri + "getServiceList");
- },
- getTransportList: function () {
- return transport.call(_uri + "getTransportList");
- }
+module.exports = function (info, id, type, isWritable, capacity, availableCapacity, isRemoveable) {
+ return {
+ info: info,
+ id: id,
+ type: type,
+ isWritable: isWritable,
+ capacity: capacity,
+ availableCapacity: availableCapacity,
+ isRemoveable: isRemoveable
+ };
};
-_self.__defineGetter__("IMEI", function () {
- return transport.call(_uri + "IMEI");
-});
-
-_self.__defineGetter__("IMSI", function () {
- return transport.call(_uri + "IMSI");
-});
-
-_self.__defineGetter__("PIN", function () {
- return transport.call(_uri + "PIN");
-});
-
-module.exports = _self;
-
-});
-define('ripple/platform/webworks.handset/2.0.0/client/invoke', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var _uri = "blackberry/invoke/invoke",\r
- APP_URL_CAMERA = "camera://",\r
- APP_URL_CAMERA_VIDEO = "camera://video",\r
- APP_URL_MAP = "map://",\r
- APP_URL_MUSIC = "music://",\r
- APP_URL_PHOTOS = "photos://",\r
- APP_URL_VIDEOS = "videos://",\r
- APP_URL_APPWORLD = "appworld://",\r
- APP_URL_UPDATE = "update://",\r
- APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",\r
- APP_ADDRESSBOOK_ERROR = "Invalid arguments specified",\r
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
- _self;\r
-\r
-_self = {\r
- invoke: function (appType, args) {\r
- var get = {};\r
-\r
- switch (appType) {\r
-\r
- //AddressBook\r
- case 0:\r
- if (args) {\r
- if (args.view === 1 && args.contact) {\r
- throw APP_ADDRESSBOOK_ERROR; //contact cannot be used with this view\r
- }\r
- else if (args.view === 2 && !args.contact) {\r
- throw APP_ADDRESSBOOK_ERROR; //need contact for this view\r
- }\r
- }\r
-\r
- get.appType = appType;\r
- break;\r
-\r
- //Bluetooth Config\r
- case 1:\r
- get.appType = appType;\r
- break;\r
-\r
- //Calculator\r
- case 2:\r
- get.appType = appType;\r
- break;\r
-\r
- //Calendar\r
- case 3:\r
- get.appType = appType;\r
- break;\r
-\r
- //Camera\r
- case 4:\r
- if (!args || args.view === 1) {\r
- get.appType = APP_URL_CAMERA_VIDEO;\r
- } else {\r
- get.appType = APP_URL_CAMERA;\r
- }\r
- break;\r
-\r
- //Maps\r
- case 5:\r
- get.appType = APP_URL_MAP;\r
- break;\r
-\r
- //Memopad\r
- case 6:\r
- get.appType = appType;\r
- break;\r
-\r
- //Messages\r
- case 7:\r
- get.appType = appType;\r
- break;\r
-\r
- //Phone\r
- case 8:\r
- get.appType = appType;\r
- break;\r
-\r
- //Search\r
- case 9:\r
- get.appType = appType;\r
- break;\r
-\r
- //Tasks\r
- case 10:\r
- get.appType = appType;\r
- break;\r
-\r
- //Browser\r
- case 11:\r
-\r
- if (!args) {\r
- get.appType = "http://";\r
- } else {\r
- if (args.url && !args.url.match(/^https?:\/\//)) {\r
- throw APP_BROWSER_ERROR;\r
- }\r
- get.appType = args.url;\r
- }\r
-\r
- break;\r
-\r
- //Java\r
- case 12:\r
- get.appType = appType;\r
- break;\r
-\r
- default:\r
- throw "appType not supported";\r
- }\r
-\r
- transport.call(_uri, {\r
- get: get,\r
- async: true\r
- });\r
- }\r
-};\r
-\r
-_self.__defineGetter__("APP_ADDRESSBOOK", function () {\r
- return 0;\r
-});\r
-_self.__defineGetter__("APP_BLUETOOTH_CONFIG", function () {\r
- return 1;\r
-});\r
-_self.__defineGetter__("APP_CALCULATOR", function () {\r
- return 2;\r
-});\r
-_self.__defineGetter__("APP_CALENDAR", function () {\r
- return 3;\r
-});\r
-_self.__defineGetter__("APP_CAMERA", function () {\r
- return 4;\r
-});\r
-_self.__defineGetter__("APP_MAPS", function () {\r
- return 5;\r
-});\r
-_self.__defineGetter__("APP_MEMOPAD", function () {\r
- return 6;\r
-});\r
-_self.__defineGetter__("APP_MESSAGES", function () {\r
- return 7;\r
-});\r
-_self.__defineGetter__("APP_PHONE", function () {\r
- return 8;\r
-});\r
-_self.__defineGetter__("APP_SEARCH", function () {\r
- return 9;\r
-});\r
-_self.__defineGetter__("APP_TASKS", function () {\r
- return 10;\r
-});\r
-_self.__defineGetter__("APP_BROWSER", function () {\r
- return 11;\r
-});\r
-_self.__defineGetter__("APP_JAVA", function () {\r
- return 12;\r
-});\r
-\r
-module.exports = _self;\r
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/io/dir', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/Acceleration', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
- utils = require('ripple/utils'),
- _uri = "blackberry/io/dir/",
- FILE = "file://",
- _self = {};
-
-function _prunePrefix(path) {
- return path.replace(new RegExp("^" + FILE), '');
-}
-
-utils.mixin({
- getFreeSpaceForRoot: function (path) {
- return transport.call(_uri + "getFreeSpaceForRoot", {
- post: {path: _prunePrefix(path)}
- });
- },
- getRootDirs: function () {
- return transport.call(_uri + "getRootDirs", {}).map(function (dir) {
- return FILE + dir;
- });
- }
-}, _self);
-
-utils.mixin(dir, _self);
-
-module.exports = _self;
+module.exports = function (x, y, z) {
+ return {
+ x: x || 0,
+ y: y || 0,
+ z: z || 0,
+ timestamp: new Date().getTime()
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/menu', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/accelerometer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- MenuItem = require('ripple/platform/webworks.handset/2.0.0/client/MenuItem'),
+var Acceleration = require('ripple/platform/phonegap/1.0.0/Acceleration'),
utils = require('ripple/utils'),
- onSelect,
- _items = {},
- _uri = "blackberry/ui/menu/",
- _self;
-
-_self = {
- addMenuItem: function (menuItem) {
- _items[menuItem.id] = menuItem;
-
- transport.call(_uri + "addMenuItem", {
- get: {"item": menuItem}
- });
-
- if (utils.count(_items) === 1) {
- transport.poll(_uri + "onSelect", {}, function (response) {
- var item = _items[response];
+ event = require('ripple/event'),
+ _accelerometerInfo = new Acceleration(),
+ _watches = {},
+ self;
- if (item && item.callback) {
- item.callback();
- }
+module.exports = self = {
+ getCurrentAcceleration: function (onSuccess, onError) {
+ // TODO: implement error call if accelerometer is not available, to be driven by behaviours?
- return !!utils.count(_items);
- });
+ if (typeof onSuccess === "function") {
+ setTimeout(function () {
+ // TODO: build facility to trigger onError() from emulator
+ // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
+ onSuccess(utils.copy(_accelerometerInfo));
+ }, 1);
}
- },
- clearMenuItems: function () {
- _items = {};
- transport.call(_uri + "clearMenuItems");
},
- getMenuItems: function () {
- return utils.map(_items, function (item) {
- var menuItem = new MenuItem(item.isSeparator, item.ordinal, item.caption, item.callback);
- menuItem.id = item.id;
- menuItem.isDefault = item.isDefault;
- return menuItem;
- });
- },
+ watchAcceleration: function (accelerometerSuccess, accelerometerError, accelerometerOptions) {
+ var watchId = (new Date()).getTime().toString(),
+ watchObj = {};
- hasMenuItem: function (menuItem) {
- return !!_items[menuItem.id];
- },
- open: function () {
- transport.call(_uri + "open", {async: true});
- },
+ if (accelerometerOptions &&
+ accelerometerOptions.frequency && typeof
+ accelerometerOptions.frequency === "number" &&
+ accelerometerOptions.frequency === Math.floor(accelerometerOptions.frequency)) {
- removeMenuItem: function (menuItem) {
- delete _items[menuItem.id];
- transport.call(_uri + "removeMenuItem", {
- get: {item: menuItem}
- });
- },
+ watchObj = {
+ onSuccess: accelerometerSuccess,
+ onError: accelerometerError,
+ interval: accelerometerOptions.frequency
+ };
- setDefaultMenuItem: function (menuItem) {
- utils.forEach(_items, function (item) {
- item.isDefault = false;
- });
+ _watches[watchId] = watchObj;
- _items[menuItem.id].isDefault = true;
+ _watches[watchId].intervalId = setInterval(function () {
+ self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
+ }, accelerometerOptions.frequency);
- transport.call(_uri + "setDefaultMenuItem", {
- get: {id: menuItem.id}
- });
+ }
+ else {
+ if (typeof accelerometerError === "function") {
+ setTimeout(function () {
+ accelerometerError();
+ }, 1);
+ }
+ }
+
+ return watchId;
+ },
+
+ clearWatch: function (watchId) {
+ clearInterval(_watches[watchId].intervalId);
}
};
-module.exports = _self;
+event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
+ _accelerometerInfo.x = accelerometerInfo.accelerationIncludingGravity.x / 9.8;
+ _accelerometerInfo.y = accelerometerInfo.accelerationIncludingGravity.y / 9.8;
+ _accelerometerInfo.z = accelerometerInfo.accelerationIncludingGravity.z / 9.8;
+ _accelerometerInfo.timestamp = (new Date()).getTime();
+});
});
-define('ripple/platform/webworks.handset/2.0.0/client/messaging', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/ConnectionAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {};
+module.exports = function (info, id, type, currentOrientation, currentUploadBandwidth, maxDownloadBandwidth, maxUploadBandwidth, currentSignalStrength, roaming) {
+ return {
+ info: info,
+ id: id,
+ type: type,
+ currentDownloadBandwidth: currentOrientation,
+ currentUploadBandwidth: currentUploadBandwidth,
+ maxDownloadBandwidth: maxDownloadBandwidth,
+ maxUploadBandwidth: maxUploadBandwidth,
+ currentSignalStrength: currentSignalStrength,
+ roaming: roaming
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/pim', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/PowerAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {};
+module.exports = function (info, id, level, timeRemaining, isBattery, isCharging) {
+ return {
+ info: info,
+ id: id,
+ level: level,
+ timeRemaining: timeRemaining,
+ isBattery: isBattery,
+ isCharging: isCharging
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/client/push', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/sms', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _self,
- _uri = "blackberry/push/onPush",
- callbacks = {},
- PushData = require('ripple/platform/webworks.handset/2.0.0/client/PushData');
-
-_self = {
- openPushListener: function (callback, port, bbTransport, maxQueueCap) {
- callbacks["onPush" + port] = callback;
-
- transport.poll(_uri, {
- get: {
- port: port,
- bbTransport: bbTransport,
- maxQueueCap: maxQueueCap
- }
- }, function (response) {
- var func = callbacks["onPush" + port];
-
- if (func) {
- func(new PushData(response, port));
- }
-
- return !!func;
- });
- },
-
- closePushListener: function (port) {
- delete callbacks["onPush" + port];
+module.exports = {
+ send: function () {
+ throw "not implemented";
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/sms', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/service', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/message/sms/",
- onReceive,
- _self;
-
-_self = {
- addReceiveListener: function (callback) {
- onReceive = callback;
- transport.poll(_uri + "onReceive", {}, function (response) {
- if (onReceive) {
- onReceive(response.body, response.from, response.time);
- }
- return !!onReceive;
- });
- },
-
- removeReceiveListener: function () {
- if (onReceive) {
- onReceive = null;
- return true;
- }
-
- return false;
- },
-
- send: function (message, address) {
- transport.call(_uri + "send", {
- get: {
- message: message,
- address: address
- },
- async: true
- });
- }
-};
-
-_self.__defineGetter__("isListeningForMessage", function () {
- return transport.call(_uri + "isListeningForMessage", {async: false});
-});
-
-_self.__defineSetter__("isListeningForMessage", function (value) {
- transport.call(_uri + "isListeningForMessage", {
- async: false,
- get: {isListeningForMessage: value}
- });
-});
-
-module.exports = _self;
+// for form, but could probably just delete
+module.exports = {};
});
-define('ripple/platform/webworks.handset/2.0.0/client/system', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/PrintingDeviceAttributes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- system = require('ripple/platform/webworks.core/2.0.0/client/system'),
- _uri = "blackberry/system/",
- _self;
-
-_self = {
- setHomeScreenBackground: function (filePath) {
- transport.call(_uri + "setHomeScreenBackground", {
- get: {filePath: filePath},
- async: true
- });
- },
+module.exports = function (type, resolution, color, info) {
+ return {
+ type: type,
+ resolution: resolution,
+ color: color,
+ info: info
+ };
};
-(function () {
- // HACK: can't type check if system[key] is a function, sets off getters
- // also can't use utils.mixin or forEach for the same reason
- function get(i) {
- return function () {
- return system[i];
- };
- }
-
- for (var key in system) {
- if (system.hasOwnProperty(key)) {
- _self.__defineGetter__(key, get(key));
- }
- }
-}());
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/client/systemEvent', function (require, exports, module) {
+define('ripple/platform/phonegap/1.0.0/Contact', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- utils = require('ripple/utils'),
- _self,
- _callbacks = {};
-
-function _poll(evt, args, callback) {
- _callbacks[evt + args.key] = callback;
-
- transport.poll("blackberry/system/event/" + evt, {get: args}, function () {
- var func = _callbacks[evt + args.key];
+var utils = require('ripple/utils'),
+ event = require('ripple/event');
- if (func) {
- func();
+function _properties(obj) {
+ var prop, newObj = {};
+ for (prop in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
+ if (typeof obj[prop] !== "function") {
+ newObj[prop] = utils.copy(obj[prop]);
+ }
}
-
- return !!func;
- });
+ }
+ return newObj;
}
-_self = {
- onCoverageChange: function (callback) {
- _poll("onCoverageChange", {}, callback);
- },
+module.exports = function (
+ id,
+ displayName,
+ name,
+ nickname,
+ phoneNumbers,
+ emails,
+ addresses,
+ ims,
+ organizations,
+ birthday,
+ note,
+ photos,
+ categories,
+ urls
+) {
- onHardwareKey: function (key, callback) {
- _poll("onHardwareKey", {key: key}, callback);
- }
-};
+ return {
+ id: id || Math.uuid(undefined, 16),
+ displayName: displayName || null,
+ name: name || null,
+ nickname: nickname || null,
+ phoneNumbers: phoneNumbers || null,
+ emails: emails || null,
+ addresses: addresses || null,
+ ims: ims || null,
+ organizations: organizations || null,
+ birthday: birthday || null,
+ note: note || null,
+ photos: photos || null,
+ categories: categories || null,
+ urls: urls || null,
+ save: function (success, error) {
+ var _self = this,
+ lastUpdated = this.updated; // hackish
-_self.__defineGetter__("KEY_BACK", function () {
- return 0;
-});
-_self.__defineGetter__("KEY_MENU", function () {
- return 1;
-});
-_self.__defineGetter__("KEY_CONVENIENCE_1", function () {
- return 2;
-});
-_self.__defineGetter__("KEY_CONVENIENCE_2", function () {
- return 3;
-});
-_self.__defineGetter__("KEY_STARTCALL", function () {
- return 4;
-});
-_self.__defineGetter__("KEY_ENDCALL", function () {
- return 5;
-});
-_self.__defineGetter__("KEY_VOLUMEDOWN", function () {
- return 6;
-});
-_self.__defineGetter__("KEY_VOLUMEUP", function () {
- return 7;
-});
+ this.updated = new Date();
-module.exports = _self;
+ if (!this.id) {
+ this.id = Math.uuid(undefined, 16);
+ }
+
+ event.trigger("phonegap-contact-save", [_properties(this), success, function (e) {
+ _self.updated = lastUpdated;
+ error(e);
+ }]);
+ },
+ remove: function (success, error) {
+ event.trigger("phonegap-contact-remove", [this.id, success, error]);
+ },
+ clone: function () {
+ var copy = utils.copy(this);
+ copy.id = null;
+ return copy;
+ }
+ };
+};
});
-define('ripple/platform/webworks.handset/2.0.0/server/Task', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/spec', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var select = require('ripple/platform/webworks.core/2.0.0/select'),
- db = require('ripple/db'),
- utils = require('ripple/utils'),
- _KEY = "blackberry-pim-task",
- _self;
-
-function _get() {
- return db.retrieveObject(_KEY) || {};
-}
-
-function _save(tasks) {
- db.saveObject(_KEY, tasks);
-}
-
-_self = {
- save: function (get, post) {
- var tasks = _get(),
- properties = post.task,
- id = properties.uid;
-
- if (tasks[id]) {
- utils.mixin(properties, tasks[id]);
- } else {
- tasks[id] = properties;
- }
-
- _save(tasks);
+module.exports = {
- return {code: 1};
- },
+ id: "webworks.bb10",
+ version: "1.0.0",
+ name: "BlackBerry 10 WebWorks",
- remove: function (get, post) {
- var tasks = _get(),
- id = get.id;
+ persistencePrefix: "rim-bb10-",
- delete tasks[id];
+ ui: require('ripple/platform/webworks.bb10/1.0.0/spec/ui'),
+ device: require('ripple/platform/webworks.bb10/1.0.0/spec/device'),
+ config: require('ripple/platform/webworks.bb10/1.0.0/spec/config'),
+ events: require('ripple/platform/webworks.bb10/1.0.0/spec/events'),
- _save(tasks);
+ initialize: function () {
+ var event = require('ripple/event'),
+ _console = require('ripple/console'),
+ emulatorBridge = require('ripple/emulatorBridge');
- return {code: 1};
+ event.on("TinyHipposLoaded", function () {
+ var doc = emulatorBridge.document(),
+ evt = doc.createEvent("Events");
+ evt.initEvent("webworksready", true, true);
+ doc.dispatchEvent(evt);
+ _console.log("fired webworksready event!");
+ });
},
- find: function (get, post) {
- var tasks = _get(),
- match = select.from(tasks);
-
- if (post.orderBy) {
- match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
- }
-
- if (post.maxReturn) {
- match.max(post.maxReturn);
+ objects: {
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ navigator: {
+ path: "webworks.bb10/1.0.0/navigator",
+ children: {
+ geolocation: {
+ path: "w3c/1.0/geolocation"
+ }
+ }
+ },
+ blackberry: {
+ children: {
+ event: {
+ path: "webworks.bb10/1.0.0/event"
+ },
+ app: {
+ path: "webworks.bb10/1.0.0/app",
+ feature: "blackberry.app"
+ },
+ invoke: {
+ path: "webworks.bb10/1.0.0/invoke",
+ feature: "blackberry.invoke"
+ },
+ identity: {
+ path: "webworks.bb10/1.0.0/identity",
+ feature: "blackberry.identity"
+ },
+ system: {
+ path: "webworks.bb10/1.0.0/system"
+ },
+ connection: {
+ path: "webworks.bb10/1.0.0/connection"
+ },
+ ui: {
+ children: {
+ dialog: {
+ path: "webworks.bb10/1.0.0/dialog",
+ feature: "blackberry.ui.dialog"
+ }
+ }
+ },
+ }
}
-
- return {code: 1, data: match.where(post.filter)};
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/app', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/connection', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- app = require('ripple/app'),
- notifications = require('ripple/notifications'),
- constants = require('ripple/constants'),
- ui = require('ripple/ui'),
- _isForeground = true,
- _self;
-
-_self = {
- event: require('ripple/platform/webworks.handset/2.0.0/server/appEvent'),
+var deviceSettings = require('ripple/deviceSettings'),
+ _self = {};
- exit: function () {
- event.trigger("AppExit");
- return {code: 1};
- },
+_self.__defineGetter__("type", function () {
+ return deviceSettings.retrieve("NetworkStatus.connectionType");
+});
- author: function () {
- return {code: 1, data: app.getInfo().author};
- },
+_self.__defineGetter__("UNKNOWN", function () { return "unknown"; });
+_self.__defineGetter__("ETHERNET", function () { return "ethernet"; });
+_self.__defineGetter__("WIFI", function () { return "wifi"; });
+_self.__defineGetter__("BLUETOOTH_DUN", function () { return "bluetooth_dun"; });
+_self.__defineGetter__("USB", function () { return "usb"; });
+_self.__defineGetter__("VPN", function () { return "vpn"; });
+_self.__defineGetter__("BB", function () { return "rim-bb"; });
+_self.__defineGetter__("CELL_2G", function () { return "2g"; });
+_self.__defineGetter__("CELL_3G", function () { return "3g"; });
+_self.__defineGetter__("CELL_4G", function () { return "4g"; });
+_self.__defineGetter__("NONE", function () { return "none"; });
- authorEmail: function () {
- return {code: 1, data: app.getInfo().authorEmail};
- },
+module.exports = _self;
- authorURL: function () {
- return {code: 1, data: app.getInfo().authorURL};
- },
+});
+define('ripple/platform/webworks.bb10/1.0.0/event', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- copyright: function () {
- return {code: 1, data: app.getInfo().copyright};
- },
+var event = require('ripple/event'),
+ settings = require('ripple/deviceSettings'),
+ app = require('ripple/app'),
+ cons = require('ripple/console'),
+ utils = require('ripple/utils'),
+ events = {
+ batterystatus: {
+ callbacks: [],
+ feature: 'blackberry.system'
+ },
+ batterylow: {
+ callbacks: [],
+ feature: 'blackberry.system'
+ },
+ batterycritical: {
+ callbacks: [],
+ feature: 'blackberry.system'
+ },
+ connectionchange: {
+ callbacks: [],
+ feature: 'blackberry.connection'
+ },
+ invoked: {
+ callbacks: [],
+ feature: 'blackberry.invoked'
+ },
+ swipedown: {
+ callbacks: [],
+ feature: 'blackberry.app'
+ },
+ resume: {
+ callbacks: [],
+ feature: 'blackberry.app'
+ },
+ pause: {
+ callbacks: [],
+ feature: 'blackberry.app'
+ },
+ languagechange: {
+ callbacks: [],
+ feature: "blackberry.system"
+ },
+ regionchange: {
+ callbacks: [],
+ feature: "blackberry.system"
+ }
+ };
- description: function () {
- return {code: 1, data: app.getInfo().description};
- },
+function _apply(eventName, args) {
+ events[eventName].callbacks.forEach(function (cb) {
+ cb.apply(null, args);
+ });
+}
- isForeground: function () {
- return {code: 1, data: _isForeground};
- },
+event.on('DeviceBatteryStateChanged', function (charging) {
+ var info = {
+ isPlugged: charging,
+ level: parseInt(settings.retrieve('battery.level'), 10)
+ };
- id: function () {
- return {code: 1, data: app.getInfo().id};
- },
+ _apply('batterystatus', [info]);
+});
- license: function () {
- return {code: 1, data: app.getInfo().license};
- },
+event.on('DeviceBatteryLevelChanged', function (level) {
+ var info = {
+ isPlugged: settings.retrieve('battery.state'),
+ level: parseInt(level, 10)
+ };
- licenseURL: function () {
- return {code: 1, data: app.getInfo().licenseURL};
- },
+ _apply('batterystatus', [info]);
+
+ if (level === '14') {
+ _apply('batterylow', [info]);
+ }
- name: function () {
- return {code: 1, data: app.getInfo().name};
- },
+ if (level === '4') {
+ _apply('batterycritical', [info]);
+ }
+});
- version: function () {
- return {code: 1, data: app.getInfo().version};
- },
+event.on('DeviceConnectionChanged', function (info) {
+ _apply('connectionchange', [info]);
+});
- requestBackground: function () {
- ui.showOverlay("background-window", function (background) {
- var button = background.children["background-return"];
+event.on("LanguageChanged", function (lang) {
+ _apply("languagechange", [lang]);
+});
- if (button) {
- button.addEventListener("click", _self.requestForeground);
- }
- _isForeground = false;
- event.trigger("AppRequestBackground");
- });
+event.on("RegionChanged", function (lang) {
+ _apply("regionchange", [lang]);
+});
- return {code: 1};
- },
+event.on("AppInvoke", function (invokeInfo) {
+ var invokeTargets = app.getInfo().invokeTargets;
- requestForeground: function () {
- ui.hideOverlay("background-window", function (background) {
- var button = background.children["background-return"];
+ if (!invokeTargets) {
+ cons.log("The application cannot be invoked, please add a rim:invoke-target node in config.xml");
+ return;
+ }
- if (button) {
- button.removeEventListener("click", _self.requestForeground);
- }
- _isForeground = true;
- event.trigger("AppRequestForeground");
+ if (invokeTargets.some(function (target) {
+ return target.filter.some(function (filter) {
+ return (
+ (!filter.property ||
+ (filter.property && filter.property[0]["@attributes"].var === "exts" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
+ return invokeInfo.extension.match(value);
+ })) ||
+ (filter.property && filter.property[0]["@attributes"].var === "uris" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
+ return invokeInfo.uri.match(value);
+ }))) &&
+ filter.action.some(function (action) {
+ return invokeInfo.action.match(action["#text"][0].replace("*", ""));
+ }) &&
+ filter["mime-type"].some(function (type) {
+ return invokeInfo.type.match(type["#text"][0].replace("*", ""));
+ })
+ );
});
+ })) {
+ _apply('invoked', [invokeInfo]);
+ }
+ else {
+ cons.log("Cannot invoke application, values enter to not match values in rim:invoke-target in config.xml");
+ }
+});
- return {code: 1};
- },
+event.on('AppSwipeDown', function () {
+ _apply('swipedown');
+});
- setHomeScreenIcon: function (args) {
- if (args.uri) {
- var msg = "The application set the home screen" +
- (args.hover ? " hover " : " ") +
- "icon to " + args.uri;
+event.on('AppResume', function () {
+ _apply('resume');
+});
- notifications.openNotification("normal", msg);
- return {code: 1};
- }
- else {
- return {code: 0};
- }
- },
+event.on('AppPause', function () {
+ _apply('pause');
+});
- setHomeScreenName: function (args) {
- if (args.text) {
- var msg = "The application set the home screen name to " + args.text;
- notifications.openNotification("normal", msg);
- return {code: 1};
+module.exports = {
+ addEventListener: function (type, func) {
+ this.removeEventListener(type, func);
+
+ if (!app.getInfo().features || app.getInfo().features[events[type].feature]) {
+ events[type].callbacks.push(func);
}
else {
- return {code: 1};
+ throw ("Cannot register a hanlder for the " + type + " event. Please add the '" +
+ events[type].feature + "' to your config.xml.");
}
},
- removeBannerIndicator: function () {
- event.trigger("BannerUpdated", ["", 0]);
- return {code: 1};
- },
-
- showBannerIndicator: function (args) {
- event.trigger("BannerUpdated", [args.icon, args.count]);
- return {code: 1};
- },
-
+ removeEventListener: function (type, func) {
+ var idx = events[type].callbacks.indexOf(func);
+ if (idx >= 0) {
+ delete events[type].callbacks[idx];
+ }
+ }
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/appEvent', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/navigator', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- notifications = require('ripple/notifications'),
- _bg,
- _fg,
- _exit;
-
-event.on("AppRequestBackground", function () {
- var baton = _bg;
- _bg = null;
- return baton && baton.pass({code: 1});
-});
+var nav = require('ripple/platform/w3c/1.0/navigator'),
+ utils = require('ripple/utils'),
+ deviceSettings = require('ripple/deviceSettings'),
+ _self = {};
-event.on("AppRequestForeground", function () {
- var baton = _fg;
- _fg = null;
- return baton && baton.pass({code: 1});
-});
+utils.mixin(nav, _self);
-event.on("AppExit", function () {
- var baton = _exit;
- _exit = null;
- notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
- return baton && baton.pass({code: 1});
+_self.__defineGetter__("language", function () {
+ return deviceSettings.retrieve("system.language");
});
-module.exports = {
- onBackground: function (get, post, baton) {
- baton.take();
- _bg = baton;
- return {code: 1};
- },
-
- onForeground: function (get, post, baton) {
- baton.take();
- _fg = baton;
- return {code: 1};
- },
-
- onExit: function (get, post, baton) {
- baton.take();
- _exit = baton;
- return {code: 1};
- }
-};
+module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/appointment', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- select = require('ripple/platform/webworks.core/2.0.0/select'),
- _self;
-
-function _get() {
- return db.retrieveObject("webworks-pim-appointment-list") || {};
-}
-
-function _do(func) {
- var appointments = _get();
- func(appointments);
- db.saveObject("webworks-pim-appointment-list", appointments);
-}
-
-_self = {
- find: function (get, post) {
- var appointments = _get(),
- data = select.from(appointments)
- .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
- .max(post.maxReturn)
- .where(post.filter);
-
- return {code: 1, data: data};
- },
-
- remove: function (get) {
- _do(function (appointments) {
- if (!appointments[get.uid]) {
- throw "attempting to delete a non existant appointment with uid: " + get.uid;
- }
- delete appointments[get.uid];
- });
-
- return {code: 1};
- },
-
- save: function (get, post) {
- _do(function (appointments) {
- appointments[post.appointment.uid] = post.appointment;
- });
+var devices = require('ripple/devices'),
+ _self = {};
- return {code: 1};
- }
-};
+_self.__defineGetter__("softwareVersion", function () {
+ return devices.getCurrentDevice().osVersion;
+});
+_self.__defineGetter__("hardwareId", function () {
+ return devices.getCurrentDevice().hardwareId;
+});
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/audioPlayer', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/spec/config', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//create my dom collection node in UI
-
-var utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- notifications = require('ripple/notifications'),
- Player = require('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer'),
- _handlers = {
- loadstart: {},
- canplaythrough: {},
- durationchange: {},
- ended: {},
- error: {},
- play: {},
- pause: {},
- volumechange: {},
- close: {}
- },
- extract = {
- time: function (audio) {
- return audio.currentTime;
- },
- duration: function (audio) {
- return audio.duration;
- },
- error: function (audio) {
- return audio.error;
- },
- nothing: function (audio) {
- return null;
- }
- },
- container;
-
-container = utils.createElement("section", {
- id: "webworks-audio-players"
-});
-
-document.getElementById("ui").appendChild(container);
-
-function _errClosed(method) {
- notifications.openNotification("error",
- "attempted to call " + method + " on a player that is already closed. This is a very bad thing to do :)");
- return false;
-}
-
-function _removeHandler(type, id) {
- var audio = document.getElementById(id);
-
- if (audio && _handlers[type][id]) {
- audio.removeEventListener(type, _handlers[type][id]);
- delete _handlers[type][id];
- }
-}
-
-function _addHandler(type, id, callback) {
- var audio = document.getElementById(id);
-
- if (audio) {
- _removeHandler(type, id);
- audio.addEventListener(type, callback);
- _handlers[type][id] = callback;
- }
-}
-
-function proxyEvent(from, map) {
- var audio = document.getElementById(map.id);
-
- if (audio) {
- map.baton.take();
- _addHandler(from, map.id, function () {
- _removeHandler(from, map.id);
- map.baton.pass({code: 1, data: {
- event: map.target,
- eventData: map.data(this)
- }});
- });
- }
- else {
- return {code: -1, data: {event: "EVENT_ERROR", eventData: 5}};
- }
-}
+var utils = require('ripple/utils');
module.exports = {
-
- create: function (args) {
- var id = Math.uuid(),
- audio = utils.createElement("audio", {
- id: id
- });
-
- audio.setAttribute("src", args.locator);
-
- if (args.type) {
- audio.setAttribute("type", args.type);
- }
-
- container.appendChild(audio);
- audio.load();
-
- if (audio.error) {
- throw "there was a problem opening the audio file";
- }
-
- return {code: 1, data: id};
+ fileName: "config.xml",
+ validateVersion: function (config) {
+ return true;
},
-
- play: function (args) {
- var audio = document.getElementById(args.id),
- playing;
-
- if (audio) {
- audio.play();
- audio.rimState = Player.STARTED;
- playing = !!!audio.error;
- }
- else {
- playing = _errClosed("play");
+ extractInfo: function (config) {
+ if (!config) {
+ return null;
}
- return {code: 1, data: playing};
- },
-
- pause: function (args) {
- var audio = document.getElementById(args.id),
- paused;
+ var widgetInfo = {},
+ widgetFeatures = config.widget.children.feature.validationResult,
+ accessUrls = config.widget.children.access.validationResult,
+ invokeTargets = config.rawJSON.widget[0]["rim:invoke-target"],
+ accessFeatures = config.widget.children.access.children.feature.validationResult,
+ toFeature = function (validationResult) {
+ return {
+ id: validationResult.attributes.id.value,
+ required: !validationResult.attributes.required || validationResult.attributes.required.value,
+ URIs: []
+ };
+ };
- if (audio) {
- audio.pause();
- paused = !!!audio.error;
- } else {
- paused = _errClosed("pause");
+ widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
+ widgetInfo.name = config.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
+ widgetInfo.author = config.widget.children.author.validationResult[0].value;
+ widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
+ widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
+ widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
+ widgetInfo.description = config.widget.children.description.validationResult[0].value;
+ widgetInfo.invokeTargets = invokeTargets;
+ if (config.widget.children.license.validationResult[0]) {
+ widgetInfo.license = config.widget.children.license.validationResult[0].value;
+ widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
}
- return {code: 1, data: paused};
- },
-
- close: function (args) {
- var audio = document.getElementById(args.id),
- callback = _handlers["close"][args.id],
- closed = true;
-
- if (audio) {
- if (callback) {
- callback();
+ widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
+ if (validationResult.valid) {
+ var feature = toFeature(validationResult);
+ feature.URIs.push({
+ value: utils.location().href,
+ subdomains: true
+ });
+ features = features || {};
+ features[feature.id] = feature;
}
- container.removeChild(audio);
- }
- else {
- closed = _errClosed("close");
- }
-
- return {code: 1, data: closed};
- },
-
- onStart: function (args, post, baton) {
- return proxyEvent("play", {
- id: args.id,
- baton: baton,
- target: "EVENT_START",
- data: extract.time
- });
- },
-
- onStopped: function (args, post, baton) {
- return proxyEvent("pause", {
- id: args.id,
- baton: baton,
- target: "EVENT_STOPPED",
- data: extract.time
- });
- },
-
- onBufferingStarted: function (args, post, baton) {
- return proxyEvent("loadstart", {
- id: args.id,
- baton: baton,
- target: "EVENT_BUFFERING_STARTED",
- data: extract.time
- });
- },
-
- onBufferingStopped: function (args, post, baton) {
- return proxyEvent("canplaythrough", {
- id: args.id,
- baton: baton,
- target: "EVENT_BUFFERING_STOPPED",
- data: extract.time
- });
- },
-
- onDurationUpdated: function (args, post, baton) {
- return proxyEvent("durationchange", {
- id: args.id,
- baton: baton,
- target: "EVENT_DURATION_UPDATED",
- data: extract.duration
- });
- },
-
- onEnd: function (args, post, baton) {
- return proxyEvent("ended", {
- id: args.id,
- baton: baton,
- target: "EVENT_END_OF_MEDIA",
- data: extract.duration
- });
- },
-
- onError: function (args, post, baton) {
- return proxyEvent("error", {
- id: args.id,
- baton: baton,
- target: "EVENT_ERROR",
- data: extract.error
- });
- },
+ return features;
+ }, {});
- onVolumeChange: function (args, post, baton) {
- return proxyEvent("volumechange", {
- id: args.id,
- baton: baton,
- target: "EVENT_VOLUME_CHANGED",
- data: extract.nothing
- });
- },
+ widgetInfo.features = accessUrls.map(function (access) {
+ return {
+ uri: access.attributes.uri.value,
+ subdomains: access.attributes.subdomains.value,
+ features: accessFeatures ? accessFeatures.filter(function (f) {
+ return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
+ }) : null
+ };
+ }).reduce(function (result, access) {
+ return access.features ? access.features.reduce(function (features, validationResult) {
+ var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
+ feature.URIs.push({
+ value: access.uri,
+ subdomains: access.subdomains
+ });
+ features[feature.id] = feature;
+ return features;
+ }, result) : result;
+ }, widgetInfo.features);
- onClose: function (args, post, baton) {
- return proxyEvent("close", {
- id: args.id,
- baton: baton,
- target: "EVENT_CLOSED",
- data: extract.nothing
- });
+ return widgetInfo;
},
-
- getDuration: function (args) {
- var audio = document.getElementById(args.id),
- duration;
-
- if (audio) {
- duration = audio.duration;
- }
- else {
- _errClosed("getDuration");
- duration = -1;
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:rim": {
+ attributeName: "xmlns:rim",
+ required: true,
+ type: "list",
+ listValues: ["http://www.blackberry.com/ns/widgets"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ "rim:header": {
+ attributeName: "rim:header",
+ required: false,
+ type: "string"
+ },
+ "rim:backButton": {
+ attributeName: "rim:backButton",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ "rim:hover": {
+ attributeName: "rim:hover",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "string",
+ required: false
+ },
+ "rim:copyright": {
+ attributeName: "rim:copyright",
+ type: "string",
+ required: false
+ },
+ email: {
+ attributeName: "email",
+ type: "string",
+ required: false
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 1,
+ attributes : {
+ href: {
+ attributeName: "href",
+ type: "string",
+ required: false
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ "rim:cache": {
+ nodeName: "rim:cache",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ disableAllCache: {
+ attributeName: "disableAllCache",
+ required: false,
+ type: "boolean"
+ },
+ aggressiveCacheAge: {
+ attributeName: "aggressiveCacheAge",
+ required: false,
+ type: "number"
+ },
+ maxCacheSizeTotal: {
+ attributeName: "maxCacheSizeTotal",
+ required: false,
+ type: "number"
+ },
+ maxCacheSizeItem: {
+ attributeName: "maxCacheSizeItem",
+ required: false,
+ type: "number"
+ }
+ }
+ },
+ access: {
+ nodeName: "access",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ uri: {
+ attributeName: "uri",
+ required: true,
+ type: "string"
+ },
+ subdomains: {
+ attributeName: "subdomains",
+ required: false,
+ type: "boolean"
+ }
+ },
+ children: {
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ //TODO: this should be a list
+ type: "string"
+ },
+ required: {
+ attributeName: "required",
+ required: false,
+ type: "boolean"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ }
+ }
+ }
+ }
+ },
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ //TODO: this should be a list
+ type: "string"
+ },
+ required: {
+ attributeName: "required",
+ required: false,
+ type: "boolean"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ "rim:loadingScreen": {
+ nodeName: "rim:loadingScreen",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ backgroundColor: {
+ attributeName: "backgroundColor",
+ required: false,
+ type: "string"
+ },
+ backgroundImage: {
+ attributeName: "backgroundImage",
+ required: false,
+ type: "string"
+ },
+ foregroundImage: {
+ attributeName: "foregroundImage",
+ required: false,
+ type: "string"
+ },
+ onRemotePageLoad: {
+ attributeName: "onRemotePageLoad",
+ required: false,
+ type: "boolean"
+ },
+ onLocalPageLoad: {
+ attributeName: "onLocalPageLoad",
+ required : false,
+ type: "boolean"
+ },
+ onFirstLaunch: {
+ attributeName: "onFirstLaunch",
+ required: false,
+ type: "boolean"
+ }
+ },
+ children: {
+ "rim:transitionEffect": {
+ nodeName: "rim:transitionEffect",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "type": {
+ attributeName: "type",
+ required: true,
+ type: "list",
+ listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
+ },
+ duration: {
+ attributeName: "duration",
+ required: false,
+ type: "number"
+ },
+ direction: {
+ attributeName: "direction",
+ required: false,
+ type: "list",
+ listValues: ["left", "right", "up", "down"]
+ }
+ }
+ }
+ }
+ },
+ "rim:invoke-target": {
+ nodeName: "rim:invoke-target",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ }
+ },
+ children: {
+ "type": {
+ nodeName: "type",
+ required: true,
+ occurrence: 1
+ },
+ "require-source-permissions": {
+ nodeName: "require-source-permissions",
+ required: false,
+ occurence: 0
+ },
+ "filter": {
+ nodeName: "filter",
+ required: false,
+ occurence: 0,
+ children: {
+ "action": {
+ nodeName: "action",
+ required: true,
+ occurence: 0
+ },
+ "mime-type": {
+ nodeName: "mime-type",
+ required: true,
+ occurence: 0
+ },
+ "property": {
+ nodeName: "property",
+ required: false,
+ occurenc: 0,
+ attributes: {
+ "var": {
+ attributeName: "var",
+ required: false,
+ type: "string"
+ },
+ "value": {
+ attributeName: "value",
+ required: false,
+ type: "string"
+ }
+ }
+ }
+ },
+ }
+ }
+ },
+ "rim:connection": {
+ nodeName: "rim:connection",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ timeout: {
+ attributeName: "timeout",
+ required: false,
+ type: "number"
+ }
+ },
+ children: {
+ id: {
+ nodeName: "id",
+ required: false,
+ occurrence: 0
+ }
+ }
+ },
+ "rim:navigation": {
+ nodeName: "rim:navigation",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ mode: {
+ attributeName: "mode",
+ required: false,
+ type: "list",
+ listValues: ["focus"]
+ }
+ }
+ },
+ "content": {
+ nodeName: "content",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ type: {
+ attributeName: "type",
+ required: false,
+ type: "string"
+ },
+ charset: {
+ attributeName: "charset",
+ required: false,
+ type: "string"
+ }
+ }
+ }
+ }
}
+ }
+};
- return {code: 1, data: duration};
- },
-
- getMediaTime: function (args) {
- var audio = document.getElementById(args.id),
- time;
+});
+define('ripple/platform/webworks.bb10/1.0.0/spec/device', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event');
- if (audio) {
- time = audio.currentTime;
- }
- else {
- _errClosed("getMediaTime");
- time = -1;
+module.exports = {
+ "NetworkStatus": {
+ "connectionType": {
+ "name": "Connection Type",
+ "control": {
+ "type": "select",
+ "value": "ethernet"
+ },
+ "options": {
+ "unknown": "UNKNOWN",
+ "ethernet": "ETHERNET",
+ "wifi": "WIFI",
+ "bluetooth_dun": "BLUETOOTH_DUN",
+ "usb": "USB",
+ "vpn": "VPN",
+ "rim-bb": "BB",
+ "2g": "CELL_2G",
+ "3g": "CELL_3G",
+ "4g": "CELL_4G",
+ "none": "NONE"
+ },
+ "callback": function (setting, oldSetting) {
+ event.trigger("DeviceConnectionChanged", [{oldType: oldSetting, newType: setting}]);
+ }
}
-
- return {code: 1, data: time};
},
-
- setMediaTime: function (args) {
- var audio = document.getElementById(args.id);
-
- if (audio) {
- audio.currentTime = args.value;
- }
- else {
- _errClosed("setMediaTime");
+ "identity": {
+ "uuid": {
+ "name": "uuid",
+ "control": {
+ "type": "text",
+ "value": "43A8C489"
+ }
}
-
- return {code: 1};
},
-
- getVolumeLevel: function (args) {
- var audio = document.getElementById(args.id),
- level;
-
- if (audio) {
- level = audio.volume * 100;
- }
- else {
- _errClosed("getVolumeLevel");
- level = -1;
+ "system": {
+ "language": {
+ "name": "language",
+ "control": {
+ "type": "text",
+ "value": "en_US"
+ },
+ "callback": function (setting) {
+ event.trigger("LanguageChanged", [setting]);
+ }
+ },
+ "region": {
+ "name": "region",
+ "control": {
+ "type": "text",
+ "value": "en_CA"
+ },
+ "callback": function (setting) {
+ event.trigger("RegionChanged", [setting]);
+ }
}
-
- return {code: 1, data: level};
},
+ "battery": {
+ "state": {
+ "name": "Handset is Charging",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryStateChanged", [setting]);
+ }
+ },
+ "level": {
+ "name": "Charge Level (% remaining)",
+ "control": {
+ "type": "select",
+ "value": 100
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- setVolumeLevel: function (args) {
- var audio = document.getElementById(args.id);
+ for (i = 0; i <= 100; i++) {
+ optionList[i] = i;
+ }
- if (audio) {
- audio.volume = args.value / 100;
- }
- else {
- _errClosed("setVolumeLevel");
+ return optionList;
+ }()),
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryLevelChanged", [setting]);
+ }
}
-
- return {code: 1};
},
-
- getState: function (args) {
- var audio = document.getElementById(args.id),
- state = audio ? audio.rimState || Player.PREFETCHED : Player.CLOSED;
- return {code: 1, data: state};
+ "Perimeters": {
+ "perimeter": {
+ "name": "Perimeter",
+ "control": {
+ "type": "select",
+ "value": "Consumer"
+ },
+ "options": {
+ "Enterprise": "Enterprise",
+ "Consumer": "Consumer"
+ }
+ }
}
};
});
-define('ripple/platform/webworks.handset/2.0.0/server/category', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/spec/events', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- _KEY = "blackberry-pim-category",
- _self;
-
-function _get() {
- return db.retrieveObject(_KEY) || [];
-}
-
-function _save(category) {
- var categories = _get();
- if (!categories.some(function (item) {
- return item === category;
- })) {
- categories.push(category);
- db.saveObject(_KEY, categories);
- }
-}
-
-function _remove(category) {
- var categories = _get(),
- index = categories.indexOf(category);
-
- if (index >= 0) {
- categories.splice(index, 1);
- db.saveObject(_KEY, categories);
- }
-}
+var _self,
+ event = require('ripple/event');
-_self = {
- addCategory: function (args) {
- _save(args.categoryName);
- return {code: 1};
+module.exports = {
+ "blackberry.event.swipedown": {
+ callback: function () {
+ event.trigger("AppSwipeDown");
+ }
},
- deleteCategory: function (args) {
- _remove(args.categoryName);
- return {code: 1};
+ "blackberry.event.resume": {
+ callback: function () {
+ event.trigger("AppResume");
+ }
},
- getCategories: function () {
- return {code: 1, data: _get()};
+ "blackberry.event.pause": {
+ callback: function () {
+ event.trigger("AppPause");
+ }
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/contact', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/spec/ui', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var select = require('ripple/platform/webworks.core/2.0.0/select'),
- db = require('ripple/db'),
- utils = require('ripple/utils'),
- _KEY = "blackberry-pim-contacts",
- _self;
-
-function _defaultContacts() {
- var id1 = Math.uuid(null, 16),
- id2 = Math.uuid(null, 16),
- id3 = Math.uuid(null, 16),
- id4 = Math.uuid(null, 16),
- contacts = {};
-
- contacts[id1] = {
- uuid: id1,
- firstName: "Leonardo",
- homePhone: "4567892345",
- email1: "leo@underground.com"
- };
- contacts[id2] = {
- uuid: id2,
- firstName: "Raphael",
- homePhone: "4563457890",
- email1: "raph@underground.com"
- };
- contacts[id3] = {
- uuid: id3,
- firstName: "Michelangelo",
- homePhone: "4563453425",
- email1: "mike@underground.com"
- };
- contacts[id4] = {
- uuid: id4,
- firstName: "Donatello",
- homePhone: "4563453425",
- email1: "don@undergound.com"
- };
-
- return contacts;
-}
-
-function _get() {
- return db.retrieveObject(_KEY) || _defaultContacts();
-}
-
-function _save(contacts) {
- db.saveObject(_KEY, contacts);
-}
-
-_self = {
- save: function (get, post) {
- var contacts = _get();
-
- contacts[post.contact.uid] = post.contact;
- _save(contacts);
- return {code: 1};
- },
- remove: function (get, post) {
- var contacts = _get(),
- id = get.id;
-
- delete contacts[id];
- _save(contacts);
- return {code: 1};
- },
- find: function (get, post) {
- var contacts = _get(),
- match = select.from(contacts);
-
- if (post.orderBy) {
- match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
- }
+module.exports = {
+ plugins: [
+ "accelerometer",
+ "deviceSettings",
+ "geoView",
+ "platformEvents",
+ "widgetConfig",
+ "build",
+ "invoke"
+ ]
+};
- if (post.maxReturn) {
- match.max(post.maxReturn);
- }
+});
+define('ripple/platform/webworks.bb10/1.0.0/identity', function (require, exports, module) {
+/*
+ * Copyright 2011 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 deviceSettings = require('ripple/deviceSettings'),
+ _self = {};
- return {code: 1, data: match.where(post.fieldFilter)};
- }
-};
+_self.__defineGetter__("uuid", function () {
+ return deviceSettings.retrieve("identity.uuid");
+});
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/identity/phone', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/system', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var deviceSettings = require('ripple/deviceSettings'),\r
+ devices = require('ripple/devices'),\r
+ app = require('ripple/app'),\r
+ utils = require('ripple/utils'),\r
+ _self;\r
+\r
+function _is(feature) {\r
+ return {\r
+ allowedFor: function (location) {\r
+ return feature && feature.URIs.some(function (uri) {\r
+ return uri.value === location ||\r
+ (location.indexOf(uri.value) >= 0 && uri.subdomains);\r
+ });\r
+ }\r
+ };\r
+}\r
+\r
+_self = {\r
+ hasCapability: function (capability) {\r
+ var capabilities = devices.getCurrentDevice().capabilities;\r
+ return capabilities ? capabilities.some(function (type) {\r
+ return type === capability;\r
+ }) : false;\r
+ },\r
+ hasPermission: function (desiredModule) {\r
+ var info = app.getInfo(),\r
+ feature = info.features ? info.features[desiredModule] : null;\r
+\r
+ return feature === null || _is(feature).allowedFor(utils.location().href) ? _self.ALLOW : _self.DENY;\r
+ }\r
+};\r
+\r
+_self.__defineGetter__("ALLOW", function () {\r
+ return 0;\r
+});\r
+\r
+_self.__defineGetter__("DENY", function () {\r
+ return 1;\r
+});\r
+\r
+_self.__defineGetter__("softwareVersion", function () {\r
+ return devices.getCurrentDevice().osVersion;\r
+});\r
+\r
+_self.__defineGetter__("hardwareId", function () {\r
+ return devices.getCurrentDevice().hardwareId;\r
+});\r
+\r
+_self.__defineGetter__("language", function () {\r
+ return deviceSettings.retrieve("system.language");\r
+});\r
+\r
+_self.__defineGetter__("region", function () {\r
+ return deviceSettings.retrieve("system.region");\r
+});\r
+\r
+module.exports = _self;\r
+
+});
+define('ripple/platform/webworks.bb10/1.0.0/app', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _lines = [
- {id: 1, number: 12345678910, label: "rogers", type: 1},
- {id: 2, number: 10987654321, label: "mystery", type: 0}
- ],
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ app = require('ripple/app'),
+ notifications = require('ripple/notifications'),
+ _uri = "blackberry/app/",
_self;
-function _filterLines(args) {
+_self = {
+ exit: function () {
+ notifications.openNotification("normal", "blackberry.app.exit() was called, in the real world your app will exit, here... you get this notification");
+ }
+};
- var result = _lines;
+_self.__defineGetter__("author", function () {
+ return app.getInfo().author;
+});
- if (args && typeof args.id === "number") {
- result = _lines.filter(function (line) {
- return line.id === args.id;
- });
+_self.__defineGetter__("authorEmail", function () {
+ return app.getInfo().authorEmail;
+});
- if (result.length === 0) {
- throw "invalid line id: " + args.id;
- }
- }
+_self.__defineGetter__("authorURL", function () {
+ return app.getInfo().authorURL;
+});
- return result;
-}
+_self.__defineGetter__("copyright", function () {
+ return app.getInfo().copyright;
+});
-_self = {
- getLineIds: function () {
- var lines = _lines.map(function (line) {
- return line.id;
- });
- return {
- code: 1,
- data: lines
- };
- },
- getLineLabel: function (args) {
- return {
- code: 1,
- data: _filterLines(args)[0].label
- };
- },
- getLineNumber: function (args) {
- return {
- code: 1,
- data: _filterLines(args)[0].number
- };
- },
- getLineType: function (args) {
- return {
- code: 1,
- data: _filterLines(args)[0].type
- };
- }
-};
+_self.__defineGetter__("description", function () {
+ return app.getInfo().description;
+});
+
+_self.__defineGetter__("id", function () {
+ return app.getInfo().id;
+});
+
+_self.__defineGetter__("license", function () {
+ return app.getInfo().license;
+});
+
+_self.__defineGetter__("licenseURL", function () {
+ return app.getInfo().licenseURL;
+});
+
+_self.__defineGetter__("name", function () {
+ return app.getInfo().name;
+});
+
+_self.__defineGetter__("version", function () {
+ return app.getInfo().version;
+});
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/identity', function (require, exports, module) {
+define('ripple/platform/webworks.bb10/1.0.0/invoke', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+var notifications = require('ripple/notifications'),\r
+ utils = require('ripple/utils'),\r
+ _self = {};\r
+\r
+function _fail(onError) {\r
+ if (onError && typeof onError === "function") {\r
+ onError("invalid invocation request");\r
+ }\r
+}\r
+\r
+_self.invoke = function (request, onSuccess, onError) {\r
+ var argsString = "";\r
+\r
+ if (!request) { // is this check even needed?\r
+ _fail(onError);\r
+ return;\r
+ } else {\r
+ if (request) {\r
+ utils.forEach(request, function (arg, key) {\r
+ argsString += key + " = " + arg + "</br>";\r
+ });\r
+\r
+ notifications.openNotification("normal", "Requested to invoke external application with the following arguments:</br> " +\r
+ argsString + "</br>");\r
+ }\r
+ else {\r
+ _fail(onError);\r
+ return;\r
+ }\r
+ }\r
+};\r
+\r
+_self.__defineGetter__("ACTION_OPEN", function () {\r
+ return "bb.action.OPEN";\r
+});\r
+_self.__defineGetter__("ACTION_VIEW", function () { \r
+ return "bb.action.VIEW"; \r
+});\r
+_self.__defineGetter__("ACTION_SHARE", function () {\r
+ return "bb.action.SHARE";\r
+});\r
+\r
+module.exports = _self;\r
+
+});
+define('ripple/platform/webworks.bb10/1.0.0/dialog', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var _self,
- Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
- Transport = require('ripple/platform/webworks.handset/2.0.0/client/identity/Transport'),
- utils = require('ripple/utils'),
- platform = require('ripple/platform'),
- deviceSettings = require('ripple/deviceSettings'),
- _transportTypes = [
- {name: "TCP Cellular", type: "TCP Cellular"},
- {name: "Wap", type: "Wap"},
- {name: "Wap 2.0", type: "Wap 2.0"},
- {name: "MDS", type: "MDS"},
- {name: "BIS B", type: "Bis B"},
- {name: "Unite!", type: "Unite!"},
- {name: "TCP Wifi", type: "TCP Wifi"},
- ],
- _services = [
- new Service(),
- new Service()
- ];
+ ui = require('ripple/ui'),
+ event = require('ripple/event'),
+ isDialogVisible = false,
+ visibleDialogArgs,
+ utils = require('ripple/utils');
-function _isTransportAvailable(transport) {
- return deviceSettings.retrieveAsBoolean("transports." + transport.type);
+function getButtonsForDialogType(dialogType) {
+ switch (dialogType) {
+ case _self.D_OK:
+ return ["Ok"];
+ case _self.D_SAVE:
+ return ["Save", "Discard"];
+ case _self.D_DELETE:
+ return ["Delete", "Cancel"];
+ case _self.D_YES_NO:
+ return ["Yes", "No"];
+ case _self.D_OK_CANCEL:
+ return ["Ok", "Cancel"];
+ default:
+ throw new Error("Invalid dialog type: " + dialogType);
+ }
}
-utils.mixin({
- name: "Super Dave Osborne",
- emailAddress: "dave@stunt.com",
- isDefault: true,
- type: Service.TYPE_EMAIL
-}, _services[0]);
+event.on("LayoutChanged", function () {
+ if (isDialogVisible) {
+ closeDialog();
+ //Used to resize dialog on orientation change
+ _self.ask(visibleDialogArgs);
+ }
+});
-utils.mixin({
- name: "Fred Penner",
- emailAddress: "fred@fredpenner.com",
- isDefault: false,
- type: Service.TYPE_CONTACT
-}, _services[1]);
+function closeDialog() {
+ var buttonsDiv = document.getElementById("dialog-buttons"),
+ messageDiv = document.getElementById("dialog-message");
+
+ ui.hideOverlay("dialog-window", function (dialog) {
+ buttonsDiv.innerHTML = "";
+ messageDiv.innerHTML = "";
+ isDialogVisible = false;
+ });
+}
+
+function ask(args, callback) {
+ if (!args) {
+ throw ("No arguments provided");
+ } else if (!args.buttons || !args.message) {
+ throw ("Invalid arguments");
+ }
+ visibleDialogArgs = args;
+
+ ui.showOverlay("dialog-window", function (dialog) {
+ var container = document.getElementById("viewport-container"),
+ height = window.getComputedStyle(container, null).getPropertyValue("height"),
+ width = window.getComputedStyle(container, null).getPropertyValue("width"),
+ sizeDiv = document.getElementById("dialog-wrapper"),
+ positionDiv = document.getElementById("dialog-window"),
+ titleDiv = document.getElementById("dialog-title"),
+ buttonsDiv = document.getElementById("dialog-buttons"),
+ messageDiv = document.getElementById("dialog-message"),
+ position, size;
+
+ if (!messageDiv || !buttonsDiv) {
+ return;
+ }
+
+ dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");
+
+ position = "overlay-dialog";
+ size = "overlay-dialog-wrapper";
+
+ if (args.settings && args.settings.position) {
+ position += " overlay-dialog-" + args.settings.position;
+ }
+
+ if (args.settings && args.settings.size) {
+ size += " overlay-dialog-wrapper-" + args.settings.size;
+ }
+
+ positionDiv.setAttribute("class", position);
+ sizeDiv.setAttribute("class", size);
+
+ titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
+ messageDiv.innerHTML = args.message;
+ isDialogVisible = true;
+
+ args.buttons.forEach(function (button) {
+ var buttonElement = utils.createElement("input", {
+ "type": "button",
+ "value": button
+ });
+ buttonElement.addEventListener("click", function () {
+ var buttonIndex = args.buttons.indexOf(button);
+ closeDialog();
+ callback(buttonIndex);
+ });
+ buttonsDiv.appendChild(buttonElement);
+ });
+ }, true);
+}
_self = {
- getDefaultService: function () {
- var serices = _services.filter(function (service) {
- return service.isDefault === true;
+ customAskAsync: function (message, choices, callback, settings) {
+ ask({
+ message: message,
+ buttons: choices,
+ settings: settings
+ }, function (response) {
+ if (callback) {
+ callback(response);
+ }
});
- return {code: 1, data: serices};
- },
- getServiceList: function () {
- return {code: 1, data: _services};
},
- getTransportList: function () {
- var transports = _transportTypes.filter(function (transport) {
- return _isTransportAvailable(transport);
- }).map(function (transport) {
- return new Transport(transport.name, transport.type);
+
+ standardAskAsync: function (message, type, callback, settings) {
+ var choices = getButtonsForDialogType(type);
+ ask({
+ message: message,
+ buttons: choices,
+ settings: settings
+ }, function (response) {
+ if (callback) {
+ callback(response);
+ }
});
- return {code: 1, data: transports};
- },
- IMEI: function () {
- return {code: 1, data: deviceSettings.retrieve("identity.IMEI")};
- },
- IMSI: function () {
- return {code: 1, data: deviceSettings.retrieve("identity.IMSI")};
- },
- PIN: function () {
- return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
- },
- phone: require('ripple/platform/webworks.handset/2.0.0/server/identity/phone')
+ }
};
+_self.__defineGetter__("D_OK", function () {
+ return 0;
+});
+
+_self.__defineGetter__("D_SAVE", function () {
+ return 1;
+});
+
+_self.__defineGetter__("D_DELETE", function () {
+ return 2;
+});
+
+_self.__defineGetter__("D_YES_NO", function () {
+ return 3;
+});
+
+_self.__defineGetter__("D_OK_CANCEL", function () {
+ return 4;
+});
+
+_self.__defineGetter__("BOTTOM", function () {
+ return "bottomCenter";
+});
+
+_self.__defineGetter__("CENTER", function () {
+ return "middleCenter";
+});
+
+_self.__defineGetter__("TOP", function () {
+ return "topCenter";
+});
+
+_self.__defineGetter__("SIZE_FULL", function () {
+ return "full";
+});
+
+_self.__defineGetter__("SIZE_LARGE", function () {
+ return "large";
+});
+
+_self.__defineGetter__("SIZE_MEDIUM", function () {
+ return "medium";
+});
+
+_self.__defineGetter__("SIZE_SMALL", function () {
+ return "small";
+});
+
+_self.__defineGetter__("SIZE_TALL", function () {
+ return "tall";
+});
+
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/invoke', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/fsCache', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var notifications = require('ripple/notifications'),
+var fs = require('ripple/dbfs'),
+ utils = require('ripple/utils'),
+ _console = require('ripple/console'),
constants = require('ripple/constants'),
- type = "normal",
- name = {
- "0": "Address Book",
- "1": "Bluetooth Config",
- "2": "Calculator",
- "3": "Calendar",
- "camera://": "Camera",
- "camera://video": "Video Camera",
- "map://": "Maps",
- "6": "Memopad",
- "7": "Messages",
- "8": "Phone",
- "9": "Search",
- "10": "Tasks",
- "11": "Browser",
- "http://": "Browser",
- "12": "Java",
+ event = require('ripple/event'),
+ bbUtils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
+ FileProperties = require('ripple/platform/webworks.core/2.0.0/client/FileProperties'),
+ _cache = {},
+ _self;
+
+function _createPath(path) {
+ var parts = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
+ workflow = jWorkflow.order();
+
+ parts.forEach(function (part, index) {
+ var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+
+ workflow.andThen(function (prev, baton) {
+ baton.take();
+ fs.mkdir(dir, baton.pass, baton.pass);
+ });
+ });
+
+ workflow.start(_self.refresh);
+}
+event.on("FileSystemInitialized", function () {
+ _createPath("/SDCard");
+ _createPath("/store/home/user/music");
+ _createPath("/store/home/user/pictures");
+ _createPath("/store/home/user/videos");
+ _createPath("/store/home/user/videos");
+ _createPath("/accounts/1000/appdata/emulatedapp/data");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/bookmarks");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/books");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/camera");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/documents");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/downloads");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/misc");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/music");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/photos");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/print");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/videos");
+ _createPath("/accounts/1000/appdata/emulatedapp/shared/voice");
+});
+
+function _fsError(e) {
+ _self.refresh();
+ if (e.code !== 1) { // suppress file not found error
+ _console.error("FileSystem error (code " + e.code + ")");
+ }
+}
+
+function _walk(path, parent) {
+ fs.ls(path, function (entries) {
+ parent.children = parent.children || {};
+
+ entries.forEach(function (entry) {
+ parent.children[entry.name] = entry;
+ parent.children[entry.name].properties = {};
+
+ if (entry.isDirectory) {
+ _walk(entry.fullPath, entry);
+ } else {
+ entry.file(function (file) {
+ utils.mixin(file, parent.children[entry.name].properties);
+ });
+ fs.read(entry.fullPath, function (data) {
+ parent.children[entry.name].data = data;
+ }, function (e) {
+ console.error(e);
+ });
+ }
+ });
+ }, function (e) {
+ console.error(e);
+ });
+}
+
+function _get(path) {
+ return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
+ return token === "" ? obj : (obj && obj.children ? obj.children[token] || null : null);
+ }, _cache);
+}
+
+function _getInfo(path) {
+ var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
+ name = parent.splice(parent.length - 1, 1).join(""),
+ ext = name.split(".");
+
+ return {
+ name: name,
+ extension: ext.length > 1 ? ext[ext.length - 1] : "",
+ hidden: (name.length > 0 && name[0] === ".") || false,
+ parent: parent.join("/") || "/"
};
+}
-module.exports = {
- invoke: function (opts) {
- var app = name[opts.appType];
- if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
- app = "Browser";
+function _set(path, obj) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
+
+ parent.children = parent.children || {};
+ obj.properties = obj.properties || {};
+ parent.children[child] = obj;
+}
+
+function _delete(path) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
+ });
+
+ delete parent.children[child];
+}
+
+// TODO: handle exceptions so that any respective fs command can error out
+// TODO: dateCreated is always dateModified
+
+_self = {
+ refresh: function () {
+ _cache = {};
+ _walk("/", _cache);
+ },
+ file: {
+ exists: function (path) {
+ var entry = _get(path);
+ return !!(entry && !entry.isDirectory);
+ },
+
+ deleteFile: function (path) {
+ _delete(path);
+ fs.rm(path, function () {}, _fsError);
+ },
+
+ copy: function (from, to) {
+ var fromEntry = _get(from);
+
+ _set(to, {
+ fullPath: to,
+ properties: fromEntry.properties,
+ data: fromEntry.data
+ });
+
+ fs.cp(from, to, function (entry) {
+ entry.file(function (file) {
+ entry.properties = entry.properties || {};
+ utils.mixin(file, entry.properties);
+ _set(to, entry);
+ });
+ }, _fsError);
+ },
+
+ getFileProperties: function (path) {
+ var entry = _get(path),
+ info = _getInfo(path);
+
+ fs.stat(path, function () {}, _fsError);
+
+ return new FileProperties({
+ //HACK: not sure where these should come from so check both for now.
+ dateCreated: entry.properties.lastModifiedDate || entry.lastModifiedDate,
+ dateModified: entry.properties.lastModifiedDate || entry.lastModifiedDate,
+ directory: info.parent,
+ fileExtension: info.extension,
+ isHidden: info.hidden,
+ isReadonly: false,
+ mimeType: entry.properties.type,
+ size: entry.properties.size
+ });
+ },
+
+ rename: function (path, newName) {
+ _self.dir.rename(path, newName);
+ },
+
+ readFile: function (path, success, async) {
+ var entry = _get(path);
+
+ async = async === false ? async : true;
+
+ if (!async) {
+ success(bbUtils.stringToBlob(entry.data));
+ }
+ else {
+ fs.read(path, function (data) {
+ var blob = bbUtils.stringToBlob(data);
+ if (async) {
+ success(blob);
+ }
+ entry.data = data;
+ _set(path, entry);
+ }, _fsError);
+ }
+ },
+
+ saveFile: function (path, blob) {
+ var data = bbUtils.blobToString(blob);
+
+ _set(path, {
+ lastModifiedDate: new Date(),
+ fullPath: path,
+ isDirectory: false,
+ properties: {
+ type: "",
+ size: blob.size
+ },
+ data: data
+ });
+
+ fs.write(path, data, function (entry) {
+ entry.data = data;
+ entry.file(function (file) {
+ entry.properties = entry.properties || {};
+ utils.mixin(file, entry.properties);
+ _set(path, entry);
+ });
+ }, _fsError);
}
+ },
+ dir: {
+ createNewDir: function (path) {
+ var entry = _get(path),
+ info = _getInfo(path);
- notifications.openNotification(type,
- "Requested to launch: " + app + " application.");
- return {code: 1};
- }
-};
+ if (!entry) {
+ _set(path, {
+ name: info.name,
+ isDirectory: true,
+ fullPath: path
+ });
+ }
+
+ fs.mkdir(path, function (entry) {
+ _set(path, entry);
+ }, _fsError);
+ },
+
+ deleteDirectory: function (path, recursive) {
+ _delete(path);
+ if (recursive) {
+ fs.rm(path, function () {}, _fsError, {recursive: recursive});
+ } else {
+ fs.rmdir(path, function () {}, _fsError);
+ }
+ },
+
+ exists: function (path) {
+ var entry = _get(path);
+ return !!(entry && entry.isDirectory);
+ },
+
+ getFreeSpaceForRoot: function (path) {
+ function _du(obj, size) {
+ utils.forEach(obj, function (child, key) {
+ if (child.isDirectory && child.children) {
+ size += _du(child.children, size);
+ } else if (child.properties && child.properties.size) {
+ size += child.properties.size;
+ }
+ });
+ return size;
+ }
+
+ return constants.FS_SIZE - _du(_cache.children, 0);
+ },
+
+ getParentDirectory: function (path) {
+ path = "/" + path.replace(/^\//, '').replace(/\/$/, '');
+
+ var entry = _get(path),
+ array = path.split("/");
+
+ return entry ? array.splice(0, array.length - 1).join("/") || "/" : null;
+ },
+
+ listDirectories: function (path) {
+ var dir = _get(path),
+ directories = [];
+
+ utils.forEach(dir.children, function (item) {
+ if (item.isDirectory) {
+ directories.push(item.name);
+ }
+ });
+
+ fs.ls(path, function () {}, _fsError);
+
+ return directories;
+ },
+
+ listFiles: function (path) {
+ var dir = _get(path),
+ files = [];
+
+ if (dir) {
+ utils.forEach(dir.children, function (item) {
+ if (!item.isDirectory) {
+ files.push(item.name);
+ }
+ });
+ }
+
+ fs.ls(path, function () {}, _fsError);
+
+ return files;
+ },
-});
-define('ripple/platform/webworks.handset/2.0.0/server/io/dir', function (require, exports, module) {
-/*
- * Copyright 2011 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 cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
- dir = require('ripple/platform/webworks.core/2.0.0/server/io/dir'),
- utils = require('ripple/utils'),
- _self = {};
+ rename: function (path, newName) {
+ var info = _getInfo(path),
+ parent = info.parent,
+ oldName = info.name,
+ from = (parent === "/" ? "" : parent) + "/" + oldName,
+ to = (parent === "/" ? "" : parent) + "/" + newName;
-function _packet(data) {
- return {
- code: 1,
- data: data
- };
-}
+ _delete(from);
+ _set(to, {
+ name: info.name,
+ fullPath: path
+ });
-utils.mixin({
- getFreeSpaceForRoot: function (get, post, baton) {
- return _packet(cache.dir.getFreeSpaceForRoot(post.path));
- },
- getRootDirs: function (get, post, baton) {
- return _packet(cache.dir.getRootDirs());
- }
-}, _self);
+ fs.mv(from, to, function (entry) {
+ _set(to, entry);
+ }, _fsError);
+ },
-utils.mixin(dir, _self);
+ getRootDirs: function () {
+ return _self.dir.listDirectories("/");
+ }
+ }
+};
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/memo', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/XMLHttpRequest', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- select = require('ripple/platform/webworks.core/2.0.0/select'),
- _self;
+module.exports = {
+ create: function (server) {
+ var XHR = window.XMLHttpRequest,
+ webworks = require(server);
-function _get() {
- return db.retrieveObject("webworks-pim-memo-list") || {};
-}
+ return function () {
+ var _url,
+ _async,
+ xhr = new XHR(),
+ origMethods = {
+ open: xhr.open,
+ send: xhr.send,
+ setRequestHeader: xhr.setRequestHeader
+ };
-function _do(func) {
- var memos = _get();
- func(memos);
- db.saveObject("webworks-pim-memo-list", memos);
-}
+ function onreadystatechange() {
+ if (typeof xhr.onreadystatechange === "function") {
+ xhr.onreadystatechange();
+ }
+ }
-_self = {
- find: function (get, post) {
- var memos = select.from(_get())
- .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
- .max(post.maxReturn)
- .where(post.filter);
- return {code: 1, data: memos};
- },
- remove: function (get, post) {
- _do(function (memos) {
- if (!memos[get.uid]) {
- throw "attempting to delete a non existant memo with uid: " + get.uid;
+ function statemachine(getResult) {
+ var state = 0,
+ incState = function (prev, baton) {
+ state++;
+ if (_async) {
+ baton.take();
+ window.setTimeout(baton.pass, 1);
+ }
+ },
+ setResponse = function (result) {
+ xhr.__defineGetter__("status", function () {
+ return 200;
+ });
+
+ xhr.__defineGetter__("responseText", function () {
+ return result !== null && result !== undefined ?
+ JSON.stringify(result) : null;
+ });
+ };
+
+ xhr.__defineGetter__("readyState", function () {
+ return state;
+ });
+
+ jWorkflow.order(incState)
+ .andThen(onreadystatechange)
+ .andThen(incState)
+ .andThen(onreadystatechange)
+ .andThen(incState)
+ .andThen(onreadystatechange)
+ .andThen(getResult)
+ .andThen(setResponse)
+ .andThen(incState)
+ .andThen(onreadystatechange)
+ .start();
}
- delete memos[get.uid];
- });
- return {code: 1};
- },
- save: function (get, post) {
- _do(function (memos) {
- memos[post.memo.uid] = post.memo;
- });
- return {code: 1};
+
+ xhr.setRequestHeader = function (header, value) {
+ if (!_url.match(/^webworks:\/\//)) {
+ origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
+ }
+ };
+
+ xhr.open = function (method, url, async, user, password) {
+ _url = url;
+ _async = async;
+
+ if (!_url.match(/^webworks:\/\//)) {
+ origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
+ }
+ };
+
+ xhr.send = function (post) {
+ if (!_url.match(/^webworks:\/\//)) {
+ origMethods.send.apply(xhr, Array.prototype.slice.call(arguments));
+ return;
+ }
+
+ var params = _url.match(/\?(.*)$/),
+ objPath = _url.match(/^webworks:\/\/([^\?]*)/)[1].split("/"),
+ apiMethod = objPath.reduce(function (obj, name) {
+ return obj[name];
+ }, webworks),
+ postParams = {},
+ get = {};
+
+ if (params) {
+ params[1].split("&").forEach(function (param) {
+ var pair = param.split("="),
+ key = decodeURIComponent(pair[0]),
+ value = decodeURIComponent(pair[1]);
+ // parsing undefied with JSON throws exception
+ get[key] = value === "undefined" ? undefined : JSON.parse(value);
+ });
+ }
+
+ if (post) {
+ post.split("&").forEach(function (param) {
+ var pair = param.split("="),
+ value;
+ try {
+ value = JSON.parse(decodeURIComponent(pair[1]));
+ } catch (e) {
+ value = pair[1] === "undefined" ? undefined : pair[1];
+ }
+
+ postParams[pair[0]] = value;
+ });
+ }
+
+ statemachine(function (prev, baton) {
+ return apiMethod(get, postParams, baton);
+ });
+ };
+
+ return xhr;
+ };
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/menu', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/io/file', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _menuItems = {},
- event = require('ripple/event'),
- events = require('ripple/platform/webworks.core/2.0.0/client/events'),
- ui = require('ripple/ui'),
- devices = require('ripple/devices'),
- utils = require('ripple/utils'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- _self,
- isMenuOpen = false,
- _baton,
- menuWindow = document ? document.getElementById("menu-window") : undefined;
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/io/file/",
+ FILE = "file://",
+ _onFileOpened;
-if (menuWindow) {
- menuWindow.addEventListener("click", function () {
- _self.close();
- });
+function _prunePrefix(path) {
+ return path.replace(new RegExp("^" + FILE), '');
}
-event.on("LayoutChanged", function () {
- if (isMenuOpen) {
- _self.close();
- //Used to resize menu on orientation change
- _self.open();
- }
-});
-
-event.on("HardwareKeyDefault", function (key) {
- if (key === 1 || key === "1") { //menu button key
- if (isMenuOpen) {
- _self.close();
- }
- else {
- _self.open();
- }
- }
-});
-
-event.on("MenuItemSelected", function (menuItem) {
- var baton = _baton;
- _baton = null;
- return baton && baton.pass({code: 1, data: menuItem});
-});
-
-event.on("MenuItemChanged", function (menuItem) {
- _menuItems[menuItem.id] = menuItem;
-});
-
-_self = {
-
- onSelect : function (args, post, baton) {
- baton.take();
- _baton = baton;
+module.exports = {
+ copy: function (from, to) {
+ transport.call(_uri + "copy", {
+ post: {from: _prunePrefix(from), to: _prunePrefix(to)}
+ });
},
-
- addMenuItem: function (args) {
- if (!args) {
- throw "item not found";
- }
- _menuItems[args.item.id] = args.item;
- event.trigger("MenuChanged", [_menuItems]);
- return {code: 1};
+ deleteFile: function (path) {
+ transport.call(_uri + "deleteFile", {
+ post: {path: _prunePrefix(path)}
+ });
},
-
- clearMenuItems: function () {
- _menuItems = {};
- event.trigger("MenuChanged", [utils.copy(_menuItems)]);
- return {code: 1};
+ exists: function (path) {
+ return transport.call(_uri + "exists", {
+ post: {path: _prunePrefix(path)}
+ });
},
+ getFileProperties: function (path) {
+ var properties = transport.call(_uri + "getFileProperties", {
+ post: {path: _prunePrefix(path)}
+ });
+ properties.directory = FILE + properties.directory;
+ return properties;
+ },
+ open: function (path, newName) {
+ transport.call(_uri + "open", {
+ post: {path: _prunePrefix(path)}
+ });
+ },
+ readFile: function (path, onFileOpened, async) {
+ async = async === false ? false : true;
- open: function () {
- function _return() {
- return {code: 1};
- }
-
- if (utils.count(_menuItems) === 0) {
- _return();
- }
-
- ui.showOverlay("menu-window", function (menu) {
- var container = document.getElementById("viewport-container"),
- height = window.getComputedStyle(container, null).getPropertyValue("height"),
- width = window.getComputedStyle(container, null).getPropertyValue("width"),
- menuButtons = document.getElementById("menu-buttons"),
- sorted,
- menuItem;
-
- if (!menuButtons) {
- _return();
- }
-
- menu.setAttribute("style", "display:block;height:" + height + "; width:" + width + ";");
- isMenuOpen = true;
-
- sorted = utils.map(_menuItems, function (item) {
- return item;
- }).sort(function (a, b) {
- return a.ordinal - b.ordinal;
- });
+ var uri = _uri + "readFile",
+ args = {
+ post: {path: _prunePrefix(path), async: async}
+ },
+ callResult;
- menuButtons.innerHTML = "";
- sorted.forEach(function (item) {
- if (!item.isSeparator) {
- if (item.isDefault) {
- menuItem = utils.createElement("div", {
- "class": "overlay-menu-item-default",
- "id": "default-menu-item"
- });
- }
- else {
- menuItem = utils.createElement("div", {
- "class": "overlay-menu-item"
- });
- }
- menuItem.innerHTML = item.caption;
+ _onFileOpened = onFileOpened;
- menuItem.addEventListener("click", function () {
- _baton.pass({code: 1, data: item.id});
- });
- }
- else {
- menuItem = utils.createElement("hr", {});
+ if (async) {
+ transport.poll(uri, args, function (data, res) {
+ if (_onFileOpened) {
+ _onFileOpened(FILE + data.fullPath, data.blobData);
}
- menuButtons.appendChild(menuItem);
- tooltip.create("#default-menu-item", "Default Item");
+ return false;
});
- }, true);
-
- event.trigger("MenuOpened", []);
-
- _return();
+ } else {
+ callResult = transport.call(uri, args);
+ _onFileOpened(FILE + callResult.fullPath, callResult.blobData);
+ }
},
-
- close: function () {
- ui.hideOverlay("menu-window", function (menu) {
- var menuButtons = document.getElementById("menu-buttons");
- menuButtons.innerHTML = "";
- isMenuOpen = false;
- menu.setAttribute("style", "display:none;");
-
+ rename: function (path, newName) {
+ transport.call(_uri + "rename", {
+ post: {path: _prunePrefix(path), newName: newName}
});
- return {code: 1};
},
-
- removeMenuItem: function (args) {
- delete _menuItems[args.item.id];
- event.trigger("MenuChanged", [_menuItems]);
- return {code: 1};
- },
-
- setDefaultMenuItem: function (args) {
-
- utils.forEach(_menuItems, function (item) {
- item.isDefault = false;
+ saveFile: function (path, blob) {
+ transport.call(_uri + "saveFile", {
+ post: {path: _prunePrefix(path), blob: blob}
});
-
- _menuItems[args.id].isDefault = true;
-
- event.trigger("DefaultItemChanged", [_menuItems[args.id]]);
- return {code: 1};
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/message', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/io/dir', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- select = require('ripple/platform/webworks.core/2.0.0/select'),
- Message = require('ripple/platform/webworks.handset/2.0.0/client/Message'),
- _self;
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
+ _uri = "blackberry/io/dir/",
+ FILE = "file://";
-function _get() {
- return db.retrieveObject("webworks-message-list") || {};
+function _prunePrefix(path) {
+ return path.replace(new RegExp("^" + FILE), '');
}
-function _do(func) {
- var messages = _get();
- func(messages);
- db.saveObject("webworks-message-list", messages);
+function _addPrefix(path) {
+ return FILE + path;
}
-_self = {
- find: function (get, post) {
- var data = select
- .from(_get())
- .max(post.maxReturn)
- .where(post.filter);
- return {code: 1, data: data};
+module.exports = {
+ createNewDir: function (path) {
+ transport.call(_uri + "createNewDir", {
+ post: {path: _prunePrefix(path)}
+ });
},
-
- remove: function (get, post) {
- _do(function (messages) {
- if (!messages[get.uid]) {
- throw "attempting to delete a non existant message with uid: " + get.uid;
- }
- delete messages[get.uid];
+ deleteDirectory: function (path, recursive) {
+ transport.call(_uri + "deleteDirectory", {
+ post: {path: _prunePrefix(path), recursive: recursive}
});
- return {code: 1};
},
-
- save: function (get, post) {
- _do(function (messages) {
- var orig = messages[post.message.uid],
- updated = utils.copy(post.message);
-
- updated.folder = orig ? orig.folder : Message.FOLDER_DRAFT;
- updated.status = orig ? orig.status : Message.STATUS_DRAFT;
-
- messages[post.message.uid] = updated;
+ exists: function (path) {
+ return transport.call(_uri + "exists", {
+ post: {path: _prunePrefix(path)}
});
- return {code: 1};
},
-
- send: function (get, post) {
- _do(function (messages) {
- var updated = utils.copy(get.message);
-
- updated.folder = Message.FOLDER_SENT;
- updated.status = Message.STATUS_SENT;
-
- messages[updated.uid] = updated;
+ getParentDirectory: function (path) {
+ return _addPrefix(transport.call(_uri + "getParentDirectory", {
+ post: {path: _prunePrefix(path)}
+ }));
+ },
+ listDirectories: function (path) {
+ return transport.call(_uri + "listDirectories", {
+ post: {path: _prunePrefix(path)}
+ });
+ },
+ listFiles: function (path) {
+ return transport.call(_uri + "listFiles", {
+ post: {path: _prunePrefix(path)}
+ });
+ },
+ rename: function (path, newName) {
+ transport.call(_uri + "rename", {
+ post: {path: _prunePrefix(path), newName: newName}
});
- return {code: 1};
}
};
-module.exports = _self;
-
});
-define('ripple/platform/webworks.handset/2.0.0/server/phone', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/transport', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var PhoneCall = require('ripple/platform/webworks.handset/2.0.0/client/PhoneCall'),
- PhoneLogs = require('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs'),
- CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
- select = require('ripple/platform/webworks.core/2.0.0/select'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- _KEY = "blackberry-phone-logs",
- _onPhoneEventListeners = {},
- _activeCalls = {},
- _onCallLogAdded,
- _onCallLogRemoved,
- _onCallLogUpdated,
- _onCallLogReset,
- _self;
-
-function _defaultLogs() {
- var n1 = new CallLog(),
- n2 = new CallLog(),
- m1 = new CallLog(),
- m2 = new CallLog();
-
- n1.number = "12344567";
- n1.name = "larry";
- n1.type = CallLog.TYPE_PLACED_CALL;
- n1.status = CallLog.STATUS_NORMAL;
-
- n2.number = "14567890";
- n2.name = "curly";
- n2.type = CallLog.TYPE_RECEIVED_CALL;
- n2.status = CallLog.STATUS_NORMAL;
+var _self;
- m1.number = "17659800";
- m1.name = "moe";
- m1.type = CallLog.TYPE_MISSED_CALL_UNOPENED;
- m1.status = CallLog.STATUS_NORMAL;
+function RemoteFunctionCall(functionUri) {
+ var params = {},
+ postString = "",
+ postParams = {};
- m2.number = "14567896";
- m2.name = "snarf";
- m2.type = CallLog.TYPE_MISSED_CALL_OPENED;
- m2.status = CallLog.STATUS_NORMAL;
+ function composeUri() {
+ var uri = "webworks://" + functionUri,
+ paramCount = 1,
+ param;
- return {
- normal: [n1, n2],
- missed: [m1, m2]
- };
-}
+ for (param in params) {
+ if (params.hasOwnProperty(param)) {
+ if (paramCount === 1) {
+ uri += "?";
+ } else {
+ uri += "&";
+ }
+ uri += param + "=" + params[param];
+ paramCount++;
+ }
-function _getLogs(folderID) {
- var logs = db.retrieveObject(_KEY) || _defaultLogs();
- return folderID === undefined || folderID === null ?
- logs : logs[folderID !== PhoneLogs.FOLDER_NORMAL_CALLS ? "missed" : "normal"];
-}
+ uri = uri.replace(/\&$/, "");
+ }
-function _saveLogs(logs) {
- db.saveObject(_KEY, logs);
-}
+ return uri;
+ }
-function _isMissedCall(log) {
- return (log.type === CallLog.TYPE_MISSED_CALL_UNOPENED ||
- log.type === CallLog.TYPE_MISSED_CALL_OPENED) ? true : false;
-}
+ function createXhrRequest(uri, isAsync) {
+ var request = new XMLHttpRequest(),
+ paramCount = 1,
+ param;
-function _isNormalCall(log) {
- return (log.type === CallLog.TYPE_RECEIVED_CALL ||
- log.type === CallLog.TYPE_PLACED_CALL) ? true : false;
-}
+ for (param in postParams) {
+ if (postParams.hasOwnProperty(param)) {
+ postString += param + "=" + postParams[param] + "&";
+ paramCount++;
+ }
+ }
-event.on("PhoneEvent", function (type, callId, error) {
- var baton = _onPhoneEventListeners[type];
- delete _onPhoneEventListeners[type];
+ postString = postString.replace(/\&$/, "");
- return baton && baton.pass({code: 1, data: {callId: callId, error: error}});
-});
+ // TODO: make get/post
+ request.open("POST", uri, isAsync);
+ request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-event.on("PhoneCallLogAdded", function (log) {
- var logs = _getLogs(),
- baton = _onCallLogAdded;
+ return request;
+ }
- logs[_isMissedCall(log) ? "missed" : "normal"].push(log);
- _saveLogs(logs);
+ this.addParam = function (name, value) {
+ params[name] = encodeURIComponent(JSON.stringify(value));
+ };
- _onCallLogAdded = null;
- return baton && baton.pass({code: 1, data: {log: log}});
-});
+ this.addPostParam = function (name, value) {
+ postParams[name] = encodeURIComponent(JSON.stringify(value));
+ };
-event.on("PhoneCallLogRemoved", function (log) {
- // TODO: make this be the only one responsible for deletion (instead of triggering internally)
- var baton = _onCallLogRemoved;
- _onCallLogRemoved = null;
- return baton && baton.pass({code: 1, data: {log: log}});
-});
+ this.makeSyncCall = function (success, error) {
+ var requestUri = composeUri(),
+ request = createXhrRequest(requestUri, false),
+ response, errored, cb, data;
-event.on("PhoneCallLogUpdated", function (newLog, oldLog) {
- // TODO: implement way to update with just this event
- var baton = _onCallLogUpdated;
- _onCallLogUpdated = null;
- return baton && baton.pass({code: 1, data: {
- newLog: newLog,
- oldLog: oldLog
- }});
-});
+ request.send(postString);
-event.on("PhoneCallLogReset", function () {
- _saveLogs(_defaultLogs());
- var baton = _onCallLogReset;
- _onCallLogReset = null;
- return baton && baton.pass({code: 1});
-});
+ response = JSON.parse(request.responseText || "null");
+ errored = response.code < 0;
+ cb = errored ? error : success;
+ data = errored ? response.msg : response.data;
-event.on("PhoneCallInitiated", function (call) {
- _activeCalls[call.id] = call;
-});
+ if (cb) {
+ cb(data, response);
+ }
+ else if (errored) {
+ throw data;
+ }
-event.on("PhoneCallEnded", function (call) {
- delete _activeCalls[call.id];
-});
+ return data;
+ };
-_self = {
- logs: {
- onCallLogAdded: function (get, post, baton) {
- baton.take();
- _onCallLogAdded = baton;
- },
+ this.makeAsyncCall = function (success, error) {
+ var requestUri = composeUri(),
+ request = createXhrRequest(requestUri, true);
- onCallLogRemoved: function (get, post, baton) {
- baton.take();
- _onCallLogRemoved = baton;
- },
+ request.onreadystatechange = function () {
+ if (request.readyState === 4 && request.status === 200) {
+ var response = JSON.parse(request.responseText || "null"),
+ cb = response.code < 0 ? error : success,
+ data = response.code < 0 ? response.msg : response.data;
- onCallLogUpdated: function (get, post, baton) {
- baton.take();
- _onCallLogUpdated = baton;
- },
+ return cb && cb(data, response);
+ }
+ };
- onCallLogReset: function (get, post, baton) {
- baton.take();
- _onCallLogReset = baton;
- },
+ request.send(postString);
+ };
+}
- callAt: function (get) {
- var logs = _getLogs(get.folderID !== null && get.folderID !== undefined ?
- get.folderID : PhoneLogs.FOLDER_MISSED_CALLS);
- return {code: 1, data: logs.length > get.index ? logs[get.index] : null};
- },
+_self = {
+ call: function (url, opts, success, error) {
+ var request = new RemoteFunctionCall(url),
+ name;
- deleteCallAt: function (get) {
- var logs = _getLogs(),
- subLog = _getLogs(get.folderID),
- deleted = false,
- type, log;
+ opts = opts || {};
- if (subLog.length > get.index &&
- (type = _isNormalCall(subLog[get.index]) ? "normal" : "missed") &&
- (log = logs[type].splice(get.index, 1))) {
- event.trigger("PhoneCallLogRemoved", [log]);
- _saveLogs(logs);
- deleted = true;
+ if (opts.get) {
+ for (name in opts.get) {
+ if (Object.hasOwnProperty.call(opts.get, name)) {
+ request.addParam(name, opts.get[name]);
+ }
}
+ }
- return {code: 1, data: deleted};
- },
-
- find: function (get, post) {
- var data = select.from(_getLogs(post.folderID !== null && post.folderID !== undefined ?
- post.folderID : PhoneLogs.FOLDER_MISSED_CALLS))
- .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
- .max(post.maxReturn)
- .where(post.filter, select.ops.phone);
- return {code: 1, data: data};
- },
-
- numberOfCalls: function (get) {
- return {code: 1, data: _getLogs(get.folderID !== null && get.folderID !== undefined ?
- get.folderID : PhoneLogs.FOLDER_MISSED_CALLS).length};
+ if (opts.post) {
+ for (name in opts.post) {
+ if (Object.hasOwnProperty.call(opts.post, name)) {
+ request.addPostParam(name, opts.post[name]);
+ }
+ }
}
- },
- onPhoneEvent: function (get, post, baton) {
- baton.take();
- _onPhoneEventListeners[get.eventType] = baton;
+ return opts.async ? request.makeAsyncCall(success, error) : request.makeSyncCall(success, error);
},
- activeCalls: function () {
- var data = utils.map(_activeCalls, function (callItem) {
- var call = new PhoneCall(callItem.onhold);
- call.outgoing = callItem.outgoing;
- call.recipientName = callItem.recipient.name;
- call.recipientNumber = callItem.recipient.number;
- return call;
- });
- return {code: 1, data: data};
- },
+ poll: function (url, opts, callback) {
+ opts = opts || {};
+ opts.async = true;
- inActiveCall: function () {
- return {code: 1, data: utils.count(_activeCalls) > 0 ? true : false};
+ _self.call(url, opts, function (data, response) {
+ if (callback(data, response)) {
+ _self.poll(url, opts, callback);
+ }
+ });
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/push', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- utils = require('ripple/utils'),
- _handlers = {},
- _self;
-
-function listenersChanged() {
- var ports = utils.map(_handlers, function (handler) {
- return handler.port;
- });
- event.trigger("PushListenersChanged", [ports]);
-}
+define('ripple/platform/webworks.core/2.0.0/client/system', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
+ _uri = "blackberry/system/",\r
+ _self;\r
+\r
+_self = {\r
+ hasCapability: function (capability) {\r
+ return transport.call(_uri + "hasCapability", {\r
+ get: {capability: capability}\r
+ });\r
+ },\r
+\r
+ hasDataCoverage: function () {\r
+ return transport.call(_uri + "hasDataCoverage");\r
+ },\r
+\r
+ hasPermission: function (desiredModule) {\r
+ return transport.call(_uri + "hasPermission", {\r
+ get: {desiredModule: desiredModule}\r
+ });\r
+ },\r
+\r
+ isMassStorageActive: function () {\r
+ return transport.call(_uri + "isMassStorageActive");\r
+ }\r
+};\r
+\r
+_self.__defineGetter__("model", function () {\r
+ return transport.call(_uri + "model");\r
+});\r
+_self.__defineGetter__("scriptApiVersion", function () {\r
+ return transport.call(_uri + "scriptApiVersion");\r
+});\r
+_self.__defineGetter__("softwareVersion", function () {\r
+ return transport.call(_uri + "softwareVersion");\r
+});\r
+\r
+_self.__defineGetter__("ALLOW", function () {\r
+ return 0;\r
+});\r
+_self.__defineGetter__("DENY", function () {\r
+ return 1;\r
+});\r
+_self.__defineGetter__("PROMPT", function () {\r
+ return 2;\r
+});\r
+_self.__defineGetter__("NOT_SET", function () {\r
+ return 3;\r
+});\r
+\r
+module.exports = _self;\r
-event.on("Push", function (data, port) {
- var handler = _handlers["port_" + port];
- delete _handlers["port_" + port];
- window.setTimeout(function () {
- if (!_handlers["port_" + port]) {
- //doesn't look like they are coming back ;)
- listenersChanged();
- }
- }, 100);
- return handler && handler.baton.pass({code: 1, data: data});
});
-
-_self = {
-
- onPush: function (args, post, baton) {
- if (!args.port) {
- throw "no port specified";
- }
- else if (typeof args.port !== 'number') {
- throw "port is not a number";
- }
- baton.take();
- _handlers["port_" + args.port] = {
- port: args.port,
- baton: baton
- };
- listenersChanged();
- }
-};
-
-module.exports = _self;
+define('ripple/platform/webworks.core/2.0.0/client/dialog', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Research In Motion Limited.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
+ _uri = "blackberry/ui/dialog/",\r
+ _self;\r
+\r
+function getButtonsForDialogType(dialogType) {\r
+ switch (dialogType) {\r
+ case _self.D_OK:\r
+ return ["Ok"];\r
+ case _self.D_SAVE:\r
+ return ["Save", "Discard"];\r
+ case _self.D_DELETE:\r
+ return ["Delete", "Cancel"];\r
+ case _self.D_YES_NO:\r
+ return ["Yes", "No"];\r
+ case _self.D_OK_CANCEL:\r
+ return ["Ok", "Cancel"];\r
+ default:\r
+ throw new Error("Invalid dialog type: " + dialogType);\r
+ }\r
+}\r
+\r
+_self = {\r
+ customAskAsync: function (message, choices, callback, settings) {\r
+ return transport.call(_uri + "ask", {\r
+ async: true,\r
+ get: {\r
+ message: message,\r
+ buttons: choices,\r
+ settings: settings\r
+ }\r
+ }, function (response) {\r
+ if (callback) {\r
+ callback(response);\r
+ }\r
+ });\r
+ },\r
+\r
+ standardAskAsync: function (message, type, callback, settings) {\r
+ var choices = getButtonsForDialogType(type);\r
+ return transport.call(_uri + "ask", {\r
+ async: true,\r
+ get: {\r
+ message: message,\r
+ buttons: choices,\r
+ settings: settings\r
+ }\r
+ }, function (response) {\r
+ if (callback) {\r
+ callback(response);\r
+ }\r
+ });\r
+ }\r
+};\r
+\r
+_self.__defineGetter__("D_OK", function () {\r
+ return 0;\r
+});\r
+\r
+_self.__defineGetter__("D_SAVE", function () {\r
+ return 1;\r
+});\r
+\r
+_self.__defineGetter__("D_DELETE", function () {\r
+ return 2;\r
+});\r
+\r
+_self.__defineGetter__("D_YES_NO", function () {\r
+ return 3;\r
+});\r
+\r
+_self.__defineGetter__("D_OK_CANCEL", function () {\r
+ return 4;\r
+});\r
+\r
+_self.__defineGetter__("BOTTOM", function () {\r
+ return "bottomCenter";\r
+});\r
+\r
+_self.__defineGetter__("CENTER", function () {\r
+ return "middleCenter";\r
+});\r
+\r
+_self.__defineGetter__("TOP", function () {\r
+ return "topCenter";\r
+});\r
+\r
+_self.__defineGetter__("SIZE_FULL", function () {\r
+ return "full";\r
+});\r
+\r
+_self.__defineGetter__("SIZE_LARGE", function () {\r
+ return "large";\r
+});\r
+\r
+_self.__defineGetter__("SIZE_MEDIUM", function () {\r
+ return "medium";\r
+});\r
+\r
+_self.__defineGetter__("SIZE_SMALL", function () {\r
+ return "small";\r
+});\r
+\r
+_self.__defineGetter__("SIZE_TALL", function () {\r
+ return "tall";\r
+});\r
+\r
+module.exports = _self;\r
});
-define('ripple/platform/webworks.handset/2.0.0/server/sms', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/events', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _listener,
- _isListening = false,
- notifications = require('ripple/notifications'),
- constants = require('ripple/constants'),
- event = require('ripple/event'),
- _console = require('ripple/console'),
- _onReceive,
+var _handlers = [],
_self;
-event.on("MessageReceived", function (message) {
- if (!_isListening || message.type !== 'sms') {
- return;
- }
-
- var baton = _onReceive;
- _onReceive = null;
- _isListening = false;
- return baton && baton.pass({code: 1, data: message});
-});
-
_self = {
- onReceive: function (args, post, baton) {
- baton.take();
- _onReceive = baton;
- _isListening = !!_onReceive;
+ eventsMap: {
+ getHandlerById: function (handlerId) {
+ return _handlers[handlerId];
+ },
+ addHandler: function (handler) {
+ _handlers.push(handler);
+ return _handlers.length - 1;
+ },
+ removeHandler: function (handlerId) {
+ if (handlerId > -1 && handlerId < _handlers.length) {
+ delete _handlers[handlerId]; //cannot splice because all published IDs would refer to the wrong handler
+ }
+ }
},
- send: function (args) {
- var msg = "To " + args.address + ": " + args.message;
- notifications.openNotification("normal", msg);
- _console.log(msg);
- return {code: 1};
+ registerEventHandler : function (eventName, eventCallback, eventParams) {
+ return _self.eventsMap.addHandler(eventCallback);
},
- isListeningForMessage: function (get, post, baton) {
- if (get && typeof get.isListeningForMessage === "boolean") {
- _isListening = get.isListeningForMessage;
- }
-
- return {code: 1, data: _isListening};
+ getEventHandler : function (handlerId) {
+ return _self.eventsMap.getHandlerById(handlerId);
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.handset/2.0.0/server/systemEvent', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/utils', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- _onCoverageChange,
- _onHardwareKey = {};
+var _blobs = {};
-event.on("CoverageChange", function () {
- var baton = _onCoverageChange;
- _onCoverageChange = null;
- return baton && baton.pass({code: 1});
-});
+function _blobBuilder() {
+ var BlobBuilder = BlobBuilder || WebKitBlobBuilder;
+ return new BlobBuilder();
+}
-event.on("HardwareKey", function (key) {
- var baton = _onHardwareKey["key_" + key];
- delete _onHardwareKey["key_" + key];
+module.exports = {
+ parseURL: function (theUrl) {
+ /********START IDEA BORROWING*******/
+ // parseUri 1.2.2
+ // (c) Steven Levithan <stevenlevithan.com>
+ // MIT License
- if (baton) {
- baton.pass({code: 1});
- }
- else {
- event.trigger("HardwareKeyDefault", [key]);
- }
-});
+ function parseUri(str) {
+ var o = parseUri.options,
+ m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
+ uri = {},
+ i = 14;
-module.exports = {
- onCoverageChange: function (args, post, baton) {
- baton.take();
- _onCoverageChange = baton;
+ while (i--) {
+ uri[o.key[i]] = m[i] || "";
+ }
+
+ uri[o.q.name] = {};
+ uri[o.q.arrayName] = [];
+ uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
+ if ($1) {
+ uri[o.q.name][$1] = $2;
+ uri[o.q.arrayName].push($2);
+ }
+ });
+
+ return uri;
+ }
+
+ parseUri.options = {
+ strictMode: false,
+ key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
+ q: {
+ name: "queryKey",
+ arrayName: "queryArray",
+ parser: /(?:^|&)([^&=]*)=?([^&]*)/g
+ },
+ parser: {
+ strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
+ loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
+ }
+ };
+ /********END IDEA BORROWING*******/
+
+ parseUri.strictMode = "strict";
+ var uri = parseUri(theUrl),
+ retVal = {
+ getURLParameter : function (key) {
+ return uri.queryKey[key];
+ },
+
+ getURLParameterByIndex : function (index) {
+ return uri.queryArray[index];
+ }
+ };
+
+ //Add default values for the http/https port if they weren't specified in the URL. The above parser returns undefined. We need the values
+ //to be compatible with the BB version of API.
+ if (uri["port"] === "") {
+ if (uri["protocol"] === "http") {
+ uri["port"] = "80";
+ }
+ else if (uri["protocol"] === "https") {
+ uri["port"] = "443";
+ }
+ else {
+ uri["port"] = "0";
+ }
+ }
+
+ retVal.__defineGetter__("host", function () {
+ return uri["host"];
+ });
+ retVal.__defineGetter__("port", function () {
+ return parseInt(uri["port"], 10);
+ });
+
+ return retVal;
},
- onHardwareKey: function (args, post, baton) {
- baton.take();
- _onHardwareKey["key_" + args.key] = baton;
+ generateUniqueId: function () {
+ return Math.floor(Math.random() * Number.MAX_VALUE);
+ },
+
+ blobToString: function (blob, encoding) {
+ return _blobs[blob.id];
+ },
+
+ stringToBlob: function (string, encoding) {
+ var id = Math.uuid(undefined, 16),
+ blob = _blobBuilder(),
+ finalBlob;
+
+ _blobs[id] = string;
+ blob.append(string);
+
+ finalBlob = blob.getBlob();
+ finalBlob.id = id;
+ finalBlob.length = finalBlob.size;
+
+ return finalBlob;
}
};
});
-define('ripple/platform/webworks.handset/2.0.0/server', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/client/FileProperties', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- platform = "ripple/platform/webworks.handset/2.0.0/server/",
- core = "ripple/platform/webworks.core/2.0.0/server/",
- systemEvent = require(platform + 'systemEvent'),
- system = {};
-
-// ugh, thanks to the spec...
-system.event = systemEvent;
-utils.mixin(require(core + "system"), system);
+function FileProperties(props) {
+ props = props || {};
-module.exports = {
- blackberry: {
- invoke: require(platform + "invoke"),
- system: system,
- app: require(platform + "app"),
- identity: require(platform + "identity"),
- message: {
- sms: require(platform + "sms"),
- message: require(platform + "message")
- },
- push: require(platform + "push"),
- pim: {
- Task: require(platform + "Task"),
- category: require(platform + "category"),
- memo: require(platform + "memo"),
- appointment: require(platform + "appointment"),
- contact: require(platform + "contact")
- },
- audio: {
- player: require(platform + "audioPlayer")
- },
- ui: {
- menu: require(platform + "menu"),
- dialog: require(core + "dialog")
- },
- phone: require(platform + "phone"),
- io: {
- dir: require(platform + "io/dir"),
- file: require(core + "io/file")
- }
+ function _get(val) {
+ return function () {
+ return props[val];
+ };
}
-};
+
+ this.__defineGetter__("dateCreated", _get("dateCreated")); //tablet only
+ this.__defineGetter__("dateModified", _get("dateModified"));
+ this.__defineGetter__("directory", _get("directory"));
+ this.__defineGetter__("fileExtension", _get("fileExtension"));
+ this.__defineGetter__("isHidden", _get("isHidden"));
+ this.__defineGetter__("isReadonly", _get("isReadonly")); //handset only
+ this.__defineGetter__("mimeType", _get("mimeType")); //handset only
+ this.__defineGetter__("size", _get("size"));
+}
+
+module.exports = FileProperties;
});
-define('ripple/platform/webworks.handset/2.0.0/spec/device', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/select', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event');
-
-module.exports = {
- "transports": {
- "TCP Cellular": {
- "name": "Cellular TCP",
- "control": {
- "type": "checkbox",
- "value": true
- }
+var utils = require('ripple/utils'),
+ _select,
+ _predicates = {
+ "==": function (left, right) {
+ return left === right;
},
- "Wap": {
- "name": "WAP",
- "control": {
- "type": "checkbox",
- "value": false
- }
+ "!=": function (left, right) {
+ return left !== right;
},
- "Wap 2.0": {
- "name": "WAP 2.0",
- "control": {
- "type": "checkbox",
- "value": false
- }
+ "<": function (left, right) {
+ return left < right;
},
- "MDS": {
- "name": "MDS",
- "control": {
- "type": "checkbox",
- "value": true
- }
+ ">": function (left, right) {
+ return left > right;
},
- "Bis B": {
- "name": "BIS B",
- "control": {
- "type": "checkbox",
- "value": true
- }
+ "<=": function (left, right) {
+ return left <= right;
},
- "Unite!": {
- "name": "Unite",
- "control": {
- "type": "checkbox",
- "value": false
- }
+ ">=": function (left, right) {
+ return left >= right;
},
- "TCP Wifi": {
- "name": "Wifi TCP",
- "control": {
- "type": "checkbox",
- "value": true
- }
- }
- },
- "identity": {
- "IMEI": {
- "name": "IMEI",
- "control": {
- "type": "text",
- "value": "123456786543210"
- }
+ "REGEX": function (left, right) {
+ return left && left.match(new RegExp(right));
},
- "IMSI": {
- "name": "IMSI",
- "control": {
- "type": "text",
- "value": "310150123456789"
- }
+ "CONTAINS": function (left, right) {
+ return left.indexOf(right) >= 0;
+ }
+ };
+
+function isFilter(field) {
+ return field && field.operator !== undefined && field.operator !== null;
+}
+
+function extractValue(item, field) {
+ return field.split(".").reduce(function (value, prop) {
+ return value[prop];
+ }, item);
+}
+
+function copy(items) {
+ //use a reduce to ensure that we always just return an array
+ //not the most performant but will whitewash the result
+ return utils.reduce(items, function (array, item) {
+ array.push(item);
+ return array;
+ }, []);
+}
+
+_select = {
+ ops: {
+ find: {
+ 0: "!=",
+ 1: "==",
+ 2: "<",
+ 3: "<=",
+ 4: ">",
+ 5: ">=",
+ 8: "REGEX",
+ 16: "AND",
+ 32: "OR",
+ 64: "CONTAINS"
},
- "PIN": {
- "name": "PIN",
- "control": {
- "type": "text",
- "value": "43A8C489"
- }
+ phone: {
+ 0: "!=",
+ 1: "==",
+ 2: "<",
+ 3: "<=",
+ 4: ">",
+ 5: ">=",
+ 8: "AND",
+ 16: "OR",
+ 32: "CONTAINS"
}
},
- "system": {
- "isMassStorageActive": {
- "name": "Mass Storage Is Connected",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "hasDataCoverage": {
- "name": "Has Data Coverage",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("CoverageChange");
- require('ripple/bus').send("network", setting);
- }
- },
- "lag": {
- "name": "Lag the network",
- "control": {
- type: "checkbox",
- value: false
- },
- "callback": function (setting) {
- require('ripple/bus').send("lag", setting);
- }
- },
- "network": {
- "name": "Data Network",
- "control": {
- "type": "select",
- "value": "3GPP"
+ from: function (items) {
+ var _getPredicate = function (filter, operators) {
+
+ var noOp = function () {
+ return false;
+ },
+ operator = (function () {
+ var result = operators[filter.operator] || filter.operator,
+ exists = function (op) {
+ return result === op;
+ };
+
+ return utils.some(operators, exists) ? result : "";
+ }());
+
+ return function (item) {
+ var left = extractValue(item, filter.leftField),
+ right = filter.rightField,
+ predicate = _predicates[operator] || noOp;
+
+ return filter.negate ? !predicate(left, right) : predicate(left, right);
+ };
+
},
- "options": {
- "3GPP" : "3GPP",
- "CDMA": "CDMA",
- "iDEN": "iDEN",
- "Wi-Fi": "Wi-Fi"
+ _applyFilter = function (filter, operators) {
+ var result = [],
+ left,
+ right,
+ op;
+
+ if (isFilter(filter.leftField) && isFilter(filter.rightField)) {
+
+ left = _select.from(items).where(filter.leftField);
+ right = _select.from(items).where(filter.rightField);
+ op = operators[filter.operator] || filter.operator;
+
+ switch (op) {
+ case "AND":
+ result = left.filter(function (item) {
+ return right.indexOf(item) >= 0;
+ });
+ break;
+ case "OR":
+ result = left.concat(right.filter(function (item) {
+ return left.indexOf(item) < 0;
+ }));
+ break;
+ }
+
+ if (filter.negate) {
+ //reverse the result set.
+ result = utils.filter(items, function (item) {
+ return result.indexOf(item) < 0;
+ });
+ }
+ }
+ else {
+ result = utils.filter(items, _getPredicate(filter, operators));
+ }
+
+ return result;
},
- "callback": function (setting) {
- event.trigger("CoverageChange");
- }
- }
- }
-};
+ _orderBy,
+ _max,
+ _direction,
+ _self = {
+ orderBy: function (prop, dir) {
+ _orderBy = prop;
+ _direction = dir || "asc";
+ return _self;
+ },
+ max: function (max) {
+ _max = max;
+ return _self;
+ },
+ where: function (filter, ops) {
+ var result = isFilter(filter) ? _applyFilter(filter, ops || _select.ops.find) : copy(items);
-});
-define('ripple/platform/webworks.handset/2.0.0/spec/events', function (require, exports, module) {
-/*
- * Copyright 2011 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 _self,
- utils = require('ripple/utils'),
- event = require('ripple/event'),
- events = require('ripple/platform/webworks.core/2.0.0/spec/events');
+ result.sort(function (a, b) {
+ if (a[_orderBy] < b[_orderBy]) {
+ return _direction === "asc" ? -1 : 1;
+ }
+ else if (a[_orderBy] > b[_orderBy]) {
+ return _direction === "asc" ? 1: -1;
+ }
+ return 0;
+ });
-_self = {
- "system.event.onExit": {
- callback: function () {
- event.trigger("AppExit");
- }
- },
- "system.event.onCoverageChange": {
- callback: function () {
- event.trigger("CoverageChange");
- }
- },
- "system.event.onHardwareKey": {
- args: [
- "Back",
- "Menu",
- "Convenience 1",
- "Convenience 2",
- "Start Call",
- "End Call",
- "Volume Down",
- "Volume Up"
- ],
- callback: function (key) {
- event.trigger("HardwareKey", [key]);
- }
+ return result.slice(0, _max === null || _max === -1 ? undefined : _max); // slice in V8 returns empty array if null
+ }
+ };
+
+ return _self;
}
};
-utils.mixin(events, _self);
-
-module.exports = _self;
+module.exports = _select;
});
-define('ripple/platform/webworks.handset/2.0.0/spec/ui', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/spec/config', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-module.exports = {
- plugins: [
- "accelerometer",
- "deviceSettings",
- "geoView",
- "platformEvents",
- "widgetConfig",
- "messaging",
- "push",
- "phone",
- "build"
- ]
-};
+var utils = require('ripple/utils');
-});
-define('ripple/platform/webworks.handset/2.0.0/spec', function (require, exports, module) {
-/*
- * Copyright 2011 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 = {
+ fileName: "config.xml",
+ validateVersion: function (config) {
+ return true;
+ },
+ extractInfo: function (config) {
+ if (!config) {
+ return null;
+ }
- id: "webworks.handset",
- version: "2.0.0",
- name: "WebWorks",
+ var widgetInfo = {},
+ widgetFeatures = config.widget.children.feature.validationResult,
+ accessUrls = config.widget.children.access.validationResult,
+ accessFeatures = config.widget.children.access.children.feature.validationResult,
+ toFeature = function (validationResult) {
+ return {
+ id: validationResult.attributes.id.value,
+ required: !validationResult.attributes.required || validationResult.attributes.required.value,
+ URIs: []
+ };
+ };
- persistencePrefix: "rim-handset-",
+ widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
+ widgetInfo.name = config.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
+ widgetInfo.author = config.widget.children.author.validationResult[0].value;
+ widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
+ widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
+ widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
+ widgetInfo.description = config.widget.children.description.validationResult[0].value;
+ if (config.widget.children.license.validationResult[0]) {
+ widgetInfo.license = config.widget.children.license.validationResult[0].value;
+ widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
+ }
- ui: require('ripple/platform/webworks.handset/2.0.0/spec/ui'),
- device: require('ripple/platform/webworks.handset/2.0.0/spec/device'),
- config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
- events: require('ripple/platform/webworks.handset/2.0.0/spec/events'),
+ widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
+ if (validationResult.valid) {
+ var feature = toFeature(validationResult);
+ feature.URIs.push({
+ value: utils.location().href,
+ subdomains: true
+ });
+ features = features || {};
+ features[feature.id] = feature;
+ }
+ return features;
+ }, {});
- initialize: function () {},
+ widgetInfo.features = accessUrls.map(function (access) {
+ return {
+ uri: access.attributes.uri.value,
+ subdomains: access.attributes.subdomains.value,
+ features: accessFeatures ? accessFeatures.filter(function (f) {
+ return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
+ }) : null
+ };
+ }).reduce(function (result, access) {
+ return access.features ? access.features.reduce(function (features, validationResult) {
+ var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
+ feature.URIs.push({
+ value: access.uri,
+ subdomains: access.subdomains
+ });
+ features[feature.id] = feature;
+ return features;
+ }, result) : result;
+ }, widgetInfo.features);
- objects: {
- XMLHttpRequest: {
- path: "webworks.handset/2.0.0/XMLHttpRequest"
- },
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
- navigator: {
- path: "w3c/1.0/navigator",
- children: {
- geolocation: {
- path: "w3c/1.0/geolocation"
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:rim": {
+ attributeName: "xmlns:rim",
+ required: true,
+ type: "list",
+ listValues: ["http://www.blackberry.com/ns/widgets"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ "rim:header": {
+ attributeName: "rim:header",
+ required: false,
+ type: "string"
+ },
+ "rim:backButton": {
+ attributeName: "rim:backButton",
+ required: false,
+ type: "string"
}
- }
- },
- blackberry: {
- path: "webworks.handset/2.0.0/client/blackberry",
+ },
children: {
- pim: {
- path: "webworks.handset/2.0.0/client/pim",
- feature: "blackberry.pim.category|blackberry.pim.Task|blackberry.pim.Recurrence|blackberry.pim.Reminder|blackberry.pim.Appointment|blackberry.pim.Address|blackberry.pim.Attendee|blackberry.pim.Memo|blackberry.pim.Contact",
- children: {
- category: {
- path: "webworks.handset/2.0.0/client/category",
- feature: "blackberry.pim.category"
- },
- Task: {
- path: "webworks.handset/2.0.0/client/Task",
- feature: "blackberry.pim.Task"
+ name: {
+ nodeName: "name",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
},
- Recurrence: {
- path: "webworks.handset/2.0.0/client/Recurrence",
- feature: "blackberry.pim.Recurrence"
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
},
- Reminder: {
- path: "webworks.handset/2.0.0/client/Reminder",
- feature: "blackberry.pim.Reminder"
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
},
- Appointment: {
- path: "webworks.handset/2.0.0/client/Appointment",
- feature: "blackberry.pim.Appointment"
+ "rim:hover": {
+ attributeName: "rim:hover",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "string",
+ required: false
},
- Address: {
- path: "webworks.handset/2.0.0/client/Address",
- feature: "blackberry.pim.Address"
+ "rim:copyright": {
+ attributeName: "rim:copyright",
+ type: "string",
+ required: false
},
- Attendee: {
- path: "webworks.handset/2.0.0/client/Attendee",
- feature: "blackberry.pim.Attendee"
+ email: {
+ attributeName: "email",
+ type: "string",
+ required: false
},
- Memo: {
- path: "webworks.handset/2.0.0/client/Memo",
- feature: "blackberry.pim.Memo"
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
},
- Contact: {
- path: "webworks.handset/2.0.0/client/Contact",
- feature: "blackberry.pim.Contact"
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
}
}
},
- phone: {
- children: {
- Phone: {
- path: "webworks.handset/2.0.0/client/Phone",
- feature: "blackberry.phone.Phone"
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 1,
+ attributes : {
+ href: {
+ attributeName: "href",
+ type: "string",
+ required: false
},
- PhoneLogs: {
- path: "webworks.handset/2.0.0/client/PhoneLogs",
- feature: "blackberry.phone.PhoneLogs|blackberry.phone.Find",
- children: {
- CallLog: {
- path: "webworks.handset/2.0.0/client/CallLog"
- }
- }
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
},
- Find: {
- children: {
- FilterExpression: {
- path: "webworks.handset/2.0.0/client/FilterExpression",
- feature: "blackberry.phone.Find"
- }
- }
+ "its:dir": {
+ attributeName: "its:dir",
+ required: false,
+ type: "list",
+ listValues: ["rtl", "ltr", "lro", "rlo"]
}
}
},
- message: {
- path: "webworks.handset/2.0.0/client/messaging",
- feature: "blackberry.message.sms|blackberry.message",
- children: {
- sms: {
- path: "webworks.handset/2.0.0/client/sms",
- feature: "blackberry.message.sms"
+ "rim:cache": {
+ nodeName: "rim:cache",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ disableAllCache: {
+ attributeName: "disableAllCache",
+ required: false,
+ type: "boolean"
},
- Message: {
- path: "webworks.handset/2.0.0/client/Message",
- feature: "blackberry.message"
+ aggressiveCacheAge: {
+ attributeName: "aggressiveCacheAge",
+ required: false,
+ type: "number"
+ },
+ maxCacheSizeTotal: {
+ attributeName: "maxCacheSizeTotal",
+ required: false,
+ type: "number"
+ },
+ maxCacheSizeItem: {
+ attributeName: "maxCacheSizeItem",
+ required: false,
+ type: "number"
}
}
},
- transport: {
- path: "webworks.core/2.0.0/client/transport"
- },
- events: {
- path: "webworks.core/2.0.0/client/events"
- },
- app: {
- path: "webworks.handset/2.0.0/client/app",
- feature: "blackberry.app",
+ access: {
+ nodeName: "access",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ uri: {
+ attributeName: "uri",
+ required: true,
+ type: "string"
+ },
+ subdomains: {
+ attributeName: "subdomains",
+ required: false,
+ type: "boolean"
+ }
+ },
children: {
- event: {
- path: "webworks.handset/2.0.0/client/appEvent",
- feature: "blackberry.app.event"
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ //TODO: this should be a list
+ type: "string"
+ },
+ required: {
+ attributeName: "required",
+ required: false,
+ type: "boolean"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ }
+ }
}
}
},
- invoke: {
- path: "webworks.handset/2.0.0/client/invoke",
- feature: "blackberry.invoke",
- children: {
- AddressBookArguments: {
- path: "webworks.handset/2.0.0/client/AddressBookArguments",
- feature: "blackberry.invoke.AddressBookArguments"
- },
- BrowserArguments: {
- path: "webworks.handset/2.0.0/client/BrowserArguments",
- feature: "blackberry.invoke.BrowserArguments"
- },
- CameraArguments: {
- path: "webworks.handset/2.0.0/client/CameraArguments",
- feature: "blackberry.invoke.CameraArguments"
- },
- CalendarArguments: {
- path: "webworks.handset/2.0.0/client/CalendarArguments",
- feature: "blackberry.invoke.CalendarArguments"
- },
- JavaArguments: {
- path: "webworks.handset/2.0.0/client/JavaArguments",
- feature: "blackberry.invoke.JavaArguments"
- },
- MapsArguments: {
- path: "webworks.handset/2.0.0/client/MapsArguments",
- feature: "blackberry.invoke.MapsArguments"
- },
- MemoArguments: {
- path: "webworks.handset/2.0.0/client/MemoArguments",
- feature: "blackberry.invoke.MemoArguments"
- },
- MessageArguments: {
- path: "webworks.handset/2.0.0/client/MessageArguments",
- feature: "blackberry.invoke.MessageArguments"
- },
- PhoneArguments: {
- path: "webworks.handset/2.0.0/client/PhoneArguments",
- feature: "blackberry.invoke.PhoneArguments"
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ id: {
+ attributeName: "id",
+ required: true,
+ //TODO: this should be a list
+ type: "string"
},
- SearchArguments: {
- path: "webworks.handset/2.0.0/client/SearchArguments",
- feature: "blackberry.invoke.SearchArguments"
+ required: {
+ attributeName: "required",
+ required: false,
+ type: "boolean"
},
- TaskArguments: {
- path: "webworks.handset/2.0.0/client/TaskArguments",
- feature: "blackberry.invoke.TaskArguments"
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
}
}
},
- identity: {
- path: "webworks.handset/2.0.0/client/identity",
- feature: "blackberry.identity",
- children: {
- Transport: {
- path: "webworks.handset/2.0.0/client/identity/Transport",
- feature: "blackberry.identity"
+ "rim:loadingScreen": {
+ nodeName: "rim:loadingScreen",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ backgroundColor: {
+ attributeName: "backgroundColor",
+ required: false,
+ type: "string"
},
- Service: {
- path: "webworks.handset/2.0.0/client/identity/Service",
- feature: "blackberry.identity"
+ backgroundImage: {
+ attributeName: "backgroundImage",
+ required: false,
+ type: "string"
},
- phone: {
- path: "webworks.handset/2.0.0/client/identity/phone",
- feature: "blackberry.identity.phone"
- }
- }
- },
- system: {
- path: "webworks.handset/2.0.0/client/system",
- feature: "blackberry.system",
- children: {
- event: {
- path: "webworks.handset/2.0.0/client/systemEvent",
- feature: "blackberry.system.event"
+ foregroundImage: {
+ attributeName: "foregroundImage",
+ required: false,
+ type: "string"
+ },
+ onRemotePageLoad: {
+ attributeName: "onRemotePageLoad",
+ required: false,
+ type: "boolean"
+ },
+ onLocalPageLoad: {
+ attributeName: "onLocalPageLoad",
+ required : false,
+ type: "boolean"
+ },
+ onFirstLaunch: {
+ attributeName: "onFirstLaunch",
+ required: false,
+ type: "boolean"
}
- }
- },
- ui: {
+ },
children: {
- dialog: {
- path: "webworks.core/2.0.0/client/dialog",
- feature: "blackberry.ui.dialog"
- },
- menu: {
- path: "webworks.handset/2.0.0/client/menu",
- children: {
- MenuItem: {
- path: "webworks.handset/2.0.0/client/MenuItem"
+ "rim:transitionEffect": {
+ nodeName: "rim:transitionEffect",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "type": {
+ attributeName: "type",
+ required: true,
+ type: "list",
+ listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
+ },
+ duration: {
+ attributeName: "duration",
+ required: false,
+ type: "number"
+ },
+ direction: {
+ attributeName: "direction",
+ required: false,
+ type: "list",
+ listValues: ["left", "right", "up", "down"]
}
}
}
}
},
- utils: {
- path: "webworks.core/2.0.0/client/utils",
- feature: "blackberry.utils"
- },
- find: {
- feature: "blackberry.find",
+ "rim:connection": {
+ nodeName: "rim:connection",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ timeout: {
+ attributeName: "timeout",
+ required: false,
+ type: "number"
+ }
+ },
children: {
- FilterExpression: {
- path: "webworks.handset/2.0.0/client/FilterExpression",
- feature: "blackberry.find"
+ id: {
+ nodeName: "id",
+ required: false,
+ occurrence: 0
}
}
},
- push: {
- path: "webworks.handset/2.0.0/client/push",
- feature: "blackberry.push"
- },
- audio: {
- path: "webworks.handset/2.0.0/client/audio",
- feature: "blackberry.audio",
- children: {
- Player: {
- path: "webworks.handset/2.0.0/client/AudioPlayer",
- feature: "blackberry.audio.Player"
+ "rim:navigation": {
+ nodeName: "rim:navigation",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ mode: {
+ attributeName: "mode",
+ required: false,
+ type: "list",
+ listValues: ["focus"]
}
}
},
- io: {
- children: {
- dir: {
- path: "webworks.handset/2.0.0/client/io/dir",
- feature: "blackberry.io.dir"
+ "content": {
+ nodeName: "content",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
},
- file: {
- path: "webworks.core/2.0.0/client/io/file",
- feature: "blackberry.io.file"
+ type: {
+ attributeName: "type",
+ required: false,
+ type: "string"
+ },
+ charset: {
+ attributeName: "charset",
+ required: false,
+ type: "string"
}
}
}
};
});
-define('ripple/platform/webworks.tablet/2.0.0/XMLHttpRequest', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/spec/events', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+var event = require('ripple/event');
-var xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
-module.exports = xhr.create("ripple/platform/webworks.tablet/2.0.0/server");
-
-});
-define('ripple/platform/webworks.tablet/2.0.0/client/BrowserArguments', function (require, exports, module) {
-/*
- * Copyright 2011 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.
- */
-//blackberry.invoke.BrowserArguments ( url : String , [transport : blackberry.identity.Transport ] )
-module.exports = function (url, transport) {
- return {
- url: url
- };
+module.exports = {
+ "app.event.onBackground": {
+ callback: function () {
+ event.trigger("AppRequestBackground");
+ }
+ },
+ "app.event.onForeground": {
+ callback: function () {
+ event.trigger("AppRequestForeground");
+ }
+ }
};
});
-define('ripple/platform/webworks.tablet/2.0.0/client/CameraArguments', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/server/io/file', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-//blackberry.invoke.CameraArguments ( )
-var _self = function () {
+var cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
+ constants = require('ripple/constants'),
+ notifications = require('ripple/notifications');
+
+function _packet(data) {
return {
- //readwrite property Number view
- view: 0
+ code: 1,
+ data: data
};
-};
+}
-//const Number VIEW_CAMERA = 0
-_self.__defineGetter__("VIEW_CAMERA", function () {
- return 0;
-});
-//const Number VIEW_RECORDER = 1
-_self.__defineGetter__("VIEW_RECORDER", function () {
- return 1;
-});
+module.exports = {
+ copy: function (get, post, baton) {
+ cache.file.copy(post.from, post.to);
+ return _packet();
+ },
+ deleteFile: function (get, post, baton) {
+ cache.file.deleteFile(post.path);
+ return _packet();
+ },
+ exists: function (get, post, baton) {
+ return _packet(cache.file.exists(post.path));
+ },
+ getFileProperties: function (get, post, baton) {
+ return _packet(cache.file.getFileProperties(post.path));
+ },
+ open: function (get, post, baton) {
+ var msg = "Attempting to open file: " + post.path;
+ notifications.openNotification("normal", msg);
+ return _packet(cache.file.exists(post.path));
+ },
+ readFile: function (get, post, baton) {
+ var val;
-module.exports = _self;
+ if (post.async) {
+ baton.take();
+ }
+
+ cache.file.readFile(post.path, function (data) {
+ if (post.async) {
+ baton.pass(_packet({
+ fullPath: post.path,
+ blobData: data
+ }));
+ } else {
+ val = data;
+ }
+ }, post.async);
+
+ if (!post.async) {
+ return _packet({
+ fullPath: post.path,
+ blobData: val
+ });
+ }
+ },
+ rename: function (get, post, baton) {
+ cache.file.rename(post.path, post.newName);
+ return _packet();
+ },
+ saveFile: function (get, post, baton) {
+ cache.file.saveFile(post.path, post.blob);
+ return _packet();
+ }
+};
});
-define('ripple/platform/webworks.tablet/2.0.0/client/app', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/server/io/dir', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/app/",
- _self;
+var cache = require('ripple/platform/webworks.core/2.0.0/fsCache');
-_self = {
- exit: function () {
- transport.call(_uri + "exit", {async: true});
+function _packet(data) {
+ return {
+ code: 1,
+ data: data
+ };
+}
+
+module.exports = {
+ createNewDir: function (get, post, baton) {
+ cache.dir.createNewDir(post.path);
+ return _packet();
+ },
+ deleteDirectory: function (get, post, baton) {
+ cache.dir.deleteDirectory(post.path, post.recursive);
+ return _packet();
+ },
+ exists: function (get, post, baton) {
+ return _packet(cache.dir.exists(post.path));
+ },
+ getParentDirectory: function (get, post, baton) {
+ return _packet(cache.dir.getParentDirectory(post.path));
+ },
+ listDirectories: function (get, post, baton) {
+ return _packet(cache.dir.listDirectories(post.path));
+ },
+ listFiles: function (get, post, baton) {
+ return _packet(cache.dir.listFiles(post.path));
+ },
+ rename: function (get, post, baton) {
+ cache.dir.rename(post.path, post.newName);
+ return _packet();
}
};
-_self.__defineGetter__("author", function () {
- return transport.call(_uri + "author");
-});
-
-_self.__defineGetter__("authorEmail", function () {
- return transport.call(_uri + "authorEmail");
-});
-
-_self.__defineGetter__("authorURL", function () {
- return transport.call(_uri + "authorURL");
-});
-
-_self.__defineGetter__("copyright", function () {
- return transport.call(_uri + "copyright");
-});
-
-_self.__defineGetter__("description", function () {
- return transport.call(_uri + "description");
-});
-
-_self.__defineGetter__("id", function () {
- return transport.call(_uri + "id");
-});
-
-_self.__defineGetter__("license", function () {
- return transport.call(_uri + "license");
-});
-
-_self.__defineGetter__("licenseURL", function () {
- return transport.call(_uri + "licenseURL");
-});
-
-_self.__defineGetter__("name", function () {
- return transport.call(_uri + "name");
-});
-
-_self.__defineGetter__("version", function () {
- return transport.call(_uri + "version");
-});
-
-module.exports = _self;
-
});
-define('ripple/platform/webworks.tablet/2.0.0/client/appEvent', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/server/system', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _callbacks = {},
+var deviceSettings = require('ripple/deviceSettings'),
+ devices = require('ripple/devices'),
+ app = require('ripple/app'),
+ client = require('ripple/platform/webworks.core/2.0.0/client/system'),
+ utils = require('ripple/utils'),
+ notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ platform = require('ripple/platform'),
_self;
-function _poll(evt, handler) {
- _callbacks[evt] = handler;
-
- transport.poll("blackberry/app/event/" + evt, {}, function () {
- var func = _callbacks[evt];
-
- if (func) {
- func();
+function _is(feature) {
+ return {
+ allowedFor: function (location) {
+ return feature && feature.URIs.some(function (uri) {
+ return uri.value === location ||
+ (location.indexOf(uri.value) >= 0 && uri.subdomains);
+ });
}
-
- return !!func;
- });
+ };
}
_self = {
- onBackground: function (handler) {
- _poll("onBackground", handler);
+ hasCapability: function (args) {
+ var capabilities = devices.getCurrentDevice().capabilities;
+ return {
+ code: 1,
+ data: capabilities ? capabilities.some(function (type) {
+ return type === args.capability;
+ }) : false
+ };
},
-
- onForeground: function (handler) {
- _poll("onForeground", handler);
+ isMassStorageActive: function () {
+ return {code: 1, data: deviceSettings.retrieveAsBoolean("system.isMassStorageActive")};
},
-
- onSwipeDown: function (handler) {
- _poll("onSwipeDown", handler);
+ hasDataCoverage: function () {
+ return {code: 1, data: deviceSettings.retrieveAsBoolean("system.hasDataCoverage")};
+ },
+ softwareVersion: function () {
+ return {code: 1, data: devices.getCurrentDevice().osVersion};
+ },
+ model: function () {
+ return {code: 1, data: devices.getCurrentDevice().model};
+ },
+ scriptApiVersion: function () {
+ return {code: 1, data: platform.current().version};
+ },
+ setHomeScreenBackground: function (args) {
+ var path = args.filePath,
+ msg = "Set home screen background to " + path + ".";
+ notifications.openNotification("normal", msg);
+ return {code: 1};
},
+ hasPermission: function (args) {
+ var info = app.getInfo(),
+ feature = info.features ? info.features[args.desiredModule] : null;
- onSwipeStart: function (handler) {
- _poll("onSwipeStart", handler);
+ return {code: 1, data: feature === null || _is(feature).allowedFor(utils.location().href) ? client.ALLOW : client.DENY};
+ },
+ network: function () {
+ return {code: 1, data: deviceSettings.retrieve("system.network")};
}
};
module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/client/identity', function (require, exports, module) {
+define('ripple/platform/webworks.core/2.0.0/server/dialog', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- _uri = "blackberry/identity/",
- _self = {};
+var event = require('ripple/event'),
+ devices = require('ripple/devices'),
+ ui = require('ripple/ui'),
+ utils = require('ripple/utils'),
+ isDialogVisible = false,
+ visibleDialogArgs,
+ _self;
-_self.__defineGetter__("PIN", function () {
- return transport.call(_uri + "PIN");
-});
+function closeDialog() {
+ var buttonsDiv = document.getElementById("dialog-buttons"),
+ messageDiv = document.getElementById("dialog-message");
-module.exports = _self;
+ ui.hideOverlay("dialog-window", function (dialog) {
+ buttonsDiv.innerHTML = "";
+ messageDiv.innerHTML = "";
+ isDialogVisible = false;
+ });
+}
+event.on("LayoutChanged", function () {
+ if (isDialogVisible) {
+ closeDialog();
+ //Used to resize dialog on orientation change
+ _self.ask(visibleDialogArgs);
+ }
});
-define('ripple/platform/webworks.tablet/2.0.0/client/invoke', function (require, exports, module) {
-/*\r
- * Copyright 2011 Research In Motion Limited.\r
- *\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-var _uri = "blackberry/invoke/invoke",\r
- APP_TYPE = "appType",\r
- APP_URL_CAMERA = "camera://",\r
- APP_URL_CAMERA_VIDEO = "camera://video",\r
- APP_URL_MAP = "map://",\r
- APP_URL_MUSIC = "music://",\r
- APP_URL_PHOTOS = "photos://",\r
- APP_URL_VIDEOS = "videos://",\r
- APP_URL_APPWORLD = "appworld://",\r
- APP_URL_UPDATE = "update://",\r
- APP_TYPE_ERROR = "appType not supported",\r
- APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",\r
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),\r
- _self;\r
-\r
-_self = {\r
- invoke: function (appType, args) {\r
- var get = {};\r
-\r
- switch (appType) {\r
-\r
- //Camera\r
- case 4:\r
- if (!args || args.view === 1) {\r
- get.appType = APP_URL_CAMERA_VIDEO;\r
- } else {\r
- get.appType = APP_URL_CAMERA;\r
- }\r
- break;\r
-\r
- //Maps\r
- case 5:\r
- get.appType = APP_URL_MAP;\r
- break;\r
-\r
- //Browser\r
- case 11:\r
-\r
- if (!args) {\r
- get.appType = "http://";\r
- }\r
- else {\r
- get.appType = args.url.split("://");\r
-\r
- if (get.appType.length === 1) {\r
- get.appType = "http://" + get.appType[0];\r
- }\r
- else if (get.appType.length === 2) {\r
- if (get.appType[0].indexOf("http") !== 0) {\r
- throw APP_BROWSER_ERROR;\r
- }\r
- else {\r
- get.appType = args.url;\r
- }\r
- }\r
- }\r
- break;\r
-\r
- //Music\r
- case 13:\r
- get.appType = APP_URL_MUSIC;\r
- break;\r
-\r
- //Photos\r
- case 14:\r
- get.appType = APP_URL_PHOTOS;\r
- break;\r
-\r
- //Videos\r
- case 15:\r
- get.appType = APP_URL_VIDEOS;\r
- break;\r
-\r
- //AppWorld\r
- case 16:\r
- get.appType = APP_URL_APPWORLD;\r
- break;\r
-\r
- //Update\r
- case 17:\r
- get.appType = APP_URL_UPDATE;\r
- break;\r
-\r
- default:\r
- throw APP_TYPE_ERROR;\r
- }\r
-\r
- transport.call(_uri, {\r
- get: get,\r
- async: true\r
- });\r
- }\r
-};\r
-\r
-_self.__defineGetter__("APP_CAMERA", function () {\r
- return 4;\r
-});\r
-_self.__defineGetter__("APP_MAPS", function () {\r
- return 5;\r
-});\r
-_self.__defineGetter__("APP_BROWSER", function () {\r
- return 11;\r
-});\r
-_self.__defineGetter__("APP_MUSIC", function () {\r
- return 13;\r
-});\r
-_self.__defineGetter__("APP_PHOTOS", function () {\r
- return 14;\r
-});\r
-_self.__defineGetter__("APP_VIDEOS", function () {\r
- return 15;\r
-});\r
-_self.__defineGetter__("APP_APPWORLD", function () {\r
- return 16;\r
-});\r
-\r
-module.exports = _self;\r
-});
-define('ripple/platform/webworks.tablet/2.0.0/client/io/dir', function (require, exports, module) {
-/*
- * Copyright 2011 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 dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
- utils = require('ripple/utils'),
- _self = {};
+_self = {
-utils.mixin({
- appDirs: {
- "app": {
- "storage" : {
- "path" : "file:///accounts/1000/appdata/emulatedapp/data"
+ ask: function (args, post, baton) {
+ if (!args) {
+ throw ("No arguments provided");
+ } else if (!args.buttons || !args.message) {
+ throw ("Invalid arguments");
+ }
+ baton.take();
+ visibleDialogArgs = args;
+
+ ui.showOverlay("dialog-window", function (dialog) {
+ var container = document.getElementById("viewport-container"),
+ height = window.getComputedStyle(container, null).getPropertyValue("height"),
+ width = window.getComputedStyle(container, null).getPropertyValue("width"),
+ sizeDiv = document.getElementById("dialog-wrapper"),
+ positionDiv = document.getElementById("dialog-window"),
+ titleDiv = document.getElementById("dialog-title"),
+ buttonsDiv = document.getElementById("dialog-buttons"),
+ messageDiv = document.getElementById("dialog-message"),
+ position, size;
+
+ if (!messageDiv || !buttonsDiv) {
+ return;
}
- },
- "shared": {
- "bookmarks": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/bookmarks"
- },
- "books": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/books"
- },
- "camera": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/camera"
- },
- "documents": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/documents"
- },
- "downloads": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/downloads"
- },
- "misc": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/misc"
- },
- "music": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/music"
- },
- "photos": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/photos"
- },
- "print": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/print"
- },
- "videos": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/videos"
- },
- "voice": {
- "path" : "file:///accounts/1000/appdata/emulatedapp/shared/voice"
+
+ dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");
+
+ position = "overlay-dialog";
+ size = "overlay-dialog-wrapper";
+
+ if (args.settings && args.settings.position) {
+ position += " overlay-dialog-" + args.settings.position;
}
- }
- }
-}, _self);
-utils.mixin(dir, _self);
+ if (args.settings && args.settings.size) {
+ size += " overlay-dialog-wrapper-" + args.settings.size;
+ }
+
+ positionDiv.setAttribute("class", position);
+ sizeDiv.setAttribute("class", size);
+
+ titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
+ messageDiv.innerHTML = args.message;
+ isDialogVisible = true;
+
+ args.buttons.forEach(function (button) {
+ var buttonElement = utils.createElement("input", {
+ "type": "button",
+ "value": button
+ });
+ buttonElement.addEventListener("click", function () {
+ var buttonIndex = args.buttons.indexOf(button);
+ closeDialog();
+ baton.pass({code: 1, data: buttonIndex});
+ });
+ buttonsDiv.appendChild(buttonElement);
+ });
+ }, true);
+ }
+};
module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/client/system', function (require, exports, module) {
+define('ripple/platform/wac/1.0/CallRecordTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- system = require('ripple/platform/webworks.core/2.0.0/client/system'),
- _uri = "blackberry/system/";
-
-system.__defineGetter__("scriptApiVersion", function () {
- return transport.call(_uri + "softwareVersion");
-});
-
-
-module.exports = system;
+module.exports = {
+ RECEIVED: "received",
+ OUTGOING: "outgoing",
+ MISSED: "missed"
+};
});
-define('ripple/platform/webworks.tablet/2.0.0/client/systemEvent', function (require, exports, module) {
+define('ripple/platform/wac/1.0/ApplicationTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
- api = "blackberry/system/event/";
+var utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ _self = {};
-function _poll(evt, handler) {
- transport.poll(api + evt, {}, function (data, response) {
- if (handler) {
- handler(data);
- }
- return !!handler;
+utils.forEach(constants.PLATFORMS.WAC.APPLICATIONS, function (application) {
+ _self.__defineGetter__(application, function () {
+ return application;
});
-}
+});
-module.exports = {
- deviceBatteryLevelChange: function (handler) {
- _poll("deviceBatteryLevelChange", handler);
- },
- deviceBatteryStateChange: function (handler) {
- _poll("deviceBatteryStateChange", handler);
- }
-};
+module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/server/app', function (require, exports, module) {
+define('ripple/platform/wac/1.0/Device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- app = require('ripple/app'),
+var constants = require('ripple/constants'),
+ exception = require('ripple/exception'),
+ _console = require('ripple/console'),
+ utils = require('ripple/utils'),
+ notifications = require('ripple/notifications'),
+ ApplicationTypes = require('ripple/platform/wac/1.0/ApplicationTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ _applicationTypes = {
+ FILES: "FILES",
+ MEDIAPLAYER: "MEDIAPLAYER",
+ PHONECALL: "PHONECALL",
+ PICTURES: "PICTURES"
+ },
_self;
+function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
+}
+
_self = {
- event: require('ripple/platform/webworks.tablet/2.0.0/server/appEvent'),
+ // Properties
+ clipboardString: undefined,
+ widgetEngineName: undefined,
+ widgetEngineProvider: undefined,
+ widgetEngineVersion: undefined,
- exit: function () {
- event.trigger("AppExit");
- return {code: 1};
+ // Methods
+ getAvailableApplications: function () {
+ return constants.PLATFORMS.WAC.APPLICATIONS || [];
},
- author: function () {
- return {code: 1, data: app.getInfo().author};
+ getDirectoryFileNames: function () {
+ _throwUnsupportedException("Device.getDirectoryFileNames");
},
-
- authorEmail: function () {
- return {code: 1, data: app.getInfo().authorEmail};
+ getFile: function () {
+ _throwUnsupportedException("Device.getFile");
},
- authorURL: function () {
- return {code: 1, data: app.getInfo().authorURL};
- },
+ launchApplication: function launchApplication(application, startParameter) {
+ if (!application || typeof(application) !== "string") {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER,
+ "Invalid argument 'application' at Device.launchApplication(): expected to be of type 'string' but was of type: " + (application ? typeof(application) : "null"),
+ Exception);
+ }
- copyright: function () {
- return {code: 1, data: app.getInfo().copyright};
- },
+ if (startParameter && typeof(startParameter) !== "string") {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER,
+ "Invalid argument 'startParameter' at Device.launchApplication(): expected to be 'string' but was : " + typeof(startParameter),
+ Exception);
+ }
- description: function () {
- return {code: 1, data: app.getInfo().description};
- },
+ // rudimentary implementation for now
+ var message = "The widget has requested application: '" + application + "' to be launched. \n\n";
- id: function () {
- return {code: 1, data: app.getInfo().id};
- },
+ if (startParameter) {
+ message += "The following start parameter was sent in: " + startParameter + "\n\n";
+ }
- license: function () {
- return {code: 1, data: app.getInfo().license};
- },
+ if (_applicationTypes[application] && !startParameter) {
+ message += "Launching this application can also be done with an optional startParameter which was not provided" + "\n\n";
+ }
- licenseURL: function () {
- return {code: 1, data: app.getInfo().licenseURL};
- },
+ if (!ApplicationTypes[application]) {
+ message += "Note: the application requested is not part of the common values specified by the WAC API.";
+ }
- name: function () {
- return {code: 1, data: app.getInfo().name};
+ notifications.openNotification("normal", message);
+ _console.log(message);
},
- version: function () {
- return {code: 1, data: app.getInfo().version};
- }
-};
-
-module.exports = _self;
-
-});
-define('ripple/platform/webworks.tablet/2.0.0/server/appEvent', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- notifications = require('ripple/notifications'),
- _bg,
- _fg,
- _swipeDown,
- _swipeStart,
- _exit;
-
-event.on("AppExit", function () {
- var baton = _exit;
- _exit = null;
- notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
- return baton && baton.pass({code: 1});
-});
-
-event.on("AppRequestBackground", function () {
- var baton = _bg;
- _bg = null;
- return baton && baton.pass({code: 1});
-});
-
-event.on("AppRequestForeground", function () {
- var baton = _fg;
- _fg = null;
- return baton && baton.pass({code: 1});
-});
-
-event.on("AppSwipeDown", function () {
- var baton = _swipeDown;
- _swipeDown = null;
- return baton && baton.pass({code: 1});
-});
-
-event.on("AppSwipeStart", function () {
- var baton = _swipeStart;
- _swipeStart = null;
- return baton && baton.pass({code: 1});
-});
-
-module.exports = {
- onBackground: function (get, post, baton) {
- baton.take();
- _bg = baton;
- return {code: 1};
+ copyFile: function () {
+ _throwUnsupportedException("Device.copyFile");
},
-
- onForeground: function (get, post, baton) {
- baton.take();
- _fg = baton;
- return {code: 1};
+ deleteFile: function () {
+ _throwUnsupportedException("Device.deleteFile");
},
-
- onSwipeDown: function (get, post, baton) {
- baton.take();
- _swipeDown = baton;
- return {code: 1};
+ findFiles: function () {
+ _throwUnsupportedException("Device.findFiles");
+ },
+ getFileSystemRoots: function () {
+ _throwUnsupportedException("Device.getFileSystemRoots");
+ },
+ getFileSystemSize: function () {
+ _throwUnsupportedException("Device.getFileSystemSize");
+ },
+ moveFile: function () {
+ _throwUnsupportedException("Device.moveFile");
+ },
+ onFilesFound: function () {
+ _throwUnsupportedException("Device.onFilesFound");
+ },
+ setRingtone: function () {
+ _throwUnsupportedException("Device.setRingtone");
},
- onSwipeStart: function (get, post, baton) {
- baton.take();
- _swipeStart = baton;
- return {code: 1};
- }
-};
-
-});
-define('ripple/platform/webworks.tablet/2.0.0/server/identity', function (require, exports, module) {
-/*
- * Copyright 2011 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 deviceSettings = require('ripple/deviceSettings');
-
-module.exports = {
- PIN: function () {
- return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
- }
-};
-
-});
-define('ripple/platform/webworks.tablet/2.0.0/server/invoke', function (require, exports, module) {
-/*
- * Copyright 2011 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 notifications = require('ripple/notifications'),
- constants = require('ripple/constants'),
- type = "normal",
- name = {
- "camera://": "Camera",
- "camera://video": "Video Camera",
- "map://": "Maps",
- "http://": "Browser",
- "music://": "Music",
- "photos://": "Photos",
- "videos://": "Videos",
- "appworld://": "App World",
- "update://": "Update"
- };
-
-module.exports = {
- invoke: function (opts) {
- var app = name[opts.appType];
- if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
- app = "Browser";
- }
-
- notifications.openNotification(type,
- "Requested to launch: " + app + " application.");
- return {code: 1};
+ vibrate: function (duration) {
+ utils.validateArgumentType(duration, "number", ExceptionTypes.INVALID_PARAMETER, "duration paramter is not a number", new Exception());
+ notifications.openNotification("normal", "Vibrating for " + duration + " second(s).");
}
+
};
+_self.__defineGetter__("widgetEngineName", function () {
+ return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_NAME;
});
-define('ripple/platform/webworks.tablet/2.0.0/server/systemEvent', function (require, exports, module) {
+
+_self.__defineGetter__("widgetEngineProvider", function () {
+ return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_PROVIDER;
+});
+
+_self.__defineGetter__("widgetEngineVersion", function () {
+ return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_VERSION;
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/wac/1.0/Account', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- _onBatteryStateChange,
- _onBatteryLevelChange,
- _states = {
- UNKNOWN: 0,
- FULL: 1,
- CHARGING: 2,
- UNPLUGGED: 3
- },
- _battery = {
- state: _states.UNKNOWN,
- charging: null,
- level: null
- };
-
-function _getState() {
- return _battery.level === 100 ? _states.FULL :
- _battery.charging ? _states.CHARGING : _states.UNPLUGGED;
-}
+var deviceSettings = require('ripple/deviceSettings'),
+ _self;
-function _pass(baton, data) {
- if (baton) {
- baton.pass({code: 1, data: data});
- }
-}
+_self = {
+ accountName: undefined,
+ accountId: undefined
+};
-event.on("DeviceBatteryStateChanged", function (charging) {
- _battery.charging = charging;
- _battery.state = _getState();
- _pass(_onBatteryStateChange, _battery.state);
+_self.__defineGetter__("accountName", function () {
+ return deviceSettings.retrieve("Account.accountName");
});
-event.on("DeviceBatteryLevelChanged", function (level) {
- level = parseInt(level, 10);
-
- _battery.level = level;
- _pass(_onBatteryLevelChange, level);
-
- if (level === 100) {
- _battery.state = _getState();
- _pass(_onBatteryStateChange, _battery.state);
- }
+_self.__defineGetter__("accountId", function () {
+ return deviceSettings.retrieve("Account.accountId");
});
-module.exports = {
- deviceBatteryLevelChange: function (get, post, baton) {
- baton.take();
- _onBatteryLevelChange = baton;
- },
- deviceBatteryStateChange: function (get, post, baton) {
- baton.take();
- _onBatteryStateChange = baton;
- }
-};
+module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/server', function (require, exports, module) {
+define('ripple/platform/wac/1.0/AccountInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- platform = "ripple/platform/webworks.tablet/2.0.0/server/",
- core = "ripple/platform/webworks.core/2.0.0/server/",
- systemEvent = require(platform + 'systemEvent'),
- system = {};
+var deviceSettings = require('ripple/deviceSettings'),
+ _self = {
+ phoneUserUniqueId: undefined,
+ phoneMSISDN: undefined,
+ phoneOperatorName: undefined,
+ userAccountBalance: undefined,
+ userSubscriptionType: undefined
+ };
-// ugh, thanks to the spec...
-system.event = systemEvent;
-utils.mixin(require(core + "system"), system);
+_self.__defineGetter__("phoneUserUniqueId", function () {
+ return deviceSettings.retrieve("AccountInfo.phoneUserUniqueId");
+});
-module.exports = {
- blackberry: {
- identity: require(platform + "identity"),
- app: require(platform + "app"),
- invoke: require(platform + "invoke"),
- system: system,
- ui: {
- dialog: require(core + "dialog")
- },
- io: {
- dir: require(core + "io/dir"),
- file: require(core + "io/file")
- }
- }
-};
+_self.__defineGetter__("phoneMSISDN", function () {
+ return deviceSettings.retrieve("AccountInfo.phoneMSISDN");
+});
+_self.__defineGetter__("phoneOperatorName", function () {
+ return deviceSettings.retrieve("AccountInfo.phoneOperatorName");
});
-define('ripple/platform/webworks.tablet/2.0.0/spec/device', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event');
-module.exports = {
- "transports": {
- "TCPCellular": {
- "name": "Cellular TCP",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "WAP": {
- "name": "WAP",
- "control": {
- "type": "checkbox",
- "value": false
- }
- },
- "WAP2": {
- "name": "WAP 2.0",
- "control": {
- "type": "checkbox",
- "value": false
- }
- },
- "MDS": {
- "name": "MDS",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "BISB": {
- "name": "BIS B",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "Unite": {
- "name": "Unite!",
- "control": {
- "type": "checkbox",
- "value": false
- }
- },
- "TCPWifi": {
- "name": "Wifi TCP",
- "control": {
- "type": "checkbox",
- "value": true
- }
- }
- },
- "identity": {
- "PIN": {
- "name": "PIN",
- "control": {
- "type": "text",
- "value": "43A8C489"
- }
- }
- },
- "battery": {
- "state": {
- "name": "Handset is Charging",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("DeviceBatteryStateChanged", [setting]);
- }
- },
- "level": {
- "name": "Charge Level (% remaining)",
- "control": {
- "type": "select",
- "value": 100
- },
- "options": (function () {
- var i,
- optionList = {};
+_self.__defineGetter__("userAccountBalance", function () {
+ return deviceSettings.retrieve("AccountInfo.userAccountBalance");
+});
- for (i = 0; i <= 100; i++) {
- optionList[i] = i;
- }
+_self.__defineGetter__("userSubscriptionType", function () {
+ return deviceSettings.retrieve("AccountInfo.userSubscriptionType");
+});
- return optionList;
- }()),
- "callback": function (setting) {
- event.trigger("DeviceBatteryLevelChanged", [setting]);
- }
- }
- },
- "system": {
- "isMassStorageActive": {
- "name": "Mass Storage Is Connected",
- "control": {
- "type": "checkbox",
- "value": true
- }
- },
- "hasDataCoverage": {
- "name": "Has Data Coverage",
- "control": {
- "type": "checkbox",
- "value": true
- },
- "callback": function (setting) {
- event.trigger("CoverageChange");
- require('ripple/bus').send("network", setting);
- }
- },
- "lag": {
- "name": "Lag the network",
- "control": {
- type: "checkbox",
- value: false
- },
- "callback": function (setting) {
- require('ripple/bus').send("lag", setting);
- }
- },
- "network": {
- "name": "Data Network",
- "control": {
- "type": "select",
- "value": "3GPP"
- },
- "options": {
- "3GPP" : "3GPP",
- "CDMA": "CDMA",
- "iDEN": "iDEN",
- "Wi-Fi": "Wi-Fi"
- },
- "callback": function (setting) {
- event.trigger("CoverageChange");
- }
- }
- }
-};
+module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/spec/events', function (require, exports, module) {
+define('ripple/platform/wac/1.0/DataNetworkInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self,
+var event = require('ripple/event'),
utils = require('ripple/utils'),
- event = require('ripple/event'),
- events = require('ripple/platform/webworks.core/2.0.0/spec/events');
+ _console = require('ripple/console'),
+ deviceSettings = require('ripple/deviceSettings'),
+ DataNetworkConnectionTypes = require('ripple/platform/wac/1.0/DataNetworkConnectionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
_self = {
- "app.event.onSwipeDown": {
- callback: function () {
- event.trigger("AppSwipeDown");
- }
- },
- "app.event.onSwipeStart": {
- callback: function () {
- event.trigger("AppSwipeStart");
- }
+ isDataNetworkConnected: undefined,
+ networkConnectionType: undefined,
+ onNetworkConnectionChanged: undefined,
+
+ getNetworkConnectionName: function (networkConnectionType) {
+ var foundConnectionType;
+ utils.validateArgumentType(networkConnectionType, "string", ExceptionTypes.INVALID_PARAMETER, "networkConnectionType is invalid, expected a string", new Exception());
+ foundConnectionType = DataNetworkConnectionTypes[networkConnectionType.toUpperCase()];
+ return foundConnectionType || null;
}
};
-utils.mixin(events, _self);
+event.on("DataNetworkConnectionChanged", function (newConnectionName) {
+ var callback = _self.onNetworkConnectionChanged,
+ msg = "Fired onNetworkConnectionChanged with newConnectionName: " + newConnectionName;
+
+ if (callback && typeof callback === "function") {
+ callback.apply(null, [newConnectionName]);
+ }
+ else {
+ msg += " --> BUT there was no registered callback found.";
+ }
+
+ _console.log(msg);
+});
+
+_self.__defineGetter__("isDataNetworkConnected", function () {
+ return deviceSettings.retrieveAsBoolean("DataNetworkInfo.isDataNetworkConnected");
+});
+
+_self.__defineGetter__("networkConnectionType", function () {
+ var value = deviceSettings.retrieve("DataNetworkInfo.networkConnectionType");
+ return value instanceof Array ? value : [value];
+});
module.exports = _self;
});
-define('ripple/platform/webworks.tablet/2.0.0/spec/ui', function (require, exports, module) {
+define('ripple/platform/wac/1.0/MessageTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
- plugins: [
- "accelerometer",
- "deviceSettings",
- "geoView",
- "platformEvents",
- "widgetConfig",
- "build"
- ]
+ EmailMessage: "email",
+ MMSMessage: "mms",
+ SMSMessage: "sms"
};
});
-define('ripple/platform/webworks.tablet/2.0.0/spec', function (require, exports, module) {
+define('ripple/platform/wac/1.0/MessageFolderTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
module.exports = {
+ DRAFTS: "drafts",
+ INBOX: "inbox",
+ OUTBOX: "outbox",
+ SENTBOX: "sentbox"
+};
- id: "webworks.tablet",
- version: "2.0.0",
- name: "WebWorks-TabletOS",
+});
+define('ripple/platform/wac/1.0/spec', function (require, exports, module) {
+module.exports = {
- persistencePrefix: "rim-tablet-",
+ id: "wac",
+ version: "1.0",
+ name: "WAC",
+ type: "plaform",
- ui: require('ripple/platform/webworks.tablet/2.0.0/spec/ui'),
- device: require('ripple/platform/webworks.tablet/2.0.0/spec/device'),
- config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
- events: require('ripple/platform/webworks.tablet/2.0.0/spec/events'),
+ persistencePrefix: "wac-",
- initialize: function () {},
+ config: require('ripple/platform/wac/1.0/spec/config'),
+ device: require('ripple/platform/wac/1.0/spec/device'),
+ ui: require('ripple/platform/wac/1.0/spec/ui'),
+ events: require('ripple/platform/wac/1.0/spec/events'),
objects: {
- XMLHttpRequest: {
- path: "webworks.tablet/2.0.0/XMLHttpRequest"
- },
- Coordinates: {
- path: "w3c/1.0/Coordinates"
- },
- Position: {
- path: "w3c/1.0/Position"
- },
- PositionError: {
- path: "w3c/1.0/PositionError"
- },
navigator: {
- path: "w3c/1.0/navigator",
- children: {
- geolocation: {
- path: "w3c/1.0/geolocation"
- }
- }
+ path: "w3c/1.0/navigator"
},
- blackberry: {
+ WidgetManager: {
+ path: "wac/1.0/WidgetManager",
+ feature: "http://jil.org/jil/api/1.1.1/widgetmanager"
+ },
+ Widget: {
+ path: "wac/1.0/Widget",
+ feature: "http://jil.org/jil/api/1.1/widget",
children: {
- transport: {
- path: "webworks.core/2.0.0/client/transport"
- },
- events: {
- path: "webworks.core/2.0.0/client/events"
- },
- app: {
- path: "webworks.tablet/2.0.0/client/app",
- feature: "blackberry.app",
+ Device: {
+ path: "wac/1.0/Device",
+ feature: "http://jil.org/jil/api/1.1/device",
children: {
- event: {
- path: "webworks.tablet/2.0.0/client/appEvent",
- feature: "blackberry.app.event"
+ AccountInfo: {
+ path: "wac/1.0/AccountInfo",
+ feature: "http://jil.org/jil/api/1.1/accountinfo"
+ },
+ ApplicationTypes: {
+ path: "wac/1.0/ApplicationTypes",
+ feature: "http://jil.org/jil/api/1.1.5/applicationtypes"
+ },
+ DataNetworkInfo: {
+ path: "wac/1.0/DataNetworkInfo",
+ feature: "http://jil.org/jil/api/1.1.1/datanetworkinfo",
+ children: {
+ DataNetworkConnectionTypes: {
+ path: "wac/1.0/DataNetworkConnectionTypes"
+ }
+ }
+ },
+ DeviceInfo: {
+ path: "wac/1.0/DeviceInfo",
+ feature: "http://jil.org/jil/api/1.1/deviceinfo"
+ },
+ DeviceStateInfo: {
+ path: "wac/1.0/DeviceStateInfo",
+ feature: "http://jil.org/jil/api/1.1/devicestateinfo",
+ children: {
+ Config: {
+ path: "wac/1.0/Config",
+ feature: "http://jil.org/jil/api/1.1/config"
+ },
+ AccelerometerInfo: {
+ path: "wac/1.0/AccelerometerInfo",
+ feature: "http://jil.org/jil/api/1.1/accelerometerinfo"
+ }
+ }
+ },
+ File: {
+ path: "wac/1.0/File",
+ feature: "http://jil.org/jil/api/1.1.1/file"
+ },
+ PositionInfo: {
+ path: "wac/1.0/PositionInfo",
+ feature: "http://jil.org/jil/api/1.1/positioninfo"
+ },
+ RadioInfo: {
+ path: "wac/1.0/RadioInfo",
+ feature: "http://jil.org/jil/api/1.1.1/radioinfo",
+ children: {
+ RadioSignalSourceTypes: {
+ path: "wac/1.0/RadioSignalSourceTypes",
+ feature: "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes"
+ }
+ }
+ },
+ PowerInfo: {
+ path: "wac/1.0/PowerInfo",
+ feature: "http://jil.org/jil/api/1.1/powerinfo"
}
}
},
- invoke: {
- path: "webworks.tablet/2.0.0/client/invoke",
- feature: "blackberry.invoke",
+ ExceptionTypes: {
+ path: "wac/1.0/ExceptionTypes",
+ feature: "http://jil.org/jil/api/1.1.5/exceptiontypes"
+ },
+ Exception: {
+ path: "wac/1.0/Exception",
+ feature: "http://jil.org/jil/api/1.1.5/exception"
+ },
+ Multimedia: {
+ path: "wac/1.0/Multimedia",
+ feature: "http://jil.org/jil/api/1.1/multimedia",
children: {
- BrowserArguments: {
- path: "webworks.tablet/2.0.0/client/BrowserArguments",
- feature: "blackberry.invoke.BrowserArguments"
+ Camera: {
+ path: "wac/1.0/Camera",
+ feature: "http://jil.org/jil/api/1.1.2/camera"
},
- CameraArguments: {
- path: "webworks.tablet/2.0.0/client/CameraArguments",
- feature: "blackberry.invoke.CameraArguments"
+ AudioPlayer: {
+ path: "wac/1.0/AudioPlayer",
+ feature: "http://jil.org/jil/api/1.1/audioplayer"
+ },
+ VideoPlayer: {
+ path: "wac/1.0/VideoPlayer",
+ feature: "http://jil.org/jil/api/1.1.2/videoplayer"
}
}
},
- identity: {
- path: "webworks.tablet/2.0.0/client/identity",
- feature: "blackberry.identity"
- },
- system: {
- path: "webworks.tablet/2.0.0/client/system",
+ Telephony: {
+ path: "wac/1.0/Telephony",
+ feature: "http://jil.org/jil/api/1.1.1/telephony",
children: {
- event: {
- path: "webworks.tablet/2.0.0/client/systemEvent"
+ CallRecord: {
+ path: "wac/1.0/CallRecord",
+ feature: "http://jil.org/jil/api/1.1/callrecord"
+ },
+ CallRecordTypes: {
+ path: "wac/1.0/CallRecordTypes",
+ feature: "http://jil.org/jil/api/1.1.1/callrecordtypes"
}
}
},
- ui: {
+ PIM: {
+ path: "wac/1.0/PIM",
+ feature: "http://jil.org/jil/api/1.1.1/pim",
children: {
- dialog: {
- path: "webworks.core/2.0.0/client/dialog",
- feature: "blackberry.ui.dialog"
+ AddressBookItem: {
+ path: "wac/1.0/AddressBookItem",
+ feature: "http://jil.org/jil/api/1.1/addressbookitem"
+ },
+ CalendarItem: {
+ path: "wac/1.0/CalendarItem",
+ feature: "http://jil.org/jil/api/1.1/calendaritem"
+ },
+ EventRecurrenceTypes: {
+ path: "wac/1.0/EventRecurrenceTypes",
+ feature: "http://jil.org/jil/api/1.1/eventrecurrencetypes"
}
}
},
- utils: {
- path: "webworks.core/2.0.0/client/utils",
- feature: "blackberry.utils"
- },
- io: {
+ Messaging: {
+ path: "wac/1.0/Messaging",
+ feature: "http://jil.org/jil/api/1.1/messaging",
children: {
- dir: {
- path: "webworks.tablet/2.0.0/client/io/dir",
- feature: "blackberry.io.dir"
+ Account: {
+ path: "wac/1.0/Account",
+ feature: "http://jil.org/jil/api/1.1/account"
},
- file: {
- path: "webworks.core/2.0.0/client/io/file",
- feature: "blackberry.io.file"
+ Attachment: {
+ path: "wac/1.0/Attachment",
+ feature: "http://jil.org/jil/api/1.1/attachment"
+ },
+ Message: {
+ path: "wac/1.0/Message",
+ feature: "http://jil.org/jil/api/1.1/message"
+ },
+ MessageFolderTypes: {
+ path: "wac/1.0/MessageFolderTypes",
+ feature: "http://jil.org/jil/api/1.1.4/messagefoldertypes"
+ },
+ MessageQuantities: {
+ path: "wac/1.0/MessageQuantities",
+ feature: "http://jil.org/jil/api/1.1/messagequantities"
+ },
+ MessageTypes: {
+ path: "wac/1.0/MessageTypes",
+ feature: "http://jil.org/jil/api/1.1/messagetypes"
}
}
}
}
}
}
+
};
});
-define('ripple/platform', function (require, exports, module) {
+define('ripple/platform/wac/1.0/PIM', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _current,
- db = require('ripple/db'),
+var _self,
+ exception = require('ripple/exception'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ AddressBookItem = require('ripple/platform/wac/1.0/AddressBookItem'),
+ CalendarItem = require('ripple/platform/wac/1.0/CalendarItem'),
utils = require('ripple/utils'),
- _console = require('ripple/console'),
- app = require('ripple/app'),
- event = require('ripple/event'),
- spec = require('ripple/platform/spec'),
- _self;
+ db = require('ripple/db'),
+ constants = require('ripple/constants');
-function _getRequestedPlatform() {
- var requestedPlatform = null,
- enableRippleArg = utils.queryString().enableripple,
- platform;
+function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
+}
- if (enableRippleArg) {
- enableRippleArg = enableRippleArg.split('-');
- platform = spec.get(enableRippleArg[0], enableRippleArg[1]);
- if (platform) {
- requestedPlatform = { name: platform.id, version: platform.version };
- }
+function _toAddressBookItem(contact) {
+ if (!contact) {
+ return null;
}
- return requestedPlatform;
-}
+ var addressBookItem = new AddressBookItem();
-function _validatePlatform(platform, defaultPlatform) {
- if (!platform ||
- !spec[platform.name] ||
- !spec[platform.name][platform.version] ||
- (spec[platform.name][platform.version] && !spec[platform.name][platform.version].objects)) {
- return defaultPlatform;
- }
- return platform;
-}
+ utils.forEach(contact, function (prop, key) {
+ addressBookItem[key] = contact[key];
+ });
-function _getPlatform() {
- return require('ripple/platform/' + _current.name + "/" + _current.version + "/spec");
+ return addressBookItem;
}
-function _getCurrentPlatform() {
- var uriParams, platform = {};
+function _toCalendarItem(item) {
+ if (!item) {
+ return null;
+ }
- uriParams = utils.getURIParams(document.documentURI);
- if (uriParams && uriParams.platform) {
- var platformName = uriParams.platform.split("-")[0], platformVersion;
+ var calendarItem = new CalendarItem();
- if (platformName === "mobile" || platformName === "tizen") {
- platformName = "tizen";
- platformVersion = "2.0";
- }
- else {
- platformName = "ivi";
- platformVersion = "3.0";
- }
- platform.name = platformName;
- platform.version = platformVersion;
+ utils.forEach(item, function (prop, key) {
+ calendarItem[key] = item[key];
+ });
- return platform;
- }
+ return calendarItem;
+}
- return undefined;
+function _getData(type) {
+ var data = db.retrieveObject(type) || [];
+ return data;
}
-_self = {
- initialize: function () {
- var firstAvailablePlatform = utils.map(this.getList(), function (platform) {
- return utils.map(platform, function (details, version) {
- return {name: details.id, version: version};
- })[0];
- })[0];
+function _saveData(type, items) {
+ db.saveObject(type, items);
+}
- _current = _getRequestedPlatform() || _getCurrentPlatform() ||
- db.retrieveObject("api-key") || firstAvailablePlatform;
- _current = _validatePlatform(_current, firstAvailablePlatform);
+function _getContacts() {
+ var contacts = _getData(constants.PIM.ADDRESS_LIST_KEY),
+ gord,
+ dan,
+ brent,
+ pj,
+ mark;
- db.saveObject("api-key", _current);
+ if (contacts.length === 0) {
- _console.prefix = _current.name;
- },
+ gord = new AddressBookItem();
+ gord.addressBookItemId = "0";
+ gord.fullName = "Gord Tanner";
+ gord.eMail = "gord@tinyHippos.com";
+ gord.company = "tinyHippos Inc";
+ gord.title = "Code Poet";
+ gord.address = "121 Charles Street W, Kitchener, Ontario, Canada";
- getList: function () {
- var platformList = {};
- utils.forEach(spec, function (platform, platformKey) {
- utils.forEach(platform, function (version, versionKey) {
- platformList[platformKey] = platformList[platformKey] || {};
- platformList[platformKey][versionKey] = {
- "id": version.id,
- "name": version.name,
- "type": version.type,
- "text": require('ripple/platform/' + platformKey + "/" + versionKey + "/spec").version
- };
- });
- });
+ dan = new AddressBookItem();
+ dan.addressBookItemId = "1";
+ dan.fullName = "Dan Silivestru";
+ dan.eMail = "dan@tinyHippos.com";
+ dan.company = "tinyHippos Inc";
+ dan.title = "Co-Founder And Chief Technology Officer";
+ dan.address = "121 Charles Street W, Kitchener, Ontario, Canada";
- return platformList;
- },
+ pj = new AddressBookItem();
+ pj.addressBookItemId = "2";
+ pj.fullName = "PJ Lowe";
+ pj.eMail = "pj@tinyHippos.com";
+ pj.company = "tinyHippos Inc";
+ pj.title = "Co-Founder And Chief Operations Officer";
+ pj.address = "121 Charles Street W, Kitchener, Ontario, Canada";
- getPersistencePrefix: function (id) {
- return _getPlatform().persistencePrefix + (id || app.getInfo().id) + "-";
- },
+ brent = new AddressBookItem();
+ brent.addressBookItemId = "2";
+ brent.fullName = "Brent Lintner";
+ brent.eMail = "brent@tinyHippos.com";
+ brent.company = "tinyHippos Inc";
+ brent.title = "Co-Founder And Chief Operations Officer";
+ brent.address = "121 Charles Street W, Kitchener, Ontario, Canada";
- current: function () {
- return _getPlatform();
- },
+ mark = new AddressBookItem();
+ mark.addressBookItemId = "3";
+ mark.fullName = "Mark McArdle";
+ mark.eMail = "mark@tinyHippos.com";
+ mark.company = "tinyHippos Inc";
+ mark.title = "Chief Executive Officer";
+ mark.address = "121 Charles Street W, Kitchener, Ontario, Canada";
- changeEnvironment: function (platform, deviceId, callback) {
- var save = jWorkflow.order(function (prev, baton) {
- baton.take();
- db.saveObject("api-key", platform, null, baton.pass);
- }).andThen(function (prev, baton) {
- baton.take();
- db.save("device-key", deviceId, null, baton.pass);
- }).andThen(function (prev, baton) {
- //remove the persisted value for the layout
- baton.take();
- db.save("layout", null, null, baton.pass);
- }).andThen(function () {
- event.trigger("PlatformChangedEvent", [], true);
- _console.prefix = null;
- _console.log("Emulator :: loading platform " + platform.name);
- });
+ contacts.push(gord);
+ contacts.push(dan);
+ contacts.push(pj);
+ contacts.push(brent);
+ contacts.push(mark);
- save.start(callback);
+ _saveData(constants.PIM.ADDRESS_LIST_KEY, contacts);
}
-};
-
-module.exports = _self;
-
-});
-define('ripple/resizer', function (require, exports, module) {
-/*
- * Copyright 2011 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 db = require('ripple/db'),
- exception = require('ripple/exception'),
- utils = require('ripple/utils'),
- devices = require('ripple/devices'),
- constants = require('ripple/constants'),
- event = require('ripple/event'),
- _win,
- _doc,
- _self;
-
-function _validateLayoutType(layoutType) {
- return (layoutType === "landscape" || layoutType === "portrait");
-}
-
-function _validateOrientation(orientation) {
- return (orientation === "landscape" || orientation === "portrait");
-}
-
-function _getContainers() {
- return {
- device: {
- div: document.getElementById("device-container"),
- containerClass: document.getElementById("device-container").getAttribute("class") || ""
- },
- viewport: {
- div: document.getElementById("viewport-container"),
- containerClass: document.getElementById("viewport-container").getAttribute("class") || ""
- },
- "menu-button": {
- div: document.getElementById(constants.COMMON.MENU_BUTTON),
- containerClass: document.getElementById(constants.COMMON.MENU_BUTTON).getAttribute("class") || ""
- },
- "back-button": {
- div: document.getElementById(constants.COMMON.BACK_BUTTON),
- containerClass: document.getElementById(constants.COMMON.BACK_BUTTON).getAttribute("class") || ""
- }
- };
+ return contacts.map(_toAddressBookItem);
}
-function _setContainers(containers, device, orientation) {
- var suffix = {
- portrait: "-wrapper" + (device.skin ? "-" + device.skin : ""),
- landscape: "-wrapper-landscape" + (device.skin ? "-" + device.skin : "")
- };
-
- utils.forEach(containers, function (container, key) {
- container.div.setAttribute("class", container.containerClass.replace(/\s.*$/, "") + " " + key + suffix[orientation]);
- });
+function _getEvents() {
+ var events = _getData(constants.PIM.CALENDAR_LIST_KEY);
+ return events.map(_toCalendarItem);
}
-function _getDimensions(device, orientation) {
- return {
- deviceWidth: orientation === "portrait" ? device.screen.width : device.screen.height,
- deviceHeight: orientation === "portrait" ? device.screen.height : device.screen.width,
- paddingLeft: device.viewPort[orientation].paddingLeft,
- paddingTop: device.viewPort[orientation].paddingTop,
- viewPort: {
- width: device.viewPort[orientation].width,
- height: device.viewPort[orientation].height
- }
- };
+function _get(type, id, fetchIDFunc) {
+ var items = _getData(type);
+ return items.reduceRight(function (match, item) {
+ return fetchIDFunc(item) === id ? item : match;
+ }, null);
}
-function _formatSkin(containers, dimensions) {
- var scaleFactor = dimensions.deviceWidth / dimensions.viewPort.width,
- scaleString = "scale(" + scaleFactor + ")";
-
- containers.device.div.style.width = (dimensions.deviceWidth + 4) + "px";
- containers.device.div.style.height = (dimensions.deviceHeight + 4) + "px";
- containers.viewport.div.style.width = dimensions.viewPort.width + "px";
- containers.viewport.div.style.height = dimensions.viewPort.height + "px";
- containers.viewport.div.style.padding = "0";
-
- jQuery('#viewport-container').css('-webkit-transform', scaleString);
- jQuery('#viewport-container').css('-webkit-transform-origin', 'left top');
+function _getAddressBookID(item) {
+ return item.addressBookItemId;
}
-function _setOrientation(layout) {
- _win.orientation = window.orientation = layout === "portrait" ? 0 : 90;
+function _getCalendarID(item) {
+ return item.calendarItemId;
}
-function _upDateHWKeyPanelPosition(orientation, scaleFactor) {
- var left = 0;
-
- if (orientation === 'portrait') {
- if (db.retrieve("layout") === "portrait") {
- left = 350 + $('#device-layout').width()*scaleFactor;
- } else {
- left = 470 + $('#device-layout').height()*scaleFactor;
- }
- } else {
- if (db.retrieve("layout") === "portrait") {
- left = 490 + $('#device-layout').height()*scaleFactor;
- } else {
- left = 350 + $('#device-layout').width()*scaleFactor;
- }
- }
-
- $("#hwkeys-panel").css("top", "40px");
- $("#hwkeys-panel").css("left", left+"px");
+function _getContact(id) {
+ return _toAddressBookItem(_get(constants.PIM.ADDRESS_LIST_KEY, id, _getAddressBookID));
}
-function _getTransformString(orientation, scaleFactor) {
- var transformString = "",
- offset;
-
- if (orientation === "landscape") {
- if (db.retrieve("layout") === "portrait") {
- offset = devices.getCurrentDevice().screen.height * scaleFactor + 170;
- transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
- } else {
- transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
- }
- } else {
- if (db.retrieve("layout") === "portrait") {
- transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
- } else {
- offset = devices.getCurrentDevice().screen.width * scaleFactor + 150;
- transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
- }
- }
-
- return transformString;
+function _getEvent(id) {
+ return _toCalendarItem(_get(constants.PIM.CALENDAR_LIST_KEY, id, _getCalendarID));
}
+function _add(type, item, idProp) {
+ var items = _getData(type);
-_self = {
- init: function (win, doc) {
- _win = win;
- _doc = doc;
-
- var layout = db.retrieve("layout") || "portrait";
-
- _setOrientation(layout);
-
- _win.onorientationchange = undefined;
- },
- // TODO: redo/refactor this in general, seems bloated, also devices REQUIRE viewport schemas which they shouldnt
- resize: function (device) {
- var layout = db.retrieve("layout"),
- orientation = "portrait",
- containers, dimensions;
-
- if (layout && layout === "landscape" && device.viewPort.landscape) {
- orientation = "landscape";
- }
-
- containers = _getContainers();
- _setContainers(containers, device, orientation);
-
- dimensions = _getDimensions(device, orientation);
- if (!device.skin) {
- _formatSkin(containers, dimensions);
- }
-
- event.trigger("ScreenChangeDimensions", [dimensions.viewPort.width, dimensions.viewPort.height]);
- },
-
- changeLayoutType: function (layoutType) {
- var orientation = db.retrieve("deviceOrientation") || "portrait";
- if (!_validateLayoutType(layoutType)) {
- exception.raise(exception.types.LayoutType, "unknown layout type requested!");
- }
-
- db.save("layout", layoutType);
- _self.resize(devices.getCurrentDevice());
- _self.rotateDevice(orientation);
-
- if (!_win) return;
- _setOrientation(layoutType);
- },
-
- scaleDevice: function (scaleFactor) {
- var orientation = db.retrieve("deviceOrientation") || "portrait",
- transformString = _getTransformString(orientation, scaleFactor);
- _upDateHWKeyPanelPosition(orientation, scaleFactor);
- db.save("deviceScaleFactor", scaleFactor);
- jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
- jQuery('#device-layout').css('-webkit-transform', transformString);
- },
-
- rotateDevice: function (orientation) {
- if (!_validateOrientation(orientation)) {
- exception.raise(exception.types.OrientationType, "unknown orientation type requested!");
- }
-
- db.save("deviceOrientation", orientation);
- jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
- jQuery('#device-layout').css('-webkit-transform',
- _getTransformString(orientation, db.retrieve("deviceScaleFactor")));
- _upDateHWKeyPanelPosition(orientation, db.retrieve("deviceScaleFactor"))
- if (!_win) return;
- if (_win.onorientationchange) {
- _win.onorientationchange();
- }
-
- var evt = _doc.createEvent("Event");
- evt.initEvent("orientationchange", true, true);
- _win.dispatchEvent(evt);
- }
-};
-
-module.exports = _self;
-
-});
-define('ripple/sensorSettings', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 _PERSISTENCE_KEY = "sensorsettings",
- db = require('ripple/db'),
- platform = require('ripple/platform'),
- _currentSensorSettings = {},
- _self;
-
-function _default(key) {
- var keys = key.split("."),
- defaults = platform.current().sensor;
+ if (!item[idProp]) {
+ item[idProp] = Math.uuid(undefined, 16);
+ }
- if (keys.length === 1)
- return defaults[key];
+ items.push(item);
+ _saveData(type, items);
+}
- return keys.length === 2 &&
- defaults[keys[0]] &&
- defaults[keys[0]][keys[1]] &&
- defaults[keys[0]][keys[1]].control ?
- defaults[keys[0]][keys[1]].control.value : undefined;
+function _delete(type, id, fetchIDFunc) {
+ var items = _getData(type);
+
+ _saveData(type, items.filter(function (item) {
+ return fetchIDFunc(item) !== id;
+ }));
+}
+
+function _validateArgs(min, max, len) {
+ utils.validateNumberOfArguments(min, max, len,
+ ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
+}
+
+function _validateType(arg, argType) {
+ utils.validateArgumentType(arg, argType,
+ ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
+ new Exception());
+}
+
+function _validateAddressBookItem(item) {
+ if ((item instanceof AddressBookItem) === false) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid contact, not instance of AddressBookItem.", new Exception());
+ }
}
_self = {
- initialize: function () {
- _currentSensorSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
+ addAddressBookItem: function (contact) {
+ _validateArgs(1, 1, arguments.length);
+ _validateAddressBookItem(contact);
+
+ _add(constants.PIM.ADDRESS_LIST_KEY, contact, "addressBookItemId");
},
- register: function (key, obj) {
- _currentSensorSettings[key] = obj;
+ createAddressBookGroup: function (groupName) {
+ _throwUnsupportedException("Widget.PIM.createAddressBookGroup");
+ },
+ createAddressBookItem: function () {
+ return new AddressBookItem();
+ },
+ deleteAddressBookItem: function (contactid) {
+ _validateArgs(1, 1, arguments.length);
+ _validateType(contactid, "string");
+ _delete(constants.PIM.ADDRESS_LIST_KEY, contactid, _getAddressBookID);
+ },
+ deleteAddressBookGroup: function (groupName) {
+ _throwUnsupportedException("Widget.PIM.deleteAddressBookGroup");
+ },
+ getAddressBookItem: function (contactid) {
+ _validateArgs(1, 1, arguments.length);
+ _validateType(contactid, "string");
+ return _getContact(contactid);
+ },
+ getAddressBookItemsCount: function () {
+ _validateArgs(0, 0, arguments.length);
+ var items = _getContacts();
+ return items.length;
+ },
+ getAvailableAddressGroupNames: function () {
+ _throwUnsupportedException("Widget.PIM.getAvailableAddressGroupNames");
},
+ getAddressBookGroupMembers: function (groupName) {
+ _throwUnsupportedException("Widget.PIM.getAddressBookGroupMembers");
+ },
+ findAddressBookItems: function (comparisonContact, startInx, endInx) {
+ _validateArgs(3, 3, arguments.length);
+ utils.validateMultipleArgumentTypes([comparisonContact, startInx, endInx], ["object", "number", "number"], ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
+ new Exception());
- persist: function (key, obj) {
- if (key) {
- _currentSensorSettings[key] = obj;
+ if (endInx < 0) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
}
- db.saveObject(_PERSISTENCE_KEY, _currentSensorSettings);
+ startInx = startInx < 0 ? 0 : startInx;
+
+ var contacts = _getContacts();
+ utils.find(comparisonContact, contacts, startInx, endInx, _self.onAddressBookItemsFound);
},
- retrieve: function (key) {
- return _currentSensorSettings.hasOwnProperty(key) ?
- _currentSensorSettings[key] : _default(key);
+ addCalendarItem: function (calendarItem) {
+ _validateArgs(1, 1, arguments.length);
+ _add(constants.PIM.CALENDAR_LIST_KEY, calendarItem, "calendarItemId");
+ },
+ deleteCalendarItem: function (calendarId) {
+ _validateArgs(1, 1, arguments.length);
+ _delete(constants.PIM.CALENDAR_LIST_KEY, calendarId, _getCalendarID);
+ },
+ getCalendarItem: function (calendarId) {
+ _validateArgs(1, 1, arguments.length);
+ return _getEvent(calendarId);
+ },
+ findCalendarItems: function (itemToMatch, startInx, endInx) {
+ _validateArgs(1, 3, arguments.length);
+ var events = _getEvents();
+ utils.find(itemToMatch, events, startInx, endInx, _self.onCalendarItemsFound);
},
+ getCalendarItems: function (startTime, endTime) {
+ var events = _getEvents();
- retrieveAsInt: function (key) {
- return parseInt(_self.retrieve(key), 10);
+ return events.reduce(function (matches, event) {
+ if (event.eventStartTime >= startTime && event.eventStartTime <= endTime) {
+ matches.push(event);
+ }
+ return matches;
+ }, []);
+ },
+ exportAsVCard: function (addressBookItems) {
+ _throwUnsupportedException("Widget.PIM.exportAsVCard");
},
- retrieveAsBoolean: function (key) {
- return !!_self.retrieve(key);
- }
+ onAddressBookItemsFound: undefined, // function (addressBookItemsFound) { }
+ onCalendarItemsFound: undefined, // function (calendarItemsFound) { }
+ onCalendarItemAlert: undefined, // function (calendarItem) { }
+ onVCardExportingFinish: undefined // function (vCardFilePath) { }
};
module.exports = _self;
});
-define('ripple/touchEventEmulator', function (require, exports, module) {
+define('ripple/platform/wac/1.0/AudioPlayer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var emulatorBridge = require('ripple/emulatorBridge'),
+var constants = require('ripple/constants'),
+ event = require('ripple/event'),
+ exception = require('ripple/exception'),
utils = require('ripple/utils'),
- _isMouseDown, self;
+ fileSystem = require('ripple/fileSystem'),
+ _console = require('ripple/console'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ _self,
+ _state = null,
+ _STATES = constants.MULTIMEDIA.AUDIO_STATES,
+ _currentAudioFile,
+ _audio, _loopCount;
-// NOTE: missing view, detail, touches, targetTouches, scale and rotation
-function _initTouchEvent(type, canBubble, cancelable, eventData) {
- var touchEvent = emulatorBridge.document().createEvent("Event");
- touchEvent.initEvent(type, canBubble, cancelable);
- utils.mixin(eventData, touchEvent);
- return touchEvent;
-}
+event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
+ _state = state;
+ if (typeof _self.onStateChange === 'function') {
+ _self.onStateChange.apply(_self, arguments);
+ }
+});
-function _raiseTouchEvent(mouseEvent) {
- var type = "",
- simulatedEvent,
- touchObj,
- eventData;
+_audio = utils.createElement("audio", {
+ "id": "multimedia-audio"
+});
- switch (mouseEvent.type) {
- case "mousedown":
- type = "touchstart";
- _isMouseDown = true;
- break;
- case "mousemove":
- if (!_isMouseDown) {
- return;
- }
- type = "touchmove";
- break;
- case "mouseup":
- type = "touchend";
- _isMouseDown = false;
- break;
- default:
- return;
+_audio.addEventListener('error', function () {
+ _console.warn("AudioPlayer encountered an error: " + _audio.error.code);
+ if (_audio.error.code === 4) {
+ _console.warn("AudioPlayer error 4 could be caused by missing codecs");
}
+ _state = null;
+ event.trigger("MultimediaAudioStateChanged", [null], true);
+});
- touchObj = {
- clientX: mouseEvent.pageX,
- clientY: mouseEvent.pageY,
- identifier: "",
- pageX: mouseEvent.pageX,
- pageY: mouseEvent.pageY,
- screenX: mouseEvent.pageX,
- screenY: mouseEvent.pageY,
- target: mouseEvent.target
- };
-
- eventData = {
- altKey: mouseEvent.altKey,
- ctrlKey: mouseEvent.ctrlKey,
- shiftKey: mouseEvent.shiftKey,
- metaKey: mouseEvent.metaKey,
- changedTouches: [touchObj],
- targetTouches: [touchObj],
- touches: [touchObj]
- };
+_audio.addEventListener('ended', function handleAudioEnded() {
+ event.trigger("MultimediaAudioStateChanged", [_STATES.COMPLETED], true);
+ if (_loopCount > 1) {
+ _self.open(_currentAudioFile);
+ _self.play(_loopCount--);
+ }
+});
- utils.mixin(touchObj, eventData);
+document.getElementById("ui").appendChild(_audio);
- simulatedEvent = _initTouchEvent(type, true, true, eventData);
+function _validateAndSet(state, validStates, callbackBeforeSuccess) {
+ var i, valid = false;
- mouseEvent.target.dispatchEvent(simulatedEvent);
+ for (i = 0; i < validStates.length; i++) {
+ if (validStates[i] === _state) {
+ valid = true;
+ }
+ }
- if (typeof mouseEvent.target["on" + type] === "function") {
- mouseEvent.target["on" + type].apply(mouseEvent.target, [simulatedEvent]);
+ if (!valid) {
+ _console.warn("Attempted to initiate AudioPlayer." + state +
+ " in invalid state. current state: " + _state);
+ } else {
+ if (typeof(callbackBeforeSuccess) === "function") {
+ callbackBeforeSuccess.apply();
+ }
+ event.trigger("MultimediaAudioStateChanged", [state], true);
}
+
+ return valid;
}
-function _marshalEvents(win, doc) {
- utils.forEach(["mousedown", "mousemove", "mouseup"],
- function (event) {
- doc.addEventListener(event, _raiseTouchEvent, true);
- });
+function _validateAudioType(fileUrl) {
+ var matched = fileUrl.match(/\.(\w*)$/),
+ type = matched ? matched[1] : "";
- //win.Node.prototype.ontouchstart = null;
- //win.Node.prototype.ontouchend = null;
- //win.Node.prototype.ontouchmove = null;
+ if (_audio && _audio.canPlayType("audio/" + type) === "") {
+ _console.warn("Attempting to load an audio that might not work in the current browser [" + fileUrl + "]");
+ }
}
-self = module.exports = {
- mask: function (win, doc) {
- _marshalEvents(win, doc);
- }
-};
+_self = {
+ onStateChange: undefined,
-});
-define('ripple/ui/plugins/HWKeys', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation
- *
- * 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.
- */
+ open: function (fileUrl) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open wrong number of arguments", new Exception());
+ utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open invalid parameter! expected string, fileUrl: " +
+ fileUrl, new Exception());
-var db = require('ripple/db'),
- event = require('ripple/event');
+ if (fileUrl.match(/^rtsp:\/\//)) {
+ exception.raise(exception.types.MethodNotImplemented, "rtsp:// scheme not yet supported. sorry :(");
+ }
+ _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
+ _validateAudioType(fileUrl);
+ _currentAudioFile = fileSystem.getURI(fileUrl);
+ _audio.setAttribute("src", _currentAudioFile);
+ _audio.load();
+ });
+ },
-function initHWKey() {
- var left = 0,
- orientation = db.retrieve('deviceOrientation'),
- scaleFactor = db.retrieve('deviceScaleFactor');
+ play: function (repeatTimes) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play wrong number of arguments", new Exception());
+ utils.validateArgumentType(repeatTimes, "integer", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play invalid parameter! expected integer, repeatTimes: " + repeatTimes, new Exception());
- if (orientation === 'portrait') {
- if (db.retrieve("layout") === "portrait") {
- left = 350 + $('#device-layout').width()*scaleFactor;
- } else {
- left = 470 + $('#device-layout').height()*scaleFactor;
+ if (repeatTimes < 0) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "value of repeatTimes must be greater than 0", new Exception());
}
- } else {
- if (db.retrieve("layout") === "portrait") {
- left = 490 + $('#device-layout').height()*scaleFactor;
- } else {
- left = 350 + $('#device-layout').width()*scaleFactor;
+
+ if (repeatTimes !== 0) {
+ _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
+ _loopCount = repeatTimes;
+ _audio.play();
+ });
}
- }
+ },
- $("#hwkeys-panel").css("top", "40px");
- $("#hwkeys-panel").css("left", left+"px");
- $("#hwkeys-panel").draggable({ cursor: 'move', containment: [0, 52, 1480, 800]});
+ pause: function () {
+ _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
+ _audio.pause();
+ });
+ },
- jQuery("#hwkey-menu-btn").bind("click", function () {
- event.trigger("tizenhwkeyEvent", ["menu"], true);
- });
- jQuery("#hwkey-back-btn").bind("click", function () {
- event.trigger("tizenhwkeyEvent", ["back"], true);
- });
-}
+ resume: function () {
+ _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
+ _audio.play();
+ });
+ },
-module.exports = {
- initialize: function () {
- initHWKey();
+ stop: function () {
+ _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
+ try {
+ _audio.pause();
+ _audio.currentTime = 0;
+ } catch (e) {
+ //HACK: do nothing, this could throw a dom exception 11 sometimes when playing an mp3 or before the file has loaded.
+ //see http://developer.palm.com/distribution/viewtopic.php?f=11&t=7568
+ }
+ });
}
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/about-dialog', function (require, exports, module) {
+define('ripple/platform/wac/1.0/PositionInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var bus = require('ripple/bus');
-
-module.exports = {
- initialize: function () {
- $("#about-dialog").dialog({
- resizable: false,
- draggable: false,
- modal: true,
- autoOpen: false,
- position: 'center',
- minWidth: '464',
- minHeight: '262'
- });
- },
- show: function () {
- //TODO: Restore this line once framework issue is resolved
- //var port = window.stagewebview ? stagewebview.serverPort : "9900";
- var port = "9910";
-
- bus.send("version", null, function (resp) {
- $("#about-dialog-ripple-ui-version").html("(v" + resp + ")");
- });
-
- bus.ajax(
- "GET",
- "http://127.0.0.1:" + port + "/ripple/about",
- null,
- function (resp) {
- $("#about-dialog-ripple-build-deploy-version").html("(v" + resp.data.version + ")");
- },
- function (error) {
- var version = error.data;
-
- if (error.code === 0 || error.code === 404) {
- version = "The service is not running";
- }
- $("#about-dialog-ripple-build-deploy-version").html("(" + version + ")");
- }
- );
-
- $("#about-dialog").dialog("open");
- }
-};
-
-});
-define('ripple/ui/plugins/accelerometer', function (require, exports, module) {
-/*
- * Copyright (c) 2010 Epic Train Hack
- * Copyright (c) 2011 Research In Motion Limited
- * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-var ui = require('ripple/ui'),
- goodVibrations = require('ripple/ui/plugins/goodVibrations'),
- accelerometer = require('ripple/accelerometer'),
+var geo = require('ripple/geo'),
event = require('ripple/event'),
- Rotation = require('ripple/platform/w3c/1.0/Rotation'),
- Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
- _mouseDown,
- _shiftKeyDown,
- _offsets = {
- x: 0,
- y: 0,
- z: -9.81,
- },
- _oldX,
- _oldY,
- _oldAlphaX,
- _shape =
- //
- // The front side
- //
- // x, y, z x, y, z x, y, z
- // for some strange reason for y -100 is top, 100 is bottom
- "-30,30,10, 30,30,10, 30,60,10, 100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
- "-30,30,10, 30,60,10, -30,60,10, 100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
- // front side "the phone display"
- "-20,-50,11, 20,-50,11, 20,20,11, 100,100,100,-1,0;" +
- "-20,-50,11, 20,20,11, -20,20,11, 100,100,100,-1,0;" +
- // below the display
- "-30,30,10, 30,20,10, 30,30,10, 0,0,0,-1,0;" +
- "-30,30,10, -30,20,10, 30,20,10, 0,0,0,-1,0;" +
- // above the display
- "-30,-60,10, 30,-60,10, 30,-50,10, 0,0,0,-1,0;" +
- "-30,-60,10, 30,-50,10, -30,-50,10, 0,0,0,-1,0;" +
- // left of the display
- "-30,-50,10, -20,-50,10, -20,20,10, 0,0,0,-1,0;" +
- "-30,-50,10, -20,20,10, -30,20,10, 0,0,0,-1,0;" +
- // right of the display
- "20,-50,10, 30,-50,10, 30,20,10, 0,0,0,-1,0;" +
- "20,-50,10, 30,20,10, 20,20,10, 0,0,0,-1,0;" +
-
-
- // back side, opposite side to the above one
- "-30,-60,-10, 30,60,-10, 30,-60,-10, 0,0,0,-1,0;" +
- "-30,-60,-10, -30,60,-10, 30,60,-10, 0,00,-1,0;" +
- // right side
- "30,-60,-10, 30,60,-10, 30,60,10, 50,50,80,-1,0;" +
- "30,-60,-10, 30,60,10, 30,-60,10, 50,50,80,-1,0;" +
- // left side
- "-30,-60,-10, -30,60,10, -30,60,-10, 50,50,80,-1,0;" +
- "-30,-60,-10, -30,-60,10, -30,60,10, 50,50,80,-1,0;" +
-
- // top
- "30,-60,-10, -30,-60,10, -30,-60,-10, 50,80,50,-1,0;" +
- "30,-60,-10, 30,-60,10, -30,-60,10, 50,80,50,-1,0;" +
- // bottom
- "30,60,-10, -30,60,-10, -30,60,10, 80,50,50,-1,0;" +
- "30,60,-10, -30,60,10, 30,60,10, 80,50,50,-1,0";
-
-function _shakeDevice() {
- window.setTimeout(goodVibrations.shakeDevice(8), 1);
- accelerometer.shake();
-}
-
-function _updateAccelerometerPanel(motion) {
- jQuery("#accelerometer-x").html(Math.round(motion.accelerationIncludingGravity.x * 100) / 100);
- jQuery("#accelerometer-y").html(Math.round(motion.accelerationIncludingGravity.y * 100) / 100);
- jQuery("#accelerometer-z").html(Math.round(motion.accelerationIncludingGravity.z * 100) / 100);
- jQuery("#accelerometer-alpha").html(Math.round(motion.orientation.alpha));
- jQuery("#accelerometer-beta").html(Math.round(motion.orientation.beta));
- jQuery("#accelerometer-gamma").html(Math.round(motion.orientation.gamma));
-}
-
-function _updateCanvas(a, b, g) {
- ThreeDee.loadMesh(_shape);
- g = g || 0;
- ThreeDee.rotate(0, g, 0);
- ThreeDee.rotate(b, 0, a);
- ThreeDee.backface();
- ThreeDee.shade();
- ThreeDee.zSort();
- Draw.initialize(document.querySelector("#accelerometer-canvas"));
- Draw.clear(0, 0, 480, 300);
- Draw.drawScene(ThreeDee.getTranslation(), 3);
-}
-
-function _createCanvas() {
- var node = document.querySelector("#accelerometer-canvas"),
- x = 0, y = 0, z = -9.81,
- alpha = 0, beta = 0, gamma = 0,
- cosX, sinX, cosY, sinY,
- deltaAlpha = 360;
-
- ThreeDee.setCenter(150, 100);
- ThreeDee.setLight(-300, -300, 800);
-
- node.addEventListener("mousemove", function (e) {
- if (!_mouseDown)
- return;
-
- if (!_shiftKeyDown) {
- _offsets.x = (_offsets.x + _oldX - e.offsetX) % 360;
- _offsets.y = (_offsets.y + _oldY - e.offsetY) % 360;
-
- alpha = alpha || 0;
-
- // enforce gamma in [-90,90] as per w3c spec
- gamma = -_offsets.x;
- if (gamma < -90) {
- gamma = -90;
- }
- if (gamma > 90) {
- gamma = 90;
- }
-
- // enforce beta in [-180,180] as per w3c spec
- beta = -_offsets.y % 360;
- if (beta < -180) {
- beta += 360;
- }
- else if (beta >= 180) {
- beta -= 360;
- }
-
- cosX = Math.cos((gamma) * (Math.PI / 180));
- sinX = Math.sin((gamma) * (Math.PI / 180));
- cosY = Math.cos((beta) * (Math.PI / 180));
- sinY = Math.sin((beta) * (Math.PI / 180));
- x = 9.81 * cosY * sinX;
- y = -9.81 * sinY;
- z = -9.81 * cosY * cosX;
-
- }
- else {
- deltaAlpha = (deltaAlpha - (_oldAlphaX - e.offsetX) * 2.5) % 360;
- alpha = (360 - deltaAlpha) % 360;
- }
-
- _oldX = e.offsetX;
- _oldY = e.offsetY;
- _oldAlphaX = e.offsetX;
-
- _updateCanvas(deltaAlpha, -beta, gamma);
- accelerometer.setInfo({
- x: x,
- y: y,
- z: z,
- alpha: alpha,
- beta: beta,
- gamma: gamma
- });
-
- });
-
- node.addEventListener("mousedown", function (e) {
- _oldX = e.offsetX;
- _oldY = e.offsetY;
- if (_shiftKeyDown) {
- _oldAlphaX = _oldX;
- }
- _mouseDown = true;
- });
-
- node.addEventListener("mouseup", function (e) {
- _mouseDown = false;
- });
-
- node.addEventListener("dblclick", function (e) {
- x = 0;
- y = 0;
- z = -9.81;
- alpha = 0;
- beta = 0;
- gamma = 0;
- deltaAlpha = 360;
- _resetAccelerometer();
- });
-
- document.addEventListener("mouseup", function (e) {
- //Catch mouseup events that fire when outside canvas bounds
- _mouseDown = false;
- });
-
- document.addEventListener("keydown", function (e) {
- if (e.keyCode === 16) { // Shift Key
- _shiftKeyDown = true;
- }
- });
-
- document.addEventListener("keyup", function (e) {
- if (e.keyCode === 16) { // Shift Key
- _shiftKeyDown = false;
- }
- });
-}
-
-function _resetAccelerometer() {
- _updateCanvas(0, 0);
- _oldX = 0;
- _oldY = 0;
- _oldAlphaX = 0;
- _offsets = {
- x: 0,
- y: 0,
- z: -9.81,
+ exception = require('ripple/exception'),
+ utils = require('ripple/utils'),
+ _self = {
+ latitude: undefined,
+ longitude: undefined,
+ altitude: undefined,
+ cellID: undefined,
+ accuracy: undefined,
+ altitudeAccuracy: undefined,
+ timeStamp: undefined
};
- accelerometer.setInfo({
- acceleration: new Acceleration(0, 0, 0),
- accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
- rotationRate: new Rotation(0, 0, 0),
- orientation: new Rotation(0, 0, 0),
- timestamp: new Date().getTime()
- });
-}
-module.exports = {
- panel: {
- domId: "accelerometer-container",
- collapsed: true,
- pane: "left",
- titleName: "Accelerometer",
- display: true
- },
- initialize: function () {
- _createCanvas();
-
- _resetAccelerometer();
-
- _updateAccelerometerPanel(accelerometer.getInfo());
-
- jQuery("#accelerometer-shake").click(_shakeDevice);
+utils.forEach(_self, function (value, property) {
+ _self.__defineGetter__(property, function () {
+ return geo.getPositionInfo()[property];
+ });
+});
- event.on("AccelerometerInfoChangedEvent", _updateAccelerometerPanel, this);
- }
-};
+module.exports = _self;
});
-define('ripple/ui/plugins/application', function (require, exports, module) {
+define('ripple/platform/wac/1.0/spec/config', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var event = require('ripple/event'),
+var platform = require('ripple/platform'),
utils = require('ripple/utils'),
db = require('ripple/db'),
- dbinit = require('ripple/platform/tizen/2.0/dbinit'),
- DB_APPLICATION_KEY = "tizen1-db-application",
- _data = {
- appList: {},
- installedAppList: {}
- },
- _appInstalledTemplate,
- _apps,
- _installedAppList;
-
-function _get() {
- _data = db.retrieveObject(DB_APPLICATION_KEY);
- if (_data === undefined) {
- _data = {
- appList: _apps,
- installedAppList: _installedAppList
- };
- }
-}
-
-function _save() {
- db.saveObject(DB_APPLICATION_KEY, _data);
-}
+ constants = require('ripple/constants');
-function _loadInstalledAppList() {
- var html = "";
- jQuery("#application-installed-box").empty();
- utils.forEach(_data.installedAppList, function (item) {
- html += _appInstalledTemplate.replace(/#Name/g, item.name)
- .replace(/#ID/g, item.id)
- .replace(/#IconPath/, item.iconPath)
- .replace(/#Version/, item.version)
- .replace(/#Show/, item.show)
- .replace(/#Categories/, item.categories.join("<br>"))
- .replace(/#InstallDate/, item.installDate)
- .replace(/#Size/, item.size)
- .replace(/#PackageID/, item.packageId)
- .replace(/#SharedURI/, item.sharedURI)
- .replace(/#Operation/, item.operation)
- .replace(/#URI/, item.appControl.uri)
- .replace(/#MIME/, item.appControl.mime)
- .replace(/#category/, item.appControl.category)
- .replace(/#Data/, item.appControl.data);
- });
- jQuery("#application-installed-box").accordion("destroy");
- jQuery("#application-installed-box").html(html).accordion({
- active: false,
- collapsible: true,
- autoHeight: false
- });
-}
+module.exports = {
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
+ (!configValidationObject.widget.validationResult[0].attributes["xmlns:JIL"].valid));
-function _displayInfo(text) {
- var html = "<b>" + text + "</b>";
- document.getElementById("application-error").innerHTML = html;
-}
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
+ }
-function _programChanged(status, id) {
- event.trigger("programChanged", [status, id]);
-}
+ var widgetInfo = {},
+ configFeatures,
+ configPreferences,
+ preferenceName,
+ platform;
-function updateApp(id, updateFlag) {
- var item = _data.appList[id];
- if (!item) {
- return;
- }
- _data.installedAppList[id] = {
- id: item.id,
- name: item.name,
- iconPath: item.iconPath,
- version: item.version,
- show: item.show,
- categories: item.categories,
- installDate: new Date(),
- size: item.size,
- packageId: item.packageId,
- sharedURI: item.sharedURI,
- operation: item.operation,
- appControl: {
- uri: item.appControl.uri,
- mime: item.appControl.mime,
- category: item.appControl.category,
- data: item.appControl.data
- },
- type: item.type,
- value: item.value
- };
- _save();
- if (updateFlag) {
- _programChanged("updated", id);
- } else {
- _programChanged("installed", id);
- }
- _loadInstalledAppList();
-}
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
-function removeApp(id) {
- delete _data.installedAppList[id];
- _save();
- _programChanged("uninstalled", id);
- _loadInstalledAppList();
-}
+ widgetInfo.features = {};
-event.on("install-current-app", function (item) {
- _data.installedAppList[item.id] = {
- id: item.id,
- name: item.name,
- iconPath: item.iconPath,
- version: item.version,
- show: item.show,
- categories: item.categories,
- installDate: item.installDate,
- size: item.size,
- packageId: item.packageId,
- sharedURI: item.sharedURI,
- operation: item.operation,
- appControl: {
- uri: item.appControl.uri,
- mime: item.appControl.mime,
- category: item.appControl.category,
- data: item.appControl.data
- },
- type: item.type,
- value: item.value
- };
- _loadInstalledAppList();
-});
+ configFeatures = configValidationObject.widget.children.feature.validationResult;
+ utils.forEach(configFeatures, function (f) {
+ if (f.valid === true) {
+ var feature = {id: f.attributes.name.value,
+ required: f.attributes.required.valid};
+ widgetInfo.features[feature.id] = feature;
+ }
+ });
-event.on("appServiceReplied", function () {
- _displayInfo("The application has been launched successfully");
-});
+ widgetInfo.preferences = {};
-event.on("install-apps", function (ids) {
- utils.forEach(ids, function (id) {
- updateApp(id, false);
- });
-});
+ configPreferences = configValidationObject.widget.children.preference.validationResult;
-event.on("update-apps", function (ids) {
- utils.forEach(ids, function (id) {
- updateApp(id, true);
- });
-});
+ platform = require('ripple/platform');
+ utils.forEach(configPreferences, function (preference) {
+ preferenceName = preference.attributes.name.value;
+ if (preferenceName) {
+ widgetInfo.preferences[preferenceName] = {
+ "key": preferenceName,
+ "value": preference.attributes.value.value || "",
+ "readonly": preference.attributes.readonly.value === "true"
+ };
-event.on("remove-apps", function (ids) {
- utils.forEach(ids, function (id) {
- removeApp(id);
- });
-});
+ db.save(preferenceName,
+ widgetInfo.preferences[preferenceName].value,
+ platform.getPersistencePrefix(widgetInfo.id));
+ }
+ });
-module.exports = {
- initialize: function () {
- _apps = dbinit.Application.apps;
- _installedAppList = dbinit.Application.installedAppList;
- _appInstalledTemplate = jQuery("#application-installed-template").html();
- _get();
- _save();
- _loadInstalledAppList();
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,maximum_display_mode,update,feature,access,billing. \"widget\" element MAY have following attributes: id,version,height,width,xml:lang",
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:JIL": {
+ attributeName: "xmlns:JIL",
+ required: true,
+ type: "list",
+ listValues: ["http://www.jil.org/ns/widgets1.2"]
+ },
+ "xmlns:its": {
+ attributeName: "xmlns:its",
+ helpText: "Indicates Text Directionality can be used. According to W3C spec, this feature is at risk, therefore we don't currently validate this.",
+ required: false,
+ type: "string"
+ },
+ id: {
+ attributeName: "id",
+ required: true,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ helpText: "Version must be in the following format: jil-rec-version-tag = major-version \".\" minor-version [\".\" version-desc]",
+ required: true,
+ type: "regex",
+ regex: /^\d{1,2}\.\d{1,2}(\.[A-Za-z0-9]{1,10})?$/
+ },
+ height: {
+ attributeName: "height",
+ required: true,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: true,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["floating", "fullscreen"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ }
+ },
+ children: {
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "string",
+ required: true
+ },
+ value: {
+ type: "string",
+ attributeName: "value",
+ required: false
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "short": {
+ attributeName: "short",
+ type: "string",
+ required: false
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ email: {
+ attributeName: "email",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.EMAIL
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ encoding: {
+ attributeName: "encoding",
+ type: "string",
+ required: false
+ },
+ type: {
+ attributeName: "type",
+ type: "string",
+ required: false
+ }
+ }
+ },
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "list",
+ required: true,
+ listValues: ["http://jil.org/jil/api/1.1/widget", "http://jil.org/jil/api/1.1.5/exception",
+ "http://jil.org/jil/api/1.1.5/exceptiontypes", "http://jil.org/jil/api/1.1/device",
+ "http://jil.org/jil/api/1.1/accountinfo", "http://jil.org/jil/api/1.1/deviceinfo",
+ "http://jil.org/jil/api/1.1.1/datanetworkinfo", "http://jil.org/jil/api/1.1/devicestateinfo",
+ "http://jil.org/jil/api/1.1/accelerometerinfo", "http://jil.org/jil/api/1.1/config",
+ "http://jil.org/jil/api/1.1.1/file", "http://jil.org/jil/api/1.1/positioninfo",
+ "http://jil.org/jil/api/1.1/powerinfo", "http://jil.org/jil/api/1.1.1/radioinfo",
+ "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes", "http://jil.org/jil/api/1.1.5/applicationtypes",
+ "http://jil.org/jil/api/1.1/messaging", "http://jil.org/jil/api/1.1/account",
+ "http://jil.org/jil/api/1.1/attachment", "http://jil.org/jil/api/1.1/message",
+ "http://jil.org/jil/api/1.1.4/messagefoldertypes", "http://jil.org/jil/api/1.1/messagequantities",
+ "http://jil.org/jil/api/1.1/messagetypes", "http://jil.org/jil/api/1.1/multimedia",
+ "http://jil.org/jil/api/1.1/audioplayer", "http://jil.org/jil/api/1.1.2/camera",
+ "http://jil.org/jil/api/1.1.2/videoplayer", "http://jil.org/jil/api/1.1.1/pim",
+ "http://jil.org/jil/api/1.1/addressbookitem", "http://jil.org/jil/api/1.1/calendaritem",
+ "http://jil.org/jil/api/1.1/eventrecurrencetypes", "http://jil.org/jil/api/1.1.1/telephony",
+ "http://jil.org/jil/api/1.1/callrecord", "http://jil.org/jil/api/1.1.1/callrecordtypes",
+ "http://jil.org/jil/api/1.1.1/widgetmanager"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ "JIL:maximum_display_mode": {
+ nodeName: "JIL:maximum_display_mode",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ height: {
+ attributeName: "height",
+ type: "integer",
+ required: false
+ },
+ width: {
+ attributeName: "width",
+ type: "integer",
+ required: false
+ }
+ }
+ },
+ "JIL:update": {
+ nodeName: "JIL:update",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: true,
+ regex: constants.REGEX.URL
+ },
+ period: {
+ attributeName: "period",
+ helpText: "Possible values for the period attribute are: 0, 1, 2, 3 meaning: every time the widget is opened in maximum display mode, every day, every week, every month; respectivly",
+ type: "list",
+ required: true,
+ listValues: ["0", "1", "2", "3"]
+ }
+ }
+ },
+ "JIL:access": {
+ nodeName: "JIL:access",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ network: {
+ attributeName: "network",
+ type: "boolean",
+ required: false
+ },
+ localfs: {
+ attributeName: "localfs",
+ type: "boolean",
+ required: false
+ },
+ remote_scripts: {
+ attributeName: "remote_scripts",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ "JIL:billing": {
+ nodeName: "JIL:billing",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: true
+ }
+ }
+ }
+ }
+ }
}
};
});
-define('ripple/ui/plugins/audioPlayer', function (require, exports, module) {
+define('ripple/platform/wac/1.0/spec/device', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- constants = require('ripple/constants'),
- audioObj = document.getElementById("multimedia-audio"),
- audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);
+var constants = require('ripple/constants'),
+ event = require('ripple/event');
module.exports = {
- initialize: function () {
- var audioObj = document.getElementById("multimedia-audio"),
- audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);
-
- if (audioObj) {
- event.on("MultimediaVolumeChanged", function (volume) {
- audioObj.volume = parseFloat(volume / 10);
- });
-
- audioObj.addEventListener("timeupdate", function () {
- var s = parseInt(audioObj.currentTime % 60, 10),
- m = parseInt((audioObj.currentTime / 60) % 60, 10);
+ "AccountInfo": {
+ "phoneUserUniqueId": {
+ "name": "User Unique Id",
+ "control": {
+ "type": "text",
+ "value": new Date().getTime().toString()
+ }
+ },
+ "phoneMSISDN": {
+ "name": "MSISDN",
+ "control": {
+ "type": "text",
+ "value": "15199999999"
+ }
+ },
+ "phoneOperatorName": {
+ "name": "Operator Name",
+ "control": {
+ "type": "text",
+ "value": ""
+ }
+ },
+ "userAccountBalance": {
+ "name": "Account Balance",
+ "control": {
+ "type": "number",
+ "value": 0
+ }
+ },
+ "userSubscriptionType": {
+ "name": "Subscription Type",
+ "control": {
+ "type": "select",
+ "value": "other"
+ },
+ "options": {
+ "other": "other",
+ "prepaid": "prepaid",
+ "postpaid": "postpaid"
+ }
+ }
+ },
+ "RadioInfo": {
+ "isRoaming": {
+ "name": "Is Roaming",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ },
+ "callback": function () {
+ event.trigger("RadioSignalSourceChanged");
+ }
+ },
+ "isRadioEnabled": {
+ "name": "Is Radio Enabled",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "radioSignalSource": {
+ "name": "Radio Signal Source",
+ "control": {
+ "type": "select",
+ "value": "GSM"
+ },
+ // TODO: try not to duplicate from RadioSignalSourceTypes
+ "options": {
+ "CDMA": "cdma",
+ "GSM": "gsm",
+ "LTE": "lte",
+ "TDSCDMA": "tdscdma",
+ "WCDMA": "wcdma"
+ },
+ "callback": function () {
+ event.trigger("RadioSignalSourceChanged");
+ }
+ },
+ "radioSignalStrengthPercent": {
+ "name": "Signal Strength %",
+ "control": {
+ "type": "select",
+ "value": 80
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- audioProgress.innerText = ((m > 9) ? m : "0" + m) + ':' + ((s > 9) ? s : "0" + s);
- }, false);
+ for (i = 0; i <= 100; i++) {
+ optionList[i] = i;
+ }
- event.on("MultimediaAudioStateChanged", function (state) {
- document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_STATE_FIELD_ID).innerText = state;
- document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_FILE_FIELD_ID).innerText = audioObj.getAttribute("src");
- });
+ return optionList;
+ }())
}
- }
-};
-
-});
-define('ripple/ui/plugins/build', function (require, exports, module) {
-/*
- * Copyright 2011 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 tooltip = require('ripple/ui/plugins/tooltip'),
- settings = require('ripple/ui/plugins/settings-dialog'),
- bus = require('ripple/bus');
+ },
+ "Config": {
+ "ringtoneVolume": {
+ "name": "Ringtone Volume",
+ "control": {
+ "type": "select",
+ "value": 10
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
-function handleBuild() {
- var node = $(this),
- action = node.attr('id').split("-")[2];
+ for (i = 0; i <= 10; i++) {
+ optionList[i] = i;
+ }
- if (node.hasClass("not-ready")) {
- return;
- }
+ return optionList;
+ }())
+ },
+ "msgRingtoneVolume": {
+ "name": "Msg Ringtone Volume",
+ "control": {
+ "type": "select",
+ "value": 10
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- if (!settings.can(action)) {
- settings.show(action);
- }
- else {
- settings.perform(action);
- }
-}
+ for (i = 0; i <= 10; i++) {
+ optionList[i] = i;
+ }
-function areServicesRunning(success, fail) {
- bus.ajax(
- "GET",
- "http://127.0.0.1:9910/ripple/about",
- null,
- function () {
- success();
+ return optionList;
+ }())
},
- function (error) {
- fail();
+ "vibrationSetting": {
+ "name": "Vibration",
+ "control": {
+ "type": "select",
+ "value": "off"
+ },
+ "options": {
+ "on": "ON",
+ "off": "OFF"
+ }
}
- );
-}
-
-function manageServices(action, callBack) {
- bus.send("services", action, function () {
- if (typeof callBack === "function") {
- callBack();
+ },
+ "Account": {
+ "accountName": {
+ "name": "Name",
+ "control": {
+ "type": "text",
+ "value": ""
+ }
+ },
+ "accountId": {
+ "name": "Id",
+ "control": {
+ "type": "text",
+ "value": ""
+ }
}
- });
-}
-
-module.exports = {
- panel: {
- domId: "build-container",
- collapsed: true,
- pane: "right"
},
+ "DeviceInfo": {
+ "totalMemory": {
+ "name": "Total Memory",
+ "control": {
+ "type": "range",
+ "value": 262144,
+ "min": 0,
+ "max": 4096000
+ }
+ },
+ "phoneColorDepthDefault": {
+ "name": "Color Depth",
+ "control": {
+ "type": "number",
+ "value": 24
+ }
+ }
+ },
+ "DeviceStateInfo": {
+ "availableMemory": {
+ "name": "Available Memory",
+ "control": {
+ "type": "range",
+ "value": 262144,
+ "min": 0,
+ "max": 4096000
+ }
+ },
+ "keypadLightOn": {
+ "name": "Keypad Light On",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ },
+ "backLightOn": {
+ "name": "Back Light On",
+ "control": {
+ "type": "checkbox",
+ "value": false
+ }
+ },
+ "audioPath": {
+ "name": "Audio Path",
+ "control": {
+ "type": "select",
+ "value": "receiver"
+ },
+ "options": {
+ "speaker": "speaker",
+ "receiver": "receiver",
+ "earphone": "earphone"
+ }
+ },
+ "processorUtilizationPercent": {
+ "name": "CPU Utilization %",
+ "control": {
+ "type": "select",
+ "value": "5"
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- initialize: function () {
- $("#options-menu-build").click(handleBuild);
- $("#options-menu-sign").click(handleBuild);
- $("#options-menu-launch").click(handleBuild);
-
- $('#options-menu-start-service').click(function () {
- manageServices("start", function (result) {
- $('#options-menu-services-stop').show();
- $('#options-menu-services-start').hide();
- });
- });
+ for (i = 0; i <= 100; i++) {
+ optionList[i] = i;
+ }
- $('#options-menu-stop-service').click(function () {
- manageServices("stop", function (result) {
- $('#options-menu-services-stop').hide();
- $('#options-menu-services-start').show();
- });
- });
+ return optionList;
+ }())
+ },
+ "language": {
+ "name": "Language",
+ "control": {
+ "type": "select",
+ "value": "eng"
+ },
+ "options": (function () {
+ var i,
+ optionList = {},
+ iterator = constants.LANG.ISO6392_LIST;
- $("#options-menu-settings").click(function () {
- settings.show();
- });
+ for (i = 0; i <= iterator.length; i++) {
+ optionList[iterator[i]] = iterator[i];
+ }
- if (settings.value("remoteInspector")) {
- $("#options-menu-build-warning").show();
- tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
+ return optionList;
+ }())
+ }
+ },
+ "DataNetworkInfo": {
+ "isDataNetworkConnected": {
+ "name": "Data Network Is Connected",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ }
+ },
+ "networkConnectionType": {
+ "name": "Network Connection Type",
+ "control": {
+ "type": "select",
+ "value": ["GPRS"]
+ },
+ // TODO: try not to duplicate from DataNetworkConnectionTypes
+ "options": {
+ "BLUETOOTH": "bluetooth",
+ "EDGE": "edge",
+ "EVDO": "evdo",
+ "GPRS": "gprs",
+ "IRDA": "irda",
+ "LTE": "lte",
+ "ONEXRTT": "1xrtt",
+ "WIFI": "wifi"
+ },
+ "callback": function (setting) {
+ event.trigger("DataNetworkConnectionChanged", [setting]);
+ }
}
+ },
+ "PowerInfo": {
+ "isCharging": {
+ "name": "Battery Is Charging",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryStateChanged", [setting]);
+ }
+ },
+ "percentRemaining": {
+ "name": "Battery Remaining %",
+ "control": {
+ "type": "select",
+ "value": 100
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- areServicesRunning(
- function () {
- $('#options-menu-services-stop').show();
- $('#options-menu-services-start').hide();
- },
- function () {
- $('#options-menu-services-stop').hide();
- $('#options-menu-services-start').show();
+ for (i = 0; i <= 100; i++) {
+ optionList[i] = i;
+ }
+
+ return optionList;
+ }()),
+ "callback": function (setting) {
+ event.trigger("DeviceBatteryLevelChanged", [setting]);
}
- );
+ }
}
};
});
-define('ripple/ui/plugins/call', function (require, exports, module) {
+define('ripple/platform/wac/1.0/spec/events', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2011 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.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * WITHOUT 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 event = require('ripple/event'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- _exception = {
- "unknown": "Unknown",
- "network": "Network",
- "unreachable": "Unreachable",
- "no-answer": "No Answer",
- "bad-number": "Bad Number",
- "number-not-in-use": "Number Not In Use",
- "media": "Media",
- "no-sim": "No Sim Card",
- "account-down": "Account Down",
- "credit-down": "Credit Down",
- "barred": "Barred",
- "network-busy": "Network Busy",
- "network-down": "Network Down"
- },
- _status = {
- IDLE: 0,
- DIALED: 1,
- PLACED: 2,
- INPROGRESS: 3,
- },
- _statusInfo = [
- "Waiting...;Waiting", // IDLE
- "Calling... ;Incomming call from simulator", // DIALED
- "Incomming call from ;Calling simulator", // PLACED
- "In conversation with ;In conversation with simulator" // INPROGRESS
- ],
- _data = {
- status: _status.IDLE,
- isInException: false,
- isAutoAccept: false,
- autoAcceptTimerId: null,
- conversationStartTime: null
- },
- _contactMap = {
- "861012345678": "Guest"
- },
- _CONTACT_KEY = "tizen1-contact",
- _RECORDING_KEY = "tizen1-call-recording",
- _RECORDING_PATH = "music/",
- _record = {},
- _conversationSeconds = 0,
- _conversationTimer,
- _callingEffectTimer;
-
-function _initContacts() {
- var data = db.retrieveObject(_CONTACT_KEY),
- contactsSelect = document.getElementById("call-local-phone-number"),
- displayName = null, number = null, index = 0, i;
-
- contactsSelect.innerHTML = "";
-
- utils.forEach(data, function (addrBook) {
- utils.forEach(addrBook._contacts, function (contact) {
- if (contact.name && contact.name && contact.phoneNumbers &&
- contact.phoneNumbers.length > 0) {
- displayName = contact.name.firstName + ' ' + contact.name.lastName;
- number = contact.phoneNumbers[0].number;
- _contactMap[number] = displayName;
-
- contactsSelect.appendChild(utils.createElement("option", {
- "innerText": displayName + ':' + number,
- "value": index
- }));
- index++;
- }
- });
- });
-
- if (displayName === null && number === null) {
- for (i in _contactMap) {
- displayName = _contactMap[i];
- number = i;
- contactsSelect.appendChild(utils.createElement("option", {
- "innerText": displayName + ':' + number,
- "value": index
- }));
- }
- }
-}
-function _initEventWatchers() {
- event.on("DialerLaunched", function (remoteParty) {
- var localContact = document.getElementById("call-local-phone-number");
+var event = require('ripple/event');
- if (_data.status !== _status.IDLE) {
- return;
+module.exports = {
+ "WidgetWakeup": {
+ callback: function () {
+ event.trigger("WidgetWakeup");
}
-
- localContact.appendChild(utils.createElement("option", {
- "innerText": remoteParty.displayName,
- "value": remoteParty.remoteParty,
- "selected": "selected"
- }));
- _localCall();
- });
-}
-
-function _initExceptionTypes() {
- utils.forEach(_exception, function (value, key) {
- document.getElementById("call-exception-type").appendChild(utils.createElement("option", {
- "innerText": value,
- "value": key
- }));
- });
-}
-
-function _initRecord() {
- var localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
- localPartStringList = localPartString.split(":"),
- displayName;
-
- if (localPartStringList.length > 1) {
- displayName = localPartStringList[0];
- }
- else {
- displayName = localPartString;
- }
-
- _record = {};
- _record.serviceId = (new Date()).getTime() || 0;
- _record.callParticipants = [{
- id: localPartString + ':' + displayName,
- displayName: displayName,
- contactRef: null
- }];
- _record.forwardedFrom = null;
- _record.startTime = new Date();
- _record.recording = [];
-}
-
-
-function updateConvTime() {
- var timeObj = new Date(1970, 0, 1),
- timeString;
-
- timeObj.setSeconds(_conversationSeconds);
- timeString = timeObj.toTimeString().substr(0, 8);
- jQuery("#ConvTimeString").text(timeString);
- jQuery("#ConvTimeString2").text(timeString);
- _conversationSeconds = _conversationSeconds + 1;
-}
-
-
-function CallingEffect() {
- var color = jQuery("#callingString").css('color');
- if (color === "rgb(255, 255, 255)") {
- jQuery("#callingString").css('color', "black");
- jQuery("#callingString2").css('color', "black");
- }
- else {
- jQuery("#callingString").css('color', "white");
- jQuery("#callingString2").css('color', "white");
- }
-}
-
-
-function _transferStatus() {
- var statusStringList = _statusInfo[_data.status].split(";"),
- localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
- localPartStringList = localPartString.split(":"),
- localNumber = localPartStringList[0],
- localName = _contactMap[localNumber] || localNumber;
- jQuery("#status-text").show();
- jQuery("#remote-status-text").show();
- jQuery("#call-status").show();
- jQuery("#remote-call-status").show();
- jQuery("#remotePartyName").html(localName);
- jQuery("#call-local-call").show();
- window.clearInterval(_callingEffectTimer);
-
- switch (_data.status) {
- case _status.DIALED: // local call
- jQuery("#call-remote-text").html("Accept");
- jQuery("#end-remote-text").html("Reject");
- jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
- "<span id='callingString' style='font-size: 14px;'> " + statusStringList[0] +
- "</span><br><br><br><button id='call-local-end-d' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
- jQuery("#call-local-end-d").bind("click", _localEnd);
- jQuery("#remote-call-status").html("<span style='font-size: 20px;'>Simulator Bot</span><br>" +
- "<span id='callingString2' style='font-size: 12px;'> Incoming call...</span>" +
- "<br><br><br><button id='call-remote-decline-d' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button> " +
- "<button id='call-remote-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px; background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
- jQuery("#call-remote-answer-d").bind("click", _remoteCall);
- jQuery("#call-remote-decline-d").bind("click", _remoteEnd);
- _callingEffectTimer = window.setInterval(CallingEffect, 800);
- break;
- case _status.PLACED: // Remote Call
- jQuery("#call-local-text").html("Accept");
- jQuery("#end-local-text").html("Reject");
- jQuery("#call-status").html(statusStringList[0] + localName);
- jQuery("#remote-call-status").html(statusStringList[1]);
- jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Bot</span><br>" +
- "<span id='callingString' style='font-size: 14px;'> Calling..." +
- "</span><br><br><br><button id='call-remote-end-d' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
- jQuery("#call-remote-end-d").bind("click", _remoteEnd);
- jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
- "<span id='callingString2' style='font-size: 14px;'> Incoming call...</span>" +
- "<br><br><br><button id='call-local-decline-d' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button> " +
- "<button id='call-local-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px;" +
- " background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
- jQuery("#call-local-answer-d").bind("click", _localCall);
- jQuery("#call-local-decline-d").bind("click", _localEnd);
- _callingEffectTimer = window.setInterval(CallingEffect, 800);
- break;
- case _status.INPROGRESS:
- jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" +
- "<span id='ConvTimeString' style='font-size: 14px;'>" + "00:00:00" +
- "</span><br><br><br><button id='call-local-end-d-c' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
- jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Robot</span><br>" +
- "<span id='ConvTimeString2' style='font-size: 14px;'>" + "00:00:00" +
- "</span><br><br><br><button id='call-remote-end-d-c' class='ui-corner-all' style='padding:2px;" +
- " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
- jQuery("#call-local-end-d-c").bind("click", _localEnd);
- jQuery("#call-remote-end-d-c").bind("click", _remoteEnd);
- _conversationTimer = window.setInterval(updateConvTime, 1000);
- jQuery("#call-remote-text").html("Call");
- jQuery("#end-remote-text").html("End");
- jQuery("#call-local-text").html("Call");
- jQuery("#end-local-text").html("End");
- break;
- default:
- jQuery("#call-status").html(statusStringList[0]);
- jQuery("#call-status").html("default");
- jQuery("#remote-call-status").html(statusStringList[1]);
- jQuery("#remote-call-status").html("default");
- jQuery("#call-remote-text").html("Call");
- jQuery("#end-remote-text").html("End");
- jQuery("#call-local-text").html("Call");
- jQuery("#end-local-text").html("End");
- return;
- }
-}
-
-function _startCall() {
- _data.conversationStartTime = new Date();
- event.trigger("CallInProgress", [true]);
- _data.status = _status.INPROGRESS;
- //_transferStatus();
-}
-
-function _endCall(callEndReason) {
- if (_data.autoAcceptTimerId) {
- var path = _RECORDING_PATH + _record.serviceId + ".mp3";
-
- _record.recording.push(path);
- db.saveObject(_RECORDING_KEY, path);
-
- clearTimeout(_data.autoAcceptTimerId);
- _data.autoAcceptTimerId = null;
- }
-
- _record.duration = _data.conversationStartTime ? ((new Date()) - _data.conversationStartTime) : 0;
- _data.conversationStartTime = null;
-
- _record.endReason = callEndReason;
-
- if (_data.status === _status.PLACED) {
- _record.direction = "missed-new";
- }
-
- event.trigger("CallRecorded", [_record]);
- event.trigger("CallInProgress", [false]);
-
- _data.status = _status.IDLE;
- _transferStatus();
- _record = {};
-
- _conversationSeconds = 0;
- window.clearInterval(_conversationTimer);
- jQuery("#call-status").hide();
- jQuery("#remote-call-status").hide();
-
- jQuery("#status-text").hide();
- jQuery("#remote-status-text").hide();
-}
-
-function _localCall() {
- if (_data.isInException) {
- return;
- }
-
- switch (_data.status) {
- case _status.IDLE: //local call
- _data.status = _status.DIALED;
- _initRecord();
- _record.direction = "dialed";
- break;
- case _status.PLACED:
- _data.status = _status.INPROGRESS;
- _record.direction = "received";
- if (_data.autoAcceptTimerId) {
- clearTimeout(_data.autoAcceptTimerId);
- _data.autoAcceptTimerId = null;
+ },
+ "WidgetMaximize": {
+ callback: function () {
+ event.trigger("WidgetMaximize");
}
- _startCall();
- break;
- default:
- return;
- }
-
- _transferStatus();
-
- if (_data.isInException) {
- _endCall(document.getElementById("call-exception-type").value);
- }
-}
-
-function _localEnd() {
- switch (_data.status) {
- case _status.DIALED: // Local Cancel
- case _status.INPROGRESS: // Local End
- _endCall("local");
- break;
- case _status.PLACED:
- _record.direction = "missed-new";
- _endCall("local");
- break;
- default:
- return;
- }
-}
-
-function _remoteCall() {
- if (_data.isInException) {
- return;
- }
-
- switch (_data.status) {
- case _status.IDLE: // Remote Call
- _data.status = _status.PLACED;
- _initRecord();
- if (_data.isAutoAccept) {
- _data.autoAcceptTimerId = setTimeout(_localCall, 2000);
+ },
+ "WidgetFocus": {
+ callback: function () {
+ event.trigger("WidgetFocus");
}
- break;
- case _status.DIALED: // Remote Answer
- _startCall();
- break;
- default:
- return;
- }
-
- _transferStatus();
-
- if (_data.isInException) {
- _endCall(document.getElementById("call-exception-type").value);
- }
-}
-
-function _remoteEnd() {
- switch (_data.status) {
- case _status.DIALED: // Remote Reject
- _endCall("rejected");
- break;
- case _status.INPROGRESS: // Remote End
- _endCall("remote");
- break;
- case _status.PLACED: // Remote Cancel
- _record.direction = "missed-new";
- _endCall("remote");
- break;
- default:
- return;
- }
-}
-
-function _leaveMessage() {
- if (!this.checked && _data.autoAcceptTimerId) {
- clearTimeout(_data.autoAcceptTimerId);
- _data.autoAcceptTimerId = null;
- }
- _data.isAutoAccept = this.checked;
-}
-
-function _exceptionStatus() {
- _data.isInException = this.checked;
- if (_data.isInException && (_data.status !== _status.IDLE)) {
- if (_data.status === _status.RECEIVED) { // Remote Cancel
- _record.direction = "missed-new";
- _record.duration = 0;
+ },
+ "WidgetRestore": {
+ callback: function () {
+ event.trigger("WidgetRestore");
}
- _endCall(document.getElementById("call-exception-type").value);
}
-}
-
-
-function _updateRemotePartyName() {
- jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
-}
-
-
-module.exports = {
- panel: {
- domId: "call-container",
- collapsed: true,
- pane: "left",
- titleName: "Call",
- display: true
- },
- initialize: function () {
- jQuery("#call-local-call").bind("click", _localCall);
- jQuery("#call-local-end").bind("click", _localEnd);
- jQuery("#call-remote-call").bind("click", _remoteCall);
- jQuery("#call-remote-end").bind("click", _remoteEnd);
- jQuery("#recording-status").bind("click", _leaveMessage);
- jQuery("#call-exception-status").bind("click", _exceptionStatus);
- jQuery("#call-exception-type").bind("click", null);
+};
- _initEventWatchers();
- _initContacts();
- jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
- jQuery("#call-local-phone-number").bind("change", _updateRemotePartyName);
- _initExceptionTypes();
- }
+});
+define('ripple/platform/wac/1.0/spec/ui', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ plugins: [
+ "accelerometer",
+ //"deviceSettings",
+ "fileSystem",
+ "geoView",
+/*
+ "multimedia",
+ "audioPlayer",
+ "telephony",
+*/
+ "platformEvents",
+ "storage",
+ "widgetConfig"
+ ]
};
});
-define('ripple/ui/plugins/camera', function (require, exports, module) {
+define('ripple/platform/wac/1.0/RadioInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var ui = require('ripple/ui'),
+var _self,
event = require('ripple/event'),
- video = document.getElementById('camera-video'),
- upload = document.getElementById('picture-upload'),
- select = document.getElementById('select-file'),
- take = document.getElementById('take-file'),
- pic = document.getElementById("camera-image");
+ _console = require('ripple/console'),
+ deviceSettings = require('ripple/deviceSettings');
+_self = {
+ isRoaming: undefined,
+ radioSignalStrengthPercent: undefined,
+ isRadioEnabled: undefined,
+ radioSignalSource: undefined,
+ onSignalSourceChange: undefined
+};
-select.addEventListener('click', function () {
- upload.click();
+event.on("RadioSignalSourceChanged", function () {
+ var callback = _self.onSignalSourceChange,
+ isRoaming = _self.isRoaming,
+ signalSource = _self.radioSignalSource,
+ msg = "Fired onSignalSourceChange. signalSource: " + signalSource + ", isRoaming: " + isRoaming;
+
+ if (callback && typeof callback === "function") {
+ callback.apply(null, [signalSource, isRoaming]);
+ }
+ else {
+ msg += " --> BUT there was no registered callback found.";
+ }
+
+ _console.log(msg);
});
-upload.addEventListener('change', function () {
- pic.src = window.webkitURL.createObjectURL(upload.files[0]);
- take.style.display = "inline";
+_self.__defineGetter__("radioSignalSource", function () {
+ return deviceSettings.retrieve("RadioInfo.radioSignalSource");
});
-take.addEventListener('click', function () {
- console.log("captured-image: " + pic.src);
- event.trigger('captured-image', [pic.src, upload.files[0]]);
- module.exports.hide();
+_self.__defineGetter__("isRoaming", function () {
+ return deviceSettings.retrieveAsBoolean("RadioInfo.isRoaming");
});
-module.exports = {
- show: function () {
- ui.showOverlay("camera-window");
- if (pic.src) {
- take.style.display = "inline";
- }
- else {
- take.style.display = "none";
- }
- },
- hide: function () {
- ui.hideOverlay("camera-window");
- }
-};
+_self.__defineGetter__("isRadioEnabled", function () {
+ return deviceSettings.retrieveAsBoolean("RadioInfo.isRadioEnabled");
+});
+_self.__defineGetter__("radioSignalStrengthPercent", function () {
+ return deviceSettings.retrieveAsInt("RadioInfo.radioSignalStrengthPercent");
});
-define('ripple/ui/plugins/communication', function (require, exports, module) {
+
+module.exports = _self;
+
+});
+define('ripple/platform/wac/1.0/EventRecurrenceTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+module.exports = {
+ NOT_REPEAT: "NOT_REPEAT",
+ DAILY: "DAILY",
+ EVERY_WEEKDAY: "EVERY_WEEKDAY",
+ WEEKLY_ON_DAY: "WEEKLY_ON_DAY",
+ MONTHLY_ON_DAY: "MONTHLY_ON_DAY",
+ MONTHLY_ON_DAY_COUNT: "MONTHLY_ON_DAY_COUNT",
+ YEARLY: "YEARLY"
+};
-var ui = require('ripple/ui'),
- event = require('ripple/event'),
- deviceSettings = require('ripple/deviceSettings'),
- db = require('ripple/db'),
- utils = require('ripple/utils'),
- _messageType = {
- sms: "SMS",
- mms: "MMS",
- email: "E-mail"
- },
- _attachments = [],
+});
+define('ripple/platform/wac/1.0/DataNetworkConnectionTypes', function (require, exports, module) {
/*
- _exception = {
- "": "Connection Issue",
- "unknown": "Unknown",
- "network": "Network",
- "unreachable": "Unreachable",
- "no-answer": "No Answer",
- "bad-number": "Bad Number",
- "number-not-in-use": "Number Not In Use",
- "media": "Media",
- "no-sim": "No Sim Card",
- "account-down": "Account Down",
- "credit-down": "Credit Down",
- "barred": "Barred",
- "network-busy": "Network Busy",
- "network-down": "Network Down"
- },
-*/
- _status = {
- IDLE: 0,
- DIALED: 1,
- INPROGRESS: 2,
- },
- _data = {
- status: _status.IDLE,
-// isInException: false,
- conversationStartTime: null
- },
- _contactNameArr = [],
- _contactNumArr = [],
- _CONTACT_KEY = "tizen1-contact",
- _record = {},
- _conversationSeconds = 0,
- _conversationTimer,
- _msgTimer,
- _audioPlayersStatus = [];
-
-function _showMsg() {
- var messageName = jQuery("#communication-senderName").val(),
- messageContent = jQuery("#communication-messageContent").val(),
- disMsgName = jQuery(".communication-messageContainer tr:first-child td"),
- disMsgContent = jQuery(".communication-messageContainer tr:nth-child(2) td textarea");
-
- ui.showOverlay("communication-window");
-
- disMsgName.text(messageName ? messageName : "Unknown name");
- disMsgContent.val(messageContent ? messageContent : "");
-
- jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
- .show("slide", {direction: "up"}, "fast");
- jQuery(".communication-callContainer").hide();
- jQuery(".communication-messageContainer").show();
-}
-
-function _msgEventInitialize() {
- jQuery("#communication-messageRadioStatus").hide();
- jQuery("#communication-sendMessage").unbind("click").click(function () {
- var messageItem,
- number = jQuery("#communication-senderName").val(),
- text = jQuery("#communication-messageContent").val(),
- type = jQuery("#communication-msgType").val(),
- message = {
- type: type,
- body: text,
- from: number,
- time: new Date(),
- attachments: _attachments
- };
-
- if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
- (type === 'sms' || type === 'mms')) {
- jQuery("#communication-messageRadioStatus").html('cellular radio is off<br \>Turn it on from Network Management Panel.');
- jQuery("#communication-messageRadioStatus").show();
- setTimeout(function () {
- jQuery("#communication-messageRadioStatus").hide();
- }, 3000);
- return;
- }
- if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
- type === 'email') {
- jQuery("#communication-messageRadioStatus").html('wifi radio is off<br \>Turn it on from Network Management Panel.');
- jQuery("#communication-messageRadioStatus").show();
- setTimeout(function () {
- jQuery("#communication-messageRadioStatus").hide();
- }, 3000);
- return;
- }
-
- event.trigger("MessageReceived", [message]);
- _attachments = [];
- event.trigger("CommWinShow", [true]);
- _showMsg();
-
- jQuery(".communication-messageContainer textarea").attr("disabled", "disabled");
- jQuery("#communication-messageOut td:nth-child(3)").text(jQuery("#communication-messageContent").val());
- messageItem = jQuery("#communication-messageOut").html();
- jQuery("#communication-messageDisplay").append(messageItem);
-
- clearTimeout(_msgTimer);
- _msgTimer = setTimeout(function () {
- if (_data.status === _status.IDLE) {
- ui.hideOverlay("communication-window");
- event.trigger("CommWinShow", [false]);
- } else {
- _showCall();
- }
- }, 5000);
- });
-
- jQuery("#communication-clearMessage").unbind("click").click(function () {
- jQuery("#communication-messageDisplay").empty();
- });
-
- event.on("LayoutChanged", function () {
- jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"));
-
- });
- event.on("OutsideMessageReceived", function (message) {
- var i = 0,
- recipients = [],
- recipientsStatus = {},
- messageItem;
-
- recipientsStatus.id = message.id;
- recipientsStatus.msg = message.msg;
- for (i in message.to) {
- recipientsStatus[message.to[i]] = true;
- recipients.push(message.to[i]);
- }
- for (i in message.cc) {
- recipientsStatus[message.cc[i]] = true;
- recipients.push(message.cc[i]);
- }
- for (i in message.bcc) {
- recipientsStatus[message.bcc[i]] = true;
- recipients.push(message.bcc[i]);
- }
-
- event.trigger("MessageSent", [recipientsStatus]);
- jQuery("#communication-messageIn td:nth-child(1)").text(message.body);
- messageItem = jQuery("#communication-messageIn").html();
- jQuery("#communication-messageDisplay").append(messageItem);
- });
-
- jQuery("#communication-ok").unbind("click").click(function () {
- if (_data.status === _status.IDLE) {
- ui.hideOverlay("communication-window");
- event.trigger("CommWinShow", [false]);
- } else {
- _showCall();
- }
- clearTimeout(_msgTimer);
- });
-}
-
-function _msgInitialize() {
- _msgEventInitialize();
-
- utils.forEach(_messageType, function (msgTypeText, msgType) {
- var typeNode = utils.createElement("option", {
- "innerText": msgTypeText,
- "value": msgType
- });
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ _self = {
+ "BLUETOOTH": undefined,
+ "EDGE": undefined,
+ "EVDO": undefined,
+ "GPRS": undefined,
+ "IRDA": undefined,
+ "LTE": undefined,
+ "ONEXRTT": undefined,
+ "WIFI": undefined
+ };
- jQuery("#communication-msgType").append(typeNode);
+utils.forEach(_self, function (value, property) {
+ _self.__defineGetter__(property, function () {
+ return property;
});
-}
-
-function pauseAllAudioPlayer() {
- var audios = $("#document").contents().find("audio"),
- index;
- for (var index = 0; index < audios.length; index++) {
- if (audios[index].paused) {
- _audioPlayersStatus[index] = 0;
- }
- else {
- _audioPlayersStatus[index] = 1;
- audios[index].pause();
- }
- }
-}
-
-function playAllAudioPlayer() {
- var audios = $("#document").contents().find("audio"),
- index;
- for (var index = 0; index < audios.length; index++) {
- if (_audioPlayersStatus[index] === 1) {
- audios[index].play();
- }
- }
- _audioPlayersStatus = [];
-}
-
-function _showCall() {
- var callName = jQuery("#communication-callerName").val(),
- callNum = jQuery("#communication-callNum").val(),
- disCallName = jQuery(".communication-callContainer tr:first-child td"),
- disCallNum = jQuery(".communication-callContainer tr:nth-child(2) td");
-
- ui.showOverlay("communication-window");
- event.trigger("CommWinShow", [true]);
-
- disCallName.text(callName ? callName : "Unknown Name");
- disCallNum.text(callNum ? callNum : "Unknown Number");
-
- jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
- .show("slide", {direction: "up"}, "fast");
- jQuery(".communication-callContainer").show();
- jQuery(".communication-messageContainer").hide();
- pauseAllAudioPlayer();
-}
-
-function _initRecord() {
- var callerName = jQuery("#communication-callerName").val(),
- callerNum = jQuery("#communication-callNum").val(),
- displayName = callerName ? callerName : "Unknown",
- displayNum = callerNum ? callerNum : "Unknown";
-
- _record = {};
- _record.type = "TEL";
- if ($("#is-videoCall").prop("checked") === true) {
- _record.features = ["CALL", "VIDEOCALL"];
- } else {
- _record.features = ["CALL", "VOICECALL"];
- }
- _record.remoteParties = [{
- remoteParty: displayNum,
- personId: displayName,
- }];
- _record.startTime = new Date();
-}
-
-function _endCall(callEndReason) {
- _record.duration = _data.conversationStartTime ? _conversationSeconds : 0;
-
- _data.conversationStartTime = null;
-
- switch (callEndReason) {
- case 'rejected':
- _record.direction = "REJECTED";
- break;
- case 'remote':
- _record.direction = "RECEIVED";
- break;
- case 'local':
- _record.direction = "MISSEDNEW";
- break;
- }
+});
- event.trigger("CallRecorded", [_record]);
- event.trigger("CallInProgress", [false]);
+module.exports = _self;
- _data.status = _status.IDLE;
- _record = {};
+});
+define('ripple/platform/wac/1.0/Message', function (require, exports, module) {
+/*
+ * Copyright 2011 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 exception = require('ripple/exception'),
+ Attachment = require('ripple/platform/wac/1.0/Attachment'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception');
- _conversationSeconds = 0;
- window.clearInterval(_conversationTimer);
- ui.hideOverlay("communication-window");
- event.trigger("CommWinShow", [false]);
- playAllAudioPlayer();
+function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}
-function _callEventInitialize() {
- jQuery("#communication-cellularStatus").hide();
- jQuery("#communication-callStart").unbind('click').click(
- function () {
- if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false) {
- jQuery("#communication-cellularStatus").show();
- setTimeout(function () {
- jQuery("#communication-cellularStatus").hide();
- }, 3000);
+module.exports = function () {
+ this.messageId = Math.uuid(undefined, 16);
+ this.callbackNumber = undefined;
+ this.destinationAddress = [];
+ this.isRead = undefined;
+ this.messagePriority = undefined;
+ this.messageType = undefined;
+ this.subject = undefined;
+ this.body = undefined;
+ this.sourceAddress = undefined;
+ this.validityPeriodHours = undefined;
+ this.time = undefined;
+ this.ccAddress = [];
+ this.bccAddress = [];
+ this.attachments = [];
- return;
- }
- if (_data.status === _status.IDLE) {
- _data.status = _status.DIALED;
- _initRecord();
- _showCall();
- jQuery("#callSettings tr:last-child td").text("Calling...");
- jQuery("#communication-callStart > span").text("End Call");
- jQuery("#callSettings input").attr("disabled", "disabled");
- } else {
- _endCall("local");
+ this.addAttachment = function (fileFullName) {
+ var attachment = new Attachment();
+ attachment.fileName = fileFullName;
+ this.attachments.push(attachment);
+ };
+ this.deleteAttachment = function (attachment) {
- jQuery("#callSettings tr:last-child td").text("");
- jQuery("#communication-callStart > span").text("Call");
- jQuery(".communication-callContainer tr:nth-child(3)").show();
- jQuery(".communication-callContainer tr:last-child").hide();
- jQuery("#callSettings input").removeAttr("disabled");
+ for (var i = this.attachments.length - 1; i >= 0; i--) {
+ if (this.attachments[i].fileName === attachment.fileName) {
+ this.attachments.splice(i, 1);
}
-
}
- );
+ };
+ this.saveAttachment = function (fileFullName, attachment) {
+ _throwUnsupportedException("Widget.Messaging.Message.addAddress");
+ };
+ this.addAddress = function (type, address) {
- event.on("ApplicationLoad", function () {
- switch (_data.status) {
- case _status.INPROGRESS:
- jQuery("#communication-callStart").click();
+ var addresses = address.split(";");
+
+ switch (type) {
+ case "destination":
+ this.destinationAddress = this.destinationAddress.concat(addresses);
break;
- case _status.DIALED:
- jQuery("#communication-ignore").click();
+ case "cc":
+ this.ccAddress = this.ccAddress.concat(addresses);
break;
- default:
+ case "bcc":
+ this.bccAddress = this.bccAddress.concat(addresses);
break;
}
- });
-
- jQuery("#communication-ignore").unbind('click').click(function () {
- _endCall("rejected");
-
- jQuery("#callSettings tr:last-child td").text("");
- jQuery("#communication-callStart > span").text("Call");
- jQuery("#communication-callStart").removeData();
- jQuery("#callSettings input").removeAttr("disabled");
- });
-
- jQuery("#communication-answer").unbind('click').click(function () {
- _data.conversationStartTime = new Date();
- event.trigger("CallInProgress", [true]);
- _data.status = _status.INPROGRESS;
-
- _conversationTimer = setInterval(function () {
- var timeObj = new Date(1970, 0, 1),
- timeString;
-
- timeObj.setSeconds(_conversationSeconds);
- timeString = timeObj.toTimeString().substr(0, 8);
- jQuery("#callSettings tr:last-child td").text(timeString);
- _conversationSeconds = _conversationSeconds + 1;
- }, 1000);
-
- jQuery(".communication-callContainer tr:nth-child(3)").hide();
- jQuery(".communication-callContainer tr:last-child").show();
- });
-
- jQuery("#communication-end").unbind('click').click(function () {
- _endCall("remote");
-
- jQuery("#callSettings tr:last-child td").text("");
- jQuery("#communication-callStart > span").text("Call");
- jQuery("#communication-callStart").removeData();
- jQuery(".communication-callContainer tr:nth-child(3)").show();
- jQuery(".communication-callContainer tr:last-child").hide();
- jQuery("#callSettings input").removeAttr("disabled");
- });
-/*
- jQuery("#communication-callEndReason").unbind("change").change(function () {
- if (!jQuery("#communication-callEndReason").val()) {
- _data.isInException = false;
- } else {
- _data.isInException = true;
- if (_data.isInException && (_data.status !== _status.IDLE)) {
- _endCall(jQuery("#communication-callEndReason").val());
- }
- }
-
- jQuery("#callSettings tr:last-child td").text("");
- jQuery("#communication-callStart > span").text("Call");
- jQuery("#communication-callStart").removeData();
- jQuery(".communication-callContainer tr:nth-child(3)").show();
- jQuery(".communication-callContainer tr:last-child").hide();
- jQuery("#callSettings input").removeAttr("disabled");
- });
-*/
-}
-
-function _contactInitialize() {
- var data = db.retrieveObject(_CONTACT_KEY),
- displayName = null, number = null, index = 0;
-
- _contactNameArr = [];
- _contactNumArr = [];
-
- utils.forEach(data, function (addrBook) {
- utils.forEach(addrBook._contacts, function (contact) {
- if (contact.name && contact.name && contact.phoneNumbers && contact.phoneNumbers.length > 0) {
- displayName = contact.name.firstName + ' ' + contact.name.lastName;
- number = contact.phoneNumbers[0].number;
- _contactNameArr.push(displayName);
- _contactNumArr[displayName] = number;
- index++;
- }
- });
- });
-
- jQuery("#communication-callerName").autocomplete({
- source: _contactNameArr,
- select: function (event, ui) {
- jQuery("#communication-callNum").val(_contactNumArr[ui.item.value]);
- }
- });
- jQuery("#communication-senderName").autocomplete({
- source: _contactNameArr
- });
-}
-
-function _callInitialize() {
- _callEventInitialize();
-
- _contactInitialize();
-/*
- utils.forEach(_exception, function (value, key) {
- var typeNode = utils.createElement("option", {
- "innerText": value,
- "value": key
- });
-
- jQuery("#communication-callEndReason").append(typeNode);
- });
-*/
-}
-
-function _pushEventInitialize() {
- function register(appService) {
- appService.registrationId = Math.uuid(null, 16);
-
- window.setTimeout(function () {
- var appLabel;
-
- if ($("#communication-push-" + appService.appId).length !== 0) {
- $("#" + appService.appId).click();
- $("#communication-push-status-" + appService.appId).html("||");
- $("#communication-push-status-" + appService.appId).css("color", "#ff0000");
-
- return;
- }
-
- if (!$("#communication-push-app > tbody").html()) {
- $("#communication-push-header").show();
- $("#communication-push-submit").removeAttr("disabled");
- }
-
- appLabel = appService.appControl.uri || appService.appId;
-
- $("#communication-push-app").append(
- "<tr id='communication-push-" + appService.appId + "'>" +
- "<td style='width: 90%'><input type='radio' name='communication-push-list' id='" +
- appService.appId + "' style='margin: 5px' checked='checked' />" +
- "<label for='" + appService.appId + "'>" + appLabel + "</label></td>" +
- "<td id='communication-push-status-" + appService.appId + "'>||</td>" +
- "</tr>");
-
- $("label[for='" + appService.appId + "']").css({
- "display": "inline-block",
- "width": "220px",
- "white-space": "nowrap",
- "overflow": "hidden",
- "text-overflow": "ellipsis"
- });
-
- $("#communication-push-status-" + appService.appId).css({
- "width": "10%",
- "color": "#ff0000",
- "text-align": "center",
- "font-weight": "bold",
- "font-size": "14px"
- });
-
- $("#communication-push-app tr:even").css("background-color", "white");
- $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
- }, 1);
- }
-
- function unregister(appId) {
- if ($("#communication-push-" + appId).length === 0)
- return;
-
- $("tr[id='communication-push-" + appId + "']").remove();
-
- if (!$("#communication-push-app > tbody").html()) {
- $("#communication-push-header").hide();
- $("#communication-push-submit").attr("disabled", "disabled");
-
- return;
- }
-
- if ($("input[name='communication-push-list']:checked").length === 0) {
- $("#communication-push-app input:first").click();
- }
-
- $("#communication-push-app tr:even").css("background-color", "white");
- $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
- }
-
- function connect(appId) {
- $("#communication-push-status-" + appId).html("<=>");
- $("#communication-push-status-" + appId).css("color", "#32cd32");
- }
-
- function disconnect(appId) {
- $("#communication-push-status-" + appId).html("||");
- $("#communication-push-status-" + appId).css("color", "#ff0000");
- }
+ };
- event.on("PushRequest", function (command, cmdData) {
- switch (command) {
- case "REGISTER":
- register(cmdData);
- break;
+ this.deleteAddress = function (type, address) {
+ var addresses = address.split(";"),
+ filter = function (orig) {
+ return orig.filter(function (address) {
+ return !addresses.some(function (x) {
+ return address === x;
+ });
+ });
+ };
- case "UNREGISTER":
- unregister(cmdData);
+ switch (type) {
+ case "destination":
+ this.destinationAddress = filter(this.destinationAddress);
break;
-
- case "CONNECT":
- connect(cmdData);
+ case "cc":
+ this.ccAddress = filter(this.ccAddress);
break;
-
- case "DISCONNECT":
- disconnect(cmdData);
+ case "bcc":
+ this.bccAddress = filter(this.bccAddress);
break;
}
- });
-}
-
-function _pushElementInitialize() {
- $("#communication-push-submit").attr("disabled", "disabled");
- $("#communication-push-submit").unbind('click').click(function () {
- var appId, pushMessage;
-
- appId = $("#communication-push-app :checked").attr("id");
- if (!appId)
- return;
-
- pushMessage = {
- appData: $("#communication-push-data").val(),
- alertMessage: $("#communication-push-msg").val(),
- date: new Date()
- };
-
- if (!pushMessage.appData || !pushMessage.alertMessage)
- return;
-
- event.trigger("PushNotified", [appId, pushMessage]);
- });
-
- $("#communication-push-clear").unbind('click').click(function () {
- $("#communication-push-msg").val("");
- $("#communication-push-data").val("");
- });
-}
-
-function _pushInitialize() {
- _pushEventInitialize();
- _pushElementInitialize();
-}
+ };
-module.exports = {
- panel: {
- domId: "communication-container",
- collapsed: true,
- pane: "left",
- titleName: "Communications",
- display: true
- },
- initialize: function () {
- jQuery("#communication-select").tabs();
- _callInitialize();
- _msgInitialize();
- _pushInitialize();
- }
};
});
-define('ripple/ui/plugins/configWindow', function (require, exports, module) {
+define('ripple/platform/wac/1.0/Exception', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- event = require('ripple/event'),
- db = require('ripple/db'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- platform = require('ripple/platform'),
- items = [{name: "DEVICE", id: "device-conf-panel"},
- {name: "SYSTEM SETTINGS", id: "system-settings-conf-panel"},
- {name: "NETWORK", id: "network-conf-panel"}
- ],
- _KEY = "tizen-configuration-window-setting",
- _PERSISTENCE_KEY = "devicesettings",
- _DEVICESETTING_SAVE_KEY = "tizen-configuration-window-device-setting",
- _DB_APPLICATION_KEY = "tizen1-db-application",
- _DB_APPLICATION_SAVE_KEY = "tizen-configuration-window-application-key";
-
-function reload() {
- window.tinyHipposReload = true;
- location.reload();
-}
-
-function _hideConfigWindow() {
- $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
- $("#overlayBackground").hide("fade", "slow");
-}
-
-
-function checkResolutionValue(val) {
- var ret = false;
- if (val >= 200 && val <= 2000) {
- ret = true;
- }
- return ret;
-}
-
-function _showConfigWindow() {
- var position_x;
- $("#item_container").empty();
- items.forEach(function (item) {
- $("#item_container").append('<div class="configuration-window-item">' + item.name + '</div>');
- $("#" + item.id).hide();
- });
-
- $("#content_container").show();
- $("#" + items[0].id).show("fast");
-
- $(".configuration-window-item:eq(0)").css("background-color", "#003399");
- $(".configuration-window-item:eq(0)").css("color", "#ffffff");
-
- $(".configuration-window-item").unbind('click');
- $(".configuration-window-item").bind("click", function () {
- $(".configuration-window-item").css("background-color", "#eeeeee");
- $(".configuration-window-item").css("color", "#333333");
-
- $(this).css("background-color", "#003399");
- $(this).css("color", "#ffffff");
-
- items.forEach(function (item) {
- $("#" + item.id).hide();
- });
- $("#" + items[$(this).index()].id).show("fast");
- });
-
- if ($("#configure-window-popup").is(":visible")) {
- $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
- $("#overlayBackground").hide("fade", "slow");
- return;
- }
-
- position_x = (($(window).width() - 800) / 2) < 0 ? 0 : ($(window).width() - 800) / 2;
- $("#configure-window-popup").css("top", 80);
- $("#configure-window-popup").css("left", position_x);
-
- position_x = (($(window).width() - 400) / 2) < 0 ? 0 : ($(window).width() - 400) / 2;
- $("#configure-window-done-popup").css("top", 80);
- $("#configure-window-done-popup").css("left", position_x);
-
- $("#overlayBackground").css("width", $(window).width());
- $("#overlayBackground").css("height", $(window).height());
- $("#overlayBackground").show("fade", "slow");
- $("#configure-window-popup").show("slide", {direction: "up"}, "slow");
-
- $("#configuration-window-done-btn").unbind('click');
- $("#configuration-window-done-btn").bind("click", function () {
- var platformId, version, device, type, width, height, url;
-
- // device & resolution setting
- platformId = jQuery("#platform-select").val();
- version = jQuery("#version-select").val();
- device = jQuery("#device-select").val();
- width = jQuery("#resolution-custom-width").val();
- height = jQuery("#resolution-custom-height").val();
- type = jQuery('input:radio[name="resolution-type"]:checked').val();
-
- if (type === "custom") {
- device = "custom";
- if (!checkResolutionValue(width) || !checkResolutionValue(height)) {
- return;
- }
- }
-
- if (platformId === "mobile" || platformId === "tizen") {
- platformId = "tizen";
- version = "2.0";
- }
- else {
- platformId = "ivi";
- version = "3.0";
- }
-
- platform.changeEnvironment({
- "name": platformId,
- "version": version
- }, device, function () {
- _hideConfigWindow();
- window.tinyHipposReload = true;
- url = location.href.replace(/&platform=(.+?)-(.+?)$/, "&platform=" + platformId + "-" + version);
- location.href = url;
- //reload();
- });
- });
-
- $("#configuration-window-close-btn").unbind('click');
- $("#configuration-window-close-btn").bind("click", function () {
- if ($("#configure-window-popup").is(":visible")) {
- _hideConfigWindow();
- return;
- }
- });
- tooltip.create("#configuration-window-save-btn", "Save Configuration");
- $("#configuration-window-save-btn").unbind('click');
- $("#configuration-window-save-btn").bind("click", function () {
- var _type, _device, _custom_width = 0, _custom_height = 0, programs, deviceInfo, _settings;
-
- deviceInfo = db.retrieveObject(_PERSISTENCE_KEY);
- db.saveObject(_DEVICESETTING_SAVE_KEY, deviceInfo);
-
- _device = jQuery("#device-select").val();
- _type = jQuery('input:radio[name="resolution-type"]:checked').val();
- if (_type === "custom") {
- _device = "custom";
- _custom_width = jQuery("#resolution-custom-width").val();
- _custom_height = jQuery("#resolution-custom-height").val();
- }
- _settings = {
- platformId : jQuery("#platform-select").val(),
- version : jQuery("#version-select").val(),
- device : _device,
- type : _type,
- custom_width : _custom_width,
- custom_height : _custom_height
- };
- db.saveObject(_KEY, _settings);
- programs = db.retrieveObject(_DB_APPLICATION_KEY);
- db.saveObject(_DB_APPLICATION_SAVE_KEY, programs);
+module.exports = function () {
+ this.message = "";
+ this.type = "";
- });
- tooltip.create("#configuration-window-load-btn", "Load Configuration");
- $("#configuration-window-load-btn").unbind('click');
- $("#configuration-window-load-btn").bind("click", function () {
- var platformList,
- programs,
- deviceInfo,
- _settings,
- versionSelect = document.getElementById("version-select");
- if (db.retrieveObject(_DEVICESETTING_SAVE_KEY) === undefined) {
- //Never saving data exist
- return;
- }
- //reload system & network setting
- deviceInfo = db.retrieveObject(_DEVICESETTING_SAVE_KEY);
- db.saveObject("devicesettings", deviceInfo);
- jQuery("#devicesettings-content-container").empty();
- jQuery("#networksettings-content-container").empty();
- require('ripple/deviceSettings').initialize();
- require('ripple/ui/plugins/deviceSettings').terminate();
- require('ripple/ui/plugins/deviceSettings').initialize();
+ this.toString = function () {
+ var result = this.type + ': "' + this.message + '"';
- //reload device setting
- jQuery(versionSelect).empty();
- _settings = db.retrieveObject(_KEY);
- jQuery("#platform-select").val(_settings.platformId);
- jQuery("#device-select").val(_settings.device);
- if (_settings.type === "custom") {
- $('input:radio[name="resolution-type"][value="custom"]').click();
- jQuery("#resolution-custom-width").val(parseInt(_settings.custom_width, 10));
- jQuery("#resolution-custom-height").val(parseInt(_settings.custom_height, 10));
- } else {
- $('input:radio[name="resolution-type"][value="predefined"]').click();
+ if (this.stack) {
+ result += "\n" + this.stack;
}
+ return result;
+ };
+};
- platformList = platform.getList();
- utils.forEach(platformList, function (platform) {
- utils.forEach(platform, function (version, versionNumber) {
- if (_settings.platformId === version.id) {
- versionSelect.appendChild(utils.createElement("option", {
- "innerText": versionNumber,
- "value": versionNumber
- }));
- }
- });
- });
- jQuery("#version-select").val(_settings.version);
- });
-
- $(window).bind('resize', function () {
- var position_x = 0;
- $("#configure-window-popup").css("top", 80);
- position_x = (($(window).width() - 800) / 2) < 0 ? 0 : ($(window).width() - 800) / 2;
- $("#configure-window-popup").css("left", position_x);
-
- $("#configure-window-done-popup").css("top", 180);
- position_x = (($(window).width() - 400) / 2) < 0 ? 0 : ($(window).width() - 400) / 2;
- $("#configure-window-done-popup").css("left", position_x);
-
- $("#overlayBackground").css("width", $(window).width());
- $("#overlayBackground").css("height", $(window).height());
- });
-
- if (jQuery("#platform-select").val() === "ivi") {
- jQuery("#configuration-window-save-btn").hide();
- jQuery("#configuration-window-load-btn").hide();
+});
+define('ripple/platform/wac/1.0/MessageQuantities', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = {
+ totalMessageCnt: undefined,
+ totalMessageReadCnt: undefined,
+ totalMessageUnreadCnt: undefined
+};
- jQuery("#item_container :nth-child(2)").hide();
- jQuery("#item_container :nth-child(3)").hide();
+});
+define('ripple/platform/wac/1.0/AccelerometerInfo', function (require, exports, module) {
+/*
+ * Copyright 2011 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 accelerometer = require('ripple/accelerometer'),
+ _self = {};
- jQuery("#hwkeys-panel").hide();
- }
- else {
- jQuery("#configuration-window-save-btn").show();
- jQuery("#configuration-window-load-btn").show();
+_self.__defineGetter__("xAxis", function () {
+ return accelerometer.getInfo().accelerationIncludingGravity.x;
+});
- jQuery("#item_container :nth-child(2)").show();
- jQuery("#item_container :nth-child(3)").show();
+_self.__defineGetter__("yAxis", function () {
+ return accelerometer.getInfo(true).accelerationIncludingGravity.y;
+});
- jQuery("#hwkeys-panel").show();
- }
-}
+_self.__defineGetter__("zAxis", function () {
+ return accelerometer.getInfo(true).accelerationIncludingGravity.z;
+});
-module.exports = {
- initialize: function () {
- if (platform.current().id === "cordova") {
- items.splice(1, 1);
- }
- $("#options-button-config-window").bind("click", function () {
- _showConfigWindow();
- });
- }
-};
+module.exports = _self;
});
-define('ripple/ui/plugins/deviceSettings', function (require, exports, module) {
+define('ripple/platform/wac/1.0/VideoPlayer', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var event = require('ripple/event'),
- constants = require('ripple/constants'),
- deviceSettings = require('ripple/deviceSettings'),
+var _self,
+ _console = require('ripple/console'),
+ event = require('ripple/event'),
utils = require('ripple/utils'),
+ fileSystem = require('ripple/fileSystem'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
exception = require('ripple/exception'),
- platform = require('ripple/platform'),
- db = require('ripple/db'),
- _CONST = {
- "CONTENT_CONTAINER_ID": "devicesettings-content-container",
- "UKNOWN_CONTROL_MESSAGE": "Unknown device control type"
- },
- _contentContainer,
- _network_contentContainer,
- DBNETWORKSETTING_KEY = "tizen2-preFlightModeNetworksetting",
- _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;
-
-function _retrieveDeviceInfo(key) {
- var layout, rtn, deviceInfo = require('ripple/devices').getCurrentDevice();
+ _currentlySet,
+ _currentVideoFile,
+ _state = null,
+ _loopCount, _video,
+ _STATES = {
+ "OPENED": "opened",
+ "STOPPED": "stopped",
+ "PAUSED": "paused",
+ "PLAYING": "playing",
+ "COMPLETED": "completed"
+ };
- switch (key) {
- case "Device.model":
- return deviceInfo.model;
- case "Device.version":
- return deviceInfo.firmware;
- case "Device.vendor":
- return deviceInfo.manufacturer;
- case "DISPLAY.resolutionHeight":
- return deviceInfo.screen.height;
- case "DISPLAY.resolutionWidth":
- return deviceInfo.screen.width;
- case "DISPLAY.pixelAspectRatio":
- return (deviceInfo.screen.width / deviceInfo.screen.height).toFixed(2);
+function _validateVideoType(fileUrl) {
+ var matched = fileUrl.match(/\.(\w*)$/),
+ maps = {
+ "ogv": "ogg",
+ "flv": "mp4"
+ },
+ type = matched ? matched[1] : "";
- case "DISPLAY.physicalWidth":
- return Number((deviceInfo.screen.width / deviceInfo.ppi).toFixed(2));
- case "DISPLAY.physicalHeight":
- return Number((deviceInfo.screen.height / deviceInfo.ppi).toFixed(2));
- case "DISPLAY.dpiY":
- case "DISPLAY.dotsPerInchHeight":
- return deviceInfo.ppi;
- case "DISPLAY.dpiX":
- case "DISPLAY.dotsPerInchWidth":
- return deviceInfo.ppi;
- case "OperatingSystem.version":
- return deviceInfo.osVersion;
- case "OperatingSystem.name":
- return deviceInfo.osName;
- case "OperatingSystem.vendor":
- return deviceInfo.manufacturer;
- case "DEVICE_ORIENTATION.status":
- layout = db.retrieve("layout");
- if (layout === null || layout === undefined) {
- layout = deviceInfo.defaultOrientation || "portrait";
- }
- if (layout === "portrait") {
- return "PORTRAIT_PRIMARY";
- } else {
- return "LANDSCAPE_PRIMARY";
- }
- break;
- case "WIFI_NETWORK.status":
- case "CELLULAR_NETWORK.status":
- rtn = deviceSettings.retrieve(key);
- if (rtn === true) {
- return "ON";
- } else {
- return "OFF";
- }
- break;
- case "CPU.load":
- rtn = deviceSettings.retrieve(key);
- if (rtn > 1) {
- rtn = 1;
- deviceSettings.persist(key, rtn);
- }
- if (rtn < 0) {
- rtn = 0;
- deviceSettings.persist(key, rtn);
- }
- return rtn;
- case "DISPLAY.brightness":
- rtn = deviceSettings.retrieve(key);
- if (rtn > 1) {
- rtn = 1;
- deviceSettings.persist("DISPLAY.brightness", rtn);
- }
- if (rtn < 0) {
- rtn = 0;
- deviceSettings.persist("DISPLAY.brightness", rtn);
- }
- return rtn;
- case "BUILD.manufacturer":
- return deviceInfo.manufacturer;
- default:
- return deviceSettings.retrieve(key);
+ if (_video && _video.canPlayType("video/" + (maps[type] || type)) === "") {
+ _console.warn("Attempting to load a video that might not work in the current browser [" + fileUrl + "]");
}
}
-function _retrieveSettingName(type) {
+function _validateAndSet(state, validStates, callbackBeforeSuccess) {
+ var i, valid = false;
- switch (type) {
- case "CellularHardware":
- return "Cellular Hardware";
- case "CellularNetwork":
- return "Cellular Network";
- case "MemoryUnit":
- return "Memory Unit";
- case "OperatingSystem":
- return "Operating System";
- case "WebRuntime":
- return "Web Runtime";
- case "WiFiHardware":
- return "WiFi Hardware";
- case "WiFiNetwork":
- return "WiFi Network";
- default:
- return type;
+ for (i = 0; i < validStates.length; i++) {
+ if (validStates[i] === _state) {
+ valid = true;
+ }
}
-}
-
-function _appendSettingNode(labelNode, inputNode, label) {
- var frag = document.createDocumentFragment(),
- rowNode = frag.appendChild(utils.createElement("tr")),
- tempTdNode;
-
- rowNode.appendChild(utils.createElement("td"))
- .appendChild(labelNode);
-
- tempTdNode = rowNode.appendChild(utils.createElement("td"));
- if (label) {
- tempTdNode.appendChild(label);
+ if (!valid) {
+ _console.warn("Attempted to initiate VideoPlayer." + state +
+ " in invalid state. current state: " + _state);
+ } else {
+ if (typeof(callbackBeforeSuccess) === "function") {
+ callbackBeforeSuccess.apply();
+ }
+ event.trigger("MultimediaVideoStateChanged", [state], true);
}
- tempTdNode.appendChild(inputNode);
-
- return frag;
+ return valid;
}
-function _getCurrentSetting(setting, settingType, key) {
- var ret, savedSetting, fullKey;
- fullKey = settingType + "." + key;
- savedSetting = _retrieveDeviceInfo(fullKey);
- if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
- if (savedSetting === "ON") {
- savedSetting = true;
- } else {
- savedSetting = false;
- }
+event.on("MultimediaVideoStateChanged", function (state) {
+ _state = state;
+ if (typeof _self.onStateChange === "function") {
+ _self.onStateChange.apply(_self, [state]);
}
- ret = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;
- return ret;
-}
+});
-function _buildDOMNode(setting, settingType, key) {
- var settingsNode, tagName, jNode,
- fullKey = settingType + "." + key,
- savedSetting = _retrieveDeviceInfo(fullKey),
- // TODO: move this into Utils (isSet method)
- currentSetting,
- domNode,
- domNodeLabel = null;
+_self = module.exports = {
+ onStateChange: undefined,
- if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
- if (savedSetting === "ON") {
- savedSetting = true;
- } else {
- savedSetting = false;
+ open: function (fileUrl) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
+ "VideoPlayer.open invalid number of arguments", new Exception());
+ utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER,
+ "VideoPlayer.open expected valid fileUrl but got ->" + fileUrl, new Exception());
+
+ if (!_video) {
+ return;
}
- }
- currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;
- switch (setting.control.type) {
- case "text":
- case "number":
- case "range":
- case "checkbox":
- tagName = "input";
- break;
- case "textarea":
- tagName = "textarea";
- break;
- case "select":
- tagName = "select";
- break;
- case "label":
- tagName = "label";
- break;
- default:
- exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
- }
+ _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
+ _validateVideoType(fileUrl);
+ _currentVideoFile = fileSystem.getURI(fileUrl);
+ _video.setAttribute("src", _currentVideoFile);
+ _video.setAttribute("width", "100%");
+ _video.addEventListener("ended", function () {
+ event.trigger("MultimediaVideoStateChanged", [_STATES.COMPLETED], true);
+ if (_loopCount > 1) {
+ _self.open(_currentVideoFile);
+ _self.play(_loopCount--);
+ }
+ }, false);
+ });
+ },
- settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);
- settingsNode.setAttribute("id", "device-settings-" + settingType + "-" + key);
+ setWindow: function (domObject) {
+ utils.validateNumberOfArguments(0, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
+ "VideoPlayer.setWindow invalid number of arguments", new Exception());
- // TODO: this should really be part of utils.createControl? add element of type "range" with label?
- if (setting.control.type === "range") {
- domNodeLabel = utils.createElement("label", {
- "class": constants.UI.LEFT_RANGE_LABEL_CLASS
- });
- }
+ if (_currentlySet) {
+ _currentlySet.removeChild(_video);
+ _currentlySet = null;
+ _video = null;
+ }
- domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": "configure-window-text-label"}), settingsNode, domNodeLabel);
+ if (domObject !== null) {
+ _video = utils.createElement("video", {
+ "id": "multimedia-video"
+ });
+ domObject.appendChild(_video);
+ _currentlySet = domObject;
+ event.trigger("MultimediaAppVideoPlayerCreated", [_video], true);
+ }
+ },
- jNode = jQuery(settingsNode);
- if (tagName !== "label") {
- jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);
- }
+ play: function (repeatTimes) {
+ utils.validateNumberOfArguments(1, 1, arguments.length,
+ ExceptionTypes.INVALID_PARAMETER, "invalid number of arguments (expected one)", new Exception());
- switch (setting.control.type) {
- case "checkbox":
- jNode.bind("click", function () {
- var checked = this.checked ? true : false;
- deviceSettings.persist(fullKey, checked);
- if (typeof setting.callback === "function") {
- setting.callback(checked);
+ if (typeof repeatTimes !== "number" || repeatTimes < 0) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "VideoPlayer.play was passed an invalid number of play times: " + repeatTimes, new Exception());
+ }
+ if (repeatTimes !== 0) {
+ if (!_video) {
+ return;
}
+ _loopCount = repeatTimes;
+ _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
+ _video.play();
+ });
+ }
+ },
+
+ pause: function () {
+ if (!_video) {
+ return;
+ }
+ _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
+ _video.pause();
});
+ },
- if (currentSetting === true) {
- jNode.attr("checked", "checked");
+ resume: function () {
+ if (!_video) {
+ return;
}
+ _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
+ _video.play();
+ });
+ },
- break;
+ stop: function () {
+ if (!_video) {
+ return;
+ }
+ _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
+ _video.pause();
+ _video.setAttribute("src", _currentVideoFile); // hack
+ });
+ }
- case "text":
- case "textarea":
- case "number":
- jNode.val(currentSetting);
- utils.bindAutoSaveEvent(jNode, function () {
- if (setting.control.type === "number") {
- deviceSettings.persist(fullKey, Number(jNode.val()));
- } else {
- deviceSettings.persist(fullKey, jNode.val());
- }
+};
- if (typeof setting.callback === "function") {
- setting.callback(jNode.val());
- }
- });
- break;
+});
+define('ripple/platform/wac/1.0/CallRecord', function (require, exports, module) {
+/*
+ * Copyright 2011 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 = function () {
+ this.callRecordType = undefined;
+ this.callRecordId = undefined;
+ this.callRecordAddress = undefined;
+ this.callRecordName = undefined;
+ this.durationSeconds = undefined;
+ this.startTime = undefined;
+};
- case "label":
- jNode.text(currentSetting);
- break;
+});
+define('ripple/platform/wac/1.0/Widget', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ _console = require('ripple/console'),
+ app = require('ripple/app'),
+ platform = require('ripple/platform'),
+ exception = require('ripple/exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ _self;
- case "select":
- case "range":
- if (setting.control.type === "select") {
- utils.forEach(setting.options, function (value, option) {
- jNode.append(utils.createElement("option", {
- "value": option,
- "innerText": value
- }));
- });
+event.on("ScreenChangeDimensions", function (height, width) {
+ try {
+ // TODO: are these per spec to call?
+ if (typeof app.onMaximize === 'function') {
+ app.onMaximize();
}
- else {
- if (domNodeLabel) {
- domNodeLabel.innerText = currentSetting;
- }
+ if (typeof app.onRestore === 'function') {
+ app.onRestore();
}
-
- jNode.val(currentSetting)
- .bind("change", function () {
- if (setting.control.type === "range" && domNodeLabel) {
- domNodeLabel.innerText = jQuery(this).val();
- }
- deviceSettings.persist(fullKey, jQuery(this).val());
-
- if (typeof setting.callback === "function") {
- setting.callback(jQuery(this).val(), currentSetting);
- }
- }
- );
+ _console.log("called Widget.onRestore and Widget.onMaximize callback function");
+ }
+ catch (e) {
+ exception.handle(e, false);
}
+});
- // TODO: Brent, do in DeviceSettings on load instead?
- if (currentSetting !== setting.control.value) {
- deviceSettings.register(fullKey, currentSetting);
+event.on("WidgetWakeup", function () {
+ if (_self.onWakeup) {
+ _self.onWakeup();
}
+});
- return domNode;
-}
+event.on("WidgetMaximize", function () {
+ if (_self.onMaximize) {
+ _self.onMaximize();
+ }
+});
-function displayBrightnessCB(value) {
- if (value > 1) value = 1;
- if (value < 0) value = 0;
- if (document.getElementById("device-settings-DISPLAY-brightness").value === value) {
- return;
+event.on("WidgetFocus", function () {
+ if (_self.onFocus) {
+ _self.onFocus();
}
- deviceSettings.persist("DISPLAY.brightness", Number(value));
- document.getElementById("device-settings-DISPLAY-brightness").value = value;
-}
+});
-function cpuLoadCB(value) {
- if (value > 1) value = 1;
- if (value < 0) value = 0;
- if (document.getElementById("device-settings-CPU-load").value === value) {
- return;
+event.on("WidgetRestore", function () {
+ if (_self.onRestore) {
+ _self.onRestore();
}
- deviceSettings.persist("CPU.load", Number(value));
- document.getElementById("device-settings-CPU-load").value = value;
-}
+});
-function availCapacityCB(value) {
- var capacity = deviceSettings.retrieve("STORAGE.capacity");
- if (Number(value) > Number(capacity)) value = capacity;
- if (Number(value) < 0) value = 0;
- deviceSettings.persist("STORAGE.availableCapacity", Number(value));
- document.getElementById("device-settings-STORAGE-availableCapacity").value = Number(value);
-}
+_self = {
+ onWakeup: undefined,
+ onMaximize: undefined,
+ onFocus: undefined,
+ onRestore: undefined,
-function wiFiNetworkStatusCB(value) {
- document.getElementById("device-settings-WIFI_NETWORK-status").checked = value;
-}
+ openURL: function (url) {
+ window.open(url);
+ },
-function flightModeChangedCB(value) {
- var networkSettings = {};
- if (value === true) {
- networkSettings['wifiSetting'] = deviceSettings.retrieve("WIFI_NETWORK.status");
- networkSettings['cellularSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
- //networkSettings['bluetoothSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
- //networkSettings['nfcSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
- db.saveObject(DBNETWORKSETTING_KEY, networkSettings);
+ setPreferenceForKey: function (value, key) {
- deviceSettings.persist("CELLULAR_NETWORK.status", false);
- deviceSettings.persist("WIFI_NETWORK.status", false);
- event.trigger("nfc-power-setting", [false]);
- event.trigger("bt-power-setting", [false]);
+ utils.validateNumberOfArguments(1, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid number of paramters", new Exception());
+ utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid parameter! Key:" +
+ key + ", Value: " + value, new Exception());
- document.getElementById("device-settings-WIFI_NETWORK-status").checked = false;
- document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = false;
- $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'> (Disabled for Flight Mode)</span>");
- document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;
+ var msg = "",
+ prefix;
+ if (app.isPreferenceReadOnly(key)) {
+ msg += "Cannot modify a read only preference. Preference key: " + key;
+ }
+ else {
+ prefix = platform.getPersistencePrefix();
+ if (value === null) {
+ msg += "deleting preference " + key;
+ db.remove(key, prefix);
+ }
+ else {
+ msg += "setting preference " + key + " == " + value;
+ utils.validateArgumentType(value, "string", ExceptionTypes.INVALID_PARAMETER, msg, new Exception());
+ db.save(key, value, prefix);
+ }
+ }
- } else {
- networkSettings = db.retrieveObject(DBNETWORKSETTING_KEY)||{"wifiSetting": true, "cellularSetting": true};
- deviceSettings.persist("WIFI_NETWORK.status", networkSettings['wifiSetting']);
- deviceSettings.persist("CELLULAR_NETWORK.status", networkSettings['cellularSetting']);
- document.getElementById("device-settings-WIFI_NETWORK-status").checked = networkSettings['wifiSetting'];
- document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = networkSettings['cellularSetting'];
- $("#config_flight_mode_notice").remove();
- document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = false;
- }
-}
-function cellularNetworkStatusCB(value) {
- document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = value;
-}
+ _console.log(msg);
-function layoutCB(value) {
- if (value === 'portrait') {
- deviceSettings.register("DEVICE_ORIENTATION.status", "PORTRAIT_PRIMARY");
- document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "PORTRAIT_PRIMARY";
- } else {
- deviceSettings.register("DEVICE_ORIENTATION.status", "LANDSCAPE_PRIMARY");
- document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "LANDSCAPE_PRIMARY";
- }
-}
+ // Trigger storageUpdatedEvent
+ event.trigger("StorageUpdatedEvent");
-// goes through current platforms device settings
-// adds nodes to panel and binds respective events
-// talks to DeviceSettings for persistence
-module.exports = {
- initialize: function () {
- var settings, value;
- _contentContainer = document.getElementById(_CONTAINER_ID);
- _network_contentContainer = document.getElementById("networksettings-content-container");
+ },
- settings = platform.current().device;
- utils.forEach(settings, function (settingSection, settingType) {
+ // return value or undefined
+ preferenceForKey: function (key) {
- var currentTableNode, currentTableNode2, settingNameNode, settingName = _retrieveSettingName(settingType);
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid number of parameters", new Exception());
+ utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid paramters", new Exception());
- settingNameNode = utils.createElement("h3", { "innerText": settingName });
- settingNameNode.setAttribute("class", "configure-window-session-title");
+ var prefix = platform.getPersistencePrefix(),
+ value = db.retrieve(key, prefix);
- if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
- _network_contentContainer.appendChild(settingNameNode);
- currentTableNode2 = utils.createElement("table", {
- "class": constants.UI.PANEL_TABLE_CLASS
- });
- currentTableNode2.setAttribute("class", "configure-window-panel-table");
- _network_contentContainer.appendChild(currentTableNode2);
- }
- else {
- _contentContainer.appendChild(settingNameNode);
- currentTableNode = utils.createElement("table", {
- "class": constants.UI.PANEL_TABLE_CLASS
- });
- currentTableNode.setAttribute("class", "configure-window-panel-table");
- _contentContainer.appendChild(currentTableNode);
- }
+ if (!value && value !== "") {
+ value = undefined;
+ }
- utils.forEach(settingSection, function (setting, key) {
- if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
- currentTableNode2.appendChild(_buildDOMNode(setting, settingType, key));
- }
- else {
- currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
- }
- value = _getCurrentSetting(setting, settingType, key);
- if (setting.callback) {
- setting.callback(value);
- }
- });
- });
+ _console.log("retrieving preference " + key + " == " + value);
- if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
- $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'> (Disabled for Flight Mode)</span>");
- document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;
- }
+ return value;
- event.on("DisplayBrightnessChanged", displayBrightnessCB);
- event.on("DisplayBrightnessChangedByPower", displayBrightnessCB);
- event.on("CpuLoadChanged", cpuLoadCB);
- event.on("AvailCapacityChanged", availCapacityCB);
- event.on("CpuLoadChangedByPower", cpuLoadCB);
- event.on("FlightModeChanged", flightModeChangedCB);
- event.on("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
- event.on("CellularNetworkStatusChanged", cellularNetworkStatusCB);
- event.on("LayoutChanged", layoutCB);
- },
- terminate: function () {
- event.deleteEventHandler("DisplayBrightnessChanged", displayBrightnessCB);
- event.deleteEventHandler("DisplayBrightnessChangedByPower", displayBrightnessCB);
- event.deleteEventHandler("CpuLoadChanged", cpuLoadCB);
- event.deleteEventHandler("AvailCapacityChanged", availCapacityCB);
- event.deleteEventHandler("FlightModeChanged", flightModeChangedCB);
- event.deleteEventHandler("CpuLoadChangedByPower", cpuLoadCB);
- event.deleteEventHandler("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
- event.deleteEventHandler("CellularNetworkStatusChanged", cellularNetworkStatusCB);
- event.deleteEventHandler("LayoutChanged", layoutCB);
}
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/devices', function (require, exports, module) {
+define('ripple/platform/wac/1.0/DeviceInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- db = require('ripple/db'),
- resizer = require('ripple/resizer');
+var utils = require('ripple/utils'),
+ deviceSettings = require('ripple/deviceSettings'),
+ platform = require('ripple/platform'),
+ devices = require('ripple/devices'),
+ _self;
-function _getTextZooming(zooming) {
- return zooming + '%';
+_self = {
+ ownerInfo: undefined, // return AddressBookItem
+ phoneColorDepthDefault: undefined,
+ phoneFirmware: undefined,
+ phoneManufacturer: undefined,
+ phoneModel: undefined,
+ phoneOS: undefined,
+ phoneSoftware: undefined,
+ phoneScreenHeightDefault: undefined,
+ phoneScreenWidthDefault: undefined,
+ totalMemory: undefined
+};
+
+function _getDeviceAttribute(attr) {
+ var devicePointer = devices.getCurrentDevice();
+ utils.forEach(attr.split("."), function (dot) {
+ devicePointer = devicePointer[dot];
+ });
+ return devicePointer;
}
-module.exports = {
- panel: {
- domId: "devices-container",
- collapsed: true,
- pane: "left",
- titleName: "Orientation and Zooming",
- display: true
- },
+_self.__defineGetter__("phoneColorDepthDefault", function () {
+ return deviceSettings.retrieveAsInt("DeviceInfo.phoneColorDepthDefault");
+});
- initialize: function () {
- var zooming = document.getElementById(constants.ENCAPSULATOR.ZOOMING);
- function updateZoomingValues() {
- var zoomingText, scaleFactor;
+_self.__defineGetter__("phoneFirmware", function () {
+ return _getDeviceAttribute("firmware");
+});
- zoomingText = _getTextZooming(zooming.value);
- jQuery('#screen-zooming-label').html(zoomingText);
+_self.__defineGetter__("phoneManufacturer", function () {
+ return _getDeviceAttribute("manufacturer");
+});
- // Zooming device skin
- scaleFactor = zooming.value / 100;
- resizer.scaleDevice(scaleFactor);
- }
+_self.__defineGetter__("phoneOS", function () {
+ return _getDeviceAttribute("osName") + " " + _getDeviceAttribute("osVersion");
+});
- function initializeValues() {
- var zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING);
+_self.__defineGetter__("phoneModel", function () {
+ return _getDeviceAttribute("model");
+});
- if (!zoomingValue) {
- zoomingValue = 100;
- }
- jQuery("#" + constants.ENCAPSULATOR.ZOOMING).val(zoomingValue);
- updateZoomingValues();
- }
+_self.__defineGetter__("phoneSoftware", function () {
+ return _getDeviceAttribute("osVersion");
+});
- jQuery("#" + constants.ENCAPSULATOR.ZOOMING).bind("change", function () {
- updateZoomingValues();
- db.save(constants.ENCAPSULATOR.ZOOMING, zooming.value);
- });
+_self.__defineGetter__("phoneScreenHeightDefault", function () {
+ return _getDeviceAttribute("screen.height");
+});
- initializeValues();
- }
-};
+_self.__defineGetter__("phoneScreenWidthDefault", function () {
+ return _getDeviceAttribute("screen.width");
+});
+
+_self.__defineGetter__("totalMemory", function () {
+ return deviceSettings.retrieveAsInt("DeviceInfo.totalMemory");
+});
+module.exports = _self;
});
-define('ripple/ui/plugins/download', function (require, exports, module) {
+define('ripple/platform/wac/1.0/Camera', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var db = require('ripple/db'),
- event = require('ripple/event'),
+var exception = require('ripple/exception'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ constants = require('ripple/constants'),
+ _console = require('ripple/console'),
utils = require('ripple/utils'),
- _data = {
- DB_DOWNLOAD_KEY : "tizen1-db-download",
- resources : []
- },
- _cleanInputs, intervalId,
- _downloads;
-
-function _get() {
- _downloads = [
- {id: "0001", url : "http://tizen.org/small_file.zip", size : "5", speed : "1.0", estimatedTime : "5", MIMEType : "application/zip"},
- {id: "0002", url : "http://tizen.org/big_file.zip", size : "20", speed : "1.0", estimatedTime : "20", MIMEType : "application/zip"},
- {id: "0003", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-hq.png", size : "3937596", speed : "1968798", estimatedTime : "2", MIMEType : "image/png"},
- {id: "0004", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-lq.png", size : "589", speed : "589", estimatedTime : "1", MIMEType : "image/png"}
- ];
- _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
- if (db.retrieveObject(_data.DB_DOWNLOAD_KEY) && db.retrieveObject(_data.DB_DOWNLOAD_KEY).length === 0) {
- _data.resources = _downloads;
- } else {
- _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
- }
- _save();
-}
+ notifications = require('ripple/notifications'),
+ _currentlySet,
+ _img,
+ _buttons,
+ _self,
+ _videoCapture;
-function _save() {
- db.saveObject(_data.DB_DOWNLOAD_KEY, _data.resources);
- event.trigger('downloadResourceChanged');
-}
-function checkURL(url) {
- var rg = new RegExp("((^http)|(^https)|(^ftp)):\/\/()+");
- return rg.test(url);
-}
+function _populateWindow(domObject) {
+ var record = document.createElement("button"),
+ pause = document.createElement("button"),
+ stop = document.createElement("button");
-function loadResources() {
- var installed = document.getElementById("download-resource"), node, i;
- installed.innerHTML = "";
- for (i in _data.resources) {
- node = utils.createElement("option", {
- "innerText": _data.resources[i].url,
- "value": _data.resources[i].id
- });
- installed.appendChild(node);
- }
- _cleanInputs();
-}
+ _img = document.createElement("img");
+ _img.setAttribute("id", "jil-camera-window");
+ //_img.setAttribute("src", document.querySelector("#extension-url").innerHTML + constants.CAMERA.WINDOW_ANIMATION);
+ _img.setAttribute("src", document.documentURI.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION);
+ _img.setAttribute("width", "100%");
+ _currentlySet = domObject;
+ domObject.appendChild(_img);
-function _displayInfo(text) {
- var info = document.getElementById("download-error");
- info.innerHTML = text;
- if (intervalId) {
- clearTimeout(intervalId);
- }
- intervalId = setTimeout(clearDisplayInfo, 5000);
-}
+ _buttons = document.createElement("div");
+ _buttons.setAttribute("id", "jil-camera-window-buttons");
+ _buttons.setAttribute("style", "display: none");
-function clearDisplayInfo() {
- document.getElementById('download-error').innerHTML = '';
-}
+ record.setAttribute("id", "jil-camera-window-buttons-record");
+ record.innerHTML = "Record";
+ pause.setAttribute("id", "jil-camera-window-buttons-pause");
+ pause.innerHTML = "Pause";
+ stop.setAttribute("id", "jil-camera-window-buttons-stop");
+ stop.innerHTML = "Stop";
+ stop.addEventListener("click", _self.stopVideoCapture);
-function _cleanInputs() {
- document.getElementById("download-url").value = "";
- document.getElementById("download-size").value = "";
- document.getElementById("download-speed").value = "";
- document.getElementById("download-time").innerText = "0";
- document.getElementById("download-MIMEType").value = "";
-}
+ _buttons.appendChild(record);
+ _buttons.appendChild(pause);
+ _buttons.appendChild(stop);
-function checkProperties(optionType, url, size, speed, time, MIMEType) {
- var back = true;
- if (url === "" || size === "" || speed === "" || time === "" || MIMEType === "") {
- _displayInfo(optionType + " failed, empty input.");
- back = false;
- }
- if (!checkURL(url)) {
- _displayInfo(optionType + " failed, 'URL' is invalid.");
- back = false;
- }
- if (size <= 0 || speed <= 0) {
- _displayInfo(optionType + " failed, invalid input.");
- back = false;
- }
- return back;
-}
+ domObject.appendChild(_buttons);
-function showUpdateNotification() {
- var url = document.getElementById("download-url").value,
- size = document.getElementById("download-size").value,
- speed = document.getElementById("download-speed").value,
- MIMEType = document.getElementById("download-MIMEType").value,
- isValid = true;
- if (url === "" || size === "" || speed === "" || MIMEType === "" || !checkURL(url) || size <= 0 || speed <= 0) {
- isValid = false;
- }
- if (isValid) {
- _displayInfo("Resource changed, please Add or Update the content.");
- }
}
-function _adding() {
- var id, time, url, size, speed, MIMEType, object, i, isValid;
- url = document.getElementById("download-url").value;
- size = document.getElementById("download-size").value;
- speed = document.getElementById("download-speed").value;
- MIMEType = document.getElementById("download-MIMEType").value;
- time = size / speed;
- id = Math.uuid(null, 16);
-
- isValid = checkProperties("Add", url, size, speed, time, MIMEType);
- if (!isValid)
- return;
- if (_data.resources.length !== 0) {
- for (i in _data.resources) {
- if (url === _data.resources[i].url) {
- _displayInfo("Add failed, the download resource is already available.");
- return;
- }
- }
+function _verifySetWindow(method) {
+ if (!_img) {
+ exception.raise(ExceptionTypes.UNKNOWN, "Camera." +
+ method + " was (most likely) called before using the setWindow method.", new Exception());
}
- document.getElementById("download-time").innerText = Math.round(time * 100) / 100;
- object = {'id': id, 'url': url, 'size': size, 'speed': speed, 'estimatedTime': time, MIMEType: MIMEType};
- _data.resources.push(object);
- _save();
- loadResources();
}
-function _update() {
- var id, time, url, size, speed, MIMEType, i, isExist = false, isValid;
-
- id = document.getElementById("download-resource").value;
- url = document.getElementById("download-url").value;
- size = document.getElementById("download-size").value;
- speed = document.getElementById("download-speed").value;
- MIMEType = document.getElementById("download-MIMEType").value;
- time = size / speed;
+_self = {
+ onCameraCaptured: undefined, //function (fileName) { }
- if (_data.resources.length === 0) {
- _displayInfo("Update failed, there is no download resource now.");
- return;
- }
- isValid = checkProperties("Update", url, size, speed, time, MIMEType);
- if (!isValid)
- return;
- for (i in _data.resources) {
- if (_data.resources[i].url === url) {
- isExist = true;
- _data.resources[i] = {id: id, url : url, size : size, speed : speed, estimatedTime: time, MIMEType: MIMEType};
- loadResources();
- _save();
- break;
- }
- }
- if (!isExist)
- _displayInfo("Update failed, the download resource doesn't exist.");
-}
+ captureImage: function (fileName, lowRes) {
+ utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "captureImage invalid number of parameters", new Exception());
+ utils.validateMultipleArgumentTypes([fileName, lowRes], ['string', 'boolean'], ExceptionTypes.INVALID_PARAMETER, "invalid parameter type", new Exception());
-function _delete() {
- var i, id;
- id = document.getElementById("download-resource").value;
- if (id) {
- for (i in _data.resources) {
- if (_data.resources[i].id === id) {
- _data.resources.splice(i, 1);
- _save();
- loadResources();
- }
+ _verifySetWindow("captureImage");
+ var msg = constants.CAMERA.WARNING_TEXT;
+ msg = msg.replace("{file}", fileName);
+ notifications.openNotification("normal", msg);
+ _console.log("simulated saved image as: " + fileName);
+ if (_self.onCameraCaptured) {
+ _self.onCameraCaptured.apply(_self, [fileName]);
}
- }
-}
-function _showAppDetail(id) {
- var i;
- for (i in _data.resources) {
- if (id === _data.resources[i].id) {
- document.getElementById("download-time").innerText = Math.round(_data.resources[i].estimatedTime * 100) / 100;
- jQuery("#download-url").val(_data.resources[i].url);
- jQuery("#download-size").val(_data.resources[i].size);
- jQuery("#download-speed").val(_data.resources[i].speed);
- jQuery("#download-MIMEType").val(_data.resources[i].MIMEType);
- }
- }
-}
+ return fileName;
+ },
+ setWindow: function (domObject) {
-function _changeAppData() {
- var id = jQuery("#download-resource").val();
- _showAppDetail(id);
-}
-function changeValue() {
- var size = document.getElementById("download-size").value,
- speed = document.getElementById("download-speed").value;
- if (size > 0 && speed > 0) {
- document.getElementById("download-time").innerText = Math.round(size / speed * 100) / 100;
- } else {
- document.getElementById("download-time").innerText = "";
- }
-}
-function checkInputValue(input) {
- if (input.value === "" || input.value <= 0) {
- input.style['border-color'] = 'red';
- _displayInfo("Invalided value.");
- } else {
- if (input.style['border-color']) {
- input.style.removeProperty('border-color');
- }
- changeValue();
- //showUpdateNotification();
- }
-}
-module.exports = {
- panel: {
- domId: "download-container",
- collapsed: true,
- pane: "left",
- titleName: "Download",
- display: true
+ if (_currentlySet) {
+ _currentlySet.removeChild(_img);
+ _currentlySet.removeChild(_buttons);
+ _currentlySet = null;
+ _img = null;
+ _buttons = null;
+ }
+ if (domObject !== null) {
+ _populateWindow(domObject);
+ }
},
- initialize: function () {
- _get();
- loadResources();
+ startVideoCapture: function (fileName, lowRes, maxDurationSeconds, showDefaultControls) {
+ _verifySetWindow("startVideoCapture");
+ utils.validateNumberOfArguments(1, 4, arguments.length, ExceptionTypes.INVALID_PARAMETER, "startVideoCapture invalid number of parameters", new Exception());
+ utils.validateMultipleArgumentTypes(
+ [fileName, lowRes, maxDurationSeconds, showDefaultControls],
+ ['string', 'boolean', 'integer', 'boolean'],
+ ExceptionTypes.INVALID_PARAMETER,
+ "invalid parameter type", new Exception());
+ _console.log("started recording video");
+ var interval = window.setTimeout(function () {
+ _self.stopVideoCapture();
+ }, maxDurationSeconds * 1000);
- document.getElementById("download-add").addEventListener("click", _adding, false);
- document.getElementById("download-update").addEventListener("click", _update, false);
- document.getElementById("download-delete").addEventListener("click", _delete, false);
+ if (showDefaultControls) {
+ _buttons.removeAttribute("style");
+ }
- jQuery("#download-resource").bind("focus change", function () {
- var url = document.getElementById("download-url"),
- size = document.getElementById("download-size"),
- speed = document.getElementById("download-speed"),
- MIMEType = document.getElementById("download-MIMEType");
- if (url.style['border-color']) {
- url.style.removeProperty('border-color');
- }
- if (MIMEType.style['border-color']) {
- MIMEType.style.removeProperty('border-color');
- }
- if (size.value > 0 && size.style['border-color']) {
- size.style.removeProperty('border-color');
- }
- if (speed.value > 0 && speed.style['border-color']) {
- speed.style.removeProperty('border-color');
- }
- _changeAppData();
- });
- jQuery("#download-speed").bind("blur", function () {
- changeValue();
- });
- jQuery("#download-size").bind("blur", function () {
- changeValue();
- });
- jQuery("#download-speed").bind("change", function () {
- checkInputValue(this);
- });
- jQuery("#download-size").bind("change", function () {
- checkInputValue(this);
- });
- jQuery("#download-speed").bind("change", function () {
- checkInputValue(this);
- });
- jQuery("#download-url").bind("change", function () {
- if (this.style['border-color']) {
- this.style.removeProperty('border-color');
+ _videoCapture = {
+ fileName: fileName,
+ stop: function () {
+ window.clearInterval(interval);
+ var msg = constants.CAMERA.WARNING_TEXT;
+ msg = msg.replace("{file}", fileName);
+ notifications.openNotification("normal", msg);
+ if (_self.onCameraCaptured) {
+ _self.onCameraCaptured.apply(_self, [fileName]);
+ }
}
- if (this.value && checkURL(this.value)) {
- //showUpdateNotification();
- } else {
- _displayInfo("Invalided URL.");
- this.style['border-color'] = 'red';
+ };
+
+ return fileName;
+ },
+ stopVideoCapture: function () {
+ utils.validateNumberOfArguments(0, 0, arguments.length, ExceptionTypes.INVALID_PARAMETER, "stopVideoCapture invalid number of parameters", new Exception());
+ if (_videoCapture) {
+ _console.log("simulated saving a video as: " + _videoCapture.fileName);
+ if (_buttons) {
+ _buttons.setAttribute("style", "display: none");
}
- });
+ _videoCapture.stop();
+ _videoCapture = null;
+ }
}
+
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/eulaCheck', function (require, exports, module) {
+define('ripple/platform/wac/1.0/RadioSignalSourceTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- bus = require('ripple/bus');
-
-function _initializeEulaCheck() {
- var width = jQuery(document).width(),
- p = (width / 2) - 277;
-
-
- $(".eula-window").show();
- $(".eula-dialog").show().css({left: p + "px"});
+var _self,
+ utils = require('ripple/utils');
- $("#eula-accept").click(function () {
- bus.send("acceptEula", null, function (result) {
- $(".eula-window").hide();
- $(".eula-dialog").hide();
- });
- });
+_self = {
+ "CDMA": undefined,
+ "GSM": undefined,
+ "LTE": undefined,
+ "TDSCDMA": undefined,
+ "WCDMA": undefined
+};
- $("#eula-decline").click(function () {
- bus.send("disable", null, null);
+utils.forEach(_self, function (value, property) {
+ _self.__defineGetter__(property, function () {
+ return property;
});
-}
-
-module.exports = {
- initialize: function () {
- //HACK: there has to be a better way!!!
- if ($("#extension-url").val().match(/geelfhphabnejjhdalkjhgipohgpdnoc/)) {
- // do nothing, extension was installed from the Chrome Store
- return;
- }
+});
- bus.send("checkEula", null, function (response) {
- console.log("eula response: ", response);
- if (response === false) {
- _initializeEulaCheck();
- }
- });
- }
-};
+module.exports = _self;
});
-define('ripple/ui/plugins/exec-dialog', function (require, exports, module) {
+define('ripple/platform/wac/1.0/File', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-function exec(func) {
- return function () {
- var val = $("#exec-response").val();
-
- //TODO: handle multiple args
- func.apply(null, val ? [JSON.parse(val)] : []);
- $("#exec-dialog").dialog("close");
- };
-}
-
-module.exports = {
- initialize: function () {
- $("#exec-dialog").dialog({
- autoOpen: false,
- modal: true,
- title: "I Haz Cheeseburger?!?!",
- width: 500,
- position: 'center'
- }).hide();
-
- $("#exec-success").button();
- $("#exec-fail").button();
- },
-
- show: function (service, action, success, fail) {
- console.log(service);
- console.log(action);
- $("#exec-service").text(service);
- $("#exec-action").text(action);
- $("#exec-dialog").dialog("open");
- $("#exec-success").unbind().bind('click', exec(success));
- $("#exec-fail").unbind().bind('click', exec(fail));
- }
+module.expots = function () {
+ this.createDate = undefined;
+ this.fileName = undefined;
+ this.filePath = undefined;
+ this.fileSize = undefined;
+ this.isDirectory = undefined;
+ this.lastModifyDate = undefined;
};
});
-define('ripple/ui/plugins/fileSystem', function (require, exports, module) {
+define('ripple/platform/wac/1.0/AddressBookItem', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ db = require('ripple/db'),
constants = require('ripple/constants'),
- fileSystem = require('ripple/fileSystem'),
- fileSystemPaths = fileSystem.getFileSystemPaths();
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
-module.exports = {
- panel: {
- domId: "filsystem-container",
- collapsed: true,
- pane: "left"
- },
- initialize: function () {
- var fileSystemPaths = fileSystem.getFileSystemPaths();
+function _validateArgs(min, max, len) {
+ utils.validateNumberOfArguments(min, max, len,
+ ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
+}
- utils.forEach(fileSystemPaths, function (value, key) {
- utils.bindAutoSaveEvent(jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val(value.uri), function () {
- value.uri = jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val();
- fileSystem.updateFileSystemPaths(fileSystemPaths);
- });
- });
+function _validateType(arg, argType) {
+ utils.validateArgumentType(arg, argType,
+ ExceptionTypes.INVALID_PARAMETER, "argument of wrong type provided",
+ new Exception());
+}
+
+module.exports = function () {
+ function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}
+
+ this.addressBookItemId = undefined;
+ this.fullName = undefined;
+ this.mobilePhone = undefined;
+ this.homePhone = undefined;
+ this.workPhone = undefined;
+ this.eMail = undefined;
+ this.company = undefined;
+ this.title = undefined;
+ this.address = undefined;
+
+ this.setAttributeValue = function (attribute, value) {
+ _validateArgs(2, 2, arguments.length);
+ _validateType(attribute, "string");
+ this[attribute] = value;
+ };
+ this.setAddressGroupNames = function (groups) {
+ _throwUnsupportedException("PIM.AddressBookItem.setAddressGroupNames");
+ };
+ this.getAttributeValue = function (attribute) {
+ _validateArgs(1, 1, arguments.length);
+ _validateType(attribute, "string");
+ return this[attribute];
+ };
+ this.getAddressGroupNames = function () {
+ _throwUnsupportedException("PIM.AddressBookItem.getAddressGroupNames");
+ };
+ this.getAvailableAttributes = function () {
+ return utils.reduce(this, function (attributes, value, key) {
+ if (typeof(value) !== 'function') {
+ attributes.push(key);
+ }
+ return attributes;
+ }, []).sort();
+ };
+ this.update = function () {
+ var items = db.retrieveObject(constants.PIM.ADDRESS_LIST_KEY),
+ that = this,
+ itemIndex = items.reduce(function (current, value, i) {
+ return value.addressBookItemId === that.addressBookItemId ?
+ i : current;
+ }, -1);
+
+ if (itemIndex >= 0) {
+ items[itemIndex] = this;
+ db.saveObject(constants.PIM.ADDRESS_LIST_KEY, items);
+ }
+ else {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "Address Book Item not found: " + (this.addressBookItemId || ""), new Exception());
+ }
+
+ };
};
});
-define('ripple/ui/plugins/firstRunCheck', function (require, exports, module) {
+define('ripple/platform/wac/1.0/DeviceStateInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* limitations under the License.
*/
var utils = require('ripple/utils'),
- _platform = require('ripple/platform'),
- db = require('ripple/db');
+ exception = require('ripple/exception'),
+ _console = require('ripple/console'),
+ geo = require('ripple/geo'),
+ event = require('ripple/event'),
+ deviceSettings = require('ripple/deviceSettings'),
+ PositionInfo = require('ripple/platform/wac/1.0/PositionInfo'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ _self;
-function _handleFirstRunResponse(platform, version) {
- var device = jQuery("#device-select").val(),
- api = {
- name: platform.id,
- version: version
- };
+event.on("ScreenChangeDimensions", function (width, height) {
+ try {
+ if (typeof _self.onScreenChangeDimensions === 'function') {
+ _self.onScreenChangeDimensions(width, height);
+ }
+ _console.log("called DeviceStateInfo.onScreenChangeDimensions callback function with width = " + width + " and height = " + height);
+ } catch (e) {
+ exception.handle(e, false);
+ }
+});
+_self = {
+ availableMemory: undefined,
+ language: undefined,
+ keypadLightOn: undefined,
+ backLightOn: undefined,
+ processorUtilizationPercent: undefined,
+ audioPath: undefined,
- _platform.changeEnvironment(api, device, function () {
- window.tinyHipposReload = true;
- location.reload();
- });
-}
+ onPositionRetrieved: undefined,
-function _addPlatformButton(platform, version) {
- var section = jQuery(".platform-select-buttons"),
- buttonID = "platform-" + platform.id,
- button = utils.createElement("button", {
- "id": buttonID,
- "class": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
- });
+ requestPositionInfo: function (method) {
+ utils.validateNumberOfArguments(1, 1, arguments.length,
+ ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid number of parameters", new Exception());
+ utils.validateArgumentType(method, "string",
+ ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid parameter", new Exception());
- button.appendChild(utils.createElement("span", {
- "class": "ui-button-text",
- "innertext" : platform.name
- }));
+ if (!(method.match(/gps|agps|cellid/))) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER,
+ "Invalid method, expected (gps, agps or cellid)", Exception);
+ }
- section.append(button);
+ if (typeof _self.onPositionRetrieved === "function") {
+ var delay = geo.delay * 1000,
+ timeout = geo.timeout;
+ setTimeout(function () {
+ var pos = PositionInfo,
+ errorObj = {};
- document.getElementById(buttonID).addEventListener("click", function () {
- _handleFirstRunResponse(platform, version);
- });
-}
+ if (timeout) {
+ //create
+ utils.forEach(pos, function (val, key) {
+ errorObj[key] = undefined;
+ });
+ pos = errorObj;
+ }
+ _self.onPositionRetrieved(pos, method);
+ }, delay);
+ }
+ },
-function _initializeFirstRunCheck() {
- var savedPlatform = db.retrieveObject("api-key"),
- firstRunOverlayNode, firstRunOptionsNode,
- width, p;
+ onScreenChangeDimensions: undefined,
- if (!savedPlatform) {
- width = jQuery(document).width();
- p = (width / 2) - 277;
+ onFlipEvent: undefined
+};
- firstRunOverlayNode = jQuery(".first-run-window").css({display: 'block'});
- firstRunOptionsNode = jQuery(".platform-select-dialog").css({display: 'block', left: p + "px"});
+_self.__defineGetter__("availableMemory", function () {
+ return deviceSettings.retrieveAsInt("DeviceStateInfo.availableMemory");
+});
- utils.forEach(_platform.getList(), function (platform) {
- utils.forEach(platform, function (details, version) {
- _addPlatformButton(details, version);
- });
- });
- }
-}
+_self.__defineGetter__("language", function () {
+ return deviceSettings.retrieve("DeviceStateInfo.language");
+});
-module.exports = {
- initialize: function () {
- if (utils.map(_platform.getList(), function (platform) {
- return platform;
- }).length > 1) {
- _initializeFirstRunCheck();
- }
- }
-};
+_self.__defineGetter__("keypadLightOn", function () {
+ return deviceSettings.retrieveAsBoolean("DeviceStateInfo.keypadLightOn");
+});
+_self.__defineGetter__("backLightOn", function () {
+ return deviceSettings.retrieveAsBoolean("DeviceStateInfo.backLightOn");
});
-define('ripple/ui/plugins/geoDB', function (require, exports, module) {
+
+_self.__defineGetter__("audioPath", function () {
+ return deviceSettings.retrieve("DeviceStateInfo.audioPath");
+});
+
+_self.__defineGetter__("processorUtilizationPercent", function () {
+ return deviceSettings.retrieve("DeviceStateInfo.processorUtilizationPercent");
+});
+
+module.exports = _self;
+
+
+});
+define('ripple/platform/wac/1.0/Attachment', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
- _GEO_OBJECTS = "tizen1.0-geocode-objects",
- _geoList, _currentGeo, _saveID, _showGeoDetail;
-
-function _getGeo() {
- var geoList = [],
- data = db.retrieveObject(_GEO_OBJECTS);
-
- utils.forEach(data, function (geo) {
- geoList.push(geo);
- });
- return geoList;
-}
-
-function _saveGeo() {
- db.saveObject(_GEO_OBJECTS, _geoList);
-}
-
-function GeoEntry(addr, coord) {
- var _self;
- _self = {
- address : addr || null,
- coordinate : coord || null
- };
- return _self;
-}
-
-function _updateGeoDBSelect() {
- var geoDBSelect = document.getElementById("geo-select"),
- geoNode, i;
-
- geoDBSelect.innerHTML = "";
- for (i = 0; i < _geoList.length; i++) {
- geoNode = utils.createElement("option", {
- "innerText": "(" + _geoList[i].coordinate.latitude + ", " + _geoList[i].coordinate.longitude + ")",
- "value": i
- });
- if (_currentGeo === Number(geoNode.value)) {
- geoNode.selected = true;
- _showGeoDetail(_geoList[_currentGeo].coordinate, _geoList[_currentGeo].address);
- }
- geoDBSelect.appendChild(geoNode);
- }
-}
-
-function _showGeoDetail(coord, addr) {
- jQuery("#geoDB-latitude").val(coord.latitude);
- jQuery("#geoDB-longitude").val(coord.longitude);
- jQuery("#geoDB-altitude").val(coord.altitude);
- jQuery("#geoDB-accuracy").val(coord.accuracy);
- jQuery("#geoDB-altitudeAccuracy").val(coord.altitudeAccuracy);
- jQuery("#geoDB-heading").val(coord.heading);
- jQuery("#geoDB-speed").val(coord.speed);
-
- jQuery("#geoDB-country").val(addr.country);
- jQuery("#geoDB-region").val(addr.region);
- jQuery("#geoDB-county").val(addr.county);
- jQuery("#geoDB-city").val(addr.city);
- jQuery("#geoDB-street").val(addr.street);
- jQuery("#geoDB-streetNumber").val(addr.streetNumber);
- jQuery("#geoDB-premises").val(addr.premises);
- jQuery("#geoDB-additionalInformation").val(addr.additionalInformation);
- jQuery("#geoDB-postalCode").val(addr.postalCode);
-}
-
-function _changeGeoData() {
- var id = Number(jQuery("#geo-select").val());
- _currentGeo = id;
- _showGeoDetail(_geoList[id].coordinate, _geoList[id].address);
-}
-
-function _triggerReadOnly(on) {
- if (on === true) {
- jQuery("#geoDB-table input").attr("readonly", "readonly");
- jQuery("#geoDB-add").show();
- jQuery("#geoDB-modify").show();
- jQuery("#geoDB-delete").show();
- jQuery("#geo-select").removeAttr("disabled");
- jQuery("#geoDB-save").hide();
- jQuery("#geoDB-cancel").hide();
- } else {
- jQuery("#geoDB-table input").removeAttr("readonly");
- jQuery("#geoDB-add").hide();
- jQuery("#geoDB-modify").hide();
- jQuery("#geoDB-delete").hide();
- jQuery("#geo-select").attr("disabled", "disabled");
- jQuery("#geoDB-save").show();
- jQuery("#geoDB-cancel").show();
- }
-}
-
-function _addGeoData() {
- _triggerReadOnly(false);
- jQuery("#geoDB-table input").val("");
- _saveID = _geoList.length;
- jQuery("#geo-select").val("");
-}
-function _modifyGeoData() {
- _triggerReadOnly(false);
- _saveID = _currentGeo;
-}
-function _deleteGeoData() {
- _geoList.splice(_currentGeo, 1);
- _saveGeo();
- _currentGeo = 0;
- _updateGeoDBSelect();
-}
-function _saveGeoData() {
- var entry;
- entry = new GeoEntry(new lbs.StructuredAddress({
- country: jQuery("#geoDB-country").val(),
- region: jQuery("#geoDB-region").val(),
- county: jQuery("#geoDB-county").val(),
- city: jQuery("#geoDB-city").val(),
- street: jQuery("#geoDB-street").val(),
- streetNumber: jQuery("#geoDB-streetNumber").val(),
- premises: jQuery("#geoDB-premises").val(),
- additionalInformation: jQuery("#geoDB-additionalInformation").val(),
- postalCode: jQuery("#geoDB-postalCode").val()
- }),
- new lbs.GeoCoordinates({
- latitude: parseFloat(jQuery("#geoDB-latitude").val()),
- longitude: parseFloat(jQuery("#geoDB-longitude").val()),
- altitude: parseFloat(jQuery("#geoDB-altitude").val()),
- accuracy: parseFloat(jQuery("#geoDB-accuracy").val()),
- altitudeAccuracy: parseFloat(jQuery("#geoDB-altitudeAccuracy").val()),
- heading: parseFloat(jQuery("#geoDB-heading").val()),
- speed: parseFloat(jQuery("#geoDB-speed").val())
- }));
- if (_saveID === _geoList.length)
- _geoList.push(entry);
- else
- _geoList[_saveID] = entry;
-
- _saveGeo();
- _currentGeo = _saveID;
- _updateGeoDBSelect();
- _triggerReadOnly(true);
-}
-
-function _cancelGeoData() {
- _triggerReadOnly(true);
- _updateGeoDBSelect();
-}
-
-module.exports = {
- panel: {
- domId: "geoDB-container",
- collapsed: true,
- pane: "right"
- },
-
- initialize: function () {
- _currentGeo = 0; // set _geoList[0] as default value
- _geoList = _getGeo();
- _updateGeoDBSelect();
- _triggerReadOnly(true);
-
- jQuery("#geo-select").bind("change", function () {
- _changeGeoData();
- });
- jQuery("#geoDB-add").bind("click", function () {
- _addGeoData();
- });
- jQuery("#geoDB-modify").bind("click", function () {
- _modifyGeoData();
- });
- jQuery("#geoDB-delete").bind("click", function () {
- _deleteGeoData();
- });
- jQuery("#geoDB-save").bind("click", function () {
- _saveGeoData();
- });
- jQuery("#geoDB-cancel").bind("click", function () {
- _cancelGeoData();
- });
- }
+module.exports = function () {
+ this.fileName = "";
+ this.MIMEType = "";
+ this.size = 0;
};
});
-define('ripple/ui/plugins/geoView', function (require, exports, module) {
+define('ripple/platform/wac/1.0/Multimedia', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- geo = require('ripple/geo'),
- db = require('ripple/db'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- platform = require('ripple/platform'),
- markers,
- _gpsMapZoomLevel,
- _routePoints = [],
- _routes = [],
- _routeMarkers,
- _lineLayer,
- _drawLineTimeout,
- _playFrequency = 0,
- _originalNavigator = window.navigator,
- _locationSharing = false;
- _playState = {'play': false, 'replay': false};
-
-function _initTimeZone() {
- var allTZ, dbTZ, node = jQuery("#time-locale-select"),
- timezone = require('ripple/platform/tizen/2.0/timezone_info'),
- alarms, time;
-
- function triggerAlarm() {
- time = new Date();
- alarms = db.retrieveObject("tizen1.0-db-alarms");
- if (alarms !== null) {
- utils.forEach(alarms, function (obj) {
- if (obj.id !== undefined) {
- event.trigger("CheckAlarm", [obj.id]);
- }
- });
- }
- }
- window.setInterval(triggerAlarm, 1000);
-
- allTZ = timezone.getAllTimezone();
- utils.forEach(allTZ, function (tz) {
- node.append(utils.createElement("option", {
- "value": tz,
- "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
- }));
- });
- dbTZ = db.retrieve("tizen-timezone");
- if (timezone.isValidTimezone(dbTZ)) {
- node.val(dbTZ);
- } else {
- db.save("tizen-timezone", node.val());
- }
- node.bind("change", function () {
- db.save("tizen-timezone", node.val());
- });
-}
-
-function _updateGpsMap() {
- var positionInfo = geo.getPositionInfo(),
- mapContainer = document.getElementById(constants.GEO.OPTIONS.MAP_CONTAINER);
-
- if (mapContainer && jQuery(mapContainer).is(':visible')) {
- geo.map.setCenter(new OpenLayers.LonLat(positionInfo.longitude, positionInfo.latitude).transform(
- new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel, true);
- }
-
- if (_lineLayer) {
- geo.map.removeLayer(_lineLayer);
- geo.map.addLayer(_lineLayer);
- }
-}
-
-function _updateGpsMapZoom(goUp) {
- if (goUp && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) {
- _gpsMapZoomLevel++;
- }
- else if (!goUp && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN) {
- _gpsMapZoomLevel--;
- }
-
- _updateGpsMap();
- db.save(constants.GEO.MAP_ZOOM_KEY, _gpsMapZoomLevel);
-}
-
-function _getTextHeading(heading) {
- if (heading >= 337.5 || (heading >= 0 && heading <= 22.5)) {
- return 'N';
- }
-
- if (heading >= 22.5 && heading <= 67.5) {
- return 'NE';
- }
-
- if (heading >= 67.5 && heading <= 112.5) {
- return 'E';
- }
- if (heading >= 112.5 && heading <= 157.5) {
- return 'SE';
- }
-
- if (heading >= 157.5 && heading <= 202.5) {
- return 'S';
- }
-
- if (heading >= 202.5 && heading <= 247.5) {
- return 'SW';
- }
-
- if (heading >= 247.5 && heading <= 292.5) {
- return 'W';
- }
-
- if (heading >= 292.5 && heading <= 337.5) {
- return 'NW';
- }
-}
-
-function _updateRoutes() {
- var i, j, k, lon_step, lat_step;
- _routes = [];
-
- for (i = 0; i < _routePoints.length - 1; i++) {
- lon_step = (_routePoints[i + 1].lonlat.lon - _routePoints[i].lonlat.lon) / 50;
- lat_step = (_routePoints[i + 1].lonlat.lat - _routePoints[i].lonlat.lat) / 50;
-
- _routes.push(new OpenLayers.LonLat(_routePoints[i].lonlat.lon, _routePoints[i].lonlat.lat));
- for (j = 1, k = _routes.length; j < 50; j++, k++) {
- _routes.push(new OpenLayers.LonLat(_routes[k - 1].lon + lon_step, _routes[k - 1].lat + lat_step));
- }
- }
- _routes.push(new OpenLayers.LonLat(
- _routePoints[_routePoints.length - 1].lonlat.lon,
- _routePoints[_routePoints.length - 1].lonlat.lat)
- );
-}
-
-function _drawLine(array) {
- var GEO_OPTIONS = constants.GEO.OPTIONS,
- latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
- longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
- lonlat = new OpenLayers.LonLat(array[0].lon, array[0].lat).transform(
- new OpenLayers.Projection("EPSG:900913"),
- new OpenLayers.Projection("EPSG:4326")
- ),
- points = new Array(
- new OpenLayers.Geometry.Point(array[0].lon, array[0].lat),
- new OpenLayers.Geometry.Point(array[1].lon, array[1].lat)
- ),
- line = new OpenLayers.Geometry.LineString(points),
- style = {
- strokeColor: '#0000ff',
- strokeOpacity: 1,
- strokeWidth: 3
- },
- lineFeature = new OpenLayers.Feature.Vector(line, null, style);
-
- if (!_lineLayer) {
- _lineLayer = new OpenLayers.Layer.Vector("Line Layer");
- geo.map.addLayer(_lineLayer);
- }
-
- _lineLayer.addFeatures([lineFeature]);
- longitude.value = lonlat.lon;
- latitude.value = lonlat.lat;
-
- if (_playFrequency % 10 === 0) {
- geo.map.panTo(new OpenLayers.LonLat(array[0].lon, array[0].lat), _gpsMapZoomLevel);
- }
- _playFrequency++;
-}
-
-function clearRoute() {
- if (!_playState.play) {
- _routePoints.forEach(function (item) {
- _routeMarkers.removeMarker(item.marker);
- });
- _routePoints = [];
- _routes = [];
- _lineLayer.removeFeatures(_lineLayer.features);
- }
-}
-
-function setRoute() {
- var clickHandler = new OpenLayers.Handler.Click(
- this,
- {
- click: function (e) {
- if (geo.map.calculateBounds(null, 1) === null) {
- geo.map.zoomTo(geo.map.zoom);
- }
- var location = geo.map.getLonLatFromViewPortPx(e.xy),
- size = new OpenLayers.Size(21, 25),
- offset = new OpenLayers.Pixel(-(size.w / 2), -size.h),
- icon = new OpenLayers.Icon('images/map_marker.png', size, offset),
- marker = new OpenLayers.Marker(new OpenLayers.LonLat(location.lon, location.lat), icon);
+var event = require('ripple/event'),
+ VideoPlayer = require('ripple/platform/wac/1.0/VideoPlayer'),
+ AudioPlayer = require('ripple/platform/wac/1.0/AudioPlayer'),
+ constants = require('ripple/constants'),
+ _volume = 5,
+ _audioState,
+ _videoState,
+ _self;
- geo.map.addLayer(_routeMarkers);
- _routeMarkers.addMarker(marker);
- _routePoints.push({
- lonlat : location,
- marker : marker
- });
- }
- },
- {double: true}
- );
- clickHandler.dblclick = function () {
- _updateRoutes();
- this.deactivate();
- };
+event.on("MultimediaVolumeChanged", function updateVolume(volume) {
+ _volume = volume;
+});
- if (!_playState.play) {
- clickHandler.setMap(geo.map);
- clickHandler.activate();
- }
-}
+event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
+ _audioState = state;
+});
-function playRoute() {
- var speed = document.getElementById("play-route-speed"),
- getPlaySpeed = function () {
- return 20 / speed.value * 1000 / 50;
- },
- draw = function () {
- if (_routes.length <= 1) {
- window.clearTimeout(_drawLineTimeout);
- geo.map.panTo(new OpenLayers.LonLat(
- _routePoints[_routePoints.length - 1].lonlat.lon,
- _routePoints[_routePoints.length - 1].lonlat.lat),
- _gpsMapZoomLevel);
- _playState.play = false;
- _playState.replay = true;
- document.getElementById('play-btn-icon').src = "images/play.png";
- } else {
- _drawLine(_routes);
- _routes.splice(0, 1);
- _drawLineTimeout = window.setTimeout(draw, getPlaySpeed());
- }
- };
+event.on("MultimediaVideoStateChanged", function updateVideoState(state) {
+ _videoState = state;
+});
- if (!_playState.play && _routes.length !== 0) {
- if (_lineLayer && _playState.replay) {
- _lineLayer.removeFeatures(_lineLayer.features);
- _updateRoutes();
- }
- draw();
- _playState.play = true;
- document.getElementById('play-btn-icon').src = "images/pause.png";
- } else if (_playState.play) {
- window.clearTimeout(_drawLineTimeout);
- _playState.play = false;
- _playState.replay = false;
- document.getElementById('play-btn-icon').src = "images/play.png";
- }
-}
+_self = {
-function skipTo(position) {
- if (_routes.length !== 0) {
- var index = (position === 'start' ? 0 : _routePoints.length - 1);
- window.clearTimeout(_drawLineTimeout);
- _lineLayer.removeFeatures(_lineLayer.features);
- geo.map.panTo(new OpenLayers.LonLat(_routePoints[index].lonlat.lon, _routePoints[index].lonlat.lat), _gpsMapZoomLevel);
- _routes = [];
- _updateRoutes();
- _playFrequency = 0;
- _playState.play = false;
- _playState.replay = false;
- document.getElementById('play-btn-icon').src = "images/play.png";
- }
-}
+ isAudioPlaying: undefined,
+ isVideoPlaying: undefined,
-module.exports = {
- panel: {
- domId: "gps-container",
- collapsed: true,
- pane: "left",
- titleName: "Geolocation",
- display: true
+ getVolume: function () {
+ return _volume;
},
- initialize: function () {
- var GEO_OPTIONS = constants.GEO.OPTIONS,
- positionInfo = geo.getPositionInfo(),
- positionEvent = "PositionInfoUpdatedEvent",
- latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
- longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
- altitude = document.getElementById(GEO_OPTIONS.ALTITUDE),
- accuracy = document.getElementById(GEO_OPTIONS.ACCURACY),
- altitudeAccuracy = document.getElementById(GEO_OPTIONS.ALTITUDE_ACCURACY),
- heading = document.getElementById(GEO_OPTIONS.HEADING),
- speed = document.getElementById(GEO_OPTIONS.SPEED),
- cellID = document.getElementById(GEO_OPTIONS.CELL_ID),
- delay = document.getElementById(GEO_OPTIONS.DELAY),
- delayLabel = document.getElementById(GEO_OPTIONS.DELAY_LABEL),
- headingLabel = document.getElementById(GEO_OPTIONS.HEADING_LABEL),
- headingMapLabel = document.getElementById(GEO_OPTIONS.HEADING_MAP_LABEL),
- timeout = document.getElementById(GEO_OPTIONS.TIMEOUT),
- gpxMultiplier = document.getElementById(GEO_OPTIONS.GPXMULTIPLIER),
- gpxReplayStatus = document.getElementById(GEO_OPTIONS.GPXREPLAYSTATUS),
- gpxGo = $(document.getElementById(GEO_OPTIONS.GPXGO)).find("span")[0],
- mapContainer = document.getElementById(GEO_OPTIONS.MAP_CONTAINER),
- map = null,
- track = [],
- _replayingGpxFile = false,
- _haltGpxReplay = false;
-
- function updateGeo() {
- if (parseFloat(latitude.value) > 90)
- latitude.value = 90;
- else if (parseFloat(latitude.value) < -90)
- latitude.value = -90;
-
- if (parseFloat(longitude.value) > 180)
- longitude.value = 180;
- else if (parseFloat(longitude.value) < -180)
- longitude.value = -180;
-
- geo.updatePositionInfo({
- latitude: parseFloat(latitude.value),
- longitude: parseFloat(longitude.value),
- altitude: parseInt(altitude.value, 10),
- accuracy: parseInt(accuracy.value, 10),
- altitudeAccuracy: parseInt(altitudeAccuracy.value, 10),
- heading: heading.value ? parseFloat(heading.value) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
- speed: speed.value ? parseInt(speed.value, 10) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
- cellID: cellID.value,
- timeStamp: new Date()
- },
- delay.value,
- timeout.checked);
- }
-
- function updateHeadingValues() {
- var headingDeg = parseFloat(heading.value),
- headingText = _getTextHeading(parseFloat(heading.value));
-
- headingLabel.innerText = headingText;
- headingMapLabel.innerHTML = headingText + "</br>" + headingDeg + "°";
- }
-
- function updateValsFromMap() {
- var center = geo.map.getCenter().transform(
- new OpenLayers.Projection("EPSG:900913"),
- new OpenLayers.Projection("EPSG:4326"));
- longitude.value = center.lon;
- latitude.value = center.lat;
- updateGeo();
- }
-
- function initializeValues() {
- latitude.value = positionInfo.latitude;
- longitude.value = positionInfo.longitude;
- altitude.value = positionInfo.altitude;
- accuracy.value = positionInfo.accuracy;
- altitudeAccuracy.value = positionInfo.altitudeAccuracy;
- cellID.value = positionInfo.cellID;
- delay.value = document.getElementById(GEO_OPTIONS.DELAY_LABEL).innerText = geo.delay || 0;
- if (geo.timeout) {
- timeout.checked = true;
- }
- updateHeadingValues();
- }
- function initMap() {
- var marker, clickHandler;
- // override image location so we don't have to include image assets
- OpenLayers.ImgPath = 'http://openlayers.org/api/img/';
+ stopAll: function () {
+ VideoPlayer.stop();
+ AudioPlayer.stop();
+ }
+};
- // init map
- geo.map = new OpenLayers.Map(mapContainer, { controls: [] });
+_self.__defineGetter__("isAudioPlaying", function () {
+ return _audioState === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
+});
- // add controls and OSM map layer
- geo.map.addLayer(new OpenLayers.Layer.OSM());
- geo.map.addControl(new OpenLayers.Control.Navigation());
+_self.__defineGetter__("isVideoPlaying", function () {
+ return _videoState === "playing";
+});
- // override behaviour of click to pan and double click to zoom in
- clickHandler = new OpenLayers.Handler.Click(
- this,
- {
- click: function (e) {
- if (geo.map.calculateBounds(null, 1) === null) {
- geo.map.zoomTo(geo.map.zoom);
- }
- var location = geo.map.getLonLatFromViewPortPx(e.xy);
- geo.map.panTo(new OpenLayers.LonLat(location.lon, location.lat), _gpsMapZoomLevel);
- },
+module.exports = _self;
- dblclick: function () {
- _updateGpsMapZoom(true);
- }
- },
- {double: true}
- );
+});
+define('ripple/platform/wac/1.0/CalendarItem', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ db = require('ripple/db'),
+ exception = require('ripple/exception'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
- // add click handler to map
- clickHandler.setMap(geo.map);
- clickHandler.activate();
+module.exports = function () {
+ this.calendarItemId = undefined;
+ this.alarmDate = undefined;
+ this.eventStartTime = undefined;
+ this.eventEndTime = undefined;
+ this.eventName = undefined;
+ this.eventNotes = undefined;
+ this.alarmed = undefined;
- // update long and lat when map is panned
- geo.map.events.register("moveend", map, function () {
- updateValsFromMap();
- });
- geo.map.events.register("zoomend", map, function (obj) {
- if ((obj.object.zoom > _gpsMapZoomLevel && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) ||
- (obj.object.zoom < _gpsMapZoomLevel && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN)) {
- _gpsMapZoomLevel = obj.object.zoom;
- }
- });
+ this.update = function () {
+ var events = db.retrieveObject(constants.PIM.CALENDAR_LIST_KEY) || [],
+ that = this,
+ eventIndex = events.reduce(function (match, value, i) {
+ return value.calendarItemId === that.calendarItemId ?
+ i : match;
+ }, -1);
- markers = new OpenLayers.Layer.Markers("markers");
- _routeMarkers = new OpenLayers.Layer.Markers("markers");
- geo.map.addLayer(markers);
- event.on("ApplicationState", function (obj) {
- if (obj && obj[0].id === 'gps-container' && obj.hasClass('ui-box-open')) {
- _updateGpsMap();
+ if (eventIndex >= 0) {
+ events[eventIndex] = this;
+ db.saveObject(constants.PIM.CALENDAR_LIST_KEY, events);
+ }
+ else {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "Calendar Item not found: " + (this.calendarItemId || ""), new Exception());
+ }
+ };
+};
- // Update the position if user accept location sharing
- if (_locationSharing === false) {
- _originalNavigator.geolocation.getCurrentPosition(function(geoPosition) {
- geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
- new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
- _locationSharing = true;
- });
- }
+});
+define('ripple/platform/wac/1.0/Config', function (require, exports, module) {
+/*
+ * Copyright 2011 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 utils = require('ripple/utils'),
+ notifications = require('ripple/notifications'),
+ constants = require('ripple/constants'),
+ deviceSettings = require('ripple/deviceSettings'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ _self = {
+ ringtoneVolume: undefined,
+ msgRingtoneVolume: undefined,
+ vibrationSetting: undefined,
- // Simulator is loaded with geo panel folded, now it's the first time it's unfolded
- if (!marker) {
- // Only when the geo panel is unfolded, getCenter() will go well
- marker = new OpenLayers.Marker(geo.map.getCenter(),
- new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
- markers.addMarker(marker);
+ setDefaultRingtone: function (ringtoneUrl) {
+ utils.validateArgumentType(ringtoneUrl, "string", ExceptionTypes.INVALID_PARAMETER, "ringtoneUrl paramter is not a string", new Exception());
+ notifications.openNotification("normal", "Setting default ringtone to: " + ringtoneUrl);
+ },
- navigator.geolocation.getCurrentPosition(function (geoPosition) {
- geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
- new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
- });
- }
- }
- });
- _updateGpsMap();
+ setAsWallpaper: function (wallpaperUrl) {
+ utils.validateArgumentType(wallpaperUrl, "string", ExceptionTypes.INVALID_PARAMETER, "wallpaperUrl paramter is not a string", new Exception());
+ notifications.openNotification("normal", "Setting wallpaper to: " + wallpaperUrl);
+ }
+ };
- // Simulator is loaded with geo panel unfolded
- if (mapContainer && jQuery(mapContainer).is(':visible')) {
- marker = new OpenLayers.Marker(geo.map.getCenter(),
- new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
- markers.addMarker(marker);
+_self.__defineGetter__("ringtoneVolume", function () {
+ return deviceSettings.retrieve("Config.ringtoneVolume");
+});
- navigator.geolocation.getCurrentPosition(function (geoPosition) {
- geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
- new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
- _locationSharing = true;
- });
- }
+_self.__defineGetter__("msgRingtoneVolume", function () {
+ return deviceSettings.retrieve("Config.msgRingtoneVolume");
+});
- geo.map.events.register("move", map, function () {
- markers.clearMarkers();
- marker = new OpenLayers.Marker(geo.map.getCenter(),
- new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
- markers.addMarker(marker);
- });
- }
+_self.__defineGetter__("vibrationSetting", function () {
+ return deviceSettings.retrieve("Config.vibrationSetting");
+});
- function loadGpxFile(win, fail, args) {
- var reader = new FileReader(),
- file = args[0],
- _xml,
- t,
- att,
- lastAtt,
- _ele,
- _timestamp,
- _lastTimestamp,
- _useTimestamp = new Date().getTime(),
- _tempTimestamp,
- _tempPosition,
- _lastPosition,
- _useLastTimestamp,
- _heading = 0,
- _speed = 0,
- _dist = 0,
- navUtils = new utils.navHelper();
+module.exports = _self;
- reader.onload = function (e) {
- _xml = e.target.result;
- t = $(_xml).find('trkpt');
+});
+define('ripple/platform/wac/1.0/WidgetManager', function (require, exports, module) {
+/*
+ * Copyright 2011 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 exception = require('ripple/exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception');
- track = [];
+module.exports = {
+ // This method is used to check the installation status of a specific widget.
+ checkWidgetInstallationStatus: function () {
- utils.forEach(t, function (p, i) {
- if (!isNaN(i)) {
- att = t[i].attributes;
- lastAtt = t[i - 1] ? t[i - 1].attributes : {};
- _ele = $(t[i]).find("ele")[0];
- _timestamp = $(t[i]).find("time")[0];
- _lastTimestamp = $(t[i - 1]).find("time")[0];
+ exception.raise(ExceptionTypes.UNSUPPORTED, "WidgetManager.checkWidgetInstallationStatus not supported", new Exception());
+ }
+};
- if (_timestamp) {
- //files recorded with endomondo and others have timestamps, this is not a route plan but a record of a track
- _useTimestamp = new Date(_timestamp.innerText).getTime();
- }
+});
+define('ripple/platform/wac/1.0/Telephony', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _self,
+ exception = require('ripple/exception'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants'),
+ Device = require('ripple/platform/wac/1.0/Device'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception');
- if (t[i - 1]) {
- _dist = navUtils.getDistance(att["lat"].value, att["lon"].value, lastAtt["lat"].value, lastAtt["lon"].value);
- if (_lastTimestamp) {
- _useLastTimestamp = new Date(_lastTimestamp.innerText).getTime();
- }
- else {
- //routes from YOURS come in as tracks (rather than routes under the GPX schema), but with no timestamps. This is a route.
- _useLastTimestamp = _useTimestamp;
- _useTimestamp += Math.round(_dist / 22.2222 * 1000); //80km/h in m/s
- }
+function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
+}
- _heading = navUtils.getHeading(lastAtt["lat"].value, lastAtt["lon"].value, att["lat"].value, att["lon"].value);
- _speed = (_dist / ((_useTimestamp - _useLastTimestamp) / 1000)).toFixed(2);
+_self = {
- if (!_lastTimestamp) {
- //on YOURS routes, make sure we have at least one update a second
- _tempTimestamp = _useLastTimestamp;
+ // Public Callbacks
+ onCallEvent: undefined,// function (callType, phoneNumber) { },
+ onCallRecordsFound: undefined,// function (callRecords) { };
- while (_useTimestamp - _tempTimestamp > 1000) {
- _tempTimestamp += 1000;
- _lastPosition = track[track.length - 1].coords;
- _tempPosition = navUtils.simulateTravel(_lastPosition.latitude, _lastPosition.longitude, _heading, _speed);
- track.push({
- coords: {
- latitude: _tempPosition.latitude,
- longitude: _tempPosition.longitude,
- altitude: _ele ? _ele.innerText : 0,
- accuracy: 150,
- altitudeAccuracy: 80,
- heading: _heading,
- speed: _speed
- },
- timestamp: _tempTimestamp
- });
- }
- }
- }
+ // Public Methods
+ initiateVoiceCall: function (phoneNumber) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "initiateVoiceCall invalid number of parameters", new Exception());
+ //HACK: should this be hardcoded?
+ //I am still not even sure this is the correct behaviour
+ Device.launchApplication("PHONECALL", phoneNumber);
- track.push({
- coords: {
- latitude: att["lat"].value,
- longitude: att["lon"].value,
- altitude: _ele ? _ele.innerText : 0,
- accuracy: 150,
- altitudeAccuracy: 80,
- heading: _heading,
- speed: _speed
- },
- timestamp: _useTimestamp
- });
- }
- });
- };
- reader.onerror = function (e) {
- fail(e);
- };
- reader.readAsText(file.target.files[0], "UTF-8");
+ if (_self.onCallEvent) {
+ //HACK: shouldn't be hardcoded
+ //also what should the context be? isn't spec'ed
+ _self.onCallEvent.apply(_self, ["outgoing", phoneNumber]);
}
+ },
+ getCallRecordCnt: function (callRecordType) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecordCnt invalid number of parameters", new Exception());
+ var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
- function replayGpxTrack() {
- if (_replayingGpxFile) {
- _haltGpxReplay = true;
- gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
- }
- else {
- if (track.length > 0) {
- _haltGpxReplay = false;
- gpxGo.innerText = constants.GEO.GPXGO_LABELS.STOP;
-
- latitude.value = track[0].coords.latitude;
- longitude.value = track[0].coords.longitude;
- altitude.value = track[0].coords.altitude;
- accuracy.value = track[0].coords.accuracy;
- altitudeAccuracy.value = track[0].coords.altitudeAccuracy;
- heading.value = track[0].coords.heading;
- speed.value = track[0].coords.speed;
+ return utils.sum(calls, function (call) {
+ return call.callRecordType === callRecordType;
+ });
+ },
+ getCallRecord: function (callRecordType, id) {
+ utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecord invalid number of parameters", new Exception());
+ var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
- updateGeo();
- updateHeadingValues();
- _triggerEvent();
+ return utils.map(calls, function (call) {
+ return call.callRecordType === callRecordType ? call : null;
+ }).reduce(function (match, call) {
+ return match || call.callRecordId === id || null;
+ }, null);
+ },
+ deleteCallRecord: function (callRecordType, id) {
+ utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteCallRecord invalid number of parameters", new Exception());
+ var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
+ indexToDelete = calls.reduce(function (result, call, index) {
+ return call.callRecordType === callRecordType &&
+ call.callRecordId === id ? index : result;
+ }, -1);
- moveNextGpxTrack(1);
- }
- }
+ if (indexToDelete >= 0) {
+ calls.splice(indexToDelete, 1);
+ db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
}
- function moveNextGpxTrack(i)
- {
- if (_haltGpxReplay) {
- _replayingGpxFile = false;
- _haltGpxReplay = false;
- console.log("Ripple :: User interrupted replay of GPX file (Aye Captain, answers All Stop.)");
- }
- else {
- _replayingGpxFile = true;
- var _timeMultiplier = !isNaN(gpxMultiplier.value) ? gpxMultiplier.value : 1,
- _step = 0,
- _interval = 0;
+ },
- while (_interval < 250) {
- _step++;
- if ((i + _step) >= track.length) { break; }
- _interval = (track[i + _step].timestamp - track[i].timestamp) / _timeMultiplier;
+ deleteAllCallRecords: function (callRecordType) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteAllCallRecords invalid number of parameters", new Exception());
+ var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
+ indexesToDelete = calls.reduce(function (result, call, index) {
+ if (call.callRecordType === callRecordType) {
+ result.push(index);
}
+ return result;
+ }, []);
- gpxReplayStatus.textContent = (_interval / 1000).toFixed(2) + "s (" + (_interval / 1000 * _timeMultiplier).toFixed(2) + "s realtime), " + (i + 1) + " of " + track.length + " (stepping " + _step + " at " + _timeMultiplier + "x)";
-
- setTimeout(function () {
- latitude.value = track[i].coords.latitude;
- longitude.value = track[i].coords.longitude;
- altitude.value = track[i].coords.altitude;
- accuracy.value = track[i].coords.accuracy;
- altitudeAccuracy.value = track[i].coords.altitudeAccuracy;
- heading.value = track[i].coords.heading;
- speed.value = track[i].coords.speed;
-
- updateGeo();
- updateHeadingValues();
- _triggerEvent();
+ utils.forEach(indexesToDelete, function (index) {
+ calls.splice(index, 1);
+ });
- if (track[i + _step]) {
- moveNextGpxTrack(i + _step);
- }
- else {
- if (i < track.length - 1) {
- moveNextGpxTrack(track.length - 1);
- }
- else {
- _replayingGpxFile = false;
- gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
- console.log("Ripple :: Finished replaying GPX file (Arriving at our destination, assuming standard orbit Captain.)");
- }
- }
- }, _interval);
- }
+ if (indexesToDelete.length > 0) {
+ db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
}
- // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
- if (platform.current().id === 'phonegap' ||
- platform.current().id === 'webworks' ||
- platform.current().id === 'cordova') {
- // make the fields visible
- jQuery("#geo-cellid-container").hide();
- jQuery("#geo-heading-container").show();
- jQuery("#geo-speed-container").show();
- }
- else {
- jQuery("#geo-cellid-container").show();
- jQuery("#geo-heading-container").hide();
- jQuery("#geo-speed-container").hide();
- }
+ },
- _gpsMapZoomLevel = db.retrieve(constants.GEO.MAP_ZOOM_KEY) || 14;
+ findCallRecords: function (comparisonRecord, startInx, endInx) {
+ utils.validateNumberOfArguments(1, 3, arguments.length, ExceptionTypes.INVALID_PARAMETER, "findCallRecords invalid number of parameters", new Exception());
+ var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
+ utils.find(comparisonRecord, calls, startInx, endInx, _self.onCallRecordsFound);
- jQuery("#geo-map-zoom-decrease").bind("click", function () {
- _updateGpsMapZoom(false);
- });
+ }
- jQuery("#geo-map-zoom-increase").bind("click", function () {
- _updateGpsMapZoom(true);
- });
+};
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LATITUDE), updateGeo);
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LONGITUDE), updateGeo);
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE), updateGeo);
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ACCURACY), updateGeo);
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE_ACCURACY), updateGeo);
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.CELL_ID), updateGeo);
+module.exports = _self;
- jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
- jQuery("#play-route-speed").bind("change", function () {
- jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
- });
- jQuery("#clear-route-btn").bind("click", function () {
- clearRoute();
- });
- jQuery("#set-route-btn").bind("click", function () {
- setRoute();
- });
- jQuery("#play-route-btn").bind("click", function () {
- playRoute();
- });
- jQuery("#back-route-btn").bind("click", function () {
- skipTo("start");
- });
- jQuery("#forward-route-btn").bind("click", function () {
- skipTo("end");
- });
+});
+define('ripple/platform/wac/1.0/Messaging', function (require, exports, module) {
+/*
+ * Copyright 2011 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 exception = require('ripple/exception'),
+ utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ notifications = require('ripple/notifications'),
+ _console = require('ripple/console'),
+ Message = require('ripple/platform/wac/1.0/Message'),
+ MessageTypes = require('ripple/platform/wac/1.0/MessageTypes'),
+ Exception = require('ripple/platform/wac/1.0/Exception'),
+ ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');
- jQuery("#" + GEO_OPTIONS.DELAY).bind("change", function () {
- updateGeo();
- delayLabel.innerText = delay.value;
- });
- jQuery("#" + GEO_OPTIONS.TIMEOUT).bind("click", function () {
- updateGeo();
- });
- jQuery("#" + GEO_OPTIONS.GPXFILE).bind("change", function (a) {
- loadGpxFile(null, null, [a]);
- });
- jQuery("#" + GEO_OPTIONS.GPXGO).bind("click", function () {
- replayGpxTrack();
- });
+function _throwUnsupportedException(method) {
+ exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
+}
- // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
- if (platform.current().id === 'phonegap' || platform.current().id === 'webworks' || platform.current().id === 'cordova') {
- jQuery("#" + GEO_OPTIONS.HEADING).bind("change", function () {
- updateGeo();
- updateHeadingValues();
- });
+module.exports = {
+ onMessageArrived: undefined,
+ onMessageSendingFailure: undefined,
+ onMessagesFound: undefined,
- utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.SPEED), updateGeo);
- heading.value = positionInfo.heading;
- speed.value = positionInfo.speed;
- }
+ createMessage: function (messageType) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "createMessage invalid number of arguments", new Exception());
+ utils.validateArgumentType(messageType, "string", ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());
- initMap();
- if (navigator.onLine === false) {
- jQuery("#disable_geo_panel").show();
+ if (!utils.some(MessageTypes, function (value) {
+ return value === messageType;
+ })) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());
}
- jQuery(window).bind("online", function () {
- jQuery("#disable_geo_panel").hide();
- console.log("ONLINE");
- });
- jQuery(window).bind("offline", function () {
- jQuery("#disable_geo_panel").show();
- console.log("OFFLINE");
- });
- initializeValues();
- _initTimeZone();
+ var message = new Message();
+ message.messageType = messageType;
- event.on(positionEvent, function () {
- _updateGpsMap();
- });
+ return message;
+ },
+ deleteMessage: function () {
+ _throwUnsupportedException("Messaging.deleteMessage");
+ },
+ getMessage: function () {
+ _throwUnsupportedException("Messaging.getMessage");
+ },
+ getMessageQuantities: function () {
+ _throwUnsupportedException("Messaging.getMessageQuantities");
+ },
+ sendMessage: function (msg) {
+ utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.UNSUPPORTED, "sendMessage invalid number of arguments", new Exception());
+ if (msg instanceof Message === false) {
+ exception.raise(ExceptionTypes.INVALID_PARAMETER, "expected a valid Message object", new Exception());
+ }
- _triggerEvent();
+ //TODO: Must be modded to fail and to then call the onMessageSendingFailure callback
+ var message = "Sent " + msg.messageType + " " + msg.messageId + " to " + msg.destinationAddress;
- function _triggerEvent() {
- event.trigger(positionEvent, [{
- latitude: latitude.value,
- longitude: longitude.value,
- altitude: altitude.value,
- accuracy: accuracy.value,
- altitudeAccuracy: altitudeAccuracy.value,
- heading: heading ? heading.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
- speed: speed ? speed.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
- cellID: cellID.value,
- timeStamp: new Date()
- }]);
- }
+ // insert fail check here
+ notifications.openNotification("normal", message);
+ _console.log(message);
+ },
+ moveMessageToFolder: function () {
+ _throwUnsupportedException("Messaging.moveMessageToFolder");
+ },
+ copyMessageToFolder: function () {
+ _throwUnsupportedException("Messaging.copyMessageToFolder");
+ },
+ createFolder: function () {
+ _throwUnsupportedException("Messaging.createFolder");
+ },
+ deleteFolder: function () {
+ _throwUnsupportedException("Messaging.deleteFolder");
+ },
+ getFolderNames: function () {
+ _throwUnsupportedException("Messaging.getFolderNames");
+ },
+ findMessages: function () {
+ _throwUnsupportedException("Messaging.findMessages");
+ },
+ getCurrentEmailAccount: function () {
+ _throwUnsupportedException("Messaging.getCurrentEmailAccount");
+ },
+ getEmailAccounts: function () {
+ _throwUnsupportedException("Messaging.getEmailAccounts");
+ },
+ setCurrentEmailAccount: function () {
+ _throwUnsupportedException("Messaging.setCurrentEmailAccount");
+ },
+ deleteEmailAccount: function () {
+ _throwUnsupportedException("Messaging.deleteEmailAccount");
}
+
};
});
-define('ripple/ui/plugins/goodVibrations', function (require, exports, module) {
+define('ripple/platform/wac/1.0/ExceptionTypes', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants');
+var _self = {};
-module.exports = {
- vibrateDevice: function (milliseconds) {
- var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
- x, times;
+_self.__defineGetter__("INVALID_PARAMETER", function () {
+ return "invalid_parameter";
+});
- times = Math.floor(milliseconds / 100);
+_self.__defineGetter__("SECURITY", function () {
+ return "security";
+});
- for (x = 1; x <= times; x++) {
- node.animate({ left: -10 }, 5)
- .animate({ left: 0 }, 1)
- .animate({ left: 10 }, 5)
- .animate({ left: 0 }, 1);
+_self.__defineGetter__("UNKNOWN", function () {
+ return "unknown";
+});
- node.animate({ top: -10 }, 5)
- .animate({ top: 0 }, 1)
- .animate({ top: 10 }, 5)
- .animate({ top: 0 }, 1);
- }
- },
- shakeDevice: function (times) {
- var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
- x;
+_self.__defineGetter__("UNSUPPORTED", function () {
+ return "unsupported";
+});
- for (x = 1; x <= times; x++) {
- node.animate({ left: -25 }, 50)
- .animate({ left: 0 }, 30)
- .animate({ left: 25 }, 50)
- .animate({ left: 0 }, 30);
- }
- }
-};
+module.exports = _self;
});
-define('ripple/ui/plugins/information', function (require, exports, module) {
+define('ripple/platform/wac/1.0/PowerInfo', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- devices = require('ripple/devices'),
+var _self,
event = require('ripple/event'),
- platform = require('ripple/platform'),
- utils = require('ripple/utils'),
- app = require('ripple/app'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- db = require('ripple/db');
-
-function _updateInformationView() {
- var infoPane = document.getElementById(constants.COMMON.INFO_SECTION),
- infoList = [],
- device = devices.getCurrentDevice(),
- tempString = "",
- widgetInfo = app.getInfo(),
- layout = db.retrieve("layout") || "portrait",
- _systemSettings = db.retrieveObject("tizen2-systemsetting") || {"HOME_SCREEN": "", "LOCK_SCREEN": "", "INCOMING_CALL": "", "NOTIFICATION_EMAIL": ""};
+ _console = require('ripple/console'),
+ deviceSettings = require('ripple/deviceSettings'),
+ _lastPercentRemaining;
- //TODO: refactor this stuff to grab info from API, do this in a loop rather then hardcoded. Better DOM injection approach. This is legacy code
+_self = {
+ isCharging: undefined,
+ percentRemaining: undefined,
- infoList.push('<section id=\"information-banner\" style=\"display:none\"><img id=\"information-banner-icon\" width=\"16px\" height=\"16px\"/> <span id=\"information-banner-count\"></span></section>');
+ onChargeStateChange: undefined,
+ onLowBattery: undefined,
+ onChargeLevelChange: undefined
+};
- if (widgetInfo.icon) {
- infoList.push('<section style="position: absolute; left: 260px;" class="information-widgeticon"><img class="ui-corner-all" width="64" src="' + utils.appLocation() + widgetInfo.icon + '" alt="widget icon"/></section>');
+function _getCurrentChargeState(percentRemaining, isCharging) {
+ var batteryState;
+ if (percentRemaining === 100 && isCharging) {
+ batteryState = "full";
}
- if (widgetInfo.name) {
- infoList.push("<section><div id=\"systemSummaryAppNameContainer\" style=\"width:240px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">App Name: </label><span class=\"text-is-selectable\">" + widgetInfo.name + "</span></div></section>");
- //Update Title
- document.title = "Web Simulator - " + widgetInfo.name;
+ else if (!isCharging) {
+ batteryState = "discharging";
}
-
- infoList.push('<table class="tf_panel-table" style="border-spacing: 0px;">');
-
- if (widgetInfo.version) {
- infoList.push('<section class="information-widgetversion"><label class=\"ui-text-label\">Version: </label><span class="text-is-selectable">' + widgetInfo.version + '</span></section>');
+ else {
+ batteryState = "charging";
}
- infoList.push("<section><label class=\"ui-text-label\">Platform: </label><span class=\"text-is-selectable\">" + platform.current().name + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">Device: </label><span class=\"text-is-selectable\">" + device.name + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">OS: </label><span class=\"text-is-selectable\">" + device.osName + " " + device.osVersion + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">Manufacturer: </label><span class=\"text-is-selectable\">" + device.manufacturer + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">Screen: </label><span class=\"text-is-selectable\">" + device.screen.width + "x" + device.screen.height + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">Viewport: </label><span class=\"text-is-selectable\">" + device.viewPort[layout].width.toFixed(0) + "x" + device.viewPort[layout].height.toFixed(0) + "</span></section>");
- infoList.push("<section><label class=\"ui-text-label\">Density: </label><span class=\"text-is-selectable\">" + device.ppi + " PPI</span></section>");
- infoList.push("<section><label class=\"ui-text-label\" style=\"float:left; padding-top: 0px; \">User Agent: </label>" +
- "<div class=\"text-is-selectable\" style=\"padding-left: 80px\">" + device.userAgent + "</div></section>");
+ return batteryState;
+}
- if (device.notes) {
- utils.forEach(device.notes, function (note) {
- tempString += "<li class=\"text-is-selectable\">" + note + "</li>";
- });
- infoList.push("<section><div style=\"clear:both;\"></div><label class=\"ui-text-label\">Notes: </label><ul>" + tempString + "</ul></section>");
+event.on("DeviceBatteryStateChanged", function (isCharging) {
+ var callback = _self.onChargeStateChange,
+ msg = "",
+ batteryLevel = _self.percentRemaining,
+ batteryState;
+
+ batteryState = _getCurrentChargeState(batteryLevel, isCharging);
+
+ msg += "Fired onChargeStateChange with batteryState: " + batteryState;
+
+ if (callback && typeof callback === "function") {
+ callback.apply(null, [batteryState]);
+ }
+ else {
+ msg += " --> BUT there was no registered callback found.";
}
- infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryHomeScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Home Screen Image: </label><span>" + _systemSettings["HOME_SCREEN"] + "</span></div></section>");
- infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryLockScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Lock Screen Image: </label><span>" + _systemSettings["LOCK_SCREEN"] + "</span></div></section>");
- infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryInComingCallContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Incoming Call Number: </label><span>" + _systemSettings["INCOMING_CALL"] + "</span></div></section>");
- infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryNotiEMailContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Notification Email: </label><span>" + _systemSettings["NOTIFICATION_EMAIL"] + "</span></div></section>");
- infoList.push("<section><div style=\"clear:both;\"></div><div id=\"NFCExclusiveModeContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">NFC Exclusive Mode: </label><span id=\"NFCExclusiveModeValue\">false</span></div></section>");
- infoPane.innerHTML = infoList.join("");
+ _console.log(msg);
+});
- // Make tooltip if it needed
- if ((jQuery("#systemSummaryAppNameContainer").children("label").width() + jQuery("#systemSummaryAppNameContainer").children("span").width()) > 240) {
- tooltip.create("#systemSummaryAppNameContainer", jQuery("#systemSummaryAppNameContainer").children("span").text());
+event.on("DeviceBatteryLevelChanged", function (percentRemaining) {
+
+ var callback = _self.onChargeLevelChange,
+ lowBatteryCallback = _self.onLowBattery,
+ msg = "Fired onChargeLevelChange with percentRemaining: " + percentRemaining;
+
+ // blah, stupid Options returning strings
+ percentRemaining = parseInt(percentRemaining, 10);
+
+ if (callback && typeof callback === "function") {
+ callback.apply(null, [percentRemaining]);
}
- if ((jQuery("#systemSummaryHomeScreenContainer").children("label").width() + jQuery("#systemSummaryHomeScreenContainer").children("span").width()) > 320) {
- tooltip.create("#systemSummaryHomeScreenContainer", jQuery("#systemSummaryHomeScreenContainer").children("span").text());
+ else {
+ msg += " --> BUT there was no registered callback found.";
}
- if ((jQuery("#systemSummaryLockScreenContainer").children("label").width() + jQuery("#systemSummaryLockScreenContainer").children("span").width()) > 320) {
- tooltip.create("#systemSummaryLockScreenContainer", jQuery("#systemSummaryLockScreenContainer").children("span").text());
+
+ _console.log(msg);
+
+ if (percentRemaining <= 10) {
+
+ msg = "Fired onLowBattery with percentRemaining: " + percentRemaining;
+
+ if (lowBatteryCallback && typeof lowBatteryCallback === "function") {
+ lowBatteryCallback.apply(null, [percentRemaining]);
+ }
+ else {
+ msg += " --> BUT there was no registered callback found.";
+ }
+
+ _console.log(msg);
}
- if ((jQuery("#systemSummaryInComingCallContainer").children("label").width() + jQuery("#systemSummaryInComingCallContainer").children("span").width()) > 320) {
- tooltip.create("#systemSummaryInComingCallContainer", jQuery("#systemSummaryInComingCallContainer").children("span").text());
+
+ if (percentRemaining === 100 || (percentRemaining < 100 && _lastPercentRemaining === 100)) {
+ event.trigger("DeviceBatteryStateChanged", [_self.isCharging]);
}
- if ((jQuery("#systemSummaryNotiEMailContainer").children("label").width() + jQuery("#systemSummaryNotiEMailContainer").children("span").width()) > 320) {
- tooltip.create("#systemSummaryNotiEMailContainer", jQuery("#systemSummaryNotiEMailContainer").children("span").text());
+
+ _lastPercentRemaining = percentRemaining;
+
+});
+
+_self.__defineGetter__("isCharging", function () {
+ return deviceSettings.retrieveAsBoolean("PowerInfo.isCharging");
+});
+
+_self.__defineGetter__("percentRemaining", function () {
+ return deviceSettings.retrieveAsInt("PowerInfo.percentRemaining");
+});
+
+module.exports = _self;
+
+});
+define('ripple/platform/wac/2.0/devicestatus', function (require, exports, module) {
+/*
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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 utils = require('ripple/utils'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ _console = require('ripple/console'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ deviceSettings = require('ripple/deviceSettings'),
+ event = require('ripple/event'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ _getDeviceInfoAspect = true,
+ _getNetworkInfoAspect = true,
+ _deviceInfoAspect = ["Battery", "Device", "Display", "MemoryUnit", "OperatingSystem", "WebRuntime"],
+ _networkInfoAspect = ["CellularHardware", "CellularNetwork", "WiFiHardware", "WiFiNetwork"],
+ _aspectArray = [],
+ _propertyMap = {},
+ _watches = {},
+ _self;
+
+function _asynchErrorCallback(errorCallback, errorCode) {
+ if (errorCallback) {
+ setTimeout(function () {
+ errorCallback(errorCode);
+ }, 1);
}
}
-function _updateBanner(icon, count) {
- var bannerSection = document.getElementById("information-banner"),
- iconImg = document.getElementById("information-banner-icon"),
- countSpan = document.getElementById("information-banner-count");
+function _initialize() {
+ var aspectName, index, i;
- if (icon && (count === undefined || count !== 0)) {
- count = count || "";
- jQuery("#" + constants.COMMON.INFO_SECTION).show();
- jQuery(bannerSection).fadeToggle(1000);
- jQuery(bannerSection).fadeIn(1000);
+ _aspectArray = _deviceInfoAspect.concat(_networkInfoAspect);
+ for (index = 0; index < _aspectArray.length; index++) {
+ aspectName = _aspectArray[index];
+ _propertyMap[aspectName] = [];
+ for (i in deviceSettings.retrieve(aspectName)) {
+ _propertyMap[aspectName].push(i);
+ }
+ }
+}
+
+function _isPropertyFound(aspect, property) {
+ if (_aspectArray.length === 0) {
+ _initialize();
}
- else {
- jQuery(bannerSection).fadeOut(1000);
+
+ if (_propertyMap[aspect]) {
+ if (property) {
+ return _propertyMap[aspect].some(function (prop) {
+ return prop === property;
+ });
+ }
+ return true;
}
+ return false;
+}
- iconImg.src = utils.appLocation() + icon;
- if (icon.indexOf("http") === 0) {
- iconImg.src = icon;
+function _isPropertyAllowed(aspect) {
+ function hasAspect(asp) {
+ return asp === aspect;
}
- countSpan.innerHTML = count > 99 ? "99+" : count;
+ if ((_deviceInfoAspect.some(hasAspect) && _getDeviceInfoAspect === false) ||
+ (_networkInfoAspect.some(hasAspect) && _getNetworkInfoAspect === false)) {
+ return false;
+ }
+
+ return true;
}
-module.exports = {
- panel: {
- domId: "information-container",
- collapsed: false,
- pane: "left",
- titleName: "System Summary",
- display: true
- },
- initialize: function () {
- event.on("BannerUpdated", function (icon, count) {
- _updateBanner(icon, count);
- });
+function _isPropertyValid(prop, errorCallback) {
+ var _prop = Object(prop);
- event.on("PlatformChangedEvent", function () {
- _updateInformationView();
- });
+ if (_prop && _prop.aspect && _prop.property) {
+ if (_isPropertyFound(_prop.aspect, _prop.property) === false) {
+ _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ return false;
+ }
+ else if (_isPropertyAllowed(_prop.aspect) === false) {
+ _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.SECURITY_ERR));
+ return false;
+ }
+ }
+ else {
+ _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ return false;
+ }
+ return true;
+}
- event.on("WidgetInformationUpdated", function () {
- _updateInformationView();
- });
-
- event.on("SystemSettingChanged", function () {
- _updateInformationView();
- });
+module.exports = function () {
+ return {
+ getComponents: function (aspect) {
+ if (_isPropertyFound(aspect))
+ return ["_default"];
+ return null;
+ },
+
+ isSupported: function (aspect, property) {
+ return _isPropertyFound(aspect, property);
+ },
+
+ getPropertyValue: function (successCallback, errorCallback, prop) {
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getPropertyValue", function () {
+ if (_isPropertyValid(prop, errorCallback) !== true)
+ return undefined;
+
+ var value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
+ if (value !== undefined) {
+ successCallback(value, prop);
+ }
+ else {
+ _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_AVAILABLE_ERR));
+ }
+
+ return null;
+ });
+ },
+
+ watchPropertyChange: function (successCallback, errorCallback, prop, options) {
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "watchPropertyChange", function () {
+ if (_isPropertyValid(prop, errorCallback) !== true)
+ return undefined;
+
+ var _options = Object(options),
+ eventType = deviceSettings.retrieve(prop.aspect)[prop.property].event,
+ watchObj = {
+ eventType: eventType,
+ onEvent: function (newValue) {
+ if (watchObj.timeStamp &&
+ ((new Date()).getTime() - watchObj.timeStamp < options.minNotificationInterval)) {
+ return undefined;
+ }
+ else if (watchObj.value &&
+ (newValue > watchObj.value * (1 - _options.minChangePercent) &&
+ newValue < watchObj.value * (1 + _options.minChangePercent))) {
+ return undefined;
+ }
+
+ if (watchObj.intervalId) {
+ clearInterval(watchObj.intervalId);
+ watchObj.intervalId = setInterval(function () {
+ successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
+ }, _options.maxNotificationInterval);
+ }
+ successCallback(newValue, prop);
+ if (watchObj.timeStamp) {
+ watchObj.timeStamp = (new Date()).getTime();
+ }
+ if (watchObj.value) {
+ watchObj.value = newValue;
+ }
+ }
+ },
+ watchId = (new Date()).getTime() | 0;
+
+ if (options && _options.minNotificationInterval && _options.maxNotificationInterval &&
+ (_options.minNotificationInterval < 0 || _options.maxNotificationInterval < 0 ||
+ _options.minNotificationInterval >= _options.maxNotificationInterval)) {
+ _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ return undefined;
+ }
+
+ if (options && _options.maxNotificationInterval) {
+ watchObj.intervalId = setInterval(function () {
+ successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
+ }, _options.maxNotificationInterval);
+ }
+
+ if (options && _options.minNotificationInterval) {
+ watchObj.timeStamp = (new Date()).getTime();
+ }
+
+ if (options && _options.minChangePercent) {
+ if (_options.minNotificationInterval || _options.maxNotificationInterval) {}
+ else {
+ watchObj.value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
+ }
+ }
+
+ _watches[watchId] = watchObj;
+ if (watchObj.eventType) {
+ event.on(watchObj.eventType, watchObj.onEvent);
+ }
+
+ return watchId;
+ });
+ },
+
+ clearPropertyChange: function (watchHandler) {
+ var _handler = watchHandler | 0;
+
+ if (_watches[_handler]) {
+ event.deleteEventHandler(_watches[_handler].eventType, _watches[_handler].onEvent);
+ if (_watches[_handler].intervalId) {
+ clearInterval(_watches[_handler].intervalId);
+ }
+ delete(_watches[_handler]);
+ }
+ return null;
+ },
- event.on("ScreenChangeDimensions", function() {
- _updateInformationView();
- });
- _updateInformationView();
- }
+ handleSubFeatures: function (subFeatures) {
+ if (wac2_utils.isEmptyObject(subFeatures) ||
+ subFeatures["http://wacapps.net/api/devicestatus"] ||
+ (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"] &&
+ subFeatures["http://wacapps.net/api/devicestatus.networkinfo"])) {
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"]) {
+ _getNetworkInfoAspect = false;
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/devicestatus.networkinfo"]) {
+ _getDeviceInfoAspect = false;
+ return;
+ }
+ _console.warn("WAC-2.0-Devicestatus-handleSubFeatures: something wrong");
+ }
+ };
};
+
});
-define('ripple/ui/plugins/invoke', function (require, exports, module) {
+define('ripple/platform/wac/2.0/messagefilter', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- event = require('ripple/event');
-module.exports = {
- panel: {
- domId: "invoke-container",
- collapsed: true,
- pane: "left"
- },
- initialize: function () {
- document.getElementById("invoke-send")
- .addEventListener("click", function () {
- var invokeInfo = {};
+var _self;
- invokeInfo.uri = document.getElementById("invoke-uri-text").value;
- invokeInfo.source = document.getElementById("invoke-source-text").value;
- invokeInfo.target = document.getElementById("invoke-target-text").value;
- invokeInfo.action = document.getElementById("invoke-action-text").value;
- invokeInfo.type = document.getElementById("invoke-mime-type-text").value;
- invokeInfo.extension = document.getElementById("invoke-extension-text").value;
- invokeInfo.data = document.getElementById("invoke-data-text").value;
- if (invokeInfo.data) {
- invokeInfo.data = window.btoa(invokeInfo.data);
+_self = function (criteria) {
+ var pattern,
+ messageFilter;
+
+ messageFilter = {
+ match: function (target) {
+ var result = false, index;
+
+ if (Object.prototype.toString.call(criteria) === "[object Array]") {
+ for (index in criteria) {
+ if (_self(criteria[index]).match(target))
+ return true;
}
+ return false;
+ }
- event.trigger("AppInvoke", [invokeInfo]);
- }, false);
- }
+ switch (Object.prototype.toString.call(target)) {
+ case "[object Number]":
+ result = (criteria === target);
+ break;
+
+ case "[object String]":
+ result = pattern.test(target);
+ break;
+
+ case "[object Array]":
+ for (index in target) {
+ if (messageFilter.match(target[index]))
+ return true;
+ }
+ break;
+ }
+
+ return result;
+ }
+ };
+
+ if (typeof criteria === "string")
+ pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");
+
+ return messageFilter;
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/layout', function (require, exports, module) {
+define('ripple/platform/wac/2.0/errorcode', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- db = require('ripple/db'),
- resizer = require('ripple/resizer'),
- devices = require('ripple/devices'),
- event = require('ripple/event');
-function _initializeLayout(prev, baton) {
- var layout = db.retrieve("layout"),
- orientation = db.retrieve("deviceOrientation") || "portrait",
- layoutLandscape = document.getElementById(constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID),
- layoutPortrait = document.getElementById(constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID),
- currentDevice = devices.getCurrentDevice(),
- defaultOrientation = currentDevice ? currentDevice.defaultOrientation : null,
- layoutTypeChanged = false;
+var _self = {
+ message : []
+};
- jQuery("#" + constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID).bind("click", function () {
- layoutLandscape.setAttribute("class", "layout-selected");
- layoutPortrait.setAttribute("class", "layout-not-selected");
- resizer.rotateDevice("landscape");
- event.trigger("OrientationChanged", ["landscape"], true);
- });
+_self.__defineGetter__("UNKNOWN_ERR", function () {
+ return 0;
+});
- jQuery("#" + constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID).bind("click", function () {
- layoutLandscape.setAttribute("class", "layout-not-selected");
- layoutPortrait.setAttribute("class", "layout-selected");
- resizer.rotateDevice("portrait");
- event.trigger("OrientationChanged", ["portrait"], true);
- });
+_self.__defineGetter__("INDEX_SIZE_ERR", function () {
+ return 1;
+});
- jQuery("#" + constants.COMMON.MENU_BUTTON).bind("click", function () {
- event.trigger("HardwareKey", [1]);
- });
+_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
+ return 2;
+});
- jQuery("#" + constants.COMMON.BACK_BUTTON).bind("click", function () {
- event.trigger("HardwareKey", [0]);
- });
+_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
+ return 3;
+});
- if (!layout) {
- layout = defaultOrientation || "portrait";
- layoutTypeChanged = true;
- resizer.changeLayoutType(layout);
- }
+_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
+ return 4;
+});
- //Hide the orientation buttons that we don't need for this device
- if (!currentDevice.viewPort.landscape) {
- layoutLandscape.setAttribute("style", "display:none");
- }
+_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
+ return 5;
+});
- if (!currentDevice.viewPort.portrait) {
- layoutPortrait.setAttribute("style", "display:none");
- }
+_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
+ return 6;
+});
- if (layout && layout === "portrait") {
- layoutLandscape.setAttribute("class", "layout-not-selected");
- layoutPortrait.setAttribute("class", "layout-selected");
- }
- else if (layout && layout === "landscape") {
- layoutLandscape.setAttribute("class", "layout-selected");
- layoutPortrait.setAttribute("class", "layout-not-selected");
- }
+_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
+ return 7;
+});
- if (!layoutTypeChanged) {
- resizer.resize(currentDevice);
- }
+_self.__defineGetter__("NOT_FOUND_ERR", function () {
+ return 8;
+});
- if (orientation === "portrait") {
- layoutLandscape.setAttribute("class", "layout-not-selected");
- layoutPortrait.setAttribute("class", "layout-selected");
- } else {
- layoutLandscape.setAttribute("class", "layout-selected");
- layoutPortrait.setAttribute("class", "layout-not-selected");
- }
- resizer.rotateDevice(orientation);
-}
+_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
+ return 9;
+});
-module.exports = {
- initialize: _initializeLayout
-};
+_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
+ return 10;
+});
+_self.__defineGetter__("INVALID_STATE_ERR", function () {
+ return 11;
});
-define('ripple/ui/plugins/messaging', function (require, exports, module) {
-/*
- * Copyright 2011 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 event = require('ripple/event'),
- utils = require('ripple/utils'),
- _type = {
- sms: "SMS",
- mms: "MMS",
- email: "E-mail"
- },
- _filename_suffix = 0,
- _attachments = [];
-function _getAttachmentFileName() {
- return "attach" + _filename_suffix + ".txt";
-}
+_self.__defineGetter__("SYNTAX_ERR", function () {
+ return 12;
+});
-module.exports = {
- panel: {
- domId: "messaging-container",
- collapsed: true,
- pane: "left",
- titleName: "Messaging",
- display: true
- },
- initialize: function () {
- document.getElementById("messaging-send")
- .addEventListener("click", function () {
- var number = document.getElementById("messaging-sms-number").value,
- text = document.getElementById("messaging-text").value,
- type = document.getElementById("messaging-type").value,
- message = {
- type: type,
- body: text,
- from: number,
- time: new Date(),
- attachments: _attachments
- };
+_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
+ return 13;
+});
- event.trigger("MessageReceived", [message]);
-
- _attachments = [];
-/* TODO: add back when attachment is finished
- document.getElementById("messaging-attachments").innerHTML = "";
-*/
- _filename_suffix = 0;
- }, false);
+_self.__defineGetter__("NAMESPACE_ERR", function () {
+ return 14;
+});
-/* TODO: add back when attachment is finished
- document.getElementById("messaging-attach")
- .addEventListener("click", function () {
- var attachedFile, attachedFileCheckbox, attachedFileName;
- if (_filename_suffix > 0)
- return;
- _attachments.push({filename: _getAttachmentFileName(), content: document.getElementById("messaging-attachment-content").value});
+_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
+ return 15;
+});
- attachedFile = document.getElementById("messaging-attachments").insertRow(0);
- attachedFileName = attachedFile.insertCell(0);
- attachedFileCheckbox = attachedFile.insertCell(1);
- attachedFileName.innerHTML = _attachments[_filename_suffix].filename;
-// attachedFileCheckbox.innerHTML = '<input type="checkbox" value="' + _filename_suffix + '">';
+_self.__defineGetter__("VALIDATION_ERR", function () {
+ return 16;
+});
- document.getElementById("messaging-attachment-content").value = "";
- _filename_suffix++;
- }, false);
+_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
+ return 17;
+});
- document.getElementById("messaging-detach")
- .addEventListener("click", function () {
- _attachments = [];
- document.getElementById("messaging-attachments").innerHTML = "";
- _filename_suffix = 0;
- }, false);
-*/
- event.on("OutsideMessageReceived", function (message) {
- var numRecipients = 0,
- i = 0,
- recipients = [],
- recipientsStatus = {},
- strRecipients = document.getElementById("messaging-recipients").value;
+_self.__defineGetter__("SECURITY_ERR", function () {
+ return 18;
+});
- recipientsStatus.id = message.id;
- recipientsStatus.msg = message.msg;
- for (i in message.to) {
- recipientsStatus[message.to[i]] = true;
- recipients.push(message.to[i]);
- }
- for (i in message.cc) {
- recipientsStatus[message.cc[i]] = true;
- recipients.push(message.cc[i]);
- }
- for (i in message.bcc) {
- recipientsStatus[message.bcc[i]] = true;
- recipients.push(message.bcc[i]);
- }
- numRecipients = recipients.length;
- strRecipients = recipients.join(",");
- event.trigger("MessageSent", [recipientsStatus]);
- document.getElementById("messaging-received").innerHTML = "" + numRecipients + " recipient(s)" + " delivered";
- document.getElementById("messaging-recipients").value = strRecipients;
- document.getElementById("received-message-box").value = message.body;
- });
-
- document.getElementById("messaging-clear")
- .addEventListener("click", function () {
- document.getElementById("received-message-box").value = "";
- document.getElementById("messaging-received").innerHTML = "";
- }, false);
-
- utils.forEach(_type, function (msgTypeText, msgType) {
- var typeNode = utils.createElement("option", {
- "innerText": msgTypeText,
- "value": msgType
- });
+_self.__defineGetter__("NETWORK_ERR", function () {
+ return 19;
+});
- document.getElementById("messaging-type").appendChild(typeNode);
- });
- }
-};
+_self.__defineGetter__("ABORT_ERR", function () {
+ return 20;
+});
+_self.__defineGetter__("TIMEOUT_ERR", function () {
+ return 21;
});
-define('ripple/ui/plugins/multimedia', function (require, exports, module) {
-/*
- * Copyright 2011 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 constants = require('ripple/constants'),
- event = require('ripple/event'),
- volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
- volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);
-module.exports = {
- panel: {
- domId: "multimedia-container",
- collapsed: true,
- pane: "left"
- },
- initialize: function () {
- var volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
- volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);
+_self.__defineGetter__("INVALID_VALUES_ERR", function () {
+ return 22;
+});
- event.on("MultimediaVolumeChanged", function (volume) {
- volumeField.innerText = volume > 9 ? volume : "0" + volume;
- if (volume.value !== volume) {
- volume.value = volume;
- }
- });
+_self.__defineGetter__("IO_ERR", function () {
+ return 100;
+});
- volume.addEventListener('change', function () {
- event.trigger("MultimediaVolumeChanged", [this.value], true);
- }, false);
+_self.__defineGetter__("NOT_AVAILABLE_ERR", function () {
+ return 101;
+});
- event.on("MultimediaAudioStateChanged", function updateIsAudioPlaying(state) {
- document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PLAYING_FIELD_ID).innerHTML = state === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
- });
+function _setMessage(_self) {
+ var c, g;
+ for (c in _self) {
+ g = _self.__lookupGetter__(c);
+ if (g) {
+ _self.message[g()] = c;
+ }
}
-};
+}
+
+_setMessage(_self);
+
+module.exports = _self;
+
});
-define('ripple/ui/plugins/network', function (require, exports, module) {
+define('ripple/platform/wac/2.0/messaging', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
+var utils = require('ripple/utils'),
event = require('ripple/event'),
- deviceSettings = require('ripple/deviceSettings'),
- //dbinit = require('ripple/platform/tizen/2.0/dbinit'),
- _NFC_TAG = "tizen1.0-nfc-tag",
- _NFC_PEER = "tizen1.0-nfc-peer",
- _NFC_OUTPUT_MESSAGE = "tizen1.0-nfc-output-message",
- _powered = false,
- _isConnected = false,
- _tagNDEF = {
- type: "GENERIC_TARGET",
- isSupportedNDEF: true,
- ndefSize: 3,
- ndefs: [{
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID001",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID002",
- payload: "This is 2nd payload"
- }]
- },
- {
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID003",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID004",
- payload: "This is 2nd payload"
- }]
- },
- {
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID005",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID006",
- payload: "This is 2nd payload"
- }]
- }]
- },
- _tagRaw = {
- type: "GENERIC_TARGET",
- isSupportedNDEF: false,
- rawData : ""
+ db = require('ripple/db'),
+ exception = require('ripple/exception'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
+ Filter = require('ripple/platform/wac/2.0/messagefilter'),
+ FileSystem = require('ripple/platform/wac/2.0/filesystem'),
+ MessageSendCallback,
+ Message,
+ MessageFilter,
+ Recipients,
+ _KEY = "wac2-pim-messaging",
+ _PENDING_TIME = 600,
+ _messages = {},
+ _subscriber = {
+ onSMS: {},
+ onMMS: {},
+ onEmail: {}
},
- _peerNDEF = {
- ndef: {
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID001",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID002",
- payload: "This is 2nd payload"
- }]
- }
+ _sentStatus = {},
+ _security = {
+ "http://wacapps.net/api/messaging": [],
+ "http://wacapps.net/api/messaging.send": ["sendMessage"],
+ "http://wacapps.net/api/messaging.find": ["findMessages"],
+ "http://wacapps.net/api/messaging.subscribe": ["onSMS", "onMMS", "onEmail"],
+ "http://wacapps.net/api/messaging.write": ["update"],
+ all: true
},
- btNodes,
- _btDeviceTemplate = "",
- _btSimulatedDevs = {},
- _btBluetoothDB;
+ _fileSystem,
+ _initialized = false,
+ _self;
-function elementEnableDisableSetting(prop) {
- jQuery("#nfc-attach-msg").text("\xa0");
- jQuery("#nfc-peer-send-msg").text("\xa0");
- if (prop && prop.power !== undefined && prop.power !== null) {
- if (!prop.power) {
- $("#nfc-type").removeAttr("disabled");
- }
+function _initialize() {
+ _get();
+ if (!_fileSystem) {
+ _fileSystem = new FileSystem();
}
- if (prop && prop.connectedState !== undefined && prop.connectedState !== null) {
- if (prop.connectedState) {
- $("#nfc-type").attr("disabled", "disabled");
- $("#nfc-tag-type-text").text($("#nfc-tag-type option:selected").text());
- $("#nfc-tag-type").hide();
- $("#nfc-tag-type-text").show();
- $("#nfc-tag-NDEF-support-text").text($("#nfc-tag-NDEF-support option:selected").text());
- $("#nfc-tag-NDEF-support").hide();
- $("#nfc-tag-NDEF-support-text").show();
- $("#nfc-raw-data").attr("disabled", "disabled");
- } else {
- $("#nfc-type").removeAttr("disabled");
- $("#nfc-tag-type").show();
- $("#nfc-tag-type-text").hide();
- $("#nfc-tag-NDEF-support").show();
- $("#nfc-tag-NDEF-support-text").hide();
- $("#nfc-raw-data").removeAttr("disabled");
- }
+ _initialized = true;
+}
+
+function _get() {
+ _messages = db.retrieveObject(_KEY) || {1: [], 2: [], 3: [], 4: []};
+ utils.forEach(_messages, function (folder) {
+ utils.forEach(folder, function (messageItem) {
+ if (messageItem.timestamp)
+ messageItem.timestamp = new Date(messageItem.timestamp);
+ });
+ });
+}
+
+function _save() {
+ db.saveObject(_KEY, _messages);
+}
+
+function _updateDB(message, duplicate) {
+ _get();
+ _messages[message.folder].push(message);
+ if (duplicate)
+ _messages[duplicate.folder].push(duplicate);
+ _save();
+}
+
+function _processAttachments(message) {
+ var attachmentsFileName = [],
+ attachmentsContent = [];
+
+ function _generateAttachmentFileName(attachment) {
+ var lastDot = attachment.filename.lastIndexOf(".");
+ return attachment.filename.substring(0, lastDot) + "_" + Math.uuid(8, 16) + attachment.filename.substring(lastDot);
+ }
+
+ function _onResolveSuccess(file) {
+ var fileAttachment = file.createFile(attachmentsFileName[0]);
+
+ fileAttachment.openStream(
+ function (fs) {
+ fs.write(attachmentsContent[0]);
+ fs.close();
+ }, null, "w");
}
+
+ function _onResolveError() {
+ }
+
+ if (message.attachments.length === 0)
+ return;
+
+ attachmentsFileName.push(_generateAttachmentFileName(message.attachments[0]));
+ attachmentsContent.push(message.attachments[0].content);
+
+ _fileSystem.resolve(_onResolveSuccess, _onResolveError, "attachments", "rw");
+
+ message.attachments = utils.copy(attachmentsFileName);
}
-function _initializeElements() {
- jQuery(function () {
- var stop = false,
- wifiRadio = $("#wifi-radio"),
- isSupportNDEF, type;
+function _errorOccurred(onError, code) {
+ if (!onError)
+ return;
- // initialize main menus
- wifiRadio.buttonset();
+ setTimeout(function () {
+ onError(new DeviceApiError(code));
+ }, 1);
+}
- $("#cellular-radio").buttonset();
- $("#nfc-radio").buttonset();
- $("#bluetooth-radio").buttonset();
- $("#bearer-radio").buttonset();
+function _pendingOperate(operate, scope) {
+ var i, argumentVector = [];
- $("#wifi-radio1").prop('checked', false);
- $("#wifi-radio2").prop('checked', false);
- if (deviceSettings.retrieve("WIFI_NETWORK.status") === true) {
- $("#wifi-radio1").prop('checked', true);
- $("#wifi-radio1-label").css({'color': '#000000'});
- $("#wifi-radio2-label").css({'color': '#bbbbbb'});
- }
- else {
- $("#wifi-radio2").prop('checked', true);
- $("#wifi-radio1-label").css({'color': '#bbbbbb'});
- $("#wifi-radio2-label").css({'color': '#222222'});
- }
- $("#wifi-radio1").button("refresh");
- $("#wifi-radio2").button("refresh");
+ for (i = 0; i < arguments.length - 2; i++)
+ argumentVector[i] = arguments[i + 2];
- $("#cellular-radio1").prop('checked', false);
- $("#cellular-radio2").prop('checked', false);
- if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === true) {
- $("#cellular-radio1").prop('checked', true);
- $("#cellular-radio1-label").css({'color': '#000000'});
- $("#cellular-radio2-label").css({'color': '#bbbbbb'});
- }
- else {
- $("#cellular-radio2").prop('checked', true);
- $("#cellular-radio1-label").css({'color': '#bbbbbb'});
- $("#cellular-radio2-label").css({'color': '#222222'});
- }
+ return function () {
+ var pendingObj, pendingOperation;
- if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
- $("#cellular-radio1").prop('disabled', true);
- $("#cellular-radio2").prop('disabled', true);
- $("#panel_flight_mode_notice").show();
- }
- else {
- $("#cellular-radio1").prop('disabled', false);
- $("#cellular-radio2").prop('disabled', false);
- $("#panel_flight_mode_notice").hide();
- }
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = window.setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ if (operate)
+ operate.apply(scope, argumentVector);
+ }, _PENDING_TIME);
- $("#cellular-radio1").button("refresh");
- $("#cellular-radio2").button("refresh");
+ pendingOperation = new PendingOperation(pendingObj);
- $("#bearer-radio2").prop('checked', true);
- $("#bearer-radio2").button("refresh");
+ return pendingOperation;
+ };
+}
- $("#wifi-radio1").click(function () {
- $("#wifi-radio1-label").css({'color': '#000000'});
- $("#wifi-radio2-label").css({'color': '#bbbbbb'});
- deviceSettings.persist("WIFI_NETWORK.status", true);
- event.trigger("WiFiNetworkStatusChanged", [true]);
- });
+function _onMessage(onMessage, messageHandler) {
+ if (!messageHandler)
+ exception.raise(exception.types.Argument,
+ onMessage + " invalid messageHandler parameter",
+ new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- $("#wifi-radio2").click(function () {
- $("#wifi-radio1-label").css({'color': '#bbbbbb'});
- $("#wifi-radio2-label").css({'color': '#222222'});
- deviceSettings.persist("WIFI_NETWORK.status", false);
- event.trigger("WiFiNetworkStatusChanged", [false]);
- });
+ utils.validateArgumentType(messageHandler, "function", null,
+ "messageHandler invalid function parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- $("#cellular-radio1").click(function () {
- $("#cellular-radio1-label").css({'color': '#000000'});
- $("#cellular-radio2-label").css({'color': '#bbbbbb'});
- deviceSettings.persist("CELLULAR_NETWORK.status", true);
- event.trigger("CellularNetworkStatusChanged", [true]);
- });
+ if (!_security.all && !_security[onMessage])
+ exception.raise(exception.types.Argument,
+ onMessage + " access denied", new DeviceApiError(errorcode.SECURITY_ERR));
- $("#cellular-radio2").click(function () {
- $("#cellular-radio1-label").css({'color': '#bbbbbb'});
- $("#cellular-radio2-label").css({'color': '#222222'});
- deviceSettings.persist("CELLULAR_NETWORK.status", false);
- event.trigger("CellularNetworkStatusChanged", [false]);
- });
+ var idSubscribe = (new Date()).getTime() | 0;
+ _subscriber[onMessage][idSubscribe] = messageHandler;
- $("#nfc-radio1-label").css({'color': '#bbbbbb'});
- $("#nfc-radio2-label").css({'color': '#222222'});
+ return idSubscribe;
+}
- $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
- $("#bluetooth-radio2-label").css({'color': '#222222'});
+function _validateRecipients(message) {
+ var i;
- $("#bearer-radio1-label").css({'color': '#bbbbbb'});
- $("#bearer-radio2-label").css({'color': '#222222'});
+ for (i = 0; i < message.to.length;) {
+ message.to[i] = message.to[i].replace(/^\s*(\S*)\s*$/, '$1');
+ if (message.to[i] === "")
+ message.to.splice(i, 1);
+ else
+ i++;
+ }
+ for (i = 0; i < message.cc.length;) {
+ message.cc[i] = message.cc[i].replace(/^\s*(\S*)\s*$/, '$1');
+ if (message.cc[i] === "")
+ message.cc.splice(i, 1);
+ else
+ i++;
+ }
+ for (i = 0; i < message.bcc.length;) {
+ message.bcc[i] = message.bcc[i].replace(/^\s*(\S*)\s*$/, '$1');
+ if (message.bcc[i] === "")
+ message.bcc.splice(i, 1);
+ else
+ i++;
+ }
+ if (message.to.length + message.cc.length + message.bcc.length === 0)
+ exception.raise(exception.types.Argument,
+ "sendMessage invalid message.to parameter",
+ new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+}
- $("#nfc-radio1").click(function () {
- $("#nfc-radio2-label").css({'color': '#bbbbbb'});
- $("#nfc-radio1-label").css({'color': '#222222'});
- $("#nfc-main-container").show();
- });
+function _isValid(onSuccess, onError, message) {
+ if (onSuccess &&
+ typeof onSuccess !== "function" &&
+ typeof onSuccess !== "object") {
+ exception.raise(exception.types.Argument,
+ "sendMessage invalid successCallback parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
- $("#nfc-radio2").click(function () {
- $("#nfc-radio1-label").css({'color': '#bbbbbb'});
- $("#nfc-radio2-label").css({'color': '#222222'});
- $("#nfc-main-container").hide();
- });
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null,
+ "sendMessage invalid errorCallback parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
- $("#bluetooth-radio1").click(function () {
- $("#bluetooth-radio2-label").css({'color': '#bbbbbb'});
- $("#bluetooth-radio1-label").css({'color': '#222222'});
- $("#bluetooth-main-container").show();
- });
+ if (!onSuccess) {
+ _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
+ return false;
+ }
- $("#bluetooth-radio2").click(function () {
- $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
- $("#bluetooth-radio2-label").css({'color': '#222222'});
- $("#bluetooth-main-container").hide();
- });
+ if (message) {
+ utils.validateArgumentType(message, "object", null,
+ "sendMessage invalid message parameter",
+ new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ } else {
+ _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
+ return false;
+ }
- $("#bearer-radio1").click(function () {
- $("#bearer-radio2-label").css({'color': '#bbbbbb'});
- $("#bearer-radio1-label").css({'color': '#222222'});
- $("#bearer-main-container").show();
- });
+ if (message.type !== _self().TYPE_SMS &&
+ message.type !== _self().TYPE_MMS &&
+ message.type !== _self().TYPE_EMAIL)
+ exception.raise(exception.types.Argument,
+ "sendMessage invalid message.type parameter",
+ new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- $("#bearer-radio2").click(function () {
- $("#bearer-radio1-label").css({'color': '#bbbbbb'});
- $("#bearer-radio2-label").css({'color': '#222222'});
- $("#bearer-main-container").hide();
- });
+ if (!_security.all && !_security.sendMessage) {
+ _errorOccurred(onError, errorcode.SECURITY_ERR);
+ return false;
+ }
- // initialize nfc
- jQuery("nfc-tag-ndef-container h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
+ TypeCoerce(Message(0)).cast(message);
+ _validateRecipients(message);
+
+ return true;
+}
+
+function _getEachSentStatus(onMessageSentSuccess, onMessageSentError, message,
+ sucRecipients, failRecipients, recType) {
+ utils.forEach(message[recType], function (recipient) {
+ if (_sentStatus[recipient]) {
+ sucRecipients[recType].push(recipient);
+ if (onMessageSentSuccess) {
+ onMessageSentSuccess(recipient);
}
- });
- jQuery("#nfc-tag-ndef-container").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
- });
- jQuery("nfc-nfcpeer h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
+ } else {
+ failRecipients[recType].push(recipient);
+ if (onMessageSentError) {
+ onMessageSentError(new DeviceApiError(errorcode.UNKNOWN_ERR), recipient);
}
- });
- jQuery("#nfc-nfcpeer").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
- });
- jQuery("#nfc-tag-NDEF-support").bind("change", function () {
- isSupportNDEF = jQuery("#nfc-tag-NDEF-support").val();
- if (isSupportNDEF === "Yes") {
- jQuery("#nfc-tag-ndef-container").fadeIn();
- jQuery("#nfc-tag-raw-container").hide();
- } else {
- jQuery("#nfc-tag-ndef-container").hide();
- jQuery("#nfc-tag-raw-container").fadeIn();
+ }
+ });
+}
+
+function _getSentStatus(onSuccess, onError, message, onMessageSentSuccess, onMessageSentError) {
+ var allSentSuccess,
+ sucRecipients = new Recipients(),
+ failRecipients = new Recipients(),
+ duplicate;
+
+ _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
+ message, sucRecipients, failRecipients, "to");
+
+ if (message.type === _self().TYPE_EMAIL) {
+ _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
+ message, sucRecipients, failRecipients, "cc");
+ _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
+ message, sucRecipients, failRecipients, "bcc");
+ }
+
+ allSentSuccess = (failRecipients.total() === 0);
+
+ if (allSentSuccess) {
+ message.folder = _self().FOLDER_SENTBOX;
+ } else if (sucRecipients.total() === 0) {
+ message.folder = _self().FOLDER_DRAFTS;
+ } else {
+ duplicate = utils.copy(message);
+
+ message.to = sucRecipients.to;
+ message.cc = sucRecipients.cc;
+ message.bcc = sucRecipients.bcc;
+ message.folder = _self().FOLDER_SENTBOX;
+
+ duplicate.to = failRecipients.to;
+ duplicate.cc = failRecipients.cc;
+ duplicate.bcc = failRecipients.bcc;
+ duplicate.folder = _self().FOLDER_DRAFTS;
+ }
+
+ _updateDB(message, duplicate);
+
+ if (allSentSuccess) {
+ onSuccess();
+ } else if (onError) {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }
+}
+
+_self = function () {
+ var messaging = {
+ createMessage: function (type) {
+ type = type | 0;
+
+ if (type < _self().TYPE_SMS || type > _self().TYPE_EMAIL)
+ exception.raise(exception.types.Argument,
+ "type invalid value", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+
+ var msg = new Message(type);
+
+ return msg;
+ },
+
+ sendMessage: function (successCallback, errorCallback, message) {
+ var ret;
+
+ function _sendMessage() {
+ event.trigger("OutsideMessageReceived", [message]);
+
+ return _pendingOperate(_getSentStatus, undefined,
+ successCallback, errorCallback, message)();
}
- });
- jQuery("#nfc-type").bind("change", function () {
- type = jQuery("#nfc-type").val();
- if (type === "Tag") {
- jQuery("#nfc-nfctag").fadeIn();
- jQuery("#nfc-nfcpeer").hide();
- } else {
- jQuery("#nfc-nfctag").hide();
- jQuery("#nfc-nfcpeer").fadeIn();
+
+ function _sendEachMessage() {
+ utils.forEach(successCallback, function (value, key) {
+ utils.validateArgumentType(value, "function", null,
+ "sendMessage invalid successCallback." + key + " parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ });
+
+ event.trigger("OutsideMessageReceived", [message]);
+
+ return _pendingOperate(_getSentStatus, undefined,
+ successCallback.onsuccess, errorCallback, message,
+ successCallback.onmessagesendsuccess, successCallback.onmessagesenderror)();
}
- elementEnableDisableSetting();
- });
- jQuery("#nfc-power").bind("change", function () {
- var status;
- status = jQuery("#nfc-power").val() === "On" ? true : false;
- if (status)
- jQuery("#nfc").show();
- event.trigger("nfc-power-setting", [status]);
- });
- jQuery("#nfc-attach").bind("click", function () {
- var type, isAttached;
- isAttached = jQuery("#nfc-attach").children().text() === "Attach" ? true : false;
- jQuery("#nfc-attach-msg").text("\xa0");
- if (!_powered && isAttached) {
- jQuery("#nfc-attach-msg").text("Power:Off, attach won't work");
- return;
+ if (!_isValid(successCallback, errorCallback, message))
+ return null;
+
+ switch (typeof successCallback) {
+ case "function":
+ ret = _sendMessage();
+ break;
+
+ case "object":
+ ret = _sendEachMessage();
+ break;
}
- type = jQuery("#nfc-type").val();
- event.trigger("nfc-attach-setting", [type, isAttached]);
- });
- jQuery("#nfc-peer-send").bind("click", function () {
- jQuery("#nfc-peer-send-msg").text("\xa0");
- if (!_isConnected) {
- jQuery("#nfc-peer-send-msg").text("Disconnected. Send won't work");
- return;
+
+ return ret;
+ },
+
+ findMessages: function (successCallback, errorCallback, filter) {
+ function _findMessages() {
+ var message, result = [];
+
+ if (!_security.all && !_security.findMessages)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+
+ utils.forEach(_messages, function (folder) {
+ utils.forEach(folder, function (messageItem) {
+ if ((filter === undefined || filter === null) ||
+ (filter.id === undefined || Filter(filter.id).match(messageItem.id)) &&
+ (filter.type === undefined || Filter(filter.type).match(messageItem.type)) &&
+ (filter.folder === undefined || Filter(filter.folder).match(messageItem.folder)) &&
+ (filter.startTimestamp === undefined || (messageItem.timestamp >= filter.startTimestamp)) &&
+ (filter.endTimestamp === undefined || (messageItem.timestamp <= filter.endTimestamp)) &&
+ (filter.from === undefined || Filter(filter.from).match(messageItem.from)) &&
+ (filter.to === undefined || Filter(filter.to).match(messageItem.to)) &&
+ (filter.cc === undefined || Filter(filter.cc).match(messageItem.cc)) &&
+ (filter.bcc === undefined || Filter(filter.bcc).match(messageItem.bcc)) &&
+ (filter.body === undefined || Filter(filter.body).match(messageItem.body)) &&
+ (filter.isRead === undefined || (messageItem.isRead === filter.isRead)) &&
+ (filter.messagePriority === undefined || (messageItem.priority === filter.messagePriority)) &&
+ (filter.subject === undefined || Filter(filter.subject).match(messageItem.subject))) {
+ message = utils.copy(messageItem);
+ result.push(message);
+ }
+ });
+ });
+ successCallback(result);
}
- db.saveObject(_NFC_PEER, _peerNDEF);
- event.trigger("nfc-peer-sending-ndef", []);
- });
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findMessages", _pendingOperate(_findMessages));
+ },
- // Initialize network bearer selection
- $("#bearer-cellular-radio1").prop('checked', true);
- $("#bearer-unknown-radio2").prop('checked', true);
- $("#bearer-cellular-radio1").button("refresh");
- $("#bearer-unknown-radio2").button("refresh");
+ onSMS: function (messageHandler) {
+ return _onMessage("onSMS", messageHandler);
+ },
- $("#bearer-cellular-radio2").click(function () {
- $("#bearer-cellular button").click();
- });
+ onMMS: function (messageHandler) {
+ return _onMessage("onMMS", messageHandler);
+ },
- $("#bearer-unknown-radio2").click(function () {
- $("#bearer-unknown button").click();
- });
- });
-}
+ onEmail: function (messageHandler) {
+ return _onMessage("onEmail", messageHandler);
+ },
-function _btRender() {
- var devicesHTML, btHtmlContent = "";
+ unsubscribe: function (subscriptionHandler) {
+ var onMessage, idSubscribe;
- utils.forEach(_btSimulatedDevs, function (item) {
- var uuidsHTML = "", firstService = null;
+ utils.validateArgumentType(subscriptionHandler, "integer",
+ null, "subscriptionHandler invalid function parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
- utils.forEach(item.services, function (s, index) {
- if (!firstService) {
- firstService = s;
+ for (onMessage in _subscriber) {
+ for (idSubscribe in _subscriber[onMessage]) {
+ if (idSubscribe == subscriptionHandler) {
+ delete _subscriber[onMessage][idSubscribe];
+ return;
+ }
+ }
}
- uuidsHTML += '<option value="' + index + '">' + s.name + '</option>';
- });
+ },
- devicesHTML = _btDeviceTemplate.replace(/#name/g, item.name)
- .replace(/#address/g, item.address)
- .replace(/#class-major/, item.deviceClass.majorName)
- .replace(/#class-minor/, item.deviceClass.minorName)
- .replace(/#class-service/, item.deviceClass.servicesName.join(","))
- .replace(/#bonded/, "No")
- .replace(/#trusted/, item.isTrusted ? "Yes" : "No")
- .replace(/#connected/, "No")
- .replace(/#uuids/, uuidsHTML)
- .replace(/#service-uuid/, firstService.uuid)
- .replace(/#service-protocol/, firstService.protocol)
- .replace(/#service-state/, firstService.state || "CLOSED")
- .replace(/#id/g, item.address.replace(/:/g, ""));
+ handleSubFeatures: function (subFeatures) {
+ for (var subFeature in subFeatures) {
+ if (_security[subFeature].length === 0) {
+ _security.all = true;
+ return;
+ }
+ _security.all = false;
+ utils.forEach(_security[subFeature], function (method) {
+ _security[method] = true;
+ });
+ }
+ }
+ };
- btHtmlContent += devicesHTML;
+ messaging.__defineGetter__("TYPE_SMS", function () {
+ return 1;
});
- $("#network-bt-box").accordion("destroy");
- $("#network-bt-box").html(btHtmlContent).accordion({
- active : false,
- collapsible : true,
- autoHeight : false
+ messaging.__defineGetter__("TYPE_MMS", function () {
+ return 2;
});
-}
-
-function _btRemove(index) {
- delete _btSimulatedDevs[index];
- db.saveObject("bt-simulated-devices", _btSimulatedDevs);
- event.trigger("bt-simulated-devices-changed", []);
- _btRender();
-}
-function _bearerRelease(type, idBearer, evNetworkDisconnected) {
- if ($("#bearer-row-" + idBearer).length > 0) {
- $("tr[id='bearer-row-" + idBearer + "']").remove();
- }
+ messaging.__defineGetter__("TYPE_EMAIL", function () {
+ return 3;
+ });
- event.trigger(evNetworkDisconnected);
+ messaging.__defineGetter__("FOLDER_INBOX", function () {
+ return 1;
+ });
- $("#bearer-" + type + " tr:even").css("background-color", "white");
- $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
-}
+ messaging.__defineGetter__("FOLDER_OUTBOX", function () {
+ return 2;
+ });
-module.exports = {
- panel: {
- domId: "network-container",
- collapsed: true,
- pane: "left",
- titleName: "Network Management",
- display: true
- },
- initialize: function () {
- _initializeElements();
+ messaging.__defineGetter__("FOLDER_DRAFTS", function () {
+ return 3;
+ });
- // Events for nfc module
- event.on("nfc-power-changed", function (status) {
- _powered = status;
- if (_powered === true) {
- $("#nfc-power").val("On");
- } else {
- $("#nfc-power").val("Off");
- }
- elementEnableDisableSetting({power: status});
- });
- event.on("nfc-connectedState-changed", function (state) {
- var i, type, isSupportedNDEF, str, bytes = [];
- _isConnected = state;
- elementEnableDisableSetting({connectedState: state});
- type = jQuery("#nfc-type").val();
- if (state) {
- jQuery("#nfc-attach").children().text("Detach");
- jQuery("#nfc-tag-connection").text("Connected");
- jQuery("#nfc-peer-connection").text("Connected");
- if (type === "Tag") {
- isSupportedNDEF = jQuery("#nfc-tag-NDEF-support").val() === "Yes" ? true : false;
- if (isSupportedNDEF) {
- _tagNDEF.type = jQuery("#nfc-tag-type").val();
- db.saveObject(_NFC_TAG, _tagNDEF);
- } else {
- _tagRaw.type = jQuery("#nfc-tag-type").val();
- str = jQuery("#nfc-raw-data").val();
- for (i = 0; i < str.length; i++) {
- bytes.push(str.charCodeAt(i));
- }
- _tagRaw.rawData = bytes;
- db.saveObject(_NFC_TAG, _tagRaw);
- }
- event.trigger("nfc-tag-send", [true]);
- } else {
- event.trigger("nfc-peer-send", [true]);
- }
- } else {
- jQuery("#nfc-attach").children().text("Attach");
- jQuery("#nfc-tag-connection").text("Disconnected");
- jQuery("#nfc-peer-connection").text("Disconnected");
- jQuery("#nfc-output").text("");
- jQuery("#nfc-output-table").hide();
- if (type === "Tag") {
- event.trigger("nfc-tag-send", [false]);
- } else {
- event.trigger("nfc-peer-send", [false]);
- }
- }
- });
- event.on("nfc-output-msg", function () {
- var msg;
- msg = db.retrieve(_NFC_OUTPUT_MESSAGE);
- jQuery("#nfc-output").text(msg);
- jQuery("#nfc-output-table").show();
- });
+ messaging.__defineGetter__("FOLDER_SENTBOX", function () {
+ return 4;
+ });
- // Events for bluetooth module
- event.on("bluetoothPowerState", function (state) {
- if (state) {
- $("#bluetooth-radio1").click();
- } else {
- $("#bluetooth-radio2").click();
- }
- });
- event.on("bt-adapter-name-changed", function (name) {
- $("#bt-adapter-name").text(name);
- });
- event.on("bt-adapter-power-changed", function (state) {
- if (state) {
- $("#bt-adapter-power").text("On");
- } else {
- $("#bt-adapter-power").text("Off");
- }
- });
- event.on("bt-adapter-visible-changed", function (state) {
- if (state) {
- $("#bt-adapter-visible").text("On");
- } else {
- $("#bt-adapter-visible").text("Off");
- }
- });
- event.on("bt-device-bonded-changed", function (addr, isBonded) {
- var str = "No";
- if (isBonded) {
- str = "Yes";
- }
- jQuery("#bonded-" + addr.replace(/:/g, "")).html(str);
- });
- event.on("bt-device-connected-changed", function (addr, isConnected) {
- var str = "No";
- if (isConnected) {
- str = "Yes";
- }
- jQuery("#connected-" + addr.replace(/:/g, "")).html(str);
- });
- event.on("bt-service-state-changed", function (addr, uuid, state) {
- var str = "CLOSED";
- if (state) {
- str = "OPEN";
- }
- _btSimulatedDevs[addr].services[uuid].state = str;
- jQuery("#service-state-" + addr.replace(/:/g, "")).html(str);
- });
- event.on("bt-service-write-msg", function (addr, uuid, data) {
- var msg = "", uuidNow;
- utils.forEach(data, function (char) {
- msg += String.fromCharCode(char);
- });
- uuidNow = jQuery("#network-bt-uuid-" + addr.replace(/:/g, "")).html();
- if (uuidNow === uuid) {
- jQuery("#service-receive-textarea-" + addr.replace(/:/g, "")).html(msg);
- }
- });
+ if (!_initialized)
+ _initialize();
- // Event for network bearer selection module
- event.on("NetworkRequest", function (networkType, domainName) {
- var type = networkType.toLowerCase(), name, idBearer,
- evNetworkOpened = "NO_" + networkType + "_" + domainName,
- evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
+ return messaging;
+};
- if (!$("#bearer-" + type + "-radio1").prop("checked")) {
- event.trigger(evNetworkOpened, [false]);
- event.trigger(evNetworkDisconnected);
+MessageSendCallback = {
+ onsuccess: function () {},
+ onmessagesendsuccess: function (recipient) {},
+ onmessagesenderror: function (error, recipient) {}
+};
- return;
- }
+Message = function (type) {
+ this.id = Math.uuid(null, 16);
+ this.type = type;
+ this.folder = 0;
+ this.timestamp = new Date();
+ this.from = "";
+ this.to = [""];
+ this.cc = [""];
+ this.bcc = [""];
+ this.body = "";
+ this.isRead = false;
+ this.priority = false;
+ this.subject = "";
+ this.attachments = [""];
- name = domainName.replace(/\./, "");
- idBearer = type + '-' + name;
+ this.update = function (successCallback, errorCallback) {
+ function _update() {
+ var isFound = false;
- if ($("#bearer-row-" + idBearer).length <= 0) {
- $("#bearer-" + type).append("<tr id='bearer-row-" + idBearer + "'>" +
- "<td> <lable class='ui-text-label'>" + domainName + "</label></td>" +
- "<td><button id='bearer-btn-" + idBearer + "'>X</button>  </td>" +
- "</tr>");
+ if (!_security.all && !_security.update)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
- $("#bearer-btn-" + idBearer).click(function () {
- _bearerRelease(type, idBearer, evNetworkDisconnected);
- });
+ TypeCoerce(new Message(0)).cast(this);
+ _get();
+ utils.forEach(_messages[this.folder], function (messageItem) {
+ if (messageItem.id === this.id) {
+ !this.isRead || (messageItem.isRead = this.isRead);
+ if (this.folder === _self().FOLDER_DRAFTS) {
+ !this.type || (messageItem.type = this.type);
+ !this.to || (messageItem.to = utils.copy(this.to));
+ !this.cc || (messageItem.cc = utils.copy(this.cc));
+ !this.bcc || (messageItem.bcc = utils.copy(this.bcc));
+ !this.body || (messageItem.body = this.body);
+ !this.priority || (messageItem.priority = this.priority);
+ !this.subject || (messageItem.subject = this.subject);
+ !this.attachments || (messageItem.attachments = utils.copy(this.attachments));
+ }
+ isFound = true;
+ }
+ });
- $("#bearer-" + type + " tr:even").css("background-color", "white");
- $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
+ if (isFound) {
+ _save();
+ successCallback();
+ } else {
+ _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
}
+ }
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "update", _pendingOperate(_update, this));
+ };
+};
- event.trigger(evNetworkOpened, [true]);
- });
+MessageFilter = {
+ id: "",
+ type: [0],
+ folder: [0],
+ startTimestamp: new Date(),
+ endTimestamp: new Date(),
+ from: "",
+ to: [""],
+ cc: [""],
+ bcc: [""],
+ body: "",
+ isRead: false,
+ messagePriority: false,
+ subject: ""
+};
- event.on("NetworkRelease", function (networkType, domainName) {
- var type = networkType.toLowerCase(),
- name = domainName.replace(/\./, ""),
- idBearer = type + '-' + name,
- evNetworkDisconnected = "ND_" + networkType + "_" + domainName;
+Recipients = function () {
+ this.to = [];
+ this.cc = [];
+ this.bcc = [];
- _bearerRelease(type, idBearer, evNetworkDisconnected);
- });
+ this.total = function () {
+ return (this.to.length + this.cc.length + this.bcc.length);
+ };
+};
- // Update UI for Flight Mode changing
- event.on("FlightModeChanged", function (value) {
- if (value === true) {
- $("#cellular-radio1").prop('disabled', true);
- $("#cellular-radio2").prop('disabled', true);
- $("#panel_flight_mode_notice").show();
- }
- else {
- $("#cellular-radio1").prop('disabled', false);
- $("#cellular-radio2").prop('disabled', false);
- $("#panel_flight_mode_notice").hide();
- }
+event.on("MessageReceived", function (message) {
+ var onMessage;
- $("#cellular-radio1").button("refresh");
- $("#cellular-radio2").button("refresh");
- });
+ switch (message.type) {
+ case "sms":
+ message.type = _self().TYPE_SMS;
+ onMessage = "onSMS";
+ break;
- $("#bt-adapter-name").text(db.retrieveObject("tizen1-db-bluetooth_adapter-name") || "Tizen BT Adapter");
- _btDeviceTemplate = $("#network-bt-template").html();
- $("#network-bt-box").empty();
- btNodes = jQuery("#network-bt-device-select");
- btNodes.html("");
+ case "mms":
+ message.type = _self().TYPE_MMS;
+ onMessage = "onMMS";
+ break;
- //_btBluetoothDB = dbinit.Bluetooth;
- _btBluetoothDB = db.retrieveObject("bt-simulated-devices");
- utils.forEach(_btBluetoothDB, function (item, index) {
- btNodes.append(utils.createElement("option", {
- "value": index,
- "innerText": item.name
- }));
- });
+ case "email":
+ message.type = _self().TYPE_EMAIL;
+ onMessage = "onEmail";
+ break;
- jQuery("#network-bt-nearby-btn").click(function () {
- var index;
- index = jQuery("#network-bt-device-select").val();
- if (_btSimulatedDevs[index]) {
- return;
- }
- _btSimulatedDevs[index] = _btBluetoothDB[index];
- db.saveObject("bt-simulated-devices", _btSimulatedDevs);
- event.trigger("bt-simulated-devices-changed", []);
- _btRender();
- });
- $(".network-bt-remove-btn").live("click", function () {
- _btRemove(this.id);
- });
- $(".network-bt-send-btn").live("click", function () {
- var msg = jQuery("#service-transfer-textarea-" + this.id.replace(/:/g, "")).val(),
- uuid = jQuery("#network-bt-uuid-" + this.id.replace(/:/g, "")).html();
- event.trigger("bt-service-rawdata-received", [this.id, uuid, msg]);
- });
- $(".network-bt-service-select").live("change", function () {
- var uuid = this.children[this.selectedIndex].value,
- index = this.id,
- addr,
- service;
- addr = index.replace(/:/g, "");
- service = _btSimulatedDevs[index].services[uuid];
- jQuery("#network-bt-uuid-" + index.replace(/:/g, "")).html(service.uuid);
- jQuery("#network-bt-protocol-" + index.replace(/:/g, "")).html(service.protocol);
- jQuery("#service-state-" + index.replace(/:/g, "")).html(service.state || "CLOSED");
- jQuery("#service-transfer-textarea-" + addr).val("");
- jQuery("#service-receive-textarea-" + addr).html("");
- });
+ default:
+ break;
+ }
- //Default "Tizen Phone" is nearby
- //_btSimulatedDevs["00:02:60:00:05:63"] = _btBluetoothDB["00:02:60:00:05:63"];
- for (var address in _btBluetoothDB) {
- _btSimulatedDevs[address] = _btBluetoothDB[address];
- break;
- }
+ message.folder = _self().FOLDER_INBOX;
+ _processAttachments(message);
+ _updateDB(message);
+ utils.forEach(_subscriber[onMessage], function (subscriberCallback) {
+ subscriberCallback(message);
+ });
+});
- db.saveObject("bt-simulated-devices", _btSimulatedDevs);
- _btRender();
- }
-};
+event.on("MessageSent", function (sentStatus) {
+ _sentStatus = sentStatus;
+});
+
+module.exports = _self;
});
-define('ripple/ui/plugins/nfc', function (require, exports, module) {
+define('ripple/platform/wac/2.0/spec', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var db = require('ripple/db'),
- event = require('ripple/event'),
- _NFC_TAG = "tizen1.0-nfc-tag",
- _NFC_PEER = "tizen1.0-nfc-peer",
- _NFC_OUTPUT_MESSAGE = "tizen1.0-nfc-output-message",
- powered = false,
- polling = false,
- isConnected = false,
- _tagNDEF = {
- type: "GENERIC_TARGET",
- isSupportedNDEF: true,
- ndefSize: 2,
- ndefs: [{
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID001",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID002",
- payload: "This is 2nd payload"
- }]
- },
- {
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID001",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID002",
- payload: "This is 2nd payload"
- }]
- }]
- },
- _tagRaw = {
- type: "GENERIC_TARGET",
- isSupportedNDEF: false,
- rawData : ""
- },
- _peerNDEF = {
- ndef: {
- recordCount: 2,
- records: [{
- tnf: 1,
- type: "TypeA",
- id: "ID001",
- payload: "This is 1st payload"
- }, {
- tnf: 1,
- type: "TypeA",
- id: "ID002",
- payload: "This is 2nd payload"
- }]
- }
- };
-
-function elementEnableDisableSetting(prop) {
- jQuery("#nfc-attach-msg").text("\xa0");
- jQuery("#nfc-peer-send-msg").text("\xa0");
- if (prop && prop.power !== undefined && prop.power !== null) {
- if (prop.power) {
- $("#nfc-polling").removeAttr("disabled");
- $("#nfc-main-container").show();
- } else {
- $("#nfc-polling").attr("disabled", "disabled");
- $("#nfc-type").removeAttr("disabled");
- $("#nfc-main-container").hide();
- }
- }
- if (prop && prop.connectedState !== undefined && prop.connectedState !== null) {
- if (prop.connectedState) {
- $("#nfc-type").attr("disabled", "disabled");
- $("#nfc-tag-type-text").text($("#nfc-tag-type option:selected").text());
- $("#nfc-tag-type").hide();
- $("#nfc-tag-type-text").show();
- $("#nfc-tag-NDEF-support-text").text($("#nfc-tag-NDEF-support option:selected").text());
- $("#nfc-tag-NDEF-support").hide();
- $("#nfc-tag-NDEF-support-text").show();
- $("#nfc-raw-data").attr("disabled", "disabled");
- } else {
- $("#nfc-type").removeAttr("disabled");
- $("#nfc-tag-type").show();
- $("#nfc-tag-type-text").hide();
- $("#nfc-tag-NDEF-support").show();
- $("#nfc-tag-NDEF-support-text").hide();
- $("#nfc-raw-data").removeAttr("disabled");
- }
- }
-}
-
-function _initializeElements() {
+module.exports = {
- jQuery(function () {
- var stop = false,
- isSupportNDEF, type;
+ id: "wac",
+ version: "2.0",
+ name: "WAC",
- jQuery("nfc-tag-ndef-container h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
- }
- });
- jQuery("#nfc-tag-ndef-container").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
- });
- jQuery("nfc-nfcpeer h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
- }
- });
- jQuery("#nfc-nfcpeer").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
- });
- jQuery("#nfc-tag-NDEF-support").bind("change", function () {
- isSupportNDEF = jQuery("#nfc-tag-NDEF-support").val();
- if (isSupportNDEF === "Yes") {
- jQuery("#nfc-tag-ndef-container").fadeIn();
- jQuery("#nfc-tag-raw-container").hide();
- } else {
- jQuery("#nfc-tag-ndef-container").hide();
- jQuery("#nfc-tag-raw-container").fadeIn();
- }
- });
- jQuery("#nfc-type").bind("change", function () {
- type = jQuery("#nfc-type").val();
- if (type === "Tag") {
- jQuery("#nfc-nfctag").fadeIn();
- jQuery("#nfc-nfcpeer").hide();
- } else {
- jQuery("#nfc-nfctag").hide();
- jQuery("#nfc-nfcpeer").fadeIn();
- }
- elementEnableDisableSetting();
- });
- jQuery("#nfc-power").bind("change", function () {
- var status;
- status = jQuery("#nfc-power").val() === "On" ? true : false;
- event.trigger("nfc-power-setting", [status]);
- });
- jQuery("#nfc-polling").bind("change", function () {
- var status;
- status = jQuery("#nfc-polling").val() === "On" ? true : false;
- event.trigger("nfc-polling-setting", [status]);
- });
- jQuery("#nfc-attach").bind("click", function () {
- var type, isAttached;
- isAttached = jQuery("#nfc-attach").children().text() === "Attach" ? true : false;
- jQuery("#nfc-attach-msg").text("\xa0");
+ persistencePrefix: "wac2-",
- if (!polling && isAttached) {
- jQuery("#nfc-attach-msg").text("Polling:Off, attach won't work");
- return;
- }
- type = jQuery("#nfc-type").val();
- event.trigger("nfc-attach-setting", [type, isAttached]);
- });
- jQuery("#nfc-peer-send").bind("click", function () {
- jQuery("#nfc-peer-send-msg").text("\xa0");
- if (!isConnected) {
- jQuery("#nfc-peer-send-msg").text("Disconnected. Send won't work");
- return;
- }
- db.saveObject(_NFC_PEER, _peerNDEF);
- event.trigger("nfc-peer-sending-ndef", []);
- });
- });
-}
+ config: require('ripple/platform/wac/2.0/spec/config'),
+ ui: require('ripple/platform/wac/2.0/spec/ui'),
+ device: require('ripple/platform/wac/2.0/spec/device'),
-module.exports = {
- panel: {
- domId: "nfc-container",
- collapsed: true,
- pane: "left",
- titleName: "NFC",
- display: true
- },
- initialize: function () {
- _initializeElements();
- event.on("nfc-power-changed", function (status) {
- powered = status;
- if (powered === true) {
- $("#nfc-power").val("On");
- } else {
- $("#nfc-power").val("Off");
- }
- elementEnableDisableSetting({power: status});
- });
- event.on("nfc-polling-changed", function (status) {
- polling = status;
- if (polling === true) {
- $("#nfc-polling").val("On");
- } else {
- $("#nfc-polling").val("Off");
+ objects: {
+ Coordinates: {
+ path: "w3c/1.0/Coordinates"
+ },
+ Position: {
+ path: "w3c/1.0/Position"
+ },
+ PositionError: {
+ path: "w3c/1.0/PositionError"
+ },
+ navigator: {
+ path: "w3c/1.0/navigator",
+ children: {
+ geolocation: {
+ path: "wac/2.0/geolocation",
+ feature: "http://www.w3.org/TR/geolocation-API/"
+ }
}
- elementEnableDisableSetting();
- });
- event.on("nfc-connectedState-changed", function (state) {
- var i, type, isSupportedNDEF, str, bytes = [];
- isConnected = state;
- elementEnableDisableSetting({connectedState: state});
- type = jQuery("#nfc-type").val();
- if (state) {
- jQuery("#nfc-attach").children().text("Detach");
- jQuery("#nfc-tag-connection").text("Connected");
- jQuery("#nfc-peer-connection").text("Connected");
- if (type === "Tag") {
- isSupportedNDEF = jQuery("#nfc-tag-NDEF-support").val() === "Yes" ? true : false;
- if (isSupportedNDEF) {
- _tagNDEF.type = jQuery("#nfc-tag-type").val();
- db.saveObject(_NFC_TAG, _tagNDEF);
- } else {
- _tagRaw.type = jQuery("#nfc-tag-type").val();
- str = jQuery("#nfc-raw-data").val();
- for (i = 0; i < str.length; i++) {
- bytes.push(str.charCodeAt(i));
+ },
+ deviceapis: {
+ path: "wac/2.0/deviceapis",
+ feature: "http://wacapps.net/api/deviceapis",
+ /*
+ * Before we inject those cloned objects into the simulated application
+ * namespace, we will handle the feature requests from config.xml.
+ * Especially for:
+ * - camera.show, camera.capture
+ * - devicestatus.deviceinfo, devicestatus.networkinfo
+ * - filesystem.read, filesystem.write
+ * - messaging.send, messaging.find, messaging.subscribe, messaging.write
+ * - pim
+ * - contact.read, contact.write
+ * - calendar.read, calendar.write
+ * - task.read, task.write
+ */
+ children: {
+ accelerometer: {
+ path: "wac/2.0/accelerometer",
+ feature: "http://wacapps.net/api/accelerometer"
+ },
+ orientation: {
+ path: "wac/2.0/orientation",
+ feature: "http://wacapps.net/api/orientation"
+ },
+ camera: {
+ path: "wac/2.0/camera",
+ feature: "http://wacapps.net/api/camera|http://wacapps.net/api/camera.show|http://wacapps.net/api/camera.capture",
+ handleSubfeatures: true
+ },
+ devicestatus: {
+ path: "wac/2.0/devicestatus",
+ feature: "http://wacapps.net/api/devicestatus|http://wacapps.net/api/devicestatus.deviceinfo|http://wacapps.net/api/devicestatus.networkinfo",
+ handleSubfeatures: true
+ },
+ filesystem: {
+ path: "wac/2.0/filesystem",
+ feature: "http://wacapps.net/api/filesystem|http://wacapps.net/api/filesystem.read|http://wacapps.net/api/filesystem.write",
+ handleSubfeatures: true
+ },
+ messaging: {
+ path: "wac/2.0/messaging",
+ feature: "http://wacapps.net/api/messaging|http://wacapps.net/api/messaging.send|http://wacapps.net/api/messaging.find|http://wacapps.net/api/messaging.subscribe|http://wacapps.net/api/messaging.write",
+ handleSubfeatures: true
+ },
+ pim: {
+ children: {
+ contact: {
+ path: "wac/2.0/contact",
+ feature: "http://wacapps.net/api/pim.contact|http://wacapps.net/api/pim.contact.read|http://wacapps.net/api/pim.contact.write",
+ handleSubfeatures: true
+ },
+ calendar: {
+ path: "wac/2.0/calendar",
+ feature: "http://wacapps.net/api/pim.calendar.write|http://wacapps.net/api/pim.calendar.read|http://wacapps.net/api/pim.calendar",
+ handleSubfeatures: true
+ },
+ task: {
+ path: "wac/2.0/task",
+ feature: "http://wacapps.net/api/pim.task|http://wacapps.net/api/pim.task.read|http://wacapps.net/api/pim.task.write",
+ handleSubfeatures: true
}
- _tagRaw.rawData = bytes;
- db.saveObject(_NFC_TAG, _tagRaw);
}
- event.trigger("nfc-tag-send", [true]);
- } else {
- event.trigger("nfc-peer-send", [true]);
- }
- } else {
- jQuery("#nfc-attach").children().text("Attach");
- jQuery("#nfc-tag-connection").text("Disconnected");
- jQuery("#nfc-peer-connection").text("Disconnected");
- jQuery("#nfc-output").text("");
- jQuery("#nfc-output-table").hide();
- if (type === "Tag") {
- event.trigger("nfc-tag-send", [false]);
- } else {
- event.trigger("nfc-peer-send", [false]);
+ },
+ deviceinteraction: {
+ path: "wac/2.0/deviceinteraction",
+ feature: "http://wacapps.net/api/deviceinteraction"
}
}
- });
- event.on("nfc-output-msg", function () {
- var msg;
- msg = db.retrieve(_NFC_OUTPUT_MESSAGE);
- jQuery("#nfc-output").text(msg);
- jQuery("#nfc-output-table").show();
- });
+ }
}
};
});
-define('ripple/ui/plugins/notifications', function (require, exports, module) {
+define('ripple/platform/wac/2.0/task', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
var db = require('ripple/db'),
utils = require('ripple/utils'),
- event = require('ripple/event'),
- _notificationUIStack,
- _notificationTemplate = "";
+ _console = require('ripple/console'),
+ exception = require('ripple/exception'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ Task, TaskList, _get,
+ _ID_WITHOUT = 0, _ID_GEN_NEW = 1, _ID_FROM_PROP = 2,
+ _SIM_TASK_LIST = 0, _DEVICE_TASK_LIST = 1,
+ _HIGH_PRIORITY = 0, _MEDIUM_PRIORITY = 1, _LOW_PRIORITY = 2,
+ _STATUS_COMPLETED = 0, _STATUS_NEEDS_ACTION = 1, _STATUS_IN_PROCESS = 2, _STATUS_CANCELLED = 3,
+ _TASK_OBJECTS = "wac2.0-pim-task-objects",
+ _addTaskAllowed = true, _deleteTaskAllowed = true,
+ _updateTaskAllowed = true, _findTasksAllowed = true;
-function _remove(id) {
- delete _notificationUIStack[id];
- db.saveObject("posted-notifications", _notificationUIStack);
- event.trigger("refreshNotificationStack", [], true);
- _render();
-}
-function _removeAll() {
- _notificationUIStack = {};
- db.saveObject("posted-notifications", _notificationUIStack);
- event.trigger("refreshNotificationStack", [], true);
- $("#notification-box").empty();
- $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
- $("#remove-all-notifications-btn").hide();
-}
+module.exports = function () {
+ var _taskListArray = [],
+ _PENDING_TIME = 10;
-function _render() {
- var notificationHTML = "",
- htmlContent = "";
+ function _pendingOperate(operate) {
+ var pendingObj, pendingOperation, i, argumentVector = [];
- utils.forEach(_notificationUIStack, function (item) {
- notificationHTML = _notificationTemplate.replace(/#id/g, item.id)
- .replace(/#title/g, item.title)
- .replace(/#content/, item.content ? item.content : "")
- .replace(/#type/, item.type)
- .replace(/#statusType/, item.statusType)
- .replace(/#postedTime/, item.postedTime)
- .replace(/#iconPath/, item.iconPath ? item.iconPath : "")
- .replace(/#subIconPath/, item.subIconPath ? item.subIconPath : "")
- .replace(/#number/, item.number ? item.number : "")
- .replace(/#detailInfo/, item.detailInfo ? item.detailInfo.join() : "")
- .replace(/#backgroundImagePath/, item.backgroundImagePath ? item.backgroundImagePath : "")
- .replace(/#thumbnails/, item.thumbnails ? item.thumbnails.join() : "")
- .replace(/#soundPath/, item.soundPath ? item.soundPath : "")
- .replace(/#vibration/, item.vibration !== undefined ? (item.vibration === true ? "true" : "false") : "")
- .replace(/#appControl/, item.appControl ? item.appControl : "")
- .replace(/#appId/, item.appId ? item.appId : "")
- .replace(/#progressType/g, item.progressType ? item.progressType: "")
- .replace(/#progressValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue.toString() + "%" : "")
- .replace(/#progressBarValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue : 0)
- .replace(/#progress2Value/, (item.statusType === "PROGRESS" && item.progressType === "BYTE" && item.progressValue) ? item.progressValue.toString() + " byte(s)" : "")
- .replace(/#displayBar/g, (item.statusType !== "PROGRESS" || item.progressType !== "PERCENTAGE") ? "none" : "")
- .replace(/#display2Bar/g, (item.statusType !== "PROGRESS" || item.progressType !== "BYTE") ? "none" : "");
- htmlContent += notificationHTML;
- });
+ for (i = 0; i < arguments.length - 1; i++)
+ argumentVector[i] = arguments[i + 1];
- $("#notification-box").accordion("destroy");
- $("#notification-box").html(htmlContent).accordion({
- active : false,
- collapsible : true,
- autoHeight : false
- });
+ pendingObj = new PendingObject();
- $("#notification-box .progress-bar").each(function (index, item) {
- $(item).width(this.id);
- });
- if (utils.count(_notificationUIStack) !== 0) {
- $("#remove-all-notifications-btn").show();
- } else {
- $("#remove-all-notifications-btn").hide();
- }
- $("." + "remove-notification-btn").bind("click", function () {
- _remove(this.id);
- });
-}
+ pendingObj.pendingID = window.setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ operate.apply(this, argumentVector);
+ }, _PENDING_TIME);
-module.exports = {
- panel: {
- domId: "notification-container",
- collapsed: true,
- pane: "left",
- titleName: "Notification",
- display: true
- },
- initialize: function () {
- _notificationTemplate = $("#notification-template").html();
- $("#notification-box").empty();
- _notificationUIStack = db.retrieveObject("posted-notifications") || {};
- if (utils.count(_notificationUIStack) === 0) {
- $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
- }
- else
- _render();
- $("#remove-all-notifications-btn").bind("click", _removeAll);
+ pendingOperation = new PendingOperation(pendingObj);
- event.on("refreshNotificationUI", function () {
- _notificationUIStack = db.retrieveObject("posted-notifications");
- _render();
- });
+ return pendingOperation;
}
-};
-
-});
-define('ripple/ui/plugins/omnibar', function (require, exports, module) {
-/*
- * Copyright 2011 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 emulatorBridge = require('ripple/emulatorBridge'),
- platform = require('ripple/platform'),
- db = require('ripple/db'),
- utils = require('ripple/utils'),
- devices = require('ripple/devices'),
- constants = require('ripple/constants'),
- _event = require('ripple/event'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- histories = [];
-
-function _omnibar() {
- return document.querySelector(".omni-bar input");
-}
-
-function _persist(url) {
- db.save("current-url", url);
-}
-function _persistRoot(url) {
- db.save("root-url", url);
-}
+ /* taskProperties attribute check & paste */
+ function _checkAndPasteProperties(p, dst) {
-function _currentURL() {
- return db.retrieve("current-url") || "about:blank";
-}
+ if (p.summary !== null && p.summary !== undefined)
+ dst.summary = String(p.summary);
-function _rootURL() {
- return db.retrieve("root-url") || "about:blank";
-}
+ if (p.description !== null && p.description !== undefined)
+ dst.description = String(p.description);
-function _reload() {
- _event.trigger("ApplicationLoad", null);
- emulatorBridge.window().location.reload();
-}
+ if (p.status !== null && p.status !== undefined) {
+ if (p.status === _STATUS_COMPLETED ||
+ p.status === _STATUS_NEEDS_ACTION ||
+ p.status === _STATUS_IN_PROCESS ||
+ p.status === _STATUS_CANCELLED) {
+ dst.status = p.status;
+ } else
+ return false;
+ }
-function _loadApplication() {
- var omnibar = _omnibar(),
- xhr;
- if (omnibar.value.trim() !== "") {
- if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
- xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- if (xhr.responseText !== '') {
- _persist(omnibar.value);
- _persistRoot(omnibar.value);
- emulatorBridge.window().location.assign(omnibar.value);
- } else {
- alert("File doesn't exist!");
- return;
- }
- }
- };
- xhr.open('GET', omnibar.value, true);
- xhr.send(null);
- } else {
- omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
- _persist(omnibar.value);
- _persistRoot(omnibar.value);
- emulatorBridge.window().location.assign(omnibar.value);
+ if (p.priority !== null && p.priority !== undefined) {
+ if (p.priority === _HIGH_PRIORITY ||
+ p.priority === _MEDIUM_PRIORITY ||
+ p.priority === _LOW_PRIORITY) {
+ dst.priority = p.priority;
+ } else
+ return false;
}
- _addHistory(omnibar.value);
- }
- _event.trigger("ApplicationLoad", null);
-}
-function _hideHistory() {
- $("#app-launching-history").hide("slide", {direction: "up"}, "fast");
- $("#overlayBackground-transparent").hide();
-}
+ if (p.dueDate !== null && p.dueDate !== undefined) {
+ if (!wac2_utils.isValidDate(p.dueDate))
+ return false;
+ dst.dueDate = new Date(p.dueDate);
+ }
-function _makeHistoryItems() {
- histories = db.retrieveObject(constants.LAUNCHING_HISTORY);
- if (histories === undefined) {
- histories = [];
- }
- $("#app-launching-history").empty();
- histories.reverse();
- histories.forEach(function (item) {
- $("#app-launching-history").append('<div class="app-launching-history-item">' + item + '</div>');
- });
+ /* dueDate is a option properties.
+ "The default value is undefined.
+ If no value is provided, the task has no due date."
+ If p.dueDate is set its default value 'undefined',
+ we assign default value to dst.dueDate */
+ if (p.dueDate === undefined) {
+ dst.dueDate = undefined;
+ }
- if (histories.length === 0) {
- $("#app-launching-history").append('<div class="app-launching-history-item-empty">History empty</div>');
+ return true;
}
- $(".app-launching-history-item").unbind('click');
- $(".app-launching-history-item").bind("click", function () {
- $(".omni-bar input").val(histories[$(this).index()]);
- _loadApplication();
- _hideHistory();
- });
-}
+ function _taskFilterCheck(filter) {
+ var i;
+ if (filter.id !== undefined && filter.id !== null) {
+ filter.id = String(filter.id);
+ } else {
+ filter.id = undefined;
+ }
+ if (filter.summary !== undefined && filter.summary !== null) {
+ filter.summary = String(filter.summary);
+ } else {
+ filter.summary = undefined;
+ }
+ if (filter.description !== undefined && filter.description !== null) {
+ filter.description = String(filter.description);
+ } else {
+ filter.description = undefined;
+ }
+ if (filter.status !== undefined && filter.status !== null) {
+ if (!wac2_utils.isValidArray(filter.status)) {
+ return false;
+ }
+ for (i = 0; i < filter.status.length; i++) {
+ filter.status[i] = filter.status[i] | 0;
+ if (filter.status[i] !== _STATUS_COMPLETED &&
+ filter.status[i] !== _STATUS_NEEDS_ACTION &&
+ filter.status[i] !== _STATUS_IN_PROCESS &&
+ filter.status[i] !== _STATUS_CANCELLED) {
+ return false;
+ }
+ }
+ } else {
+ filter.status = undefined;
+ }
+ if (filter.priority !== undefined && filter.priority !== null) {
+ if (!wac2_utils.isValidArray(filter.priority)) {
+ return false;
+ }
+ for (i = 0; i < filter.priority.length; i++) {
+ filter.priority[i] = filter.priority[i] | 0;
+ if (filter.priority[i] !== _HIGH_PRIORITY &&
+ filter.priority[i] !== _MEDIUM_PRIORITY &&
+ filter.priority[i] !== _LOW_PRIORITY) {
+ return false;
+ }
+ }
+ } else {
+ filter.priority = undefined;
+ }
+ if (filter.dueDate !== undefined && filter.dueDate !== null) {
+ if (!wac2_utils.isValidDate(filter.dueDate)) {
+ return false;
+ }
+ filter.dueDate = new Date(filter.dueDate);
+ } else {
+ filter.dueDate = undefined;
+ }
+ return true;
+ }
+ function TaskProperties(prop) {
+ var _self;
+ _self = {
+ priority : _LOW_PRIORITY,
+ description : "",
+ summary : "",
+ dueDate : undefined,
+ status : _STATUS_NEEDS_ACTION
+ };
+ if (prop) {
+ if (_checkAndPasteProperties(prop, _self) === false)
+ return undefined;
+ }
+ return _self;
+ }
-function _showHistory() {
- _makeHistoryItems();
- $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
- $("#app-launching-history").show("slide", {direction: "up"}, "fast");
- $(window).bind('resize', function () {
- $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
- $("#overlayBackground-transparent").css("width", $(window).width());
- $("#overlayBackground-transparent").css("height", $(window).height());
- });
+ function Task(prop, idChoice) {
+ var id, _self = new TaskProperties(prop);
+ /* if error occurs during checking, _self is an empty object.
+ so i randomly pick description to check if property check fails */
+ if (_self.description === undefined)
+ return undefined;
- $("#history-background-overlay").show();
- $("#overlayBackground-transparent").css("width", $(window).width());
- $("#overlayBackground-transparent").css("height", $(window).height());
- $("#overlayBackground-transparent").show();
- $("#overlayBackground-transparent").unbind('click');
- $("#overlayBackground-transparent").bind("click", function () {
- _hideHistory();
- });
-}
+ switch (idChoice) {
+ case _ID_WITHOUT:
+ // do nothing
+ break;
+ case _ID_GEN_NEW:
+ id = Math.uuid(undefined, 16);
+ _self.__defineGetter__("id", function () {
+ return id;
+ });
+ break;
+ case _ID_FROM_PROP:
+ id = String(prop.id);
+ _self.__defineGetter__("id", function () {
+ return id;
+ });
+ break;
+ }
+ return _self;
+ }
-function _addHistory(uri) {
- var i = 0, thehistories = db.retrieveObject(constants.LAUNCHING_HISTORY);
- if (thehistories !== undefined) {
- for (i; i < thehistories.length; i++) {
- if (uri === thehistories[i]) {
- return;
+ function _get() {
+ var taskListArray = [],
+ data = db.retrieveObject(_TASK_OBJECTS);
+ utils.forEach(data, function (taskList) {
+ for (var t in taskList._list) {
+ if (taskList._list[t].dueDate !== undefined &&
+ taskList._list[t].dueDate !== null)
+ taskList._list[t].dueDate = new Date(taskList._list[t].dueDate);
}
+ taskListArray.push(new TaskList(taskList._list, taskList.type, taskList.name));
+ });
+
+ /* add default taskList if taskListArray is empty */
+ if (taskListArray.length === 0) {
+ taskListArray = [new TaskList({}, 0, "Office tasks"), new TaskList({}, 1, "Home tasks")];
}
- if (thehistories.length >= 20) {
- thehistories.reverse();
- thehistories.pop();
- thehistories.reverse();
- }
- } else {
- thehistories = [];
+
+ return taskListArray;
}
- thehistories.push(uri);
- db.saveObject(constants.LAUNCHING_HISTORY, thehistories);
-}
-_event.on("FrameHistoryChange", function (url) {
- _omnibar().value = url;
- _persist(url);
- _persistRoot(url);
-});
+ function _save() {
+ db.saveObject(_TASK_OBJECTS, _taskListArray);
+ }
-module.exports = {
- initialize: function () {
- var omnibar = _omnibar(), loc, tmp,
- url, filename, matching, deviceId,
- xhr, uriParams, platformName, platformVersion, newUrl;
+ function TaskList(taskList, type, name) {
+ var task;
+ this._list = taskList;
+ this.type = type;
+ this.name = name;
- jQuery(".logo, .beta, .left, .right, .left-panel-collapse, .right-panel-collapse").css({
- "marginTop": "35px"
- });
+ this.createTask = function (properties) {
+ task = new Task(properties, _ID_WITHOUT);
+ /* if error occurs during checking, task is an empty object.
+ so i randomly pick summary to check if property check fails */
+ if (task.summary === undefined) {
+ exception.raise(exception.types.Argument,
+ "EventProperties: input parameter contains invalid values",
+ new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ return undefined;
+ }
+ return task;
+ };
- jQuery("#settings-xhr-proxy").parent().parent().hide();
+ this.addTask = function (onSuccess, onError, task) {
+ var inner = this,
+ newTask, _task = Object(task);
+ function _addTask() {
+ var ret;
+ if (!_addTaskAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ newTask = new Task(_task, _ID_GEN_NEW);
+ /* if error occurs during checking, newTask is an empty object.
+ so i randomly pick id to check if property check fails */
+ if (newTask.id === undefined) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ ret = _pendingOperate(function () {
+ inner._list[newTask.id] = newTask;
+ _save();
+ onSuccess(new Task(newTask, _ID_FROM_PROP));
+ });
+ }
- $(".omni-bar").show();
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "addTask", _addTask);
+ };
- uriParams = utils.getURIParams(document.documentURI);
- if (uriParams.url !== undefined) {
- url = uriParams.url;
- if (url.match(/^\.[\.]?/) !== null) {
- loc = document.location;
- filename = loc.pathname.replace(/^.*[\\\/]/, '');
- matching = new RegExp(filename, "g");
- tmp = loc.protocol + "//" + loc.hostname + loc.pathname.replace(matching, "") + url;
- url = tmp;
- }
- _persist(url);
- _persistRoot(url);
- require('ripple/widgetConfig').initialize();
- require('ripple/ui/plugins/widgetConfig').initialize();
- }
+ this.updateTask = function (onSuccess, onError, task) {
+ var inner = this,
+ newTask, _task = Object(task);
+ function _updateTask() {
+ var ret;
+ if (!_updateTaskAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- omnibar.value = _currentURL();
+ if (_checkAndPasteProperties(_task, _task) === false) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- omnibar.addEventListener("keydown", function (event) {
- if (event.keyCode === '13' || event.keyCode === 13 || event.keyCode === '0' || event.keyCode === 0) { // enter or return
- if (omnibar.value.trim() !== "") {
- if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
- xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- if (xhr.responseText !== '') {
- _persist(omnibar.value);
- _persistRoot(omnibar.value);
- emulatorBridge.window().location.assign(omnibar.value);
- } else {
- alert("File doesn't exist!");
- return;
- }
- }
- };
- xhr.open('GET', omnibar.value, true);
- xhr.send(null);
+ ret = _pendingOperate(function () {
+ if (inner._list[_task.id]) {
+ newTask = new Task(inner._list[_task.id], _ID_FROM_PROP);
+ /* Don't need to double check the return of _checkAndPasteProperties
+ _task has been checked & pasted already */
+ _checkAndPasteProperties(_task, newTask);
+ inner._list[newTask.id] = newTask;
+ _save();
+ onSuccess();
} else {
- //default the protocal if not provided
- omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
- _persist(omnibar.value);
- _persistRoot(omnibar.value);
- emulatorBridge.window().location.assign(omnibar.value);
+ if (onError) {
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }
}
- _event.trigger("ApplicationLoad", null);
- _addHistory(omnibar.value);
- }
+ });
+ return ret;
}
- });
- window.addEventListener("keydown", function (event) {
- var hasMetaOrAltPressed = (event.metaKey || event.ctrlKey),
- key = parseInt(event.keyCode, 10);
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "updateTask", _updateTask);
+ };
- if (key === 82 && hasMetaOrAltPressed) { // cmd/ctrl + r
- event.preventDefault();
- _reload();
+ this.deleteTask = function (onSuccess, onError, id) {
+ var inner = this;
+ function _deleteTask() {
+ var ret;
+ /* according to spec "If any of the input parameters are not
+ compatible with the expected type for that parameter,
+ a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be
+ synchronously thrown." so an error is raised synchronously */
+ utils.validateArgumentType(id, "string", null,
+ "Task:deleteTask: " + " invalid id parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ if (!_deleteTaskAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ ret = _pendingOperate(function () {
+ if (inner._list[id]) {
+ delete inner._list[id];
+ _save();
+ onSuccess();
+ } else {
+ if (onError)
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }
+ });
+ return ret;
}
- if (key === 116) { // F5
- event.preventDefault();
- _reload();
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteTask", _deleteTask);
+ };
+
+ this.findTasks = function (onSuccess, onError, filter) {
+ var inner = this, _filter = Object(filter), tmp = [], rst = [], valid_tmp = false;
+ function _findTasks() {
+ var ret;
+ if (!_taskFilterCheck(_filter)) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (!_findTasksAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ ret = _pendingOperate(function () {
+ var i, e;
+ if (_filter.id !== undefined) {
+ tmp = wac2_utils.matchOptionString(inner._list, "id", _filter.id);
+ valid_tmp = true;
+ }
+ if (_filter.summary !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionString(tmp, "summary", _filter.summary);
+ } else {
+ tmp = wac2_utils.matchOptionString(inner._list, "summary", _filter.summary);
+ valid_tmp = true;
+ }
+ }
+ if (_filter.description !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionString(tmp, "description", _filter.description);
+ } else {
+ tmp = wac2_utils.matchOptionString(inner._list, "description", _filter.description);
+ valid_tmp = true;
+ }
+ }
+ if (_filter.status !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionShortArray(tmp, "status", _filter.status);
+ } else {
+ tmp = wac2_utils.matchOptionShortArray(inner._list, "status", _filter.status);
+ valid_tmp = true;
+ }
+ }
+ if (_filter.priority !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionShortArray(tmp, "priority", _filter.priority);
+ } else {
+ tmp = wac2_utils.matchOptionShortArray(inner._list, "priority", _filter.priority);
+ valid_tmp = true;
+ }
+ }
+ if (_filter.initialDueDate !== undefined ||
+ _filter.endDueDate !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionDate(tmp, "dueDate", _filter.initialDueDate, _filter.endDueDate);
+ } else {
+ tmp = wac2_utils.matchOptionDate(inner._list, "dueDate", _filter.initialDueDate, _filter.endDueDate);
+ valid_tmp = true;
+ }
+ }
+
+ if (valid_tmp) {
+ for (i = 0; i < tmp.length; i++) {
+ rst.push(new Task(tmp[i], _ID_FROM_PROP));
+ }
+ } else {
+ for (e in inner._list) {
+ rst.push(new Task(inner._list[e], _ID_FROM_PROP));
+ }
+ }
+ onSuccess(rst);
+ });
+ return ret;
}
- });
- document.getElementById("history-reload").addEventListener("click", _reload);
- $("#options-button-history").bind("click", function () {
- _showHistory();
- });
- tooltip.create("#history-reload", "Reload Application");
- tooltip.create("#options-button-history", "History");
- tooltip.create("#options-button-config-window", "Configuration");
- tooltip.create("#options-button-panels", "Panel Settings");
- tooltip.create("#options-button-about", "About");
- },
- currentURL: function () {
- return _currentURL();
- },
- rootURL: function () {
- return _rootURL();
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "findTasks", _findTasks);
+ };
}
+
+ this.getTaskLists = function (onSuccess, onError) {
+ function _getTaskLists() {
+ var ret;
+ ret = _pendingOperate(function () {
+ if (_taskListArray.length === 0) {
+ _taskListArray = _get();
+ }
+ onSuccess(_taskListArray);
+ }, 1);
+ return ret;
+ }
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "getTaskLists", _getTaskLists);
+ };
+
+ this.__defineGetter__("SIM_TASK_LIST", function () {
+ return 0;
+ });
+ this.__defineGetter__("DEVICE_TASK_LIST", function () {
+ return 1;
+ });
+ this.__defineGetter__("HIGH_PRIORITY", function () {
+ return 0;
+ });
+ this.__defineGetter__("MEDIUM_PRIORITY", function () {
+ return 1;
+ });
+ this.__defineGetter__("LOW_PRIORITY", function () {
+ return 2;
+ });
+ this.__defineGetter__("STATUS_COMPLETED", function () {
+ return 0;
+ });
+ this.__defineGetter__("STATUS_NEEDS_ACTION", function () {
+ return 1;
+ });
+ this.__defineGetter__("STATUS_IN_PROCESS", function () {
+ return 2;
+ });
+ this.__defineGetter__("STATUS_CANCELLED", function () {
+ return 3;
+ });
+
+ this.handleSubFeatures = function (subFeatures) {
+ if (wac2_utils.isEmptyObject(subFeatures) ||
+ subFeatures["http://wacapps.net/api/pim.task"] ||
+ (subFeatures["http://wacapps.net/api/pim.task.read"] &&
+ subFeatures["http://wacapps.net/api/pim.task.write"])) {
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/pim.task.read"] &&
+ !subFeatures["http://wacapps.net/api/pim.task.write"]) {
+ _addTaskAllowed = false;
+ _deleteTaskAllowed = false;
+ _updateTaskAllowed = false;
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/pim.task.write"] &&
+ !subFeatures["http://wacapps.net/api/pim.task.read"]) {
+ _findTasksAllowed = false;
+ return;
+ }
+ _console.warn("WAC-2.0-Task-handleSubFeatures: something wrong");
+ };
+
};
+
});
-define('ripple/ui/plugins/options', function (require, exports, module) {
+define('ripple/platform/wac/2.0/pendingoperation', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var about = require('ripple/ui/plugins/about-dialog'),
- settings = require('ripple/ui/plugins/settings-dialog'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- hide,
- show;
-
-show = function () {
- if (settings.value("remoteInspector")) {
- $("#options-menu-build-warning").show();
- tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
- }
- else {
- $("#options-menu-build-warning").hide();
- }
-
- $("#options-window").show();
- $("#options-menu").show();
-};
-
-hide = function () {
- $("#options-window").hide();
- $("#options-menu").effect("fade", {}, 300);
-};
-
-module.exports = {
- initialize: function () {
- $("#options-menu").menu().hide();
- $("#options-menu").bind("click", function (event) {
- var target = $("#" + event.target.parentElement.id),
- action;
- if (target.hasClass("not-ready")) {
- return;
+module.exports = function (pendingObj) {
+ var pending = true;
+ this.cancel = function () {
+ if (pending === true) {
+ if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
+ pending = false;
+ // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
+ clearTimeout(pendingObj.pendingID);
+ return false;
}
-
- switch (target.attr("id")) {
- case "options-menu-build":
- case "options-menu-launch":
- case "options-menu-sign":
- action = target.attr("id").split("-")[2];
- if (!settings.can(action)) {
- settings.show(action);
- }
- else {
- settings.perform(action);
- }
- break;
- case "options-menu-about":
- about.show();
- break;
- case "options-menu-settings":
- settings.show();
- break;
- default:
- break;
+ if (typeof (pendingObj.userCancel) === "function") {
+ pendingObj.userCancel();
}
- hide();
- });
-
- $("#options-window").click(hide);
-
- $("#options-button-about").bind("click", function (event) {
- about.show();
- });
-
- hide();
- }
+ clearTimeout(pendingObj.pendingID);
+ pending = false;
+ return true;
+ } else {
+ return false;
+ }
+ };
};
+
});
-define('ripple/ui/plugins/package', function (require, exports, module) {
+define('ripple/platform/wac/2.0/dbfs', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
+/* We know the dbfs is not an accurate simulation of WAC 2.0 filesystem.
+ *
+ * 1) We have tried W3C File API, as some of WAC filesystem APIs are synchronous,
+ * it is impossible to simulate them by using the asynchronous API in the main
+ * UI thread and although we could use synchronous W3C API in a worker, it is
+ * not reasonable to limit WAC filesystem API usage in a worker.
+ *
+ * 2) The problem is partially solved by using database to simulate the filesystem,
+ * For the asynchronous aspect, actually all the files are read into memory (cache
+ * object in this file) and the cache operation is synchronous. It is not perfect.
+ * And the database has 5MB limitation when running in Chrome.
+ *
+ * In the future, we might use ajax or NPAPI to get a better simulation.
+ */
+
+/* Note: The entry object is shared between this module and filesystem */
+
var db = require('ripple/db'),
utils = require('ripple/utils'),
- event = require('ripple/event'),
- dbinit = require('ripple/platform/tizen/2.0/dbinit'),
- PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
- DB_PACKAGE_KEY = "tizen-db-package",
- _data = {
- packageList: {},
- installedList: {}
- },
- _currentPackageId = null,
- _packages,
- _installedList,
- _packageListTemplate,
- _packageInstalledTemplate;
+ _console = require('ripple/console'),
+ _cache = {},
+ _self;
-function _get() {
- _data = db.retrieveObject(DB_PACKAGE_KEY);
- if (_data === undefined) {
- _data = {
- packageList: _packages,
- installedList: _installedList
- };
- }
- utils.forEach(_data.installedList, function (item) {
- item.lastModified = new Date(item.lastModified);
- });
+function _get(path) {
+ return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
+ return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
+ }, _cache);
}
-function _save() {
- db.saveObject(DB_PACKAGE_KEY, _data);
+function _getInfo(path) {
+ var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
+ name = parent.splice(parent.length - 1, 1).join("");
+
+ return {
+ name: name,
+ parent: parent.join("/") || "/"
+ };
}
-function loadPackageList() {
- var nodes = jQuery("#package-list-select");
- nodes.html("");
- utils.forEach(_data.packageList, function (item, index) {
- nodes.append(utils.createElement("option", {
- "value": index,
- "innerText": item.name
- }));
+function _set(path, obj) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
});
- renderPackageListBox($("#package-list-select option:selected").val());
+
+ parent.children = parent.children || {};
+ parent.children[child] = obj;
}
-function loadInstalledList() {
- var html = "";
- jQuery("#package-installed-box").empty();
- utils.forEach(_data.installedList, function (item) {
- html += _packageInstalledTemplate.replace(/#Name/g, item.name)
- .replace(/#ID/g, item.id)
- .replace(/#IconPath/, item.iconPath)
- .replace(/#Version/, item.version)
- .replace(/#TotalSize/, item.totalSize)
- .replace(/#DataSize/, item.dataSize)
- .replace(/#LastModified/, item.lastModified)
- .replace(/#Author/, item.author)
- .replace(/#Description/, item.description)
- .replace(/#APPIDs/, item.appIds.join("<br>"));
- });
- $("#package-installed-box").accordion("destroy");
- $("#package-installed-box").html(html).accordion({
- active: false,
- collapsible: true,
- autoHeight: false
- });
- $("." + "package-remove-btn").bind("click", function () {
- var id = this.id;
- if (id === _currentPackageId) {
- $("#msg-" + id).html("Can't Uninstall:<br> Package including running app");
- setTimeout(function () {
- $("#msg-" + id).text("");
- }, 5000);
- return;
- }
- utils.forEach(_data.packageList, function (item) {
- if (item.id === id) {
- event.trigger("remove-apps", [item.appIds]);
- }
- });
- delete _data.installedList[this.id];
- _save();
- loadPackageList();
- loadInstalledList();
- event.trigger("uninstall-package", [this.id]);
+function _delete(path) {
+ var parent = _cache,
+ tokens = path.replace(/^\//, '').split("/"),
+ child = tokens.splice(tokens.length - 1, 1).join("");
+
+ tokens.forEach(function (token) {
+ parent = parent.children[token];
});
+
+ delete parent.children[child];
}
-function renderPackageListBox(path) {
- var item, html;
- jQuery("#package-list-box").empty();
- item = _data.packageList[path];
- html = _packageListTemplate.replace(/#Path/, path)
- .replace(/#ID/, item.id)
- .replace(/#Name/, item.name)
- .replace(/#IconPath/, item.iconPath)
- .replace(/#Version/, item.version)
- .replace(/#TotalSize/, item.totalSize)
- .replace(/#DataSize/, item.dataSize)
- .replace(/#Author/, item.author)
- .replace(/#Description/, item.description)
- .replace(/#APPList/, item.appIds.join("<br>"));
- jQuery("#package-list-box").html(html);
- if (_data.installedList[item.id]) {
- jQuery("#package-update-btn").show();
- } else {
- jQuery("#package-install-btn").show();
- }
+function _save() {
+ db.saveObject("wac2-db-filesystem", _cache);
}
-function addPackage(path, type) {
- var item;
- if (!_data.packageList[path]) {
- return;
- }
- item = _data.packageList[path];
- _data.installedList[item.id] = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, new Date(),
- item.author, item.description, item.appIds
- );
- if (type === "install") {
- event.trigger("install-apps", [item.appIds]);
- } else {
- event.trigger("update-apps", [item.appIds]);
- }
- _save();
+function _walk(path, parent) {
+ _self.ls(path, function (entries) {
+ parent.children = parent.children || {};
+
+ entries.forEach(function (entry) {
+ parent.children[entry.name] = entry;
+
+ if (entry.isDirectory) {
+ _walk(entry.fullPath, entry);
+ } else {
+ /* after getting Date out of DB, Date will become
+ a string, so need to recast it back to Date */
+ if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
+ entry.lastModifiedDate = new Date(entry.lastModifiedDate);
+
+ _self.read(entry.fullPath, function (data) {
+ parent.children[entry.name].data = data;
+ }, function (e) {
+ _console.error(e);
+ });
+ }
+ });
+ }, function (e) {
+ _console.error(e);
+ });
+}
+
+function _createPath(path) {
+ var parts = path.replace(/^\//, '').split("/"),
+ workflow = jWorkflow.order();
+
+ parts.forEach(function (part, index) {
+ var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");
+
+ workflow.andThen(function (prev, baton) {
+ baton.take();
+ _self.mkdir(dir, baton.pass, baton.pass);
+ });
+ });
+
+ workflow.start();
}
-module.exports = {
- panel: {
- domId: "package-container",
- collapsed: true,
- pane: "left",
- titleName: "Packages and Applications",
- display: true
- },
+_self = {
+ // The order is consistent with _virtualRoots in filesystem.js
+ roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
initialize: function () {
- _packages = dbinit.Package.packages;
- _installedList = dbinit.Package.installedList;
- _packageListTemplate = jQuery("#package-list-template").html();
- _packageInstalledTemplate = jQuery("#package-installed-template").html();
+ // TODO: Initialize at bootstrap and emulatorBridge.link
+ _cache = db.retrieveObject("wac2-db-filesystem") || {};
+ // create real root paths if empty
+ _self.roots.every(function (root) {
+ _createPath(root);
+ return true;
+ });
+ // build the file system cache so that we could access information synchronously
+ _walk("/", _cache);
+ },
+ ls: function (path, success, error) {
+ try {
+ var dir = _get(path),
+ items = [];
- _get();
+ if (dir) {
+ utils.forEach(dir.children, function (item) {
+ items.push(item);
+ });
+ }
+ else {
+ items = {};
+ }
+
+ success(items);
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ rm: function (path, success, error, options) {
+ _delete(path);
_save();
- loadPackageList();
- loadInstalledList();
- jQuery("#package-list-select").bind("focus change", function () {
- var path = $("#package-list-select option:selected").val();
- renderPackageListBox(path);
- });
- jQuery("#package-install-btn").live("click", function () {
- var path = $("#package-list-select option:selected").val();
- addPackage(path, "install");
- _get();
- loadPackageList();
- loadInstalledList();
- event.trigger("install-packge", [path]);
- });
- jQuery("#package-update-btn").live("click", function () {
- var path = $("#package-list-select option:selected").val();
- addPackage(path, "update");
- loadPackageList();
- loadInstalledList();
- event.trigger("update-package", [path]);
- });
- jQuery("#package-select").tabs();
- event.on("installedList-updated", function () {
- _get();
- loadPackageList();
- loadInstalledList();
- });
- event.on("install-current-package", function (item) {
- _data.installedList[item.id] = new PackageInformation(
- item.id, item.name, item.iconPath, item.version,
- item.totalSize, item.dataSize, item.lastModified,
- item.author, item.description, item.appIds);
- _currentPackageId = item.id;
- loadInstalledList();
- });
+ success();
+ },
+ rmdir: function (path, success, error, options) {
+ _delete(path);
+ _save();
+ success();
+ },
+ mkdir: function (path, success, error) {
+ var entry = _get(path),
+ info = _getInfo(path);
+
+ if (!entry) {
+ _set(path, {
+ name: info.name,
+ isDirectory: true,
+ fullPath: path
+ });
+ entry = _get(path);
+ _save();
+ }
+
+ if (entry) {
+ success(entry);
+ }
+ else {
+ error({code: 1});
+ }
+ },
+ mv: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from),
+ toInfo = _getInfo(to);
+
+ fromEntry.fullPath = to;
+ fromEntry.name = toInfo.name;
+
+ _set(to, fromEntry);
+ _delete(from);
+ _save();
+ success();
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ touch: function (path, success, error) {
+ var entry = _get(path),
+ info = _getInfo(path);
+
+ if (!entry) {
+ _set(path, {
+ lastModifiedDate: new Date(),
+ name: info.name,
+ isDirectory: false,
+ fullPath: path,
+ data: ""
+ });
+ entry = _get(path);
+ }
+ _save();
+ success(entry);
+ },
+ cp: function (from, to, success, error) {
+ try {
+ var fromEntry = _get(from),
+ copied = utils.copy(fromEntry);
+
+ copied.name = _getInfo(to).name;
+ copied.fullPath = to;
+ _set(to, copied);
+ _save();
+ success();
+ }
+ catch (e) {
+ e.code = 1;
+ error(e);
+ }
+ },
+ stat: function (path, success, error) {
+ var entry = _get(path);
+
+ if (entry) {
+ success(entry);
+ } else {
+ error({code: 1});
+ }
+ },
+ write: function (path, contents, success, error, options) {
+ var entry = _get(path);
+
+ if (entry) {
+ entry.lastModifiedDate = new Date();
+ entry.data = contents;
+ _save();
+ success();
+ } else {
+ error({code: 1});
+ }
+
+ },
+ read: function (path, success, error) {
+ var entry = _get(path);
+
+ if (entry) {
+ success(utils.copy(entry.data));
+ }
+ else {
+ error({code: 1});
+ }
}
};
+module.exports = _self;
+
+
});
-define('ripple/ui/plugins/panelCollapse', function (require, exports, module) {
+define('ripple/platform/wac/2.0/spec/config', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// TODO: could use a bit of refactoring sugar
-var db = require('ripple/db'),
- constants = require('ripple/constants'),
- _LEFT_PANEL_COLLAPSE = ".left-panel-collapse",
- _RIGHT_PANEL_COLLAPSE = ".right-panel-collapse",
- _LEFT_PANEL = ".left",
- _RIGHT_PANEL = ".right",
- _SAVE_KEY = "panel-collapsed",
- platform = require('ripple/platform'),
- devices = require('ripple/devices'),
- _leftEngaged, _rightEngaged, _store;
-
-
-$(function () {
- $(window).resize(function () {
- var windowHeight = $(window).height();
- jQuery(".PanelCollapseBar").css("top", windowHeight - 56);
- jQuery("#left_div").css("height", $(window).height() - 21);
- if (_store["left"] === true) {
- jQuery("#middle_div").css("width", $(window).width());
- } else {
- jQuery("#middle_div").css("width", $(window).width());
- }
- });
-});
-
-
-function _persist() {
- db.saveObject(_SAVE_KEY, _store);
-}
-
-
-function updateZoomingValues(value, origin) {
- var scaleFactor = value / 100, scaleString;
- scaleString = "scale(" + scaleFactor + ")";
- jQuery('#device-layout').css('-webkit-transform', scaleString);
- if (origin === "center") {
- jQuery('#device-layout').css('-webkit-transform-origin', 'center top');
- } else {
- jQuery('#device-layout').css('-webkit-transform-origin', 'left top');
- }
-}
-
-
-function _process(collapseNode, panelNode, side, callback) {
- var jNode = collapseNode.children("span"),
- jPanelNode = jQuery(panelNode),
- properties = {},
- collapseProperties = {},
- options = {
- duration: 600,
- complete: callback
- },
- oldIcon, newIcon,
- zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING);
-
- if (_store[side] === true) {
- _store[side] = false;
-
- if (side === "left") {
- jQuery('#left_div').show("fast");
- collapseNode.removeClass("PanelCollapseBarCollapsed");
- collapseNode.addClass("PanelCollapseBar");
- collapseNode.children().remove();
- collapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
- collapseNode.css("top", $(window).height() - 56);
- collapseNode.css("left", 0);
- jQuery("#middle_div").css("width", $(window).width());
- updateZoomingValues(zoomingValue, "left");
- }
- oldIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");
- newIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");
-
- properties[side] = "0px";
- collapseProperties[side] = "345px";
- properties.opacity = "1";
-
- if (jQuery("#device-layout").position().left < 290 ) {
- jQuery("#device-layout").animate({left: "350px"}, 200 );
- }
- } else {
- _store[side] = true;
-
- if (side === "left") {
- collapseNode.removeClass("PanelCollapseBar");
- collapseNode.addClass("PanelCollapseBarCollapsed");
- collapseNode.children().remove();
- collapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
- collapseNode.css("top", 10);
- collapseNode.css("left", 0);
- collapseNode.css("margin-left", 0);
- jQuery('#left_div').hide("slow");
- jQuery("#middle_div").css("width", $(window).width());
- updateZoomingValues(zoomingValue, "left");
- }
-
- oldIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");
- newIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");
-
- properties[side] = "-340px";
- collapseProperties[side] = "5px";
- properties.opacity = "0.1";
- }
-
- jNode.removeClass(oldIcon).addClass(newIcon);
-
- jPanelNode.animate(properties, options);
- _persist();
-}
+var platform = require('ripple/platform'),
+ utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants');
module.exports = {
- initialize: function () {
- var rightCollapseNode = jQuery(_RIGHT_PANEL_COLLAPSE),
- leftCollapseNode = jQuery(_LEFT_PANEL_COLLAPSE),
- device = devices.getCurrentDevice(),
- zoomingValue = db.retrieve(constants.ENCAPSULATOR.ZOOMING),
- deviceNode = jQuery("#device-layout");
-
- _store = db.retrieveObject(_SAVE_KEY) || {
- left: false,
- right: false
- };
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ // no xmlns:JIL in wac 2.0 spec
+ valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;
- jQuery("#left_div").css("height", $(window).height() - 21);
- jQuery("#middle_div").css("width", $(window).width());
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
+ }
- jQuery("#device-container").bind("mousedown", function () {
- jQuery("#device-maskmask").show();
- });
+ var widgetInfo = {},
+ configFeatures,
+ configPreferences,
+ preferenceName,
+ platform;
- jQuery("#device-container").bind("mouseup", function () {
- jQuery("#device-maskmask").hide();
- });
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
- jQuery("#deviceTitleBar").bind("mousedown", function () {
- jQuery("#device-maskmask").show();
- });
+ widgetInfo.features = {};
- jQuery("#deviceTitleBar").bind("mouseup", function () {
- jQuery("#device-maskmask").hide();
+ configFeatures = configValidationObject.widget.children.feature.validationResult;
+ utils.forEach(configFeatures, function (f) {
+ if (f.valid === true) {
+ var feature = {id: f.attributes.name.value,
+ required: f.attributes.required.valid};
+ widgetInfo.features[feature.id] = feature;
+ }
});
- deviceNode.draggable({ cursor: 'move', handle: "#deviceTitleBar", containment: [0, 52, 1280, 800]});
- jQuery("#deviceTitle").text(device.name);
- if (_store.left === true) {
- jQuery(_LEFT_PANEL).css({
- left: "-340px",
- opacity: "0.1"
- });
-
- leftCollapseNode.removeClass("PanelCollapseBar");
- leftCollapseNode.addClass("PanelCollapseBarCollapsed");
- leftCollapseNode.children().remove();
- leftCollapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
- leftCollapseNode.css("top", 10);
- leftCollapseNode.css("left", 0);
- leftCollapseNode.css("margin-left", 0);
- jQuery('#left_div').hide();
- jQuery("#device-layout").css("left", "21px");
- updateZoomingValues(zoomingValue, "left");
- } else {
- jQuery('#left_div').show("fast");
- leftCollapseNode.removeClass("PanelCollapseBarCollapsed");
- leftCollapseNode.addClass("PanelCollapseBar");
- leftCollapseNode.children().remove();
- leftCollapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
- leftCollapseNode.css("top", $(window).height() - 56);
- leftCollapseNode.css("left", 0);
- jQuery("#device-layout").css("left", "350px");
- updateZoomingValues(zoomingValue, "left");
- }
+ widgetInfo.preferences = {};
- if (_store.right === true) {
- jQuery(_RIGHT_PANEL).css({
- right: "-340px",
- opacity: "0.1"
- });
+ configPreferences = configValidationObject.widget.children.preference.validationResult;
- rightCollapseNode.css({
- right: "5px"
- }).children("span").removeClass("ui-icon-arrowthick-1-e").addClass("ui-icon-arrowthick-1-w");
- }
+ platform = require('ripple/platform');
+ utils.forEach(configPreferences, function (preference) {
+ preferenceName = preference.attributes.name.value;
+ if (preferenceName) {
+ widgetInfo.preferences[preferenceName] = {
+ "key": preferenceName,
+ "value": preference.attributes.value.value || "",
+ "readonly": preference.attributes.readonly.value === "true"
+ };
- leftCollapseNode.bind("click", function () {
- if (!_leftEngaged) {
- _leftEngaged = true;
- _process(leftCollapseNode, _LEFT_PANEL, "left", function () {
- _leftEngaged = false;
- });
+ db.save(preferenceName,
+ widgetInfo.preferences[preferenceName].value,
+ platform.getPersistencePrefix(widgetInfo.id));
}
});
- rightCollapseNode.bind("click", function () {
- if (!_rightEngaged) {
- _rightEngaged = true;
- _process(rightCollapseNode, _RIGHT_PANEL, "right", function () {
- _rightEngaged = false;
- });
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,feature and preference. \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
+ },
+ defaultlocale: {
+ attributeName: "defaultlocale",
+ required: false,
+ type: "iso-language"
+ },
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ "short": {
+ attributeName: "short",
+ required: false,
+ type: "string"
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.URL
+ },
+ email: {
+ attributeName: "email",
+ required: false,
+ type: "regex",
+ regex: constants.REGEX.EMAIL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ }
+ },
+ children: {
+ span: {
+ nodeName: "span",
+ required: false,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ }
+ }
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ unique: true
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ src: {
+ attributeName: "src",
+ required: true,
+ type: "string"
+ },
+ encoding: {
+ attributeName: "encoding",
+ required: false,
+ type: "string"
+ },
+ type: {
+ attributeName: "type",
+ required: false,
+ type: "string"
+ }
+ }
+ },
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/TR/geolocation-API/",
+ "http://wacapps.net/api/deviceapis", "http://wacapps.net/api/accelerometer",
+ "http://wacapps.net/api/orientation", "http://wacapps.net/api/camera",
+ "http://wacapps.net/api/camera.show", "http://wacapps.net/api/camera.capture",
+ "http://wacapps.net/api/devicestatus", "http://wacapps.net/api/devicestatus.deviceinfo",
+ "http://wacapps.net/api/devicestatus.networkinfo", "http://wacapps.net/api/filesystem",
+ "http://wacapps.net/api/filesystem.read", "http://wacapps.net/api/filesystem.write",
+ "http://wacapps.net/api/messaging", "http://wacapps.net/api/messaging.send",
+ "http://wacapps.net/api/messaging.find", "http://wacapps.net/api/messaging.subscribe",
+ "http://wacapps.net/api/messaging.write", "http://wacapps.net/api/pim.contact",
+ "http://wacapps.net/api/pim.contact.read", "http://wacapps.net/api/pim.contact.write",
+ "http://wacapps.net/api/pim.calendar", "http://wacapps.net/api/pim.calendar.read",
+ "http://wacapps.net/api/pim.calendar.write", "http://wacapps.net/api/pim.task",
+ "http://wacapps.net/api/pim.task.read", "http://wacapps.net/api/pim.task.write",
+ "http://wacapps.net/api/deviceinteraction"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ },
+ children: {
+ param: {
+ nodeName: "param",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string",
+ },
+ value: {
+ attributeName: "value",
+ required: true,
+ type: "string",
+ }
+ }
+ }
+ }
+ },
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language",
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ name: {
+ attributeName: "name",
+ required: true,
+ type: "string"
+ },
+ value: {
+ type: "string",
+ required: false,
+ attributeName: "value"
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
+ }
+ }
+ }
}
- });
+ }
}
};
});
-define('ripple/ui/plugins/phone', function (require, exports, module) {
+define('ripple/platform/wac/2.0/spec/device', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- Phone = require('ripple/platform/webworks.handset/2.0.0/client/Phone'),
- CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
- event = require('ripple/event'),
- _console = require('ripple/console'),
- eventSelect = document.getElementById("phone-event-types"),
- eventErrorContainer = document.getElementById("phone-event-error-container"),
- eventErrorSelect = document.getElementById("phone-event-error-types");
+var event = require('ripple/event');
-function _firePhoneLogEvents(type, number, error) {
- if (type === Phone.CB_CALL_INITIATED ||
- type === Phone.CB_CALL_ANSWERED) {
- event.trigger("PhoneCallLogAdded", [{
- date: new Date(),
- number: number,
- status: CallLog.STATUS_NORMAL,
- type: CallLog.TYPE_RECEIVED_CALL
- }], true);
- } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
- type === Phone.CB_CALL_FAILED) {
- event.trigger("PhoneCallLogAdded", [{
- date: new Date(),
- number: number,
- status: CallLog.STATUS_NORMAL,
- type: CallLog.TYPE_PLACED_CALL
- }], true);
- }
+function deviceStatusEventTrigger(setting) {
+ event.trigger("DeviceStatusChanged", [setting]);
}
-function _updateActiveCalls(type, number, error) {
- if (type === Phone.CB_CALL_INITIATED ||
- type === Phone.CB_CALL_CONNECTED ||
- type === Phone.CB_CALL_CONFERENCECALL_ESTABLISHED ||
- type === Phone.CB_CALL_DIRECTCONNECT_CONNECTED ||
- type === Phone.CB_CALL_ANSWERED) {
- event.trigger("PhoneCallInitiated", [{
- id: number,
- onhold: false,
- outgoing: false,
- recipient: {
- name: "",
- number: String(number)
+module.exports = {
+ "Config": {
+ "vibratingMode": {
+ "name": "Vibrator",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("VibratingModeChanged", [setting]);
+ }
+ },
+ "soundVolume": {
+ "name": "Sound Volume",
+ "control": {
+ "type": "range",
+ "value": 100,
+ "min": 0,
+ "max": 100
+ },
+ "callback": function (setting) {
+ event.trigger("VolumeChanged", [setting]);
+ }
+ },
+ "backlight": {
+ "name": "Backlight",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "callback": function (setting) {
+ event.trigger("BacklightChanged", [setting]);
+ }
+ }
+ },
+ "Battery": {
+ "batteryLevel": {
+ "name": "Battery Remaining %",
+ "control": {
+ "type": "select",
+ "value": 100
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
+
+ for (i = 0; i <= 100; i += 10) {
+ optionList[i] = i;
+ }
+
+ return optionList;
+ }()),
+ "event": "BatteryLevelChanged",
+ "callback": function (setting) {
+ event.trigger("BatteryLevelChanged", [setting]);
+ }
+ },
+
+ "batteryBeingCharged": {
+ "name": "Battery Is Charging",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "BatteryBeingChargedChanged",
+ "callback": function (setting) {
+ event.trigger("BatteryBeingChargedChanged", [setting]);
+ }
+ },
+ },
+ "CellularHardware": {
+ "status": {
+ "name": "status",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "CellularHardwareStatusChanged",
+ "callback": function (setting) {
+ event.trigger("CellularHardwareStatusChanged", [setting]);
+ }
+ }
+ },
+ "CellularNetwork": {
+ "isInRoaming": {
+ "name": "Roaming",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "CellularNetworkIsInRoamingChanged",
+ "callback": function (setting) {
+ event.trigger("CellularNetworkIsInRoamingChanged", [setting]);
+ }
+ },
+ "mcc": {
+ "name": "mcc",
+ "control": {
+ "type": "text",
+ "value": "460",
+ "readonly": "readonly"
+ }
+ },
+ "mnc": {
+ "name": "mnc",
+ "control": {
+ "type": "text",
+ "value": "0",
+ "readonly": "readonly"
+ }
+ },
+ "signalStrength": {
+ "name": "Signal Strength",
+ "control": {
+ "type": "select",
+ "value": 100
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
+
+ for (i = 0; i <= 100; i += 10) {
+ optionList[i] = i;
+ }
+
+ return optionList;
+ }()),
+ "event": "CellularNetworkSignalStrengthChanged",
+ "callback": function (setting) {
+ event.trigger("CellularNetworkSignalStrengthChanged", [setting]);
+ }
+ },
+ "operatorName": {
+ "name": "Operator Name",
+ "control": {
+ "type": "text",
+ "value": "CMCC",
+ "readonly": "readonly"
+ }
+ }
+ },
+ "Device": {
+ "imei": {
+ "name": "IMEI",
+ "control": {
+ "type": "text",
+ "value": "860398001689659",
+ "readonly": "readonly"
+ }
+ },
+ "model": {
+ "name": "Model",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ },
+ "version": {
+ "name": "Version",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ },
+ "vendor": {
+ "name": "Vendor.",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ }
+ },
+ "Display": {
+ "resolutionHeight": {
+ "name": "Resolution Height",
+ "control": {
+ "type": "number",
+ "value": 0,
+ "readonly": "readonly"
+ }
+ },
+ "resolutionWidth": {
+ "name": "Resolution Width",
+ "control": {
+ "type": "number",
+ "value": 0,
+ "readonly": "readonly"
+ }
+ },
+ "pixelAspectRatio": {
+ "name": "Pixel Aspectratio",
+ "control": {
+ "type": "number",
+ "value": 0,
+ "readonly": "readonly"
+ }
+ },
+ "dpiY": {
+ "name": "DPI-Y",
+ "control": {
+ "type": "number",
+ "value": 0,
+ "readonly": "readonly"
+ }
+ },
+ "dpiX": {
+ "name": "DPI-X",
+ "control": {
+ "type": "number",
+ "value": 0,
+ "readonly": "readonly"
+ }
+ },
+ "colorDepth": {
+ "name": "Color Depth",
+ "control": {
+ "type": "number",
+ "value": 32,
+ "readonly": "readonly"
+ }
+ }
+ },
+ "MemoryUnit": {
+ "removable": {
+ "name": "Removable",
+ "control": {
+ "type": "checkbox",
+ "value": true,
+ "readonly": "readonly"
+ }
+ },
+ "size": {
+ "name": "Total Memory",
+ "control": {
+ "type": "number",
+ "value": 262144,
+ "readonly": "readonly"
+ }
+ },
+ "availableSize": {
+ "name": "Available Size",
+ "control": {
+ "type": "range",
+ "value": 16384,
+ "min": 0,
+ "max": 262144
+ },
+ "event": "MemoryUnitAvailableSizeChanged",
+ "callback": function (setting) {
+ event.trigger("MemoryUnitAvailableSizeChanged", [setting]);
+ }
+ }
+ },
+ "OperatingSystem": {
+ "language": {
+ "name": "Language",
+ "control": {
+ "type": "text",
+ "value": "English",
+ "readonly": "readonly"
+ }
+ },
+ "version": {
+ "name": "Version",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ },
+ "name": {
+ "name": "Name",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ },
+ "vendor": {
+ "name": "Vendor",
+ "control": {
+ "type": "text",
+ "value": "",
+ "readonly": "readonly"
+ }
+ }
+ },
+ "WebRuntime": {
+ "wacVersion": {
+ "name": "WAC Version",
+ "control": {
+ "type": "text",
+ "value": "2.0",
+ "readonly": "readonly"
+ }
+ },
+ "supportedImageFormats": {
+ "name": "Image Formats",
+ "control": {
+ "type": "text",
+ "value": "gif87, gif89, png, jpeg",
+ "readonly": "readonly"
+ },
+ "event": "WebRuntimeSupportedImageFormatsChanged",
+ "callback": function (setting) {
+ event.trigger("WebRuntimeSupportedImageFormatsChanged", [setting]);
+ }
+ },
+ "version": {
+ "name": "Web Runtime Version",
+ "control": {
+ "type": "text",
+ "value": "1.0",
+ "readonly": "readonly"
}
- }], true);
- } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
- type === Phone.CB_CALL_FAILED ||
- type === Phone.CB_CALL_DISCONNECTED ||
- type === Phone.CB_CONFERENCECALL_DISCONNECTED ||
- type === Phone.CB_CALL_DIRECTCONNECT_DISCONNECTED) {
- event.trigger("PhoneCallEnded", [{
- id: number
- }], true);
- }
-}
-
-module.exports = {
- panel: {
- domId: "phone-container",
- collapsed: true,
- pane: "right"
+ },
+ "name": {
+ "name": "Web Runtime Name",
+ "control": {
+ "type": "text",
+ "value": "Tizen Web Simulator",
+ "readonly": "readonly"
+ }
+ },
+ "vendor": {
+ "name": "Vendor Name",
+ "control": {
+ "type": "text",
+ "value": "Tizen SDK team",
+ "readonly": "readonly"
+ }
+ }
},
- initialize: function (prev, baton) {
- utils.forEach(Phone, function (value, prop) {
- if (prop.match(/^CB_/)) {
- eventSelect.appendChild(utils.createElement("option", {
- value: value,
- innerHTML: prop.replace(/^CB_(CALL_)?/, "")
- }));
+ "WiFiHardware": {
+ "status": {
+ "name": "Status",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "WiFiHardwareStatusChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiHardwareStatusChanged", [setting]);
}
-
- if (prop.match(/^CALL_ERROR_/)) {
- eventErrorSelect.appendChild(utils.createElement("option", {
- value: value,
- innerHTML: prop.replace(/^CALL_ERROR_/, "")
- }));
+ }
+ },
+ "WiFiNetwork": {
+ "ssid": {
+ "name": "SSID",
+ "control": {
+ "type": "text",
+ "value": "OfficeWLAN"
+ },
+ "event": "WiFiHardwareSsidChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiHardwareSsidChanged", [setting]);
}
- });
-
- document.getElementById("phone-event-types").addEventListener("change", function () {
- eventErrorContainer.setAttribute("style", parseInt(eventSelect.value, 10) === Phone.CB_CALL_FAILED ? "" : "display: none");
- });
-
- document.getElementById("phone-logs-clear").addEventListener("click", function () {
- event.trigger("PhoneCallLogReset");
- });
-
- document.getElementById("phone-event-send").addEventListener("click", function () {
- var type = parseInt(eventSelect.value, 10),
- error = type === Phone.CB_CALL_FAILED ? eventErrorSelect.value : undefined,
- callId = document.getElementById("phone-call-id").value;
-
- _firePhoneLogEvents(type, callId, error);
- _updateActiveCalls(type, callId, error);
+ },
+ "signalStrength": {
+ "name": "Signal Strength",
+ "control": {
+ "type": "select",
+ "value": 10
+ },
+ "options": (function () {
+ var i,
+ optionList = {};
- event.trigger("PhoneEvent", [type, callId, error]);
+ for (i = 0; i <= 10; i++) {
+ optionList[i] = i;
+ }
- _console.log("Fired PhoneEvent (type " + type + ") CallID: " +
- callId + (error ? (" (error type " + error + ")") : ""));
- }, false);
+ return optionList;
+ }()),
+ "event": "WiFiHardwareSignalStrengthChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiHardwareSignalStrengthChanged", [setting]);
+ }
+ },
+ "networkStatus": {
+ "name": "Network Status",
+ "control": {
+ "type": "checkbox",
+ "value": true
+ },
+ "event": "WiFiHardwareNetworkStatusChanged",
+ "callback": function (setting) {
+ event.trigger("WiFiHardwareNetworkStatusChanged", [setting]);
+ }
+ }
}
};
+
});
-define('ripple/ui/plugins/platform', function (require, exports, module) {
+define('ripple/platform/wac/2.0/spec/ui', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- utils = require('ripple/utils'),
- devices = require('ripple/devices'),
- platform = require('ripple/platform'),
- db = require('ripple/db');
-
-function _updatePlatformDeviceSelect(platformID, currentDeviceKey) {
- var devicesSelect = document.getElementById(constants.COMMON.DEVICE_SELECT_ID),
- listOfSortedDevices = devices.getDevicesForPlatform(platformID)
- .sort(function (a, b) {
- return (a.screen.width * a.screen.height) < (b.screen.width * b.screen.height) ? -1 : ((a.screen.width * a.screen.height) > (b.screen.width * b.screen.height) ? 1 : 0);
- });
- db.remove("viewport_width");
- db.remove("viewport_height");
- db.remove("viewportTag");
-
- devicesSelect.innerHTML = "";
- listOfSortedDevices.forEach(function (dev) {
- var deviceNode = utils.createElement("option", {
- "innerText": dev.name,
- "value": dev.id
- });
-
- if (currentDeviceKey && deviceNode.value === currentDeviceKey) {
- deviceNode.selected = true;
- }
-
- devicesSelect.appendChild(deviceNode);
- });
-
- if (platformID === "ivi") {
- jQuery("#configuration-window-save-btn").hide();
- jQuery("#configuration-window-load-btn").hide();
-
- jQuery("#item_container :nth-child(2)").hide();
- jQuery("#item_container :nth-child(3)").hide();
-
- jQuery("#hwkeys-panel").hide();
- }
- else {
- jQuery("#configuration-window-save-btn").show();
- jQuery("#configuration-window-load-btn").show();
-
- jQuery("#item_container :nth-child(2)").show();
- jQuery("#item_container :nth-child(3)").show();
-
- jQuery("#hwkeys-panel").show();
- }
-}
-
-function checkResolutionSize(evt) {
- var query_str, id_str, len;
- query_str = "#resolution-custom-" + evt.data.msg;
- id_str = "custom_" + evt.data.msg;
- len = jQuery(query_str).val();
- if (len >= 200 && len <= 2000) {
- db.save(id_str, len);
- } else {
- jQuery(query_str).val(db.retrieve(id_str));
- }
-}
-
module.exports = {
- initialize: function () {
- var currentPlatform = platform.current().id,
- currentVersion = platform.current().version,
- platformList = platform.getList(),
- platformSelect = document.getElementById(constants.COMMON.PLATFORM_SELECT_ID),
- versionSelect = document.getElementById("version-select"),
- currentDeviceKey = devices.getCurrentDevice().id,
- platformNode, versionNode;
-
- jQuery("#platform-select").bind("change", function () {
- var newPlatform = jQuery(this).val(),
- newDevice = jQuery("#device-select").val();
-
- jQuery(versionSelect).children("option").remove();
- utils.forEach(platformList, function (platform) {
- utils.forEach(platform, function (version, versionNumber) {
- if (newPlatform === version.id) {
- versionSelect.appendChild(utils.createElement("option", {
- "innerText": version.text,
- "value": versionNumber
- }));
- }
- });
- });
- _updatePlatformDeviceSelect(newPlatform, newDevice);
-
- });
-
- jQuery("#device-select").bind("focus", function () {
- $('input:radio[name="resolution-type"][value="predefined"]').click();
- });
- jQuery("#resolution-custom-width").bind("focus", function () {
- $('input:radio[name="resolution-type"][value="custom"]').click();
- });
- jQuery("#resolution-custom-height").bind("focus", function () {
- $('input:radio[name="resolution-type"][value="custom"]').click();
- });
- jQuery("#resolution-custom-width").bind("change", {msg: "width"}, checkResolutionSize);
- jQuery("#resolution-custom-height").bind("change", {msg: "height"}, checkResolutionSize);
-
- utils.forEach(platformList, function (platform, platformKey) {
- platformNode = utils.createElement("option", {
- "innerText": platformKey === "tizen" ? "mobile": platformKey,
- "value": platformKey
- });
-
- utils.forEach(platform, function (version, versionNumber) {
- versionNode = utils.createElement("option", {
- "innerText": version.text,
- "value": versionNumber
- });
-
- if (currentPlatform && version.id === currentPlatform) {
- versionSelect.appendChild(versionNode);
- if (currentVersion && currentVersion === versionNumber) {
- platformNode.selected = true;
- versionNode.selected = true;
- }
- }
- });
- platformSelect.appendChild(platformNode);
- });
-
- _updatePlatformDeviceSelect(currentPlatform, currentDeviceKey);
- }
+ plugins: [
+ "accelerometer",
+ "messaging",
+ "geoView",
+ "widgetConfig",
+ "deviceSettings"
+ ]
};
});
-define('ripple/ui/plugins/platformEvents', function (require, exports, module) {
+define('ripple/platform/wac/2.0/pendingObject', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _console = require('ripple/console'),
- platform = require('ripple/platform'),
- event = require('ripple/event'),
- exception = require('ripple/exception'),
- utils = require('ripple/utils');
-
-module.exports = {
- panel: {
- domId: "platform-events-container",
- collapsed: true,
- pane: "right",
- titleName: "Platform Events",
- display: true
- },
- initialize: function () {
- var eventSelect = document.getElementById("platform-events-select"),
- spec = platform.current();
-
- if (!spec.events) {
- return;
- }
-
- utils.forEach(spec.events, function (method, name) {
- eventSelect.appendChild(utils.createElement("option", {
- "innerText": name,
- "value": name
- }));
- });
-
- jQuery("#platform-events-fire").click(function () {
- var eventName = document.getElementById("platform-events-select").value,
- args = spec.events[eventName].args ? document.getElementById("platform-events-args").value : null,
- callback = spec.events[eventName].callback;
-
- _console.log("fired event => " + eventName);
-
- try {
- callback(args);
- } catch (e) {
- exception.throwMaskedException(e);
- }
- });
-
- jQuery(eventSelect).change(function () {
- var argsSelect = jQuery("#platform-events-args"),
- args = spec.events[this.value].args;
-
- argsSelect.empty();
-
- if (args) {
- utils.forEach(spec.events[this.value].args, function (arg, index) {
- argsSelect.append(utils.createElement("option", {
- innerText: arg,
- value: index
- }));
- });
- argsSelect.show();
- } else {
- argsSelect.hide();
- }
- });
- }
+module.exports = function (pendingObj) {
+ var cancelFlag = true;
+ this.setCancelFlag = function (flag) {
+ cancelFlag = flag;
+ };
+ this.getCancelFlag = function () {
+ return cancelFlag;
+ };
+ this.userCancel = null;
+ this.pendingID = null;
};
});
-define('ripple/ui/plugins/power', function (require, exports, module) {
+define('ripple/platform/wac/2.0/deviceinteraction', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-var db = require('ripple/db'),
- event = require('ripple/event'),
+var notifications = require('ripple/notifications'),
constants = require('ripple/constants'),
- _volume = document.getElementById(constants.BATTERY.VOLUME),
- _volumeLabel = document.getElementById(constants.BATTERY.VOLUME + "-label"),
- _charging = document.getElementById(constants.BATTERY.CHARGING),
- _battery = {
- volume: 600,
- level: 1.0,
- timerId: null,
- charge: function (isStart, isCharge, callback) {
- var currentVolume,
- checkValue = function () {
- if (_battery.level < 0 || _battery.level > 1.0 || !isStart) {
- clearInterval(_battery.timerId);
- _battery.timerId = null;
- if (_battery.level < 0)
- _battery.level = 0;
- else if (_battery.level > 1.0)
- _battery.level = 1.0;
- }
- };
-
- if (isStart && !_battery.timerId) {
- _battery.timerId = setInterval(function () {
- currentVolume = isCharge ? _battery.level * _battery.volume + 1 : _battery.level * _battery.volume - 1;
- _battery.level = currentVolume / _battery.volume;
- checkValue();
- return callback && callback();
- }, 1000);
- }
- checkValue();
- return callback && callback();
- }
- };
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ deviceSettings = require('ripple/deviceSettings'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ _self,
+ NOTIFY_DURATION_LIMIT = 5000;
-function _triggerEvent(chargingStatus, chargingTime, dischargingTime, level, type) {
- var status = {
- charging: chargingStatus,
- chargingTime: chargingTime,
- dischargingTime: dischargingTime,
- level: level,
- type: type
- };
- event.trigger("BatteryEvent", [status]); // for w3c battery api
- // for tizen systeminfo api
- if (type === "levelchange") {
- event.trigger("BatteryLevelChanged", [level]);
- }
- if (type === "chargingchange") {
- event.trigger("BatteryChargingChanged", [status]);
+function pendingOperation(f) {
+ var _FAKEWAITTIME = 0,
+ pendingObj;
+
+ if (_FAKEWAITTIME === 0) {
+ f();
+ return undefined;
}
-}
-
-function _updateLevelIcons() {
- var colors = ["black", "black", "black", "black", "black", "black", "#404040", "#606060", "#808080", "#b0b0b0", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff"],
- colorIndex = 10 - Math.round(_battery.level * 10),
- index;
-
- //map the battery level to the color range
- for (index = 0 ; index <= 5 ; index++) {
- $("#block" + index).css("backgroundColor", colors[colorIndex]);
- colorIndex++;
+ else {
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ f();
+ }, _FAKEWAITTIME);
+ return new PendingOperation(pendingObj);
}
}
-function _setVolumeReadOnly(flag) {
- if (flag) {
- $("#" + constants.BATTERY.VOLUME).hide();
- $("#" + constants.BATTERY.VOLUME + "-label").show();
+function checkDuration(duration) {
+ if (duration) {
+ duration = duration | 0;
+ if (duration <= 0 || duration > NOTIFY_DURATION_LIMIT) {
+ return NOTIFY_DURATION_LIMIT;
+ } else {
+ return duration;
+ }
} else {
- $("#" + constants.BATTERY.VOLUME).show();
- $("#" + constants.BATTERY.VOLUME + "-label").hide();
+ return NOTIFY_DURATION_LIMIT;
}
}
-function _startDischarging() {
- var remainVolume = 0;
-
- if ($("#simulate-low-battery #low-battery-remain-time").val() <= 0) {
- $("#simulate-low-battery #low-battery-remain-time").val(0);
- }
- remainVolume = Number($("#simulate-low-battery #low-battery-remain-time").val());
- if ($("#simulate-low-battery #low-battery-start-at").val() > 100) {
- $("#simulate-low-battery #low-battery-start-at").val(100);
- }
- if ($("#simulate-low-battery #low-battery-start-at").val() <= 0) {
- $("#simulate-low-battery #low-battery-start-at").val(0);
- }
- _battery.level = $("#simulate-low-battery #low-battery-start-at").val() / 100.0;
- if (_battery.level === 0 || remainVolume === 0) {
- $("#simulate-low-battery").dialog("close");
- _stopDischarging();
- return;
- }
- _setVolumeReadOnly(true);
- if (_charging.checked) {
- _charging.checked = false;
- _battery.charge(false);
- }
-
- _charging.disabled = true;
- $("#remaining-time-label").html("Remaining Time to empty (seconds)");
- $("#charging-state").html("Plugged in?");
-
- $("#remain-time").show();
- _battery.volume = remainVolume / _battery.level;
- _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
- _battery.charge(true, false, function () {
- _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
- _volume.value = (_battery.level * 100).toFixed(2);
- changeBatteryVolume();
- $("#remain-time").html(Math.round(_battery.volume * _battery.level) + " Seconds");
- _updateLevelIcons();
- if (_battery.level <= 0.0) {
- _stopDischarging();
- }
- });
- $("#simulate-low-battery").dialog("close");
- $("#simulate-low-battery-btn").hide();
- $("#stop-btn").show();
- _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingtimechange");
+function isMute() {
+ return deviceSettings.retrieve("Config.soundVolume") <= 0;
}
-function _stopDischarging() {
- _charging.disabled = false;
- _battery.level = _volume.value / 100.0;
- $("#remain-time").hide();
- $("#remain-time").html("");
- $("#remaining-time-label").html("Remaining Time (seconds)");
- _setVolumeReadOnly(false);
- _battery.charge(false);
- $("#simulate-low-battery-btn").show();
- $("#stop-btn").hide();
- _updateLevelIcons();
+function isInVibrateMode() {
+ return deviceSettings.retrieve("Config.vibratingMode");
}
-function _setCharging() {
- // update the UI parts
- if (_charging.checked) {
- _battery.volume = 600;
- _battery.level = _volume.value / 100;
- _setVolumeReadOnly(true);
- $("#remain-time").show();
- $("#remaining-time-label").html("Remaining Time to fully charged (seconds)");
- $("#charging-state").html("Plugged in - charging rate 0.17%/second");
- _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "chargingchange");
- } else {
- _battery.level = _volume.value / 100.0;
- _updateLevelIcons();
- $("#remain-time").hide();
- $("#remain-time").html("");
- _setVolumeReadOnly(false);
- $("#remaining-time-label").html("Remaining Time (seconds)");
- $("#charging-state").html("Plugged in?");
- _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingchange");
- }
- // if it's unchecked, the timer will stop in this function call, the UI update blow it
- _battery.charge(_charging.checked, true, function () {
- _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
- _volume.value = (_battery.level * 100).toFixed(2);
- changeBatteryVolume();
- $("#remain-time").html(Math.round(_battery.volume * (1 - _battery.level)) + " Seconds"); //show current remain time
- _updateLevelIcons();
- });
+function isBacklightOn() {
+ return deviceSettings.retrieve("Config.backlight");
}
-function changeBatteryVolume() {
- if (_volume.value < 0)
- _volume.value = 0;
- else if (_volume.value > 100)
- _volume.value = 100;
+var vibrator = (function () {
+ var isVibrating = false,
+ terminateAfterPattern = false,
+ pattern = null,
+ pulseIndex = 0,
+ vibrateTimeout = null,
+ terminateTimeout = null,
+ MILLILSECONDS_OF_ONE_VIBRATION = 100,
+ node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
+ movementIndex = 0,
+ movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
+ {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];
- _battery.level = _volume.value / 100.0;
- if (_charging.checked === true) {
- _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "levelchange");
- } else {
- _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "levelchange");
+ function _clearTimeout() {
+ if (vibrateTimeout) {
+ clearInterval(vibrateTimeout);
+ vibrateTimeout = null;
+ }
+ if (terminateTimeout) {
+ clearTimeout(terminateTimeout);
+ terminateTimeout = null;
+ }
+ }
+
+ function stopVibrate() {
+ isVibrating = false;
+ _clearTimeout();
+ node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
}
- db.save(constants.BATTERY.VOLUME, _volume.value);
- _updateLevelIcons();
-}
-
-function initBattery() {
- $("#" + constants.BATTERY.CHARGING).bind("change", _setCharging);
-
- $("#simulate-low-battery-btn").bind("click", function () {
- $("#simulate-low-battery").dialog("open");
- });
-
- $("#simulate-low-battery-cancel").bind("click", function () {
- $("#low-battery-start-at").val = 20; //UI initialize
- $("#low-battery-remain-time").val = 1200;
- $("#simulate-low-battery").dialog("close");
- });
-
- $("#simulate-low-battery-start").bind("click", _startDischarging);
- $("#stop-btn").bind("click", _stopDischarging);
-
- $("#" + constants.BATTERY.VOLUME).bind("change", function () {
- changeBatteryVolume();
- });
-
- _charging.checked = false;
- _battery.level = db.retrieve(constants.BATTERY.VOLUME) / 100.0;
- if (isNaN(_battery.level)) {
- _battery.level = 1;
+
+ function vibrate() {
+ //node.animate(movement[movementIndex], MILLILSECONDS_OF_ONE_VIBRATION);
+ node.css(movement[movementIndex]);
+ movementIndex = (movementIndex + 1) % 8;
}
- _volume.value = (_battery.level * 100).toFixed(2);
- _updateLevelIcons();
- $("#simulate-low-battery").dialog({
- resizable: false,
- draggable: true,
- modal: true,
- autoOpen: false,
- position: 'center',
- minWidth: '460',
- minHeight: '240'
- });
-}
-
-module.exports = {
- panel: {
- domId: "power-container",
- collapsed: true,
- pane: "left",
- titleName: "Power Manager",
- display: true
- },
-
- initialize: function () {
- initBattery();
+
+ function changePulse() {
+ //pattern != null
+ var pulse = pattern[pulseIndex];
+ if (pulse === '.') vibrate();
+ ++pulseIndex;
+ if (pulseIndex >= pattern.length) {
+ if (terminateAfterPattern) {
+ setTimeout(stopVibrate, 1);
+ return;
+ }
+ pulseIndex = 0;
+ }
+ }
+
+ function terminateVibrate() {
+ terminateAfterPattern = true;
+ terminateTimeout = null;
+ if (pattern === null) {
+ stopVibrate();
+ }
+ }
+
+ function startVibrate(duration, _pattern) {
+ if (!isInVibrateMode()) return;
+ _clearTimeout();
+ terminateAfterPattern = false;
+ movementIndex = 0;
+
+ if (_pattern) {
+ pattern = _pattern;
+ pulseIndex = 0;
+ vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
+ if (duration)
+ terminateAfterPattern = false;
+ else
+ terminateAfterPattern = true;
+ } else {
+ pattern = null;
+ vibrateTimeout = setInterval(vibrate, MILLILSECONDS_OF_ONE_VIBRATION);
+ }
+ terminateTimeout = setTimeout(terminateVibrate, checkDuration(duration));
+ isVibrating = true;
}
-};
-
-});
-define('ripple/ui/plugins/push', function (require, exports, module) {
-/*
- * Copyright 2011 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 constants = require('ripple/constants'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- db = require('ripple/db'),
- PUSH_OPTIONS = constants.PUSH.OPTIONS;
-
-function _updatePushPanel(ports) {
- var portsSelect = document.getElementById("port-select"),
- currentPort = portsSelect.value;
-
- portsSelect.innerHTML = "";
- ports.forEach(function (port) {
- portsSelect.appendChild(utils.createElement("option", {
- innerText: port,
- value: port,
- selected: currentPort === port
- }));
+ event.on("VibratingModeChanged", function (value) {
+ if (value === false) {
+ stopVibrate();
+ }
});
-}
-
-module.exports = {
- panel: {
- domId: "push-container",
- collapsed: true,
- pane: "left"
- },
- initialize: function () {
- event.on("PushListenersChanged", function (listeners) {
- _updatePushPanel(listeners);
- jQuery("#port-select").effect("highlight", {color: "#62B4C8"}, 1000);
- });
-
- _updatePushPanel([]);
-
- document.getElementById("push-send")
- .addEventListener("click", function () {
- var port = document.getElementById("port-select").value,
- text = document.getElementById(PUSH_OPTIONS.PAYLOAD).value,
- pushData = {
- headerField: ["21f39092"],
- requestURI: "/",
- source: "ripple",
- isChannelEncrypted: false,
- payload: text
- };
-
- event.trigger("Push", [pushData, port], true);
- }, false);
- utils.bindAutoSaveEvent(jQuery("#" + PUSH_OPTIONS.PAYLOAD), function () {
- db.save(PUSH_OPTIONS.PAYLOAD, document.getElementById(PUSH_OPTIONS.PAYLOAD).value);
- });
+ return {
+ startVibrate: startVibrate,
+ stopVibrate: stopVibrate
+ };
+}()); //jslint style
- document.getElementById(PUSH_OPTIONS.PAYLOAD).value = db.retrieve(PUSH_OPTIONS.PAYLOAD) || "My payload data";
+var backlight = (function () {
+ var timeout = null,
+ isNotifying = false,
+ node = jQuery("#" + constants.COMMON.VIEWPORT_CONTAINER);
+
+ function _clearTimeout() {
+ if (timeout) {
+ clearTimeout(timeout);
+ timeout = null;
+ }
}
-};
-
-});
-define('ripple/ui/plugins/sensorSettings', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation.
- *
- * 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 constants = require('ripple/constants'),
- sensorSettings = require('ripple/sensorSettings'),
- utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- platform = require('ripple/platform'),
- _CONST = {
- "CONTENT_CONTAINER_ID": "sensorsettings-content-container",
- "UKNOWN_CONTROL_MESSAGE": "Unknown sensor control type"
- },
- _contentContainer,
- _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;
-
-function _appendSettingNode(labelNode, inputNode, label) {
- var frag = document.createDocumentFragment(),
- rowNode = frag.appendChild(utils.createElement("tr")),
- tempTdNode;
-
- rowNode.appendChild(utils.createElement("td"))
- .appendChild(labelNode);
-
- tempTdNode = rowNode.appendChild(utils.createElement("td"));
-
- if (label) {
- tempTdNode.appendChild(label);
+
+ function _switch(on) {
+ node.css('opacity', on ? '':'0.4');
}
-
- tempTdNode.appendChild(inputNode);
-
- return frag;
-}
-
-function _buildDOMNode(setting, settingType, key) {
- var settingsNode, tagName, jNode,
- fullKey = settingType + "." + key,
- savedSetting = sensorSettings.retrieve(fullKey),
- // TODO: move this into Utils (isSet method)
- currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value,
- domNode,
- domNodeLabel = null;
-
- switch (setting.control.type) {
- case "text":
- case "number":
- case "range":
- case "checkbox":
- tagName = "input";
- break;
- case "textarea":
- tagName = "textarea";
- break;
- case "select":
- tagName = "select";
- break;
- default:
- exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
+
+ function switchOff() {
+ if (!isNotifying) return;
+ _clearTimeout();
+ _switch(false);
+ isNotifying = false;
}
-
- settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);
-
- // TODO: this should really be part of utils.createControl? add element of type "range" with label?
- if (setting.control.type === "range") {
- domNodeLabel = utils.createElement("label", {
- "class": constants.UI.LEFT_RANGE_LABEL_CLASS
- });
+
+ function switchOn(duration) {
+ if (isBacklightOn()) return;
+ _clearTimeout();
+ _switch(true);
+ timeout = setTimeout(switchOff, checkDuration(duration));
+ isNotifying = true;
}
- domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": constants.UI.TEXT_LABEL_CLASS}), settingsNode, domNodeLabel);
-
- jNode = jQuery(settingsNode);
- jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);
+ _switch(isBacklightOn());
+ event.on("BacklightChanged", function (value) {
+ _clearTimeout();
+ isNotifying = false;
+ _switch(value);
+ });
- switch (setting.control.type) {
- case "checkbox":
- jNode.bind("click", function () {
- var checked = this.checked ? true : false;
- sensorSettings.persist(fullKey, checked);
- if (typeof setting.callback === "function") {
- setting.callback(checked);
- }
- });
+ return {
+ switchOn : switchOn,
+ switchOff : switchOff
+ };
+}()); //jslint style
- if (currentSetting === true) {
- jNode.attr("checked", "checked");
+var beeper = (function () {
+ var isBeeping = false,
+ timeout = null,
+ beepFile = "beep.wav", //TODO: license issues
+ errorHandler = null,
+ _beeper = utils.createElement("audio", {"id": "notify-beeper"});
+
+ document.getElementById("ui").appendChild(_beeper);
+ _beeper.setAttribute("src", beepFile);
+ _beeper.setAttribute("loop", "true");
+ _beeper.load();
+
+ function _clearTimeout() {
+ if (timeout) {
+ clearTimeout(timeout);
+ timeout = false;
}
-
- break;
-
- case "text":
- case "textarea":
- case "number":
- jNode.val(currentSetting);
- utils.bindAutoSaveEvent(jNode, function () {
- sensorSettings.persist(fullKey, jNode.val());
- if (typeof setting.callback === "function") {
- setting.callback(jNode.val());
- }
- });
- break;
-
- case "select":
- case "range":
- if (setting.control.type === "select") {
- utils.forEach(setting.options, function (value, option) {
- jNode.append(utils.createElement("option", {
- "value": option,
- "innerText": value
- }));
- });
+ }
+
+ function raiseError() {
+ if (errorHandler) {
+ setTimeout(function () {
+ errorHandler(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }, 1);
}
- else {
- if (domNodeLabel) {
- domNodeLabel.innerText = currentSetting;
- }
+ }
+
+ function stopBeep() {
+ _clearTimeout();
+ if (isBeeping) {
+ try {
+ _beeper.pause();
+ } catch (e) {}
+ isBeeping = false;
}
-
- jNode.val(currentSetting)
- .bind("change", function () {
- if (setting.control.type === "range" && domNodeLabel) {
- domNodeLabel.innerText = jQuery(this).val();
- }
- sensorSettings.persist(fullKey, jQuery(this).val());
-
- if (typeof setting.callback === "function") {
- setting.callback(jQuery(this).val());
- }
- }
- );
}
-
- // TODO: Brent, do in DeviceSettings on load instead?
- if (currentSetting !== setting.control.value) {
- sensorSettings.register(fullKey, currentSetting);
+
+ _beeper.addEventListener('error', function () {
+ stopBeep();
+ raiseError();
+ });
+
+ function startBeep(onSuccess, onError, duration) {
+ errorHandler = onError;
+ try {
+ stopBeep();
+ _beeper.currentTime = 0;
+ _beeper.play();
+ isBeeping = true;
+ timeout = setTimeout(stopBeep, checkDuration(duration));
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ }catch (e) {
+ raiseError();
+ }
}
+
+ event.on("VolumeChanged", function (value) {
+ value = value | 0;
+ if (value < 0) value = 0;
+ else if (value > 100) value = 100;
+ _beeper.volume = value / 100.0;
+ });
+
+ return {
+ startBeep : startBeep,
+ stopBeep : stopBeep
+ };
+}()); //jslint style
- return domNode;
-}
-
-// goes through current platforms sensor settings
-// adds nodes to panel and binds respective events
-// talks to SensorSettings for persistence
-module.exports = {
- panel: {
- domId: "sensors-panel-container",
- collapsed: true,
- pane: "right",
- titleName: "Sensors",
- display: true
- },
- initialize: function () {
- var settings;
-
- _contentContainer = document.getElementById(_CONTAINER_ID);
+module.exports = _self = {
- settings = platform.current().sensor;
+ startNotify : function (onSuccess, onError, duration) {
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "startNotify", function () {
+ if (!isMute()) {
+ return pendingOperation(function () {
+ beeper.startBeep(onSuccess, onError, duration);
+ });
+ } else if (isInVibrateMode()) {
+ return _self.startVibrate(onSuccess, onError, duration);
+ } else {
+ return _self.lightOn(onSuccess, onError, duration);
+ }
+ });
+ },
- utils.forEach(settings, function (settingSection, settingType) {
+ stopNotify : function () {
+ beeper.stopBeep();
+ vibrator.stopVibrate();
+ backlight.switchOff();
+ },
- var currentTableNode, flag = false;
+ startVibrate : function (onSuccess, onError, duration, pattern) {
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "startVibrate", function () {
+ if (pattern) {
+ pattern = String(pattern);
+ if (!pattern.match(/[\._]{1,10}/)) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ }
- utils.forEach(settingSection, function (setting, key) {
- if (typeof setting === "object") {
- flag = true;
- return;
+ if (!isInVibrateMode()) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }, 1);
}
- });
-
- if (flag) {
- _contentContainer.appendChild(utils.createElement("h3", { "innerText": settingType }));
+ return undefined;
}
-
- currentTableNode = utils.createElement("table", {
- "class": constants.UI.PANEL_TABLE_CLASS
+
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ return pendingOperation(function () {
+ vibrator.startVibrate(duration, pattern);
});
- _contentContainer.appendChild(currentTableNode);
+ });
+ },
+
+ stopVibrate : function () {
+ vibrator.stopVibrate();
+ },
- utils.forEach(settingSection, function (setting, key) {
- if (typeof setting === "object") {
- currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
+ lightOn : function (onSuccess, onError, duration) {
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "lightOn", function () {
+ if (isBacklightOn()) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }, 1);
}
+ return undefined;
+ }
+
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ return pendingOperation(function () {
+ backlight.switchOn(duration);
+ });
+ });
+ },
+
+ lightOff : function () {
+ backlight.switchOff();
+ },
+ setWallpaper : function (onSuccess, onError, fileName) {
+ //TODO: file name, existance, extension checking.
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "setWallpaper", function () {
+ return pendingOperation(function () {
+ notifications.openNotification("normal", "setWallpaper:" + fileName);
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
});
});
}
};
+
});
-define('ripple/ui/plugins/sensors', function (require, exports, module) {
+define('ripple/platform/wac/2.0/deviceapierror', function (require, exports, module) {
/*
- * Copyright (c) 2010 Epic Train Hack
- * Copyright (c) 2011 Research In Motion Limited
- * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
+ * Copyright 2011 Intel Corporation.
*
- * 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:
+ * 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
*
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * 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.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 event = require('ripple/event'),
- accelerometer = require('ripple/accelerometer'),
- deviceSettings = require('ripple/deviceSettings'),
- Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
- Rotation = require('ripple/platform/w3c/1.0/Rotation'),
- sensorSettings = require('ripple/sensorSettings'),
- _oldX, _oldY, _oldAlphaX,
- _camera, _scene, _renderer, _mesh,
- _offsets = {
- x: 0,
- y: 0,
- z: -9.81,
- },
- _flag, // whether the browser supports webGL
- _shape =
- //
- // The front side
- //
- // x, y, z x, y, z x, y, z
- // for some strange reason for y -100 is top, 100 is bottom
- "-30,30,10, 30,30,10, 30,60,10, 100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
- "-30,30,10, 30,60,10, -30,60,10, 100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
- // front side "the phone display"
- "-20,-50,11, 20,-50,11, 20,20,11, 100,100,100,-1,0;" +
- "-20,-50,11, 20,20,11, -20,20,11, 100,100,100,-1,0;" +
- // below the display
- "-30,30,10, 30,20,10, 30,30,10, 0,0,0,-1,0;" +
- "-30,30,10, -30,20,10, 30,20,10, 0,0,0,-1,0;" +
- // above the display
- "-30,-60,10, 30,-60,10, 30,-50,10, 0,0,0,-1,0;" +
- "-30,-60,10, 30,-50,10, -30,-50,10, 0,0,0,-1,0;" +
- // left of the display
- "-30,-50,10, -20,-50,10, -20,20,10, 0,0,0,-1,0;" +
- "-30,-50,10, -20,20,10, -30,20,10, 0,0,0,-1,0;" +
- // right of the display
- "20,-50,10, 30,-50,10, 30,20,10, 0,0,0,-1,0;" +
- "20,-50,10, 30,20,10, 20,20,10, 0,0,0,-1,0;" +
+var errorcode = require('ripple/platform/wac/2.0/errorcode');
- // back side, opposite side to the above one
- "-30,-60,-10, 30,60,-10, 30,-60,-10, 0,0,0,-1,0;" +
- "-30,-60,-10, -30,60,-10, 30,60,-10, 0,00,-1,0;" +
- // right side
- "30,-60,-10, 30,60,-10, 30,60,10, 50,50,80,-1,0;" +
- "30,-60,-10, 30,60,10, 30,-60,10, 50,50,80,-1,0;" +
- // left side
- "-30,-60,-10, -30,60,10, -30,60,-10, 50,50,80,-1,0;" +
- "-30,-60,-10, -30,-60,10, -30,60,10, 50,50,80,-1,0;" +
+module.exports = function (code) {
+ for (var c in errorcode) {
+ var g = errorcode.__lookupGetter__(c);
+ if (g) {
+ this.__defineGetter__(c, g);
+ }
+ }
- // top
- "30,-60,-10, -30,-60,10, -30,-60,-10, 50,80,50,-1,0;" +
- "30,-60,-10, 30,-60,10, -30,-60,10, 50,80,50,-1,0;" +
- // bottom
- "30,60,-10, -30,60,-10, -30,60,10, 80,50,50,-1,0;" +
- "30,60,-10, -30,60,10, 30,60,10, 80,50,50,-1,0";
+ this.code = code;
+ this.message = errorcode.message[code];
+ this.type = "";
-function _createThreeDModel() {
- var node,
- shader,
- hemiLight,
- dirLight,
- material,
- uniforms,
- container,
- loader,
- directionalLight,
- isDiffuseTextureLoaded,
- isNormalTextureLoaded,
- shiftKeyDown,
- mouseDown,
- ctrlKeyDown = false;
+ this.toString = function () {
+ var result = this.type + ': "' + this.message + '"';
- if (_flag) {
- // create a 3D phone model with three.js if webGL is supported
- node = document.getElementById("accelerometer-div");
- container = document.createElement("div");
- $("#accelerometer-div").append(container);
+ if (this.stack) {
+ result += "\n" + this.stack;
+ }
+ return result;
+ };
+};
- _camera = new THREE.PerspectiveCamera(50, 1.5, 0.1, 100);
- _camera.position.set(4.32823, 3.74714, 2.62985);
- _scene = new THREE.Scene();
- _scene.add(new THREE.AmbientLight(0xffffff));
- directionalLight = new THREE.DirectionalLight(0xffffff, 1);
- directionalLight.position.set(1, 1, 1).normalize();
- _scene.add(directionalLight);
- hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
- hemiLight.color.setHSV(0.6, 0.75, 1);
- hemiLight.groundColor.setHSV(0.095, 0.5, 1);
- hemiLight.position.set(0, 500, 0);
- _scene.add(hemiLight);
- dirLight = new THREE.DirectionalLight(0xffffff, 1);
- dirLight.color.setHSV(0.1, 0.1, 1);
- dirLight.position.set(-1, 1.75, 1);
- dirLight.position.multiplyScalar(50);
- _scene.add(dirLight);
- shader = THREE.ShaderSkin["skin"];
- uniforms = THREE.UniformsUtils.clone(shader.uniforms);
- uniforms["tNormal"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tNormal.png", {}, function () {
- isNormalTextureLoaded = true;
- if (isDiffuseTextureLoaded) {
- _renderer.clear();
- _renderer.render(_scene, _camera);
- }
- });
- uniforms["uNormalScale"].value = 0.75;
- uniforms["tDiffuse"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tDiffuse.png", {}, function () {
- isDiffuseTextureLoaded = true;
- if (isNormalTextureLoaded) {
- _renderer.clear();
- _renderer.render(_scene, _camera);
- }
- });
- uniforms["uDiffuseColor"].value.setHex(0xbbbbbb);
- uniforms["uSpecularColor"].value.setHex(0x070707);
- uniforms["uAmbientColor"].value.setHex(0x111111);
- uniforms["uRoughness"].value = 0.185;
- uniforms["uSpecularBrightness"].value = 0.8;
- material = new THREE.ShaderMaterial({ fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true });
- loader = new THREE.JSONLoader(true);
- document.body.appendChild(loader.statusDomElement);
- loader.load("phoneModel.js", function (geometry) {
- loader.statusDomElement.style.display = "none";
- geometry.computeTangents();
- _mesh = new THREE.Mesh(geometry, material);
- _mesh.position.set(7, 2, -50);
- _mesh.scale.set(18, 12, 18);
- _scene.add(_mesh);
- _renderer.clear();
- _renderer.render(_scene, _camera);
- });
+});
+define('ripple/platform/wac/2.0/camera', function (require, exports, module) {
+/*
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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.
+ */
- _renderer = new THREE.WebGLRenderer({antialias: false});
- _renderer.setSize(300, 280);
- _renderer.setClearColorHex(0xffffff, 1);
- _renderer.autoClear = false;
+var utils = require('ripple/utils'),
+ constants = require('ripple/constants'),
+ _console = require('ripple/console'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils');
- container.appendChild(_renderer.domElement);
- } else { // create the model with 3d.js
- node = document.querySelector("#accelerometer-canvas");
+module.exports = function () {
+ var _cameraArray, Camera, _videoStatus = {},
+ _captureImage, _startVideoCapture,
+ _doCaptureImage, _doStartVideoCapture,
+ _doGetPreview, _doGetCameras,
+ _stopVideoCapture, _createPreviewNode,
+ _FAKEWAITTIME = 5,
+ _defaultHighRes = true,
+ _defaultImageFilename = "_capture.jpg",
+ _defaultVideoFilename = "_capture.avi",
+ _captureImageAllowed = true,
+ _startVideoCaptureAllowed = true,
+ _stopVideoCaptureAllowed = true,
+ _createPreviewNodeAllowed = true;
- jQuery("#accelerometer-div").css("display", "none");
- jQuery("#accelerometer-canvas").css("display", "block");
- ThreeDee.setCenter(150, 100);
- ThreeDee.setLight(-300, -300, 800);
- _updateCanvas(0, 0);
- }
+ _doCaptureImage = function (onSuccess, onError, capFilename, capHighRes, pendingObj) {
+ pendingObj.pendingID = setTimeout(function () {
+ var dname = "", fname = "";
+ //pretend to do sth.
+ pendingObj.setCancelFlag(false); // too late to cancel
+ if (capFilename.indexOf("/") !== -1) {
+ dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
+ fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
+ //replace extension with jpg
+ fname = fname.replace(/\.[^\/\.]+$/i, ".jpg");
+ } else {
+ dname = "";
+ fname = capFilename.replace(/\.[^\/\.]+$/i, ".jpg");
+ }
+ if (fname === "") {
+ fname = _defaultImageFilename;
+ }
+ if (fname.search(/\.jpg$/) === -1) {
+ fname = fname + ".jpg";
+ }
+ if (capHighRes) {
+ onSuccess(dname + "high-" + fname);
+ } else {
+ onSuccess(dname + "low-" + fname);
+ }
+ }, _FAKEWAITTIME);
+ };
- //change accelerometer and phone by moving the mouse and the key "shift"
- node.addEventListener("mousemove", function (event) {
- var cosX, sinX, cosY, sinY,
- alpha = accelerometer.getInfo().orientation.alpha,
- beta = accelerometer.getInfo().orientation.beta,
- gamma = accelerometer.getInfo().orientation.gamma,
- x = accelerometer.getInfo().acceleration.x,
- y = accelerometer.getInfo().acceleration.y,
- z = accelerometer.getInfo().acceleration.z;
+ _captureImage = function (onSuccess, onError, options) {
+ var pendingOperation = {}, pendingObj,
+ filename = this.id + _defaultImageFilename,
+ highRes = _defaultHighRes, opt;
- if (!mouseDown) {
- return;
+ if (onSuccess) {
+ utils.validateArgumentType(onSuccess, "function", null, "captureImage: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
}
-
- // if the shift key is pressed down, only the alpha value will be chagned
- if (!shiftKeyDown) {
- _offsets.x = (_offsets.x + _oldX - event.offsetX) % 360;
- _offsets.y = (_offsets.y + _oldY - event.offsetY) % 360;
-
- alpha = alpha || 0;
-
- // enforce gamma in [-90,90] as per w3c spec
- gamma = -_offsets.x;
- if (gamma < -90) {
- gamma = -90;
- }
- if (gamma > 90) {
- gamma = 90;
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null, "captureImage: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (options) {
+ opt = new Object(options);
+ /* NOTE: if desktinationFilename or highRes is not provided by
+ user, i.e. undefined or null, a default value is used.
+ */
+ if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
+ // TODO: validate filename via Filesystem.resolve()
+ filename = String(opt.destinationFilename);
}
-
- // enforce beta in [-180,180] as per w3c spec
- beta = -_offsets.y % 360;
- if (beta < -180) {
- beta += 360;
+ if (opt.highRes !== null && opt.highRes !== undefined) {
+ highRes = Boolean(opt.highRes);
}
- else if (beta >= 180) {
- beta -= 360;
+ }
+ if (!_captureImageAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
}
+ return undefined;
+ }
- cosX = Math.cos(gamma * (Math.PI / 180));
- sinX = Math.sin(gamma * (Math.PI / 180));
- cosY = Math.cos(beta * (Math.PI / 180));
- sinY = Math.sin(beta * (Math.PI / 180));
- x = 9.81 * cosY * sinX;
- y = -9.81 * sinY;
- z = -9.81 * cosY * cosX;
-
+ if (onSuccess) {
+ pendingObj = new PendingObject();
+ _doCaptureImage(onSuccess, onError, filename, highRes, pendingObj);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
} else {
- alpha = (alpha - (_oldAlphaX - event.offsetX) * 2.5) % 360;
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
}
- _oldX = event.offsetX;
- _oldY = event.offsetY;
- _oldAlphaX = event.offsetX;
- if (_flag)
- _updatePhoneModel(alpha, beta, gamma);
- else
- _updateCanvas(alpha, -beta, gamma);
- accelerometer.setInfo({
- x: x,
- y: y,
- z: z,
- alpha: alpha,
- beta: beta,
- gamma: gamma
- });
- }, false);
+ return undefined;
+ };
- node.addEventListener("mousedown", function (e) {
- mouseDown = true;
- _oldX = e.offsetX;
- _oldY = e.offsetY;
- if (shiftKeyDown) {
- _oldAlphaX = _oldX;
+ _stopVideoCapture = function () {
+ var dname = "", fname = "", capFilename = _videoStatus[this.id].capFilename;
+ if (_videoStatus[this.id]) {
+ if (capFilename.indexOf("/") !== -1) {
+ dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
+ fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
+ //replace extension with avi
+ fname = fname.replace(/\.[^\/\.]+$/i, ".avi");
+ } else {
+ dname = "";
+ fname = capFilename.replace(/\.[^\/\.]+$/i, ".avi");
+ }
+ if (fname === "") {
+ fname = _defaultVideoFilename;
+ }
+ if (fname.search(/\.avi$/) === -1) {
+ fname = fname + ".avi";
+ }
+ if (_videoStatus[this.id].capHighRes) {
+ _videoStatus[this.id].capSuccess(dname + "high-" + fname);
+ } else {
+ _videoStatus[this.id].capSuccess(dname + "low-" + fname);
+ }
+ delete _videoStatus[this.id];
}
- });
+ };
- node.addEventListener("mouseup", function () {
- mouseDown = false;
- });
+ _doStartVideoCapture = function (camID, onSuccess, onError, filename, highRes, pendingObj) {
+ var videoStatus = {};
+ _videoStatus[camID] = videoStatus;
+ pendingObj.userCancel = function () {
+ delete _videoStatus[camID];
+ };
+ pendingObj.getCancelFlag = function () {
+ return !!_videoStatus[camID];
+ };
+ pendingObj.pendingID = setTimeout(function () {
+ // waiting to be cancelled
+ videoStatus = {
+ capSuccess: onSuccess,
+ capError: onError,
+ capFilename: filename,
+ capHighRes: highRes
+ };
+ _videoStatus[camID] = videoStatus;
+ }, _FAKEWAITTIME);
+ };
- document.addEventListener("mouseup", function () {
- //Catch mouseup events that fire when outside canvas bounds
- mouseDown = false;
- });
+ _startVideoCapture = function (onSuccess, onError, options) {
+ var pendingOperation = {}, pendingObj,
+ filename = this.id + _defaultVideoFilename,
+ highRes = _defaultHighRes, opt;
- document.addEventListener("keydown", function (e) {
- switch (e.keyCode) {
- case 16: // Shift Key
- shiftKeyDown = true;
- break;
- case 17: // Ctrl Key
- ctrlKeyDown = true;
- break;
- case 74: // J Key
- if (shiftKeyDown && ctrlKeyDown) { //if shift+ctrl+j keydown in the meantime, console comes up rather than shift key down
- shiftKeyDown = false;
- ctrlKeyDown = false;
+ if (onSuccess) {
+ utils.validateArgumentType(onSuccess, "function", null, "startVideoCapture: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null, "startVideoCapture: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (options) {
+ opt = new Object(options);
+ /* NOTE: if desktinationFilename or highRes is not provided by
+ user, i.e. undefined or null, a default value is used.
+ */
+ if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
+ // TODO: validate filename via Filesystem.resolve()
+ filename = String(opt.destinationFilename);
+ }
+ if (opt.highRes !== null && opt.highRes !== undefined) {
+ highRes = Boolean(opt.highRes);
}
- break;
}
- });
-
- document.addEventListener("keyup", function (e) {
- if (e.keyCode === 16) { // Shift Key
- shiftKeyDown = false;
+ if (!_captureImageAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (_videoStatus[this.id]) {
+ // capture already started
+ _console.warn("WAC-2.0-startVideoCapture: capture already started");
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }, 1);
+ }
+ return undefined;
}
- });
-}
-
-// update the 3d model created by 3d.js
-function _updateCanvas(a, b, g) {
- ThreeDee.loadMesh(_shape);
- g = g || 0;
- ThreeDee.rotate(0, g, 0);
- ThreeDee.rotate(b, 0, a);
- ThreeDee.backface();
- ThreeDee.shade();
- ThreeDee.zSort();
- Draw.initialize(document.querySelector("#accelerometer-canvas"));
- Draw.clear(0, 0, 480, 300);
- Draw.drawScene(ThreeDee.getTranslation(), 3);
-}
-
-// update the 3d model created by three.js
-function _updatePhoneModel(a, b, g) {
- _mesh.rotation.x = b / 90 * 1.5;
- _mesh.rotation.y = g / 90 * 1.5;
- _mesh.rotation.z = a / 90 * 1.5;
- _renderer.clear();
- _renderer.render(_scene, _camera);
-}
-function _resetAccelerometer() {
- _oldX = 0;
- _oldY = 0;
- _oldAlphaX = 0;
- _offsets = {
- x: 0,
- y: 0,
- z: -9.81
+ if (onSuccess) {
+ pendingObj = new PendingObject();
+ _doStartVideoCapture(this.id, onSuccess, onError, filename, highRes, pendingObj);
+
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
};
- if (_flag) {
- _mesh.rotation.x = 0;
- _mesh.rotation.y = 0;
- _mesh.rotation.z = 0;
- _renderer.clear();
- _renderer.render(_scene, _camera);
- } else {
- _updateCanvas(0, 0);
- }
-
- accelerometer.setInfo({
- acceleration: new Acceleration(0, 0, 0),
- accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
- rotationRate: new Rotation(0, 0, 0),
- orientation: new Rotation(0, 0, 0),
- timestamp: new Date().getTime()
- });
- accelerometer.triggerEvent();
-}
-function _resetMagneticField() {
- jQuery("#magnetic-x").val("100");
- jQuery("#magnetic-y").val("100");
- jQuery("#magnetic-z").val("100");
-}
+ _doGetPreview = function (camID, onSuccess, onError, pendingObj) {
+ var container, demoImg, loc, imageSrc;
+ container = document.createElement("div");
+ container.setAttribute("id", camID + "-wac-2-0-camera-preview-container");
+ demoImg = document.createElement("img");
+ demoImg.setAttribute("id", camID + "-wac-2-0-camera-demo-image");
+ loc = document.location;
+ imageSrc = loc.protocol + "//" + loc.hostname + loc.pathname.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION;
+ demoImg.setAttribute("src", imageSrc);
+ demoImg.setAttribute("width", "100%");
+ container.appendChild(demoImg);
+
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false); // too late to cancel
+ onSuccess(container);
+ }, _FAKEWAITTIME);
+ };
-function _resetLightLevel() {
- $("#display-state").children().each(function() {
- if ($(this).val() === "OFF") {
- $(this).attr("selected", "true");
- this.selected = true;
+ _createPreviewNode = function (onSuccess, onError) {
+ var pendingOperation, pendingObj = {};
+ if (onSuccess) {
+ utils.validateArgumentType(onSuccess, "function", null, "createPreviewNode: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
}
- else {
- $(this).attr("selected", "false");
- this.selected = false;
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null, "createPreviewNode: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
}
- });
-}
-
-
-// set a typical mode for accelerometer simulation, when the phone drops,
-// x will become to be 0, y will become to be -9.81 and z will become to be 0
-function _setDrop() {
- //duration = 20 * 50 = 1000ms. 20 is ths number of steps and 50 is the duration of steps.
- var alpha = Number(accelerometer.getInfo().orientation.alpha),
- beta = Number(accelerometer.getInfo().orientation.beta),
- gamma = Number(accelerometer.getInfo().orientation.gamma),
- cosX, cosY, sinX, sinY, x, y, z,
- alphaStep = Math.abs(alpha) / 20,
- betaStep = Math.abs(beta - 90) / 20,
- gammaStep = Math.abs(gamma) / 20,
- counts = 0, dropTimeout,
- drop = function () {
- if (counts >= 20) {
- window.clearTimeout(dropTimeout);
- // to avoid showing "-0" or "-0.00"
- if (_flag)
- _updatePhoneModel(0, 90, 0);
- else
- _updateCanvas(0, -90, 0);
- accelerometer.setInfo({
- x: 0,
- y: -9.81,
- z: 0,
- alpha: 0,
- beta: 90,
- gamma: 0
- });
- } else {
- dropTimeout = setTimeout(drop, 50);
- step();
- counts++;
+ if (!_createPreviewNodeAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
}
- },
- step = function () {
- var _beta;
-
- alpha = alpha > 0 ? alpha - alphaStep : alpha + alphaStep;
- beta = beta > 90 ? beta - betaStep : beta + betaStep;
- gamma = gamma > 0 ? gamma - gammaStep : gamma + gammaStep;
- _beta = _flag ? beta + betaStep : -(beta + betaStep);
- if (_flag)
- _updatePhoneModel(alpha, _beta, gamma);
- else
- _updateCanvas(alpha, _beta, gamma);
+ return undefined;
+ }
+ if (onSuccess) {
+ pendingObj = new PendingObject();
+ _doGetPreview(this.id, onSuccess, onError, pendingObj);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
+ };
- cosX = Math.cos(gamma * (Math.PI / 180));
- sinX = Math.sin(gamma * (Math.PI / 180));
- cosY = Number(Math.cos(beta * (Math.PI / 180)).toFixed(6));
- sinY = Math.sin(beta * (Math.PI / 180));
- x = 9.81 * cosY * sinX;
- y = -9.81 * sinY;
- z = -9.81 * cosY * cosX;
- accelerometer.setInfo({
- x: x,
- y: y,
- z: z,
- alpha: alpha,
- beta: beta,
- gamma: gamma
- });
- _offsets.x = -gamma;
- _offsets.y = -beta;
+ Camera = function (cameraID) {
+ return {
+ id: cameraID,
+ captureImage: _captureImage,
+ startVideoCapture: _startVideoCapture,
+ stopVideoCapture: _stopVideoCapture,
+ createPreviewNode: _createPreviewNode
};
+ };
- drop();
-}
-
-function _initializeSensorSettings() {
- var sensorsInputID = ["accelerometer-alpha", "accelerometer-beta", "accelerometer-gamma", "magnetic-x", "magnetic-y", "magnetic-z"],
- magneticEvent = ["MagneticField-xChanged", "MagneticField-yChanged", "MagneticField-zChanged"],
- magneticData = ["MagneticField.x", "MagneticField.y", "MagneticField.z"],
- oldValue, oldInputX,
- inputMouseDown,
- triggerFunction,
- selectedInputID = null;
+ _cameraArray = [new Camera("rear"), new Camera("front")];
- triggerFunction = function (val, index) {
- var cosX, cosY, sinX, sinY, x, y, z,
- alpha = accelerometer.getInfo().orientation.alpha,
- beta = accelerometer.getInfo().orientation.beta,
- gamma = accelerometer.getInfo().orientation.gamma;
+ _doGetCameras = function (onSuccess, onError, pendingObj) {
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false); // too late to cancel
+ if (_cameraArray.length !== 0) {
+ onSuccess(utils.copy(_cameraArray));
+ } else {
+ // no camera
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }, 1);
+ }
+ }
+ }, _FAKEWAITTIME);
+ };
- //choose which value to change according to index
- switch (index) {
- case 0:
- alpha = val;
- break;
- case 1:
- beta = val;
- break;
- case 2:
- gamma = val;
- break;
- default:
- sensorSettings.persist(magneticData[index - 3], val);
- event.trigger(magneticEvent[index - 3], [val]);
+ this.getCameras = function (onSuccess, onError) {
+ var pendingOperation, pendingObj = {};
+ if (onSuccess) {
+ utils.validateArgumentType(onSuccess, "function", null, "getCameras: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
}
-
- //change the phone model and values of other inputs when changing a value of input
- if (_flag)
- _updatePhoneModel(alpha, beta, gamma);
- else
- _updateCanvas(alpha, -beta, gamma);
- cosX = Math.cos(gamma * (Math.PI / 180));
- sinX = Math.sin(gamma * (Math.PI / 180));
- cosY = Math.cos(beta * (Math.PI / 180));
- sinY = Math.sin(beta * (Math.PI / 180));
- x = 9.81 * cosY * sinX;
- y = -9.81 * sinY;
- z = -9.81 * cosY * cosX;
- accelerometer.setInfo({
- x: x,
- y: y,
- z: z,
- alpha: alpha,
- beta: beta,
- gamma: gamma
- });
- _offsets.x = -gamma;
- _offsets.y = -beta;
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null, "getCameras: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
+ if (onSuccess) {
+ pendingObj = new PendingObject();
+ _doGetCameras(onSuccess, onError, pendingObj);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
};
- // make the input elements more powful: drag mouse to left to decrease the value and right to increase it;
- // also change the value with arrow keys.
-
+ this.handleSubFeatures = function (subFeatures) {
+ if (wac2_utils.isEmptyObject(subFeatures) ||
+ subFeatures["http://wacapps.net/api/camera"] ||
+ (subFeatures["http://wacapps.net/api/camera.capture"] &&
+ subFeatures["http://wacapps.net/api/camera.show"])) {
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/camera.show"] &&
+ !subFeatures["http://wacapps.net/api/camera.capture"]) {
+ _captureImageAllowed = false;
+ _startVideoCaptureAllowed = false;
+ _stopVideoCaptureAllowed = false;
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/camera.capture"] &&
+ !subFeatures["http://wacapps.net/api/camera.show"]) {
+ _createPreviewNodeAllowed = false;
+ return;
+ }
+ _console.warn("WAC-2.0-Camera-handleSubFeatures: something wrong");
+ };
+};
- sensorsInputID.forEach(function (id, index) {
- jQuery("#" + id).mousedown(function (e) {
- selectedInputID = id;
- oldValue = parseInt(this.value, 10);
- oldInputX = e.offsetX;
- inputMouseDown = true;
- });
+});
+define('ripple/platform/wac/2.0/wac2_utils', function (require, exports, module) {
+/*
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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.
+ */
- jQuery("#" + id).mousemove(function (e) {
- if (inputMouseDown && (selectedInputID !== null)) {
- jQuery("#" + selectedInputID).val(parseInt(oldValue + (e.offsetX - oldInputX) / 2, 10));
- if (parseInt(this.value, 10) <= parseInt(jQuery(this).attr("minValue"), 10)) {
- this.value = jQuery(this).attr("minValue");
- }
- if (parseInt(this.value, 10) >= parseInt(jQuery(this).attr("maxValue"), 10)) {
- this.value = jQuery(this).attr("maxValue");
- }
- triggerFunction(this.value, index);
- }
- });
+var utils = require('ripple/utils'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror');
- jQuery("#" + id).mouseup(function () {
- selectedInputID = null;
- inputMouseDown = false;
- });
- jQuery(document).mouseup(function () {
- selectedInputID = null;
- inputMouseDown = false;
- });
+module.exports = {
+ _wac2_regexSanitize: function (regexString) {
+ var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
+ return regexString.replace("^", "\\^")
+ .replace("$", "\\$")
+ .replace("(", "\\(")
+ .replace(")", "\\)")
+ .replace("<", "\\<")
+ .replace("[", "\\[")
+ .replace("{", "\\{")
+ .replace(/\\([^%])/, "\\\\$1") /* don't replace \\% */
+ .replace("|", "\\|")
+ .replace(">", "\\>")
+ .replace(".", "\\.")
+ .replace("*", "\\*")
+ .replace("+", "\\+")
+ .replace("?", "\\?")
+ .replace(escapePattern, "$1.*") /* replace % with .* */
+ .replace(percentPattern, "%"); /* strip excape of % */
+ },
- jQuery("#" + id).click(function () {
- this.select();
- });
+ isValidDate: function (d) {
+ if (Object.prototype.toString.call(d) !== "[object Date]")
+ return false;
+ return !isNaN(d.getTime());
+ },
- jQuery("#" + id).blur(function () {
- if (isNaN(this.value)) {
- this.value = 0;
- }
- else if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("maxValue"), 10))
- this.value = jQuery(this).attr("maxValue");
- else if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("minValue"), 10))
- this.value = jQuery(this).attr("minValue");
- else
- this.value = parseInt(this.value, 10);
- triggerFunction(this.value, index);
- });
+ isValidArray: function (a) {
+ return (Object.prototype.toString.call(a) === "[object Array]");
+ },
+
+ matchOptionArrayString: function (src, attr, pattern) {
+ /* src.obj[attr] is a StringArray */
+ var _pattern, re, _stringMatch;
+ _pattern = this._wac2_regexSanitize(pattern);
+ re = new RegExp("^" + _pattern + "$", "i");
- jQuery("#" + id).keydown(function (e) {
- switch (e.keyCode) {
- case 38:
- if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("maxValue"), 10)) {
- this.value = parseInt(this.value, 10) + 1;
- triggerFunction(this.value, index);
- }
- break;
- case 40:
- if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("minValue"), 10)) {
- this.value = parseInt(this.value, 10) - 1;
- triggerFunction(this.value, index);
- }
- break;
- default:
- return;
- }
- });
- });
-}
+ _stringMatch = function (obj, index) {
+ if (pattern.search(/^%*$/i) === 0)
+ return true;
+ if (obj[attr] === undefined || obj[attr] === null)
+ return false;
+ return obj[attr].some(function (f) {
+ return f.search(re) !== -1;
+ });
+ };
+ return utils.filter(src, _stringMatch);
+ },
-/*
-//initialize light settings
-function _initializeLightSettings() {
- var displayObj = document.getElementById("display-state"),
- DISPLAY_STATE = require('ripple/constants').POWER_RESOURCE.SCREEN.STATE,
- brightness;
+ matchOptionString: function (src, attr, pattern) {
+ /* src.obj[attr] is a string */
+ var _stringMatch, _pattern, _re;
+ _pattern = this._wac2_regexSanitize(pattern);
+ _re = new RegExp("^" + _pattern + "$", "mi");
- displayObj.addEventListener("change", function () {
- var state = displayObj.value, value;
- value = DISPLAY_STATE[state].VALUE;
- deviceSettings.persist("Display.brightness", value);
- event.trigger("DisplayBrightnessChanged", [value]);
- });
+ _stringMatch = function (obj, index) {
+ return (obj[attr].search(_re) !== -1);
+ };
+ return utils.filter(src, _stringMatch);
+ },
- brightness = deviceSettings.retrieve("Display.brightness");
- if (brightness === DISPLAY_STATE.SCREEN_OFF.MAX) {
- displayObj.options[0].selected = true;
- } else if (brightness <= DISPLAY_STATE.SCREEN_DIM.MAX) {
- displayObj.options[1].selected = true;
- } else if (brightness <= DISPLAY_STATE.SCREEN_NORMAL.MAX) {
- displayObj.options[2].selected = true;
- } else {
- displayObj.options[3].selected = true;
- }
-}
-*/
+ matchOptionDate: function (src, attr, filterStart, filterEnd) {
+ var _dateMatch;
+ _dateMatch = function (obj, index) {
+ var matched = true, valueDate = obj[attr];
+
+ if (filterStart !== undefined && filterStart !== null) {
+ matched = (valueDate.getTime() >= filterStart.getTime());
+ }
+ if (matched && (filterEnd !== undefined && filterEnd !== null)) {
+ matched = (valueDate.getTime() <= filterEnd.getTime());
+ }
+ return matched;
+ };
+ return utils.filter(src, _dateMatch);
+ },
-module.exports = {
- panel: {
- domId: "sensors-container",
- collapsed: true,
- pane: "left",
- titleName: "Sensors",
- display: true
+ matchOptionShortArray: function (src, attr, filterArray) {
+ /* src.obj[attr] is a short, filterArray is an array
+ i.e. find status is [CONFRIMED or TENTATIVE] */
+ var arraySome = function (obj, index) {
+ return filterArray.some(function (f) {
+ return f === obj[attr];
+ });
+ };
+ return utils.filter(src, arraySome);
},
- initialize: function () {
- var gl,
- testCanvas = document.getElementById("accelerometer-canvas");
- try { // check whether the browser supports webGL, returns null if not support
- gl = testCanvas.getContext("experimental-webgl");
- gl.viewport(0, 0, testCanvas.width, testCanvas.height);
- } catch (e) {
- console.log("unsupport webgl");
+ validateTypeMismatch: function (onSuccess, onError, name, callback) {
+ if (onSuccess) {
+ utils.validateArgumentType(onSuccess, "function", null,
+ name + " invalid successCallback parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
}
- _flag = gl ? true : false;
-
- accelerometer.init();
- _createThreeDModel();
- _initializeSensorSettings();
- //_initializeLightSettings();
-
- jQuery("#accelerometer-shake").click(function () {
- window.setTimeout(require('ripple/ui/plugins/goodVibrations').shakeDevice(8), 1);
- accelerometer.shake();
- });
+ if (onError) {
+ utils.validateArgumentType(onError, "function", null,
+ name + " invalid errorCallback parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+ }
- jQuery("#sensor-reset-all").click(function () {
- _resetAccelerometer();
- _resetMagneticField();
- _resetLightLevel();
- });
+ if (onSuccess) {
+ return callback && callback();
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
+ },
- jQuery("#accelerometer-drop").click(_setDrop);
+ isEmptyObject: function (obj) {
+ var prop;
- event.on("AccelerometerInfoChangedEvent", function (motion) {
- jQuery("#accelerometer-x").html(motion.accelerationIncludingGravity.x.toFixed(2));
- jQuery("#accelerometer-y").html(motion.accelerationIncludingGravity.y.toFixed(2));
- jQuery("#accelerometer-z").html(motion.accelerationIncludingGravity.z.toFixed(2));
- jQuery("#accelerometer-alpha").val(Number(motion.orientation.alpha).toFixed(2));
- jQuery("#accelerometer-beta").val(Number(motion.orientation.beta).toFixed(2));
- jQuery("#accelerometer-gamma").val(Number(motion.orientation.gamma).toFixed(2));
- }, this);
+ for (prop in obj) {
+ return false;
+ }
+ return true;
}
};
+
});
-define('ripple/ui/plugins/settings-dialog', function (require, exports, module) {
+define('ripple/platform/wac/2.0/contactfilter', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Intel Corporation.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+var utils = require('ripple/utils'),\r
+ _self;\r
+\r
+_self = function (criteria) {\r
+ var pattern,\r
+ contactFilter;\r
+\r
+ contactFilter = {\r
+ match: function (target) {\r
+ var result = false, key, value, index;\r
+\r
+ switch (Object.prototype.toString.call(target)) {\r
+ case "[object String]":\r
+ result = pattern.test(target);\r
+ break;\r
+\r
+ case "[object Object]":\r
+ for (key in criteria) {\r
+ result = true;\r
+ value = criteria[key];\r
+ if ((value !== undefined) && (!_self(value).match(target[key])))\r
+ return false;\r
+ }\r
+ break;\r
+\r
+ case "[object Array]":\r
+ for (index in target) {\r
+ if (contactFilter.match(target[index]))\r
+ return true;\r
+ }\r
+ break;\r
+ }\r
+\r
+ return result;\r
+ }\r
+ };\r
+\r
+ if (typeof criteria === "string")\r
+ pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");\r
+\r
+ return contactFilter;\r
+};\r
+\r
+module.exports = _self;\r
+
+});
+define('ripple/platform/wac/2.0/contact', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- utils = require('ripple/utils'),
- platform = require('ripple/platform'),
- notifications = require('ripple/notifications'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- bus = require('ripple/bus'),
- required = {
- build: {
- "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName"],
- "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName"],
- "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName"]
- },
- sign: {
- "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "csk_password", "p12_password", "bundle_number"],
- "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword", "bundle_number"],
- "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword"]
- },
- launch: {
- "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "device"],
- "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "device"],
- "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "simulator"]
- }
- },
- _settings = {
- get: function () {
- var settings = db.retrieveObject("build-settings", platform.getPersistencePrefix()) || {};
- settings.debug = !!settings["remoteInspector"];
- return settings;
- },
- save: function (settings) {
- db.saveObject("build-settings", settings, platform.getPersistencePrefix());
- }
+var utils = require('ripple/utils'),
+ db = require('ripple/db'),
+ constants = require('ripple/constants'),
+ exception = require('ripple/exception'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
+ Filter = require('ripple/platform/wac/2.0/contactfilter'),
+ AddressBook,
+ ContactProperties,
+ Contact,
+ Address,
+ ContactAddress,
+ PhoneNumber,
+ EmailAddress,
+ ContactFilter,
+ _KEY = "wac2-pim-contact",
+ _PENDING_TIME = 600,
+ _addressBooks = [],
+ _contacts = {},
+ _security = {
+ "http://wacapps.net/api/pim.contact": [],
+ "http://wacapps.net/api/pim.contact.read": ["findContacts"],
+ "http://wacapps.net/api/pim.contact.write": ["addContact", "updateContact", "deleteContact"],
+ all: true
},
- port = "9910",
- host = "http://127.0.0.1:" + port + "/ripple",
- progressContainer = jQuery("#options-progress"),
- progressInterval,
- _passwordFields = [
- "signingPassword",
- "devicePassword",
- "csk_password",
- "p12_password"
- ],
- _checkboxFields = [
- "remoteInspector"
- ],
- _passwords = {},
_self;
-function missing(settings, action) {
- return required[action][platform.current().id].filter(function (field) {
- return !settings.hasOwnProperty(field);
- });
-}
-
-function _isPasswordField(id) {
- var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
- return match && utils.some(_passwordFields, function (name) {
- return match.test(name);
- });
-}
-
-function _isCheckboxField(id) {
- var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
- return match && utils.some(_checkboxFields, function (name) {
- return match.test(name);
- });
-}
-
-function table(action) {
- var _table = $("<table class='panel-table'>"),
- _row = {
- row: function (item, desc, opts) {
- var id = "settings-field-" + item.toLowerCase(),
- input = "",
- save = function () {
- var s = _settings.get(),
- v = $("#" + id).val(),
- val = opts.type === "number" ? parseInt(v, 10) : v;
-
- if (_isCheckboxField(item)) {
- s[item] = $("#" + id).prop("checked");
- }
- else if (val) {
- (_isPasswordField(item) ? _passwords : s)[item] = val;
- }
- else {
- delete s[item];
- }
- _settings.save(s);
-
- if (opts.onChanged) {
- opts.onChanged(s[item]);
- }
- },
- row;
-
- opts = opts || { type: "text" };
-
- switch (opts.type) {
- case "select":
- input = "<select id='" + id + "' class='ui-state-default ui-corner-all' style='width:100%'/>";
- break;
- case "span":
- input = "<span id = '" + id + "'>" + opts.text + "</span>";
- break;
- default:
- input = "<input id='" + id + "' type='" + opts.type + "' class='ui-state-default ui-corner-all' style='width:90%' />";
- break;
- }
-
- row = $("<tr>" +
- "<td><label for='" + id + "' class='ui-text-label'>" + desc + "</label></td>" +
- "<td>" + input + "</td>" +
- "</tr>");
-
- row.appendTo(_table);
-
- //bind save handlers to the row
- utils.bindAutoSaveEvent(row.find("#" + id).change(save), save);
-
- return _row;
- },
- appendTo: function (id) {
- var fs = $("<fieldset class='main'><legend class='cap-text'>" + action + "</legend></fieldset>");
-
- $(_table).appendTo(fs);
- fs.appendTo($(id));
- }
- };
+function _errorOccurred(onError, code) {
+ if (!onError)
+ return;
- return _row;
+ setTimeout(function () {
+ onError(new DeviceApiError(code));
+ }, 1);
}
-function create() {
- var build = table('build'),
- sign = table('sign'),
- launch = table('launch');
-
- build
- .row("sdk", "SDK Path")
- .row("projectPath", "Project Root")
- .row("projectName", "Archive Name")
- .row("outputPath", "Output Folder")
- .row("remoteInspector", "Enable Remote Web Inspector", {
- type: "checkbox",
- onChanged: function (enabled) {
- if (enabled) {
- $("#options-menu-build-warning").show();
- tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
- }
- else {
- $("#options-menu-build-warning").hide();
- }
- }
- })
- .appendTo("#settings-tabs-build");
-
- switch (platform.current().id) {
- case "webworks.handset":
- sign.row("signingPassword", "Password", {
- type: "password"
- });
-
- launch.row("simulator", "Simulator", {
- type: "select"
- });
-
- launch.row("simulatorstatus", "Simulator", {
- type: "span",
- text: "Searching for simulators ..."
- });
-
- break;
-
- case "webworks.tablet":
- sign.row("csk_password", "CSK Password", {
- type: "password"
- });
- sign.row("p12_password", "P12 Password", {
- type: "password"
- });
- sign.row("bundle_number", "Bundle Number", {
- type: "number"
- });
-
- launch.row("device", "Playbook IP");
- launch.row("devicePassword", "Playbook Password", {
- type: "password"
- });
-
- break;
+function _pendingOperate(operate, scope) {
+ var i, argumentVector = [];
- case "webworks.bb10":
- sign.row("signingPassword", "Signing Password", {
- type: "password"
- });
- sign.row("bundle_number", "Bundle Number", {
- type: "number"
- });
+ for (i = 0; i < arguments.length - 2; i++)
+ argumentVector[i] = arguments[i + 2];
- launch.row("device", "Device IP");
- launch.row("devicePassword", "Device Password", {
- type: "password"
- });
+ return function () {
+ var pendingObj, pendingOperation;
- break;
- }
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = window.setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ operate.apply(scope, argumentVector);
+ }, _PENDING_TIME);
- sign.appendTo("#settings-tabs-build");
- launch.appendTo("#settings-tabs-build");
+ pendingOperation = new PendingOperation(pendingObj);
- $("#settings-field-simulator").parent().parent().hide();
+ return pendingOperation;
+ };
}
-function populate(settings) {
- var fill = function (action, prop) {
- var element = $("#settings-field-" + prop.toLowerCase());
+function _defaultContacts() {
+ var id1 = Math.uuid(null, 16),
+ id2 = Math.uuid(null, 16),
+ id3 = Math.uuid(null, 16),
+ id4 = Math.uuid(null, 16),
+ contacts = {};
- if (_isPasswordField(prop)) {
- element.val(_passwords[prop]);
- }
- else if (_isCheckboxField(prop)) {
- element.prop("checked", settings[prop]);
- }
- else {
- element.val(settings[prop]);
- }
+ contacts.PHONE_ADDRESS_BOOK = {
+ type: _self().PHONE_ADDRESS_BOOK,
+ items: [{
+ id: id1,
+ firstName: "Leonardo",
+ lastName: "Gates",
+ nicknames: ["Leo"],
+ phoneticName: "",
+ addresses: [{streetAddress: "Gran Via, 32", postalCode: "50013", city: "Zaragoza", country: "ES"}],
+ photoURI: "",
+ phoneNumbers: [],
+ emails: ["leo@underground.com"]
+ }, {
+ id: id2,
+ firstName: "Jordan",
+ lastName: "",
+ nicknames: [""],
+ phoneticName: "",
+ addresses: [],
+ photoURI: "",
+ phoneNumbers: [],
+ emails: ["jordan@underground.com"]
+ }]
};
- fill("build", "sdk");
- fill("build", "projectPath");
- fill("build", "outputPath");
- fill("build", "projectName");
- fill("build", "remoteInspector");
+ contacts.SIM_ADDRESS_BOOK = {
+ type: _self().SIM_ADDRESS_BOOK,
+ items: [{
+ id: id3,
+ firstName: "Raphael",
+ lastName: "",
+ nicknames: [""],
+ phoneticName: "",
+ addresses: [],
+ photoURI: "",
+ phoneNumbers: [],
+ emails: ["raph@underground.com"]
+ }]
+ };
- fill("sign", "signingPassword");
- fill("sign", "csk_password");
- fill("sign", "p12_password");
- fill("sign", "bundle_number");
+ contacts.DEVICE_ADDRESS_BOOK = {
+ type: _self().DEVICE_ADDRESS_BOOK,
+ items: [{
+ id: id4,
+ firstName: "Michelangelo",
+ lastName: "",
+ nicknames: [""],
+ phoneticName: "",
+ addresses: [],
+ photoURI: "",
+ phoneNumbers: [],
+ emails: ["mike@underground.com"]
+ }]
+ };
- fill("launch", "simulator");
- fill("launch", "device");
- fill("launch", "devicePassword");
+ return contacts;
}
-function url(action) {
- var target = "";
-
- switch (platform.current().id) {
- case "webworks.bb10":
- target = "bb10";
- break;
- case "webworks.tablet":
- target = "tablet";
- break;
- case "webworks.handset":
- target = "smartphone";
- break;
- }
-
- return host + "/" + action + "/" + target;
+function _get() {
+ _contacts = db.retrieveObject(_KEY) || _defaultContacts();
}
-function enable(action) {
- $("#options-menu-" + action).removeClass("not-ready");
- if (action === "launch") {
- $("#settings-field-simulatorstatus").parent().parent().hide();
- $("#settings-field-simulator").parent().parent().show();
- }
+function _save() {
+ db.saveObject(_KEY, _contacts);
}
-function disable(action) {
- $("#options-menu-" + action).addClass("not-ready");
- if (action === "launch") {
- $("#settings-field-simulatorstatus").parent().parent().show();
- $("#settings-field-simulator").parent().parent().hide();
- }
+function _initAddressBooks() {
+ _get();
+ utils.forEach(_contacts, function (contactObj, name) {
+ _addressBooks.push(new AddressBook(contactObj.type, name));
+ });
}
-function getSimulators() {
- if (!_settings.get().sdk) {
- $("#settings-field-simulatorstatus").text("");
- disable("launch");
- return;
- }
-
- bus.ajax(
- "POST",
- host + "/simulators",
- _settings.get(),
- function (resp) {
- var sims = resp.data.simulators;
-
- $("#settings-field-simulator").empty();
- if (sims.length > 0) {
- $(resp.data.simulators.map(function (sim) {
- return "<option value='" + sim + "'>" + sim + "</option>";
- }).join()).appendTo("#settings-field-simulator");
-
- enable("launch");
- }
- else {
- disable("launch");
- $("#settings-field-simulatorstatus").text("No simulators found :(");
+_self = function () {
+ var contact = {
+ getAddressBooks: function (successCallback, errorCallback) {
+ function _getAddressBooks() {
+ if (_addressBooks.length === 0) {
+ _initAddressBooks();
+ }
+ successCallback(_addressBooks);
}
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getAddressBooks", _getAddressBooks);
},
- function () {
- disable("launch");
- $("#settings-field-simulatorstatus").text("Error attempting to get simulators :(");
- }
- );
-}
-function _startProgress() {
- if (progressInterval) {
- window.clearInterval(progressInterval);
- }
- progressInterval = window.setInterval(function () {
- if (progressContainer.html().length === 5) {
- progressContainer.html(".");
- }
- else {
- progressContainer.html(progressContainer.html() + ".");
+ handleSubFeatures: function (subFeatures) {
+ for (var subFeature in subFeatures) {
+ if (_security[subFeature].length === 0) {
+ _security.all = true;
+ return;
+ }
+ _security.all = false;
+ utils.forEach(_security[subFeature], function (method) {
+ _security[method] = true;
+ });
+ }
}
- }, 250);
-}
-
-function _endProgress() {
- window.clearInterval(progressInterval);
- progressInterval = null;
- progressContainer.html("");
-}
-
-
-_self = {
- initialize: function () {
- $("#settings-dialog").dialog({
- autoOpen: false,
- modal: true,
- width: 700,
- title: "Settings",
- position: 'center'
- }).hide();
+ };
- $("#settings-tabs").tabs();
- $("#settings-action").button();
+ contact.__defineGetter__("SIM_ADDRESS_BOOK", function () {
+ return 0x0000;
+ });
- create();
+ contact.__defineGetter__("DEVICE_ADDRESS_BOOK", function () {
+ return 0x000F;
+ });
- if (platform.current().id === "webworks.handset") {
- enable("build");
- enable("sign");
- enable("settings");
+ contact.__defineGetter__("PHONE_ADDRESS_BOOK", function () {
+ return 0x00FF;
+ });
- getSimulators();
- $("#settings-field-sdk").change(getSimulators);
- }
- else if (platform.current().id === "webworks.tablet") {
- enable("build");
- enable("sign");
- enable("launch");
- enable("settings");
- }
- else if (platform.current().id === "webworks.bb10") {
- enable("build");
- enable("sign");
- enable("launch");
- enable("settings");
- }
- },
+ return contact;
+};
- can: function (action) {
- var settings = {};
+AddressBook = function (type, name) {
+ var addressBook,
+ contactItems = _contacts[name].items;
- utils.mixin(_settings.get(), settings);
- utils.mixin(_passwords, settings);
+ addressBook = {
+ createContact: function (contactProperties) {
+ var cp, contact = new Contact();
- return action && missing(settings, action).length === 0;
- },
+ if ((contactProperties !== undefined) &&
+ (contactProperties !== null)) {
+ cp = TypeCoerce(ContactProperties).cast(contactProperties);
+ !cp.firstName || (contact.firstName = utils.copy(cp.firstName));
+ !cp.lastName || (contact.lastName = utils.copy(cp.lastName));
+ !cp.nicknames || (contact.nicknames = utils.copy(cp.nicknames));
+ !cp.phoneticName || (contact.phoneticName = utils.copy(cp.phoneticName));
+ !cp.addresses || (contact.addresses = utils.copy(cp.addresses));
+ !cp.photoURI || (contact.photoURI = utils.copy(cp.photoURI));
+ !cp.phoneNumbers || (contact.phoneNumbers = utils.copy(cp.phoneNumbers));
+ !cp.emails || (contact.emails = utils.copy(cp.emails));
+ }
- value: function (prop) {
- var settings = {};
+ return contact;
+ },
- utils.mixin(_settings.get(), settings);
- return settings[prop];
- },
+ addContact: function (successCallback, errorCallback, contact) {
+ function _addContact() {
+ var c;
- show: function (action) {
- var settings = {};
+ if (!contact)
+ exception.raise(exception.types.Argument, "addContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- utils.mixin(_settings.get(), settings);
- utils.mixin(_passwords, settings);
+ if (!_security.all && !_security.addContact)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
- populate(settings);
+ c = TypeCoerce(new Contact()).cast(contact);
+ contactItems.push(c);
+ _save();
+ successCallback(c);
+ }
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "addContact", _pendingOperate(_addContact));
+ },
- $("#settings-dialog").dialog("open");
- $("#settings-action").button("option", "label", action || "Close")[action ? "show" : "hide"]();
+ updateContact: function (successCallback, errorCallback, contact) {
+ function _updateContact() {
+ var c, isFound = false;
- if (action) {
- missing(settings, action).forEach(function (field) {
- $("#settings-field-" + field.toLowerCase()).effect("highlight", {color: "red"}, 1500);
- });
+ if (!contact)
+ exception.raise(exception.types.Argument, "updateContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
- $("#settings-action").unbind("click").click(function () {
- if (_self.can(action)) {
- _self.perform(action);
- $("#settings-dialog").dialog("close");
- }
- else {
- _self.show(action);
- }
- });
- }
- },
+ if (!_security.all && !_security.updateContact)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
- perform: function (action) {
- var settings = _settings.get(),
- data = {},
- poll = function (resp) {
- var notifications = require("ripple/notifications");
+ c = TypeCoerce(new Contact()).cast(contact);
+ utils.forEach(contactItems, function (contactItem) {
+ if (contactItem.id === c.id) {
+ !c.firstName || (contactItem.firstName = utils.copy(c.firstName));
+ !c.lastName || (contactItem.lastName = utils.copy(c.lastName));
+ !c.nicknames || (contactItem.nicknames = utils.copy(c.nicknames));
+ !c.phoneticName || (contactItem.phoneticName = utils.copy(c.phoneticName));
+ !c.addresses || (contactItem.addresses = utils.copy(c.addresses));
+ !c.photoURI || (contactItem.photoURI = utils.copy(c.photoURI));
+ !c.phoneNumbers || (contactItem.phoneNumbers = utils.copy(c.phoneNumbers));
+ !c.emails || (contactItem.emails = utils.copy(c.emails));
- if (resp && resp.code !== 0) {
- notifications.openNotification("error", "Build request failed with message: " + resp.msg);
- _endProgress();
- }
- else {
- if (resp && resp.data.status === "building") {
- setTimeout(function () {
- bus.ajax(
- "GET",
- host + "/build_status/" + resp.data.id,
- null,
- poll,
- function (error) {
- notifications.openNotification("error", "Build request failed with message: " + JSON.stringify(error));
- _endProgress();
- }
- );
- }, 500);
- }
- else {
- if (action.match(/sign/)) {
- settings["bundle_number"] = $("#settings-field-bundle_number").val(parseInt($("#settings-field-bundle_number").val(), 10) + 1).val();
- _settings.save(settings);
- }
- notifications.openNotification("normal", "Build succeeded!");
- _endProgress();
+ _save();
+ isFound = true;
+ successCallback();
}
- }
- };
-
- utils.mixin(settings, data);
- utils.mixin(_passwords, data);
-
- bus.ajax(
- "POST",
- url(action),
- data,
- function (resp) {
- _startProgress();
- poll(resp);
- },
- function (error) {
- var message = "Build request failded with message: " + error.data;
-
- if (error.code === 0 || error.code === 404) {
- message += "<br>This could be due to the Build and Deploy services not running or not being installed";
- }
+ });
- notifications.openNotification("error", message);
+ if (!isFound)
+ _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
}
- );
- }
-};
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "updateContact", _pendingOperate(_updateContact));
+ },
-module.exports = _self;
+ deleteContact: function (successCallback, errorCallback, id) {
+ function _deleteContact() {
+ var isFound = false;
-});
-define('ripple/ui/plugins/settings-menu', function (require, exports, module) {
-/*
- * Copyright 2011 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 utils = require('ripple/utils'),
- constants = require('ripple/constants'),
- platform = require('ripple/platform'),
- db = require('ripple/db'),
- _applicationStateId
- ;
+ if (!_security.all && !_security.deleteContact)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
+ utils.forEach(contactItems, function (contactItem, index) {
+ if (contactItem.id === id) {
+ contactItems.splice(index, 1);
+ _save();
+ isFound = true;
+ successCallback();
+ }
+ });
-function reload() {
- window.tinyHipposReload = true;
- location.reload();
-}
+ if (!isFound)
+ _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
+ }
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "deleteContact", _pendingOperate(_deleteContact));
+ },
-function _showSettingMenu() {
- var contentTable = "",
- settings = [],
- _applicationState = [],
- _applicationStateTmp = [],
- unselectedNum = 0,
- i = 0;
+ findContacts: function (successCallback, errorCallback, filter) {
+ function _findContacts() {
+ var contact, result = [];
- if ($("#settings-menu-popup").is(":visible")) {
- $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
- $("#overlayBackground").hide("fade", "slow");
- return;
- }
+ if (!_security.all && !_security.findContacts)
+ return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);
- _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;
+ utils.forEach(contactItems, function (contactItem) {
+ if ((filter === undefined || filter === null) ||
+ (filter.id === undefined || Filter(filter.id).match(contactItem.id)) &&
+ (filter.firstName === undefined || Filter(filter.firstName).match(contactItem.firstName)) &&
+ (filter.lastName === undefined || Filter(filter.lastName).match(contactItem.lastName)) &&
+ (filter.phoneticName === undefined || Filter(filter.phoneticName).match(contactItem.phoneticName)) &&
+ (filter.nickname === undefined || Filter(filter.nickname).match(contactItem.nicknames)) &&
+ (filter.phoneNumber === undefined || Filter(filter.phoneNumber).match(contactItem.phoneNumbers)) &&
+ (filter.email === undefined || Filter(filter.email).match(contactItem.emails)) &&
+ (filter.address === undefined || Filter(filter.address).match(contactItem.addresses))) {
+ contact = new Contact(contactItem.id);
- _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];
+ contact.firstName = utils.copy(contactItem.firstName);
+ contact.lastName = utils.copy(contactItem.lastName);
+ contact.nicknames = utils.copy(contactItem.nicknames);
+ contact.phoneticName = utils.copy(contactItem.phoneticName);
+ contact.addresses = utils.copy(contactItem.addresses);
+ contact.photoURI = utils.copy(contactItem.photoURI);
+ contact.phoneNumbers = utils.copy(contactItem.phoneNumbers);
+ contact.emails = utils.copy(contactItem.emails);
- utils.forEach(_applicationStateTmp, function (obj) {
- if (obj.display)
- _applicationState.push(obj);
- });
+ result.push(contact);
+ }
+ });
+ successCallback(result);
+ }
+ return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findContacts", _pendingOperate(_findContacts));
+ }
+ };
- utils.forEach(_applicationStateTmp, function (obj) {
- if (!obj.display)
- _applicationState.push(obj);
+ addressBook.__defineGetter__("type", function () {
+ return type;
});
- $("#settings-menu-content-panel-table").remove();
-
- contentTable = '<table id="settings-menu-content-panel-table" class="settings-menu-content-table">';
- utils.forEach(_applicationState, function (obj) {
- var checked = obj.display ? 'checked="yes"':"";
- contentTable += '<tr><td><input name="panel-display-setting" type="checkbox" class="settings-menu-checkbox "' +
- checked + '></input>' +
- obj.titleName + '</td></tr>\n';
+ addressBook.__defineGetter__("name", function () {
+ return name;
});
- contentTable += "</table>";
- $("#settings-menu-container-div").append(contentTable);
- $("#settings-menu-popup").css("top", 50);
- $("#settings-menu-popup").css("left", $(window).width() - 340);
+ return addressBook;
+};
- $("#overlayBackground").css("width", $(window).width());
- $("#overlayBackground").css("height", $(window).height());
- $("#overlayBackground").show("fade", "slow");
- $("#settings-menu-popup").show("slide", {direction: "up"}, "slow");
+Address = {
+ country: "",
+ region: "",
+ county: "",
+ city: "",
+ streetAddress: "",
+ additionalInformation: "",
+ postalCode: ""
+};
- $("#settings-menu-save-btn").unbind('click');
- $("#settings-menu-save-btn").bind("click", function (event) {
- $("input[name='panel-display-setting']").each(function (i, a) {
- settings.push(a.checked);
- });
+ContactAddress = function () {
+ this.types = [""]; // "WORK", "PREF", "HOME"
+};
- utils.forEach(_applicationState, function (obj) {
- if (!settings[i])
- obj.collapsed = true;
- obj.display = settings[i];
- i++;
- }, this);
-
- db.saveObject(_applicationStateId, _applicationState);
- _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];
+ContactAddress.prototype = Address;
- $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
- $("#overlayBackground").hide("fade", "slow");
- setTimeout(reload, 500);
- });
+PhoneNumber = {
+ number: "",
+ types: [""] // "WORK", "PREF", "HOME", "VOICE", "FAX", "MSG", "CELL",
+ // "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO", "PCS"
+};
- $(".settings-menu-content-table td").unbind('click');
- $(".settings-menu-content-table td").bind("click", function (event) {
- var checkbox;
- if (($(event.target).children().length === 0)) {
- return;
- } else {
- checkbox = $(event.target).children();
- }
-
- if (checkbox.is(':checked')) {
- checkbox.prop('checked', false);
- }
- else
- checkbox.prop('checked', true);
- });
+EmailAddress = {
+ email: "",
+ types: [""] // "WORK", "PREF", "HOME"
+};
- $("#settings-menu-close-btn").unbind('click');
- $("#settings-menu-close-btn").bind("click", function (event) {
- if ($("#settings-menu-popup").is(":visible")) {
- $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
- $("#overlayBackground").hide("fade", "slow");
- return;
- }
- });
+ContactProperties = {
+ firstName: "",
+ lastName: "",
+ nicknames: [""],
+ phoneticName: "",
+ addresses: [new ContactAddress()],
+ photoURI: "",
+ phoneNumbers: [PhoneNumber],
+ emails: [EmailAddress]
+};
- $(window).bind('resize', function () {
- $("#settings-menu-popup").css("top", 50);
- $("#settings-menu-popup").css("left", $(window).width() - 340);
- $("#overlayBackground").css("width", $(window).width());
- $("#overlayBackground").css("height", $(window).height());
- });
+Contact = function (id) {
+ id = id || Math.uuid(null, 16);
- $(".settings-menu-checkbox").each(function (i, a) {
- if (a.checked === false) {
- unselectedNum++;
- }
+ this.__defineGetter__("id", function () {
+ return id;
});
+};
- if (unselectedNum === 0) {
- $("#select_unselect_text").text("Unselect All");
- $("#panelSettingSelectAll").prop('checked', true);
- }
-
- $("#panelSettingSelectAll").unbind('click');
- $("#panelSettingSelectAll").bind("click", function (event) {
- if ($("#panelSettingSelectAll").is(':checked')) {
- $("#select_unselect_text").text("Unselect All");
- $(".settings-menu-checkbox").prop('checked', true);
- }
- else {
- $("#select_unselect_text").text("Select All");
- $(".settings-menu-checkbox").prop('checked', false);
- }
- });
-}
+Contact.prototype = ContactProperties;
-module.exports = {
- initialize: function () {
- $("#options-button-panels").bind("click", function (event) {
- _showSettingMenu();
- });
- }
+ContactFilter = {
+ id: "",
+ firstName: "",
+ lastName: "",
+ phoneticName: "",
+ nickname: "",
+ phoneNumber: "",
+ email: "",
+ address: ""
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/settings', function (require, exports, module) {
+define('ripple/platform/wac/2.0/orientation', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var db = require('ripple/db'),
- constants = require('ripple/constants'),
- KEY = constants.XHR.PROXY_DISABLED_BUTTON; // TODO: one settings object for all
-function _saveAndReload(key, value) {
- jWorkflow.order(function (prev, baton) {
- baton.take();
- db.save(key, value, null, baton.pass);
- }).start(function () {
- window.tinyHipposReload = true;
- location.reload();
- });
-}
+var utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ Rotation = function (alpha, beta, gamma) {
+ return {
+ alpha: alpha || 0,
+ beta: beta || 0,
+ gamma: gamma || 0
+ };
+ },
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ _rotationInfo = new Rotation(),
+ _defaultInterval = 100,
+ _watches = {},
+ _self;
-function _initialize(prev, baton) {
- var select = document.getElementById("settings-xhr-proxy"),
- about = require('ripple/ui/plugins/about-dialog');
+module.exports = _self = {
+ getCurrentOrientation: function (onSuccess, onError) {
+ function _getCurrentOrientation() {
+ setTimeout(function () {
+ onSuccess(utils.copy(_rotationInfo));
+ }, 1);
+ return null;
+ }
- select.value = String(db.retrieve(KEY));
- select.addEventListener("change", function () {
- _saveAndReload(KEY, this.value);
- }, false);
-
- $("#options-menu-about").click(function () {
- about.show();
- });
- // TODO: reload here?
-}
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentOrientation", _getCurrentOrientation);
+ },
-module.exports = {
- panel: {
- domId: "settings-container",
- collapsed: true,
- pane: "right"
+ watchOrientation: function (orientationSuccess, orientationError, options) {
+ function _watchOrientation() {
+ var watchId = (new Date()).getTime() | 0,
+ watchObj = {},
+ opt = Object(options),
+ minNotificationInterval = opt.minNotificationInterval | 0,
+ orientationInterval = _defaultInterval;
+
+ if (minNotificationInterval > 0) {
+ orientationInterval = minNotificationInterval;
+ }
+
+ watchObj = {
+ onSuccess: orientationSuccess,
+ onError: orientationError,
+ interval: orientationInterval
+ };
+
+ _watches[watchId] = watchObj;
+
+ _watches[watchId].intervalId = setInterval(function () {
+ _self.getCurrentOrientation(_watches[watchId].onSuccess, _watches[watchId].onError);
+ }, _watches[watchId].interval);
+
+ return watchId;
+ }
+
+ return wac2_utils.validateTypeMismatch(orientationSuccess, orientationError, "watchOrientation", _watchOrientation);
},
- initialize: _initialize
+
+ clearWatch: function (watchId) {
+
+ var id = watchId | 0;
+ if (_watches[id]) {
+ clearInterval(_watches[id].intervalId);
+ delete(_watches[id]);
+ return null;
+ }
+
+ return undefined;
+ }
};
+event.on("AccelerometerInfoChangedEvent", function (orientationInfo) {
+ _rotationInfo.alpha = orientationInfo.orientation.alpha;
+ _rotationInfo.beta = orientationInfo.orientation.beta;
+ _rotationInfo.gamma = orientationInfo.orientation.gamma;
});
-define('ripple/ui/plugins/storage', function (require, exports, module) {
+
+
+});
+define('ripple/platform/wac/2.0/geolocation', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- event = require('ripple/event'),
- platform = require('ripple/platform'),
- utils = require('ripple/utils'),
- app = require('ripple/app'),
- db = require('ripple/db');
-function _updatePreferencesView() {
- var node = document.getElementById(constants.COMMON.STORAGE_TABLE_BODY_CLASS),
- countTitle = document.getElementById(constants.COMMON.STORAGE_COUNT_CONTAINER_ID);
+var geo = require('ripple/geo'),
+ Position = require('ripple/platform/w3c/1.0/Position'),
+ PositionError = require('ripple/platform/w3c/1.0/PositionError'),
+ _lastPosition = null,
+ _watches = {},
+ _defaultInterval = 100,
+ _defaultDelay = 50,
+ _self;
- // TODO: convert to appendChild
- if (node) {
- db.retrieveAll(platform.getPersistencePrefix(), function (results) {
- var str = "",
- counter = 0;
+function _createPosition() {
+ var position = new Position(),
+ positionInfo = geo.getPositionInfo();
- utils.forEach(results, function (value, key) {
- // TODO: based of current platform
- if (app.isPreferenceReadOnly(key)) {
- str += '<tr class="ui-text-highlight">';
- } else {
- str += '<tr>';
- }
- str += '<td>' + key + '</td><td>' + value + "</td></tr>";
- counter ++;
- });
+ position.coords.latitude = positionInfo.latitude;
+ position.coords.longitude = positionInfo.longitude;
+ position.coords.altitude = positionInfo.altitude;
+ position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
+ position.coords.accuracy = positionInfo.accuracy;
+ position.coords.heading = positionInfo.heading;
+ position.coords.speed = positionInfo.speed;
+ position.timestamp = positionInfo.timeStamp.getTime();
- node.innerHTML = str;
- countTitle.innerHTML = counter.toString();
+ return position;
+}
- if (counter === 0) {
- jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).addClass(constants.CSS_PREFIX.IRRELEVANT);
- }
- else {
- jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).removeClass(constants.CSS_PREFIX.IRRELEVANT);
- }
- });
+function _isValid(onSuccess, onError, options, argLength) {
+ if (argLength < 1 || argLength > 3)
+ return false;
+
+ if (typeof onSuccess !== "function") // imply onSuccess == null
+ return false;
+
+ if (onError && (typeof onError !== "function"))
+ return false;
+
+ if ((options !== undefined) &&
+ ((typeof options !== "object") ||
+ (options.enableHighAccuracy !== undefined) && (typeof options.enableHighAccuracy !== "boolean") ||
+ (options.timeout !== undefined) && (typeof options.timeout !== "number") ||
+ (options.maximumAge !== undefined) && (typeof options.maximumAge !== "number")))
+ return false;
+
+ return true;
+}
+
+function _processOptions(options) {
+ var validOptions = {
+ enableHighAccuracy: false,
+ timeout: 0,
+ maximumAge: 0
+ };
+
+ if (options !== undefined &&
+ options.maximumAge !== undefined &&
+ options.maximumAge === Math.floor(options.maximumAge) &&
+ options.maximumAge >= 0) {
+ validOptions.maximumAge = options.maximumAge | 0;
+ } else {
+ validOptions.maximumAge = 0;
+ }
+
+ if (options !== undefined &&
+ options.timeout !== undefined &&
+ options.timeout === Math.floor(options.timeout)) {
+ validOptions.timeout = (options.timeout >= 0) ? (options.timeout | 0) : 0;
+ } else {
+ validOptions.timeout = Infinity;
+ }
+
+ if (options !== undefined && options.enableHighAccuracy !== undefined) {
+ validOptions.enableHighAccuracy = options.enableHighAccuracy;
+ } else {
+ validOptions.enableHighAccuracy = false;
}
+
+ validOptions.delay = geo.delay * 1000 || _defaultDelay;
+
+ return validOptions;
}
-module.exports = {
- panel: {
- domId: "preferences",
- collapsed: true,
- pane: "left"
+function _errorOccur(code, onError) {
+ if (!onError)
+ return;
+
+ var error = new PositionError();
+
+ error.code = code;
+ switch (code) {
+ case PositionError.POSITION_UNAVAILABLE:
+ error.message = "Position unavailable";
+ break;
+
+ case PositionError.TIMEOUT:
+ error.message = "Position timed out";
+ break;
+ }
+
+ onError(error);
+}
+
+function _execute(data) {
+ return function () {
+ if (_lastPosition !== null &&
+ ((new Date()).getTime() - _lastPosition.timestamp <= data.maximumAge)) {
+ window.setTimeout(function () {
+ data.onSuccess(_lastPosition);
+ }, 1);
+ } else if (data.timeout === 0) {
+ _errorOccur(PositionError.TIMEOUT, data.onError);
+ } else {
+ window.setTimeout(function () {
+ if (data.delay <= data.timeout) {
+ _lastPosition = _createPosition();
+
+ if (_lastPosition !== null) {
+ data.onSuccess(_lastPosition);
+ } else {
+ _errorOccur(PositionError.POSITION_UNAVAILABLE, data.onError);
+ }
+ } else {
+ _errorOccur(PositionError.TIMEOUT, data.onError);
+ }
+ }, Math.min(data.delay, data.timeout));
+ }
+ };
+}
+
+function _interval(k, n) {
+ return k * Math.floor((n + k - 1) / k) || k;
+}
+
+_self = {
+ getCurrentPosition: function (onSuccess, onError, options) {
+ if (!_isValid(onSuccess, onError, options, arguments.length))
+ return;
+
+ var validData = _processOptions(options);
+
+ validData.onSuccess = onSuccess;
+ validData.onError = onError;
+
+ _execute(validData)();
},
- initialize: function () {
- jQuery("#preferences-clear-button").bind("click", function () {
- db.removeAll(platform.getPersistencePrefix());
- });
- event.on("StorageUpdatedEvent", function () {
- _updatePreferencesView();
- });
+ watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
+ if (!_isValid(geolocationSuccess, geolocationError, geolocationOptions, arguments.length))
+ return undefined;
- _updatePreferencesView();
+ var validData = _processOptions(geolocationOptions),
+ watchId = (new Date()).getTime() | 0,
+ watchObj = {
+ onSuccess: geolocationSuccess,
+ onError: geolocationError,
+ enableHighAccuracy: validData.enableHighAccuracy,
+ timeout: validData.timeout,
+ maximumAge: validData.maximumAge,
+ delay: validData.delay,
+ interval: _interval(validData.maximumAge || _defaultInterval,
+ Math.min(validData.delay, validData.timeout)),
+ };
+
+ _watches[watchId] = watchObj;
+
+ _watches[watchId].intervalId = window.setInterval(_execute(_watches[watchId]),
+ _watches[watchId].interval);
+
+ return watchId;
+ },
+
+ clearWatch: function (watchId) {
+ if (arguments.length !== 1)
+ return undefined;
+
+ var id = watchId | 0;
+
+ if (_watches[id]) {
+ window.clearInterval(_watches[id].intervalId);
+ delete _watches[id];
+
+ return null;
+ }
+
+ return undefined;
}
};
+module.exports = _self;
+
});
-define('ripple/ui/plugins/themeSwitcher', function (require, exports, module) {
+define('ripple/platform/wac/2.0/deviceapis', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var utils = require('ripple/utils'),
- db = require('ripple/db'),
- THEME_KEY = "ui-theme",
- THEME_SELECTOR = "#theme-select",
- _currentTheme;
-function _saveAndReload(key, value) {
- jWorkflow.order(function (prev, baton) {
- baton.take();
- db.save(key, value, null, baton.pass);
- }).start(function () {
- window.tinyHipposReload = true;
- location.reload();
+var platform = require('ripple/platform'),
+ app = require('ripple/app'),
+ utils = require('ripple/utils'),
+ init_done = false,
+ _activatedSet = {},
+ _activatedFeatures = [],
+ _availableSet = {},
+ _availableFeatures = [],
+ _features = {},
+ initFeaturesSet,
+ populateFeatures;
+
+populateFeatures = function (objects) {
+ utils.forEach(objects, function (obj, key) {
+ var objFeatures = {}, rpt, i, j;
+ if (obj.feature) {
+ objFeatures = obj.feature.split('|');
+ utils.forEach(objFeatures, function (feature) {
+ var avail = {uri: feature,
+ required: false,
+ param: null};
+ _availableSet[feature] = avail;
});
-}
+ if (_features) {
+ rpt = objFeatures.length;
+ j = 0;
+ for (i = 0; i < rpt; i++) {
+ if (!_features[objFeatures[j]]) {
+ objFeatures.splice(j, 1);
+ } else {
+ j++;
+ }
+ }
+ }
+ utils.forEach(objFeatures, function (feature) {
+ var avail = {uri: feature,
+ required: true,
+ param: null};
+ _activatedSet[feature] = avail;
+ });
+ }
+ if (obj.children) {
+ populateFeatures(obj.children);
+ }
+ });
+};
+
+initFeaturesSet = function () {
+ _features = utils.copy(app.getInfo().features);
+ populateFeatures(platform.current().objects);
+ utils.forEach(_activatedSet, function (obj, key) {
+ _activatedFeatures.push(obj);
+ });
+ utils.forEach(_availableSet, function (obj, key) {
+ _availableFeatures.push(obj);
+ });
+ init_done = true;
+};
module.exports = {
- initialize: function () {
- var themeToSet = db.retrieve(THEME_KEY);
+ listAvailableFeatures: function () {
+ if (!init_done)
+ initFeaturesSet();
+ return _availableFeatures;
+ },
- // Hide the theme switcher and always set the theme to light
- jQuery(".theme-switcher").hide();
- if (themeToSet !== "light") {
- _saveAndReload(THEME_KEY, "light");
- }
- return;
+ listActivatedFeatures: function () {
+ if (!init_done)
+ initFeaturesSet();
+ return _activatedFeatures;
}
};
+
});
-define('ripple/ui/plugins/time', function (require, exports, module) {
+define('ripple/platform/wac/2.0/calendar', function (require, exports, module) {
/*
- * Copyright 2012 Intel Corporation.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-function _init() {
- var db = require('ripple/db'),
- utils = require('ripple/utils'),
- allTZ, dbTZ, node = jQuery("#time-locale-select"),
- timezone = require('ripple/platform/tizen/2.0/timezone_info'),
- event = require('ripple/event'),
- alarms, time;
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ constants = require('ripple/constants'),
+ errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
+ PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ _console = require('ripple/console'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ _SIM_CALENDAR = 0, _DEVICE_CALENDAR = 1,
+ _NO_RECURRENCE = 0, _DAILY_RECURRENCE = 1, _WEEKLY_RECURRENCE = 2,
+ _MONTHLY_RECURRENCE = 3, _YEARLY_RECURRENCE = 4,
+ _TENTATIVE_STATUS = 0, _CONFIRMED_STATUS = 1, _CANCELLED_STATUS = 2,
+ _NO_ALARM = 0, _SILENT_ALARM = 1, _SOUND_ALARM = 2,
+ _calendars = [], _DB_CALENDARS_KEY = "wac2-db-calendars",
+ _FAKEWAITTIME = 5, _FAKE_LONG_WAITTIME = 10,
+ _save_calendars, _eventPropCheck, _eventFilterCheck,
+ _addEventAllowed = true, _deleteEventAllowed = true,
+ _updateEventAllowed = true, _findEventsAllowed = true,
+ CalendarEventProperties, Calendar, CalendarEvent;
- function triggerAlarm() {
- time = new Date();
- alarms = db.retrieveObject("tizen1.0-db-alarms");
- if (alarms !== null) {
- utils.forEach(alarms, function (obj) {
- if (obj.id !== undefined) {
- event.trigger("CheckAlarm", [obj.id]);
- }
- });
+_save_calendars = function (_name, _type, _events) {
+ var i;
+ for (i = 0; i < _calendars.length; i++) {
+ if (_calendars[i].name === _name && _calendars[i].type === _type) {
+ _calendars[i].events = _events;
+ break;
}
}
- window.setInterval(triggerAlarm, 1000);
+ db.saveObject(_DB_CALENDARS_KEY, _calendars);
+};
- allTZ = timezone.getAllTimezone();
- utils.forEach(allTZ, function (tz) {
- node.append(utils.createElement("option", {
- "value": tz,
- "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
- }));
- });
- dbTZ = db.retrieve("tizen-timezone");
- if (timezone.isValidTimezone(dbTZ)) {
- node.val(dbTZ);
+_eventPropCheck = function (prop, dst) {
+ var i;
+ if (prop.description !== null && prop.description !== undefined) {
+ dst.description = String(prop.description);
+ }
+ if (prop.summary !== null && prop.summary !== undefined) {
+ dst.summary = String(prop.summary);
+ }
+ if (prop.startTime !== null && prop.startTime !== undefined) {
+ if (!wac2_utils.isValidDate(prop.startTime)) {
+ return false;
+ }
+ dst.startTime = new Date(prop.startTime);
+ }
+ dst.duration = prop.duration | 0;
+ if (prop.location !== null && prop.location !== undefined) {
+ dst.location = String(prop.location);
+ }
+ if (prop.categories !== null && prop.categories !== undefined) {
+ if (!wac2_utils.isValidArray(prop.categories)) {
+ return false;
+ }
+ dst.categories = [];
+ for (i = 0; i < prop.categories.length; i++) {
+ dst.categories.push(String(prop.categories[i]));
+ }
+ }
+ if (prop.recurrence !== null && prop.recurrence !== undefined) {
+ if (prop.recurrence === _NO_RECURRENCE ||
+ prop.recurrence === _DAILY_RECURRENCE ||
+ prop.recurrence === _WEEKLY_RECURRENCE ||
+ prop.recurrence === _MONTHLY_RECURRENCE ||
+ prop.recurrence === _YEARLY_RECURRENCE) {
+ dst.recurrence = prop.recurrence | 0;
+ } else {
+ return false;
+ }
+ }
+ if (dst.recurrence === _NO_RECURRENCE) {
+ dst.expires = null;
+ dst.interval = null;
} else {
- db.save("tizen-timezone", node.val());
+ // expires and interval matters when recurrence is not NO_RECURRENCE
+ if (prop.expires !== null && prop.expires !== undefined) {
+ if (!wac2_utils.isValidDate(prop.expires)) {
+ return false;
+ }
+ dst.expires = new Date(prop.expires);
+ }
+ // expires === undefined -> to recur indefinitely
+ // expires === null -> keep dst.expires unchanged, even it's null
+ if (prop.expires === undefined) {
+ dst.expires = null;
+ }
+ if (prop.interval !== null && prop.interval !== undefined) {
+ dst.interval = prop.interval | 0;
+ }
}
- node.bind("change", function () {
- db.save("tizen-timezone", node.val());
- });
-/* FIXME: Node "trigger-alarm-id" will be removed from Time panel
- * due to "time" panel will changed to "time zone" panel(PTSDK-875)
- event.on("SendTriggerAppId", function (applicationId) {
- if (timeId !== undefined)
- clearTimeout(timeId);
- triggerNode.empty();
- triggerNode.append(utils.createElement("p", {
- "innerHTML": applicationId + " is triggered"
- }));
- triggerNode.show();
- timeId = setTimeout("jQuery('#trigger-alarm-id').empty();", 10000);// Comments will disappear after 10s
- });
-*/
-}
+ if (prop.status !== null && prop.status !== undefined) {
+ if (prop.status === _TENTATIVE_STATUS ||
+ prop.status === _CONFIRMED_STATUS ||
+ prop.status === _CANCELLED_STATUS) {
+ dst.status = prop.status | 0;
+ } else {
+ return false;
+ }
+ }
-module.exports = {
- panel: {
- domId: "time-container",
- collapsed: true,
- pane: "right",
- titleName: "Time",
- display: true
- },
- initialize: _init
+ if (prop.alarmType !== null && prop.alarmType !== undefined) {
+ if (prop.alarmType === _NO_ALARM ||
+ prop.alarmType === _SILENT_ALARM ||
+ prop.alarmType === _SOUND_ALARM) {
+ dst.alarmType = prop.alarmType;
+ } else {
+ return false;
+ }
+ }
+ if (dst.alarmType !== _NO_ALARM && prop.alarmTrigger !== undefined && prop.alarmTrigger !== undefined) {
+ dst.alarmTrigger = prop.alarmTrigger | 0;
+ }
};
-});
-define('ripple/ui/plugins/tooltip', function (require, exports, module) {
-/*
- * Copyright 2011 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 utils = require('ripple/utils'),
- _options = {
- track: true,
- delay: 0,
- showURL: false,
- fade: 250,
- extraClass: "ui-state-highlight ui-corner-all"
+_eventFilterCheck = function (filter) {
+ if (filter.id !== undefined && filter.id !== null) {
+ filter.id = String(filter.id);
+ } else {
+ filter.id = undefined;
+ }
+ if (filter.summary !== undefined && filter.summary !== null) {
+ filter.summary = String(filter.summary);
+ } else {
+ filter.summary = undefined;
+ }
+ if (filter.description !== undefined && filter.description !== null) {
+ filter.description = String(filter.description);
+ } else {
+ filter.description = undefined;
+ }
+ if (filter.location !== undefined && filter.location !== null) {
+ filter.location = String(filter.location);
+ } else {
+ filter.location = undefined;
+ }
+ if (filter.catetory !== undefined && filter.catetory !== null) {
+ filter.catetory = String(filter.catetory);
+ } else {
+ filter.catetory = undefined;
+ }
+ if (filter.status !== undefined && filter.status !== null) {
+ var i;
+ if (!wac2_utils.isValidArray(filter.status)) {
+ return false;
+ }
+ for (i = 0; i < filter.status.length; i++) {
+ filter.status[i] = filter.status[i] | 0;
+ if (filter.status[i] > _CANCELLED_STATUS || filter.status[i] < _TENTATIVE_STATUS)
+ return false;
+ }
+ } else {
+ filter.status = undefined;
+ }
+ if (filter.initialStartDate !== undefined && filter.initialStartDate !== null) {
+ if (!wac2_utils.isValidDate(filter.initialStartDate)) {
+ return false;
+ }
+ filter.initialStartDate = new Date(filter.initialStartDate);
+ } else {
+ filter.initialStartDate = undefined;
+ }
+ if (filter.endStartDate !== undefined && filter.endStartDate !== null) {
+ if (!wac2_utils.isValidDate(filter.endStartDate)) {
+ return false;
+ }
+ filter.endStartDate = new Date(filter.endStartDate);
+ } else {
+ filter.endStartDate = undefined;
+ }
+ return true;
+};
+
+CalendarEventProperties = function (prop) {
+ var _self;
+ _self = {
+ description : "",
+ summary : "",
+ startTime : new Date(),
+ duration : 0,
+ location : "",
+ categories : undefined,
+ recurrence : _NO_RECURRENCE,
+ expires : null, // ignored if recurrence == NO_RECURRENCE
+ interval : null, // ignored if recurrence == NO_RECURRENCE
+ status : _CONFIRMED_STATUS,
+ alarmTrigger : 0,
+ alarmType : _NO_ALARM
};
+ if (prop) {
+ if (_eventPropCheck(prop, _self) === false) {
+ return undefined;
+ }
+ }
+ return _self;
+};
-module.exports = {
- create: function (element, message) {
- var options = utils.copy(_options);
+CalendarEvent = function (prop, genNewID) {
+ var id, _self = new CalendarEventProperties(prop);
- options.bodyHandler = function () {
- return message;
+ /* if error occurs during checking, _self is an empty object.
+ so i randomly pick description to check if property check fails */
+ if (_self.description === undefined) {
+ return undefined;
+ }
+
+ if (genNewID === true) {
+ id = Math.uuid(undefined, 16);
+ } else {
+ id = prop.id;
+ }
+ _self.__defineGetter__("id", function () {
+ return id;
+ });
+ return _self;
+};
+
+Calendar = function (type, name, events) {
+ var _type = type,
+ _name = name,
+ _events = events, _self;
+
+ _self = {
+ createEvent: function (evtProp) {
+ var rst = {};
+ rst = new CalendarEventProperties(evtProp);
+ /* if error occurs during checking, rst is an empty object.
+ so i randomly pick description to check if property check fails */
+ if (rst.description === undefined) {
+ exception.raise(exception.types.Argument, "EventProperties: input parameter contains invalid values", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ return undefined;
+ } else {
+ return rst;
+ }
+ },
+
+ addEvent: function (onSuccess, onError, calEvent) {
+ var pendingOperation, pendingObj = {},
+ newEvent = {}, _doAddEvent, _calEvent = Object(calEvent);
+
+ _doAddEvent = function () {
+ if (!_addEventAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ newEvent = new CalendarEvent(_calEvent, true);
+ /* if newEvent.id === undefined,
+ means somthing wrong in calEvent */
+ if (newEvent.id === undefined) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ _events[newEvent.id] = newEvent;
+ _save_calendars(_name, _type, _events);
+ onSuccess(new CalendarEvent(newEvent), false);
+ }, _FAKEWAITTIME);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ };
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:addEvent", _doAddEvent);
+ },
+
+ updateEvent: function (onSuccess, onError, calEvent) {
+ var pendingOperation, pendingObj = {},
+ chkEvent, _doUpdateEvent, _calEvent = Object(calEvent);
+
+ _doUpdateEvent = function () {
+ if (!_updateEventAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (!_events[_calEvent.id]) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ chkEvent = new CalendarEvent(_events[_calEvent.id], false);
+ /* _eventPropCheck will also update chkEvent btw */
+ if (_eventPropCheck(_calEvent, chkEvent) === false) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+
+ _events[chkEvent.id] = chkEvent;
+ _save_calendars(_name, _type, _events);
+ onSuccess();
+ }, _FAKEWAITTIME);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ };
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:updateEvent", _doUpdateEvent);
+ },
+
+ deleteEvent: function (onSuccess, onError, id) {
+ var pendingOperation, pendingObj = {},
+ _doDeleteEvent;
+
+ _doDeleteEvent = function () {
+ /* according to spec "If any of the input parameters are not
+ compatible with the expected type for that parameter,
+ a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be
+ synchronously thrown."
+ so an error is raised synchronously */
+ utils.validateArgumentType(id, "string", null,
+ "Calendar:deleteEvent: " + " invalid id parameter",
+ new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
+
+ if (!_deleteEventAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (!_events[id]) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+
+ delete _events[id];
+ _save_calendars(_name, _type, _events);
+ onSuccess();
+ }, _FAKEWAITTIME);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ };
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:deleteEvent", _doDeleteEvent);
+ },
+
+ findEvents: function (onSuccess, onError, eventFilter) {
+ var pendingOperation, pendingObj = {}, i,
+ tmp = [], valid_tmp = false, rst = [], _doFindEvents,
+ _eventFilter = Object(eventFilter);
+
+ _doFindEvents = function () {
+ if (!_eventFilterCheck(_eventFilter)) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (!_findEventsAllowed) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ pendingObj = new PendingObject();
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ if (_eventFilter.id !== undefined) {
+ tmp = wac2_utils.matchOptionString(_events, "id", _eventFilter.id);
+ valid_tmp = true;
+ }
+ if (_eventFilter.summary !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionString(tmp, "summary", _eventFilter.summary);
+ } else {
+ tmp = wac2_utils.matchOptionString(_events, "summary", _eventFilter.summary);
+ valid_tmp = true;
+ }
+ }
+ if (_eventFilter.description !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionString(tmp, "description", _eventFilter.description);
+ } else {
+ tmp = wac2_utils.matchOptionString(_events, "description", _eventFilter.description);
+ valid_tmp = true;
+ }
+ }
+ if (_eventFilter.location !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionString(tmp, "location", _eventFilter.location);
+ } else {
+ tmp = wac2_utils.matchOptionString(_events, "location", _eventFilter.location);
+ valid_tmp = true;
+ }
+ }
+ if (_eventFilter.category !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionArrayString(tmp, "categories", _eventFilter.category);
+ } else {
+ tmp = wac2_utils.matchOptionArrayString(_events, "categories", _eventFilter.category);
+ valid_tmp = true;
+ }
+ }
+ if (_eventFilter.status !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionShortArray(tmp, "status", _eventFilter.status);
+ } else {
+ tmp = wac2_utils.matchOptionShortArray(_events, "status", _eventFilter.status);
+ valid_tmp = true;
+ }
+ }
+ if (_eventFilter.initialStartDate !== undefined ||
+ _eventFilter.endStartDate !== undefined) {
+ if (valid_tmp) {
+ tmp = wac2_utils.matchOptionDate(tmp, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
+ } else {
+ tmp = wac2_utils.matchOptionDate(_events, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
+ valid_tmp = true;
+ }
+ }
+
+ // to make id readonly
+ if (valid_tmp) {
+ for (i = 0; i < tmp.length; i++) {
+ rst.push(new CalendarEvent(tmp[i], false));
+ }
+ } else {
+ for (var e in _events) {
+ rst.push(new CalendarEvent(_events[e], false));
+ }
+ }
+ onSuccess(rst);
+ }, _FAKE_LONG_WAITTIME);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
+ };
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:findEvent", _doFindEvents);
+ },
+ };
+ _self.__defineGetter__("type", function () {
+ return _type;
+ });
+ _self.__defineGetter__("name", function () {
+ return name;
+ });
+ return _self;
+};
+
+module.exports = function () {
+ this.__defineGetter__("SIM_CALENDAR", function () {
+ return 0;
+ });
+ this.__defineGetter__("DEVICE_CALENDAR", function () {
+ return 1;
+ });
+ this.__defineGetter__("NO_RECURRENCE", function () {
+ return 0;
+ });
+ this.__defineGetter__("DAILY_RECURRENCE", function () {
+ return 1;
+ });
+ this.__defineGetter__("WEEKLY_RECURRENCE", function () {
+ return 2;
+ });
+ this.__defineGetter__("MONTHLY_RECURRENCE", function () {
+ return 3;
+ });
+ this.__defineGetter__("YEARLY_RECURRENCE", function () {
+ return 4;
+ });
+ this.__defineGetter__("TENTATIVE_STATUS", function () {
+ return 0;
+ });
+ this.__defineGetter__("CONFIRMED_STATUS", function () {
+ return 1;
+ });
+ this.__defineGetter__("CANCELLED_STATUS", function () {
+ return 2;
+ });
+ this.__defineGetter__("NO_ALARM", function () {
+ return 0;
+ });
+ this.__defineGetter__("SILENT_ALARM", function () {
+ return 1;
+ });
+ this.__defineGetter__("SOUND_ALARM", function () {
+ return 2;
+ });
+
+ this.getCalendars = function (onSuccess, onError) {
+ var i, pendingOperation, pendingObj = {}, cal, _doGetCalendars;
+
+ _doGetCalendars = function () {
+ pendingObj = new PendingObject();
+
+ pendingObj.pendingID = setTimeout(function () {
+ pendingObj.setCancelFlag(false);
+ cal = db.retrieveObject(_DB_CALENDARS_KEY) || [];
+ _calendars = [];
+ if (cal.length === 0) {
+ _calendars.push(new Calendar(_SIM_CALENDAR, "sim cal", {}));
+ _calendars.push(new Calendar(_DEVICE_CALENDAR, "dev cal", {}));
+ } else {
+ for (i = 0; i < cal.length; i++) {
+ /* after getting Date out of DB, Date will become
+ a string, so need to recast it back to Date */
+ /* NOTE: id becomes writable, so need to recast it
+ before passing to application */
+ for (var e in cal[i].events) {
+ if ((cal[i].events[e].startTime !== undefined) &&
+ cal[i].events[e].startTime !== null) {
+ cal[i].events[e].startTime = new Date(cal[i].events[e].startTime);
+ }
+ if ((cal[i].events[e].expires !== undefined) &&
+ cal[i].events[e].expires !== null) {
+ cal[i].events[e].expires = new Date(cal[i].events[e].expires);
+ }
+ }
+ _calendars.push(new Calendar(cal[i].type, cal[i].name, cal[i].events));
+ }
+ }
+ if (_calendars.length !== 0) {
+ onSuccess(utils.copy(_calendars));
+ } else {
+ if (onError) {
+ onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
+ }
+ }
+ }, _FAKEWAITTIME);
+ pendingOperation = new PendingOperation(pendingObj);
+ return pendingOperation;
};
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCalendars", _doGetCalendars);
+ };
- return jQuery(element).tooltip(options);
- },
-
- toggle: function () {
- jQuery.tooltip.block();
- return this.isOff();
- },
-
- isOff: function () {
- return jQuery.tooltip.blocked;
- }
+ this.handleSubFeatures = function (subFeatures) {
+ if (wac2_utils.isEmptyObject(subFeatures) ||
+ subFeatures["http://wacapps.net/api/pim.calendar"] ||
+ (subFeatures["http://wacapps.net/api/pim.calendar.read"] &&
+ subFeatures["http://wacapps.net/api/pim.calendar.write"])) {
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/pim.calendar.read"]) {
+ _addEventAllowed = false;
+ _deleteEventAllowed = false;
+ _updateEventAllowed = false;
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/pim.calendar.write"]) {
+ _findEventsAllowed = false;
+ return;
+ }
+ _console.warn("WAC-2.0-Calendar-handleSubFeatures: something wrong");
+ };
};
});
-define('ripple/ui/plugins/tooltips', function (require, exports, module) {
+define('ripple/platform/wac/2.0/filesystem', function (require, exports, module) {
/*
- * Copyright 2011 Research In Motion Limited.
+ * Copyright 2011 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-// Class: UI.Tooltips
-// Purpose: build tooltips for UI
-// See here for Tooltip Options
-// http://jquery.bassistance.de/tooltip/demo/
-var utils = require('ripple/utils'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- constants = require('ripple/constants'),
- db = require('ripple/db'),
- utils = require('ripple/utils');
-function _updateButtonText() {
- document.querySelector("#settings-toggletooltips > span")
- .innerHTML = "Turn " + (tooltip.isOff() ? "On" : "Off");
+var errorcode = require('ripple/platform/wac/2.0/errorcode'),
+ DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
+ utils = require('ripple/utils'),
+ dbfs = require('ripple/platform/wac/2.0/dbfs'),
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ _console = require('ripple/console'),
+ _maxPathLength = 256,
+ _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
+ _realRoots = dbfs.roots,
+ _r2vmap = {},
+ _v2rmap = {},
+ _initialized = false,
+ _readOnly = false,
+ _writeOnly = false,
+ _defaultMode = "rw",
+ File,
+ FileStream;
+
+function _isValidChar(c) {
+ return (c >= '0' && c <= '9') ||
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c === ' ') ||
+ (c === '_') ||
+ (c === '-') ||
+ (c === '.');
}
-module.exports = {
- initialize: function () {
- var saved = db.retrieve(constants.SETTINGS.TOOLTIPS_KEY);
+function _isValidFileName(name) {
+ var _valid = true,
+ _c;
- // blarg, tooltips are always enabled so if its saved to false disable it
- if (!tooltip.isOff() && (saved === "false" || saved === false)) {
- tooltip.toggle();
+ if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
+ _valid = false;
+ } else {
+ for (_c = 0; _c < name.length; _c++) {
+ if (!_isValidChar(name[_c])) {
+ _valid = false;
+ break;
+ }
}
-
- _updateButtonText();
-
- jQuery(constants.SETTINGS.TOOLTIPS_TOGGLE_DIV).click(function () {
- db.save(constants.SETTINGS.TOOLTIPS_KEY, !tooltip.toggle());
- _updateButtonText();
- });
}
-};
-
-});
-define('ripple/ui/plugins/touchEvent', function (require, exports, module) {
-/*
- * Copyright 2012 Intel Corporation
- *
- * 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 event = require('ripple/event'),
- db = require('ripple/db'),
- constants = require('ripple/constants'),
- colors = ["red", "green", "magenta", "blue", "yellow"],
- Point,
- intervalId,
- moveEvents = {},
- currentIndex = 0,
- enlargeRatio = 4;
+
+ return _valid;
+}
-function _exec(operation) {
- var canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
- cxt = canvas.getContext("2d"),
- altKey = document.getElementById(constants.TOUCHEVENT.ALTKEY),
- metaKey = document.getElementById(constants.TOUCHEVENT.METAKEY),
- ctrlKey = document.getElementById(constants.TOUCHEVENT.CTRLKEY),
- shiftKey = document.getElementById(constants.TOUCHEVENT.SHIFTKEY),
- key, eventType;
+function _initialize() {
+ var _i;
- if (operation === "start") {
- altKey.disabled = 'disabled';
- metaKey.disabled = 'disabled';
- ctrlKey.disabled = 'disabled';
- shiftKey.disabled = 'disabled';
- clearInterval(intervalId);
- currentIndex = 0;
- eventType = "touchEvent";
- } else if (operation === "cancel") {
- altKey.disabled = '';
- metaKey.disabled = '';
- ctrlKey.disabled = '';
- shiftKey.disabled = '';
- altKey.checked = false;
- metaKey.checked = false;
- ctrlKey.checked = false;
- shiftKey.checked = false;
- cxt.clearRect(0, 0, canvas.width, canvas.height);
- moveEvents = {};
- eventType = "touchCancel";
+ dbfs.initialize();
+
+ // set up the map between real path and virtual path
+ for (_i = 0; _i < _virtualRoots.length; _i++) {
+ _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
}
- event.trigger(eventType, [{
- data : moveEvents,
- keys : [altKey.checked, metaKey.checked, ctrlKey.checked, shiftKey.checked]
- }]);
+ utils.forEach(_r2vmap, function (value, key) {
+ _v2rmap[value] = key;
+ });
}
-Point = function (x, y, color, isDragging) {
- var _self = {};
+function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
+ var _parts = srcLocation.replace(/\/$/, '').split("/"),
+ _header, _fullPath,
+ _i;
- _self.x = x;
- _self.y = y;
- _self.color = color;
- _self.isDragging = isDragging;
+ // TODO: Initialize at bootstrap and emulatorBridge.link
+ if (!_initialized) {
+ _initialize();
+ _initialized = true;
+ }
- return _self;
-};
+ for (_i = 0; _i < _parts.length; _i++) {
+ if (!_isValidFileName(_parts[_i])) {
+ if (onError) {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }
+ return;
+ }
+ }
-module.exports = {
- panel: {
- domId: "touchEvent-container",
- collapsed: true,
- pane: "left",
- titleName: "Touch Event",
- display: true
- },
+ _header = _v2rmap[_parts[0]];
+ if (_header === undefined) {
+ if (onError) {
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }
+ return;
+ }
- initialize: function () {
- var deviceInfo = require('ripple/devices').getCurrentDevice(),
- canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
- button = document.getElementById(constants.TOUCHEVENT.OPTION),
- cxt = canvas.getContext("2d"),
- points = [],
- paint = false,
- currentPoint = {};
+ if (_parts.length === 1) {
+ _fullPath = _header;
+ } else {
+ _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
+ }
- function drawPoints() {
- var key, index, points = [], point;
+ dbfs.stat(_fullPath,
+ function (entry) {
+ onSuccess(new File(entry, accessMode));
+ },
+ function () {
+ if (onError) {
+ onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
+ }
+ });
+}
- for (key in moveEvents) {
- points = moveEvents[key];
- cxt.fillStyle = colors[key];
+function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
+ _resolveSync(srcLocation,
+ function (file) {
+ setTimeout(function () {
+ onSuccess(file);
+ }, 1);
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ accessMode);
+}
- for (index = 0; index < points.length; index++) {
- point = points[index];
- cxt.beginPath();
- cxt.arc(point.offsetX, point.offsetY, 5, 0, 2 * Math.PI, 1);
- cxt.fill();
- }
- }
- }
+File = function (entry, mode) {
+ var _entry = entry,
+ _mode = mode,
+ _parent,
+ _self;
- function endDraw(event) {
- if (paint) {
- paint = false;
- clearInterval(intervalId);
- moveEvents[currentIndex].push(event);
- drawPoints();
+ function _r2v(rpath) {
+ var i, v, r, regExp;
- currentIndex++;
- if (currentIndex === 5)
- currentIndex = 0;
+ for (i = 0; i < _virtualRoots.length; i++) {
+ v = _virtualRoots[i];
+ r = _v2rmap[v];
+ if (rpath.match("^" + r)) {
+ regExp = new RegExp("^" + r);
+ return rpath.replace(regExp, v);
}
}
- canvas.addEventListener("mousedown", function (event) {
- if (button.value === "Touch Cancel") {
- button.value = "Touch Start";
- _exec("cancel");
- }
- moveEvents[currentIndex] = [];
- currentPoint = event;
- moveEvents[currentIndex].push(event);
- paint = true;
- drawPoints();
- intervalId = setInterval(function () {
- moveEvents[currentIndex].push(currentPoint);
- }, 100);
- });
+ return "";
+ }
- canvas.addEventListener("mousemove", function (event) {
- if (paint) {
- currentPoint = event;
- drawPoints();
+ function _v2r(vpath) {
+ var i, v, r, regExp;
+
+ for (i = 0; i < _virtualRoots.length; i++) {
+ v = _virtualRoots[i];
+ r = _v2rmap[v];
+ if (vpath.match("^" + v)) {
+ regExp = new RegExp("^" + v);
+ return vpath.replace(regExp, r);
}
- });
+ }
- canvas.addEventListener("mouseup", endDraw);
- canvas.addEventListener("mouseout", endDraw);
- canvas.addEventListener("mouseleave", endDraw);
+ return "";
+ }
- document.getElementById(constants.TOUCHEVENT.OPTION).addEventListener("click", function () {
- if (!moveEvents[0])
- return;
+ function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
+ var _srcName = String(src),
+ _dstName = String(dst),
+ _src = null,
+ _dst = null,
+ _error = false,
+ _dstParent = null,
+ _dstParts = _dstName.split("/"),
+ _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");
- if (this.value === "Touch Start") {
- this.value = "Touch Cancel";
- _exec("start");
- } else if (this.value === "Touch Cancel") {
- this.value = "Touch Start";
- _exec("cancel");
+ if (!_entry.isDirectory) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
}
- }, false);
+ return undefined;
+ }
- canvas.width = deviceInfo.screen.width / enlargeRatio;
- canvas.height = deviceInfo.screen.height / enlargeRatio;
- }
-};
+ _resolveSync(_srcName,
+ function (file) {
+ _src = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
-});
-define('ripple/ui/plugins/vehicle', function (require, exports, module) {
-/*
- * 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 event = require('ripple/event'),
- exception = require('ripple/exception'),
- vehiclePanelEngine = require('ripple/platform/ivi/3.0/VehiclePanelEngine').VehiclePanelEngine,
- _vehicleGlobalVars = {
- currentAutoStatus: false,
- currentDataIndex: 0,
- timeFlag: null,
- timeInterval: 1000, //ms
- timeCurrent: 0,
- timeHistoryArray: [],
- timeHistoryLimit: 60 * 60,
- registerListeners: {},
- vehicleCache: {},
- history: {},
- notShowProperties: [
- "zone", "time", "source"
- ]
- };
+ if (_src) {
+ if (_src.parent.fullPath === _self.fullPath) {
+ if (!_readOnly && _mode !== "r") {
+ _resolveSync(_dstParentName,
+ function (file) {
+ _dstParent = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
-function _interceptString (str, length) {
- return str.length > length ? str.substring(0, length) + "...": str;
-}
+ if (_dstParent === null) {
+ return undefined;
+ }
-function _setVehicleConfigurationSel (configuration) {
- var selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
- html = "", i = 0;
+ _resolveSync(_dstName,
+ function (file) {
+ _dst = file;
+ },
+ function (e) {
+ if (e.code !== errorcode.NOT_FOUND_ERR) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ _error = true;
+ }
+ },
+ _mode);
- for (var value in configuration) {
- html += '<option value="' + value + '">' +
- 'Car ' + i +
- '</option>';
+ if (_error) {
+ return undefined;
+ }
- i++;
+ if (_src.isFile) {
+ if (_dst === null) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (_dst === null) {
+ func(_v2r(_srcName), _v2r(_dstName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+ }
+
+ return undefined;
}
- selContainer.html(html);
-}
+ _self = {
+ toURI: function () {
+ return "file://" + _entry.fullPath;
+ },
+ listFiles: function (onSuccess, onError, filter) {
+ var _filter = Object(filter),
+ _filterName = _filter.name,
+ _startModified = _filter.startModified,
+ _endModified = _filter.endModified;
-function _setVehicleConfiguration (configuration, currentType) {
- var container = jQuery("#vehicle-container #vehicle-configuration-show"),
- selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
- current, property, propertyList, item, unit, html = "", i,
- enums, showValue;
+ function _matchName(fileName) {
+ var _matched = true,
+ _name1 = String(_filterName).toLowerCase(),
+ _name2 = fileName.toLowerCase(),
+ _pattern;
- if (currentType !== selContainer.val()) {
- for (i = 0; i < selContainer[0].options.length; i++) {
- if (selContainer[0].options[i].value === currentType) {
- selContainer[0].selectedIndex = i;
- break;
+ if (_filterName !== undefined && _filterName !== null) {
+ if (!_name1.match("\\\\%")) {
+ if (_name1.match("%")) {
+ _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
+ _matched = _name2.match(_pattern) ? true : false;
+ } else {
+ _matched = (_name1 === _name2);
+ }
+ } else {
+ // % is not allowed as a part of file name
+ _matched = false;
+ }
+ }
+
+ return _matched;
}
- }
- if (i >= selContainer[0].options.length ) {
- throw "undefined configuration: " + currentType + ".";
- }
- }
- current = configuration[currentType];
- if (!current) {
- throw "undefined configuration: " + currentType + ".";
- }
+ function _matchDate(date) {
+ var _matched = true;
- for (property in current) {
- html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
+ if (_startModified !== undefined && _startModified !== null) {
+ _matched = (date.getTime() >= _startModified.getTime());
+ }
- propertyList = current[property];
- for (item in propertyList) {
- showValue = propertyList[item];
- unit = vehiclePanelEngine.getPropertyUnit(property, item);
- enums = vehiclePanelEngine.getPropertyConstant(property, item);
- if (enums) {
- showValue = enums["val" + showValue];
+ if (_matched && (_endModified !== undefined && _endModified !== null)) {
+ _matched = (date.getTime() <= _endModified.getTime());
+ }
+
+ return _matched;
}
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label"> ' + item + unit + '</td>' +
- '<td class="vehicle-property-value" id="' + property + '-' + item + '-show">' + showValue + '</td>' +
- '<td style="display: none;">' +
- '<input id="' + property + '-' + item + '-set" type="hidden" ' + 'value="' + propertyList[item] + '" />' +
- '</td></tr>';
- }
- }
+ function _matchFilter(entry) {
+ return _matchName(entry.name) && _matchDate(entry.lastModifiedDate);
+ }
- container.html(html);
- return;
-}
+ function _listFiles() {
+ var _files = [];
-function _setVehicleSupported (properties, supported) {
- var hideContainer = jQuery("#vehicle-container #vehicle-supported-hide"),
- showContainer = jQuery("#vehicle-container #vehicle-supported-show"),
- hideHtml = "", showHtml = "", tempHtml, column = 0, columnNum = 3, className,
- i, property, propertyAbbr;
+ if ((_startModified !== undefined && !wac2_utils.isValidDate(_startModified)) ||
+ (_endModified !== undefined && !wac2_utils.isValidDate(_endModified))) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- for (i = 0; i < properties.length; i++) {
- property = properties[i];
- propertyAbbr = _interceptString(property, 12);
+ if (!_entry.isDirectory) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- if (supported.indexOf(property) > -1) {
- className = "vehicle-property-supported";
- hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" checked="checked" />';
- }
- else {
- className = "vehicle-property-unsupported";
- hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" />';
- }
+ utils.forEach(_entry.children, function (child) {
+ if (_matchFilter(child)) {
+ _files.push(new File(child, _mode));
+ }
+ });
- tempHtml = '<td id="' + property + '-supported-show" ' + 'class="' + className + '" title="' + property + '">' + propertyAbbr + '</td>';
+ setTimeout(function () {
+ onSuccess(_files);
+ }, 1);
- if (column % columnNum === 0) {
- showHtml += '<tr>' + tempHtml;
- }
- else if (column % columnNum === (columnNum - 1)){
- showHtml += tempHtml + '</tr>';
- }
- else {
- showHtml += tempHtml;
- }
- column++;
- }
+ return null;
+ }
- hideContainer.html(hideHtml);
- showContainer.html(showHtml);
-}
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
+ },
+ openStream: function (onSuccess, onError, mode, encoding) {
+ function _openStream() {
+ var _openMode = String(mode),
+ _encoding = encoding ? String(encoding) : "UTF-8";
-function _setVehicleSetting (settings) {
- var settingContainer = jQuery("#vehicle-container #vehicle-setting-show"),
- property, propertyItems, item, html = "", unit, range,
- optionHtml = "", i, optionName, option, options;
+ if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+ if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
+ (_writeOnly && _openMode === "r")) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
+
+ setTimeout(function () {
+ onSuccess(new FileStream(_entry, _openMode, _encoding));
+ }, 1);
- for (property in settings) {
- html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
+ return null;
+ }
- propertyItems = settings[property];
- for (item in propertyItems) {
- unit = vehiclePanelEngine.getPropertyUnit(property, item);
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
+ },
+ readAsText: function (onSuccess, onError, encoding) {
+ function _readAsText() {
+ var _encoding = encoding ? String(encoding) : "UTF-8";
+ if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ return undefined;
+ }
- if (propertyItems[item].type === "radio" || propertyItems[item].type === "select") {
- optionHtml = "";
- options = propertyItems[item].options;
- for (i = 0; i < options.length; i++) {
- option = options[i];
- for (optionName in option) {
- if (option[optionName].toString() === propertyItems[item].value.toString()) {
- optionHtml += '<option value="' + option[optionName] + '" selected>' +
- optionName + '</option>';
- }
- else {
- optionHtml += '<option value="' + option[optionName] + '">' +
- optionName + '</option>';
- }
- break;
+ if (_writeOnly) {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
}
+ return undefined;
}
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
- '<td class="vehicle-property-value">' +
- '<select id="' + property + '-' + item + '-set">' + optionHtml + '</select>' +
- '</td></tr>';
+
+ if (_self.isFile) {
+ dbfs.read(_entry.fullPath,
+ function (data) {
+ setTimeout(function () {
+ onSuccess(data);
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
+
+ return undefined;
}
- else if (propertyItems[item].type === "range") {
- range = vehiclePanelEngine.getPropertyRange(property, item);
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
- '<td class="vehicle-property-value">' +
- '<label id="' + property + '-' + item + '-num">' + propertyItems[item].value + '</label>' +
- '<input id="' + property + '-' + item + '-set" type="range" value="' + propertyItems[item].value + '"' +
- ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />' +
- '</td></tr>';
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
+ },
+ copyTo: function (onSuccess, onError, src, dst, overwrite) {
+ function _copyTo() {
+ return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
}
- else if (propertyItems[item].type === "text") {
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label" title="' + item + unit + '">' + _interceptString(item + unit, 18) + '</td>' +
- '<td class="vehicle-property-value">' +
- '<input id="' + property + '-' + item + '-set" type="text" value="' + propertyItems[item].value + '" />' +
- '</td></tr>';
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
+ },
+ moveTo: function (onSuccess, onError, src, dst, overwrite) {
+ function _moveTo() {
+ return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
}
- }
- }
-
- settingContainer.html(html);
-}
-
-function _addArrayValueEnter (property, item, value) {
- var itemValue, html = "", i,
- id = property + '-' + item + "-set";
- itemValue = value.split(",");
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
+ },
+ createDirectory: function (dirPath) {
+ var _path = String(dirPath),
+ _parts = _path.replace(/\/$/, "").split("/"),
+ _dir = null,
+ _exist = null,
+ _current = _entry.fullPath,
+ _i;
- if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
- html += '<td colspan="3">';
- }
- else {
- html += '<tr id="'+ id + 'Array" class="vehicle-property-array">' +
- '<td colspan="3">';
- }
+ function onSuccess(entry) {
+ _dir = entry;
+ }
- if (itemValue.length === 0) {
- html += '<div class="vehicle-property-arrayItem">' +
- '<button>add</button>' +
- '<input type="text" value="0" />' +
- '<button>del</button>' +
- '</div>';
- }
- else {
- for (i = 0; i < itemValue.length; i++) {
- if (i === itemValue.length - 1) {
- html += '<div class="vehicle-property-arrayItem">' +
- '<button style="margin-left: -60px;">add</button>' +
- '<input type="text" value="' + itemValue[i] + '" />' +
- '<button >del</button>' +
- '</div>';
+ for (_i = 0; _i < _parts.length; _i++) {
+ if (!_isValidFileName(_parts[_i])) {
+ throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
+ }
}
- else {
- html += '<div class="vehicle-property-arrayItem">' +
- '<button style="display: none;">add</button>' +
- '<input type="text" value="' + itemValue[i] + '" />' +
- '<button >del</button>' +
- '</div>';
+
+ if (!entry.isDirectory) {
+ throw new DeviceApiError(errorcode.IO_ERR);
}
- }
- }
- if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
- html += '</td>';
+ _exist = _parts.reduce(function (obj, token) {
+ return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
+ }, _entry);
- jQuery("#" + id + "Array").html(html);
- }
- else {
- html += '</td></tr>';
+ if (_exist) {
+ throw new DeviceApiError(errorcode.IO_ERR);
+ }
- html += '<tr id="'+ id + 'OK" class="vehicle-property-array">' +
- '<td colspan="3">';
- html += '<button class="vehicle-property-arrayOk">OK</button>';
- html += '</td></tr>';
- }
+ if (_readOnly || _mode === "r") {
+ throw new DeviceApiError(errorcode.SECURITY_ERR);
+ }
- return html;
-}
+ for (_i = 0; _i < _parts.length; _i++) {
+ _current = _current + "/" + _parts[_i];
+ dbfs.mkdir(_current, onSuccess);
+ }
+
+ return new File(_dir, _mode);
+ },
+ createFile: function (filePath) {
+ var _name = String(filePath),
+ _file = null;
-function _setVehicleAutoRunning (autoRunning, isFill) {
- var autoContainer = jQuery("#vehicle-container #vehicle-running-show"),
- timeStamp, html = "", unit, range, property, propertyItem, value, data,
- showContainer, setContainer, valueField, options, option, optionName, i,
- enums, showValue;
+ if (!_isValidFileName(_name)) {
+ throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
+ }
- timeStamp = (new Date()).getTime();
- data = autoRunning["auto" + _vehicleGlobalVars.currentDataIndex];
- if (!data) {
- _vehicleGlobalVars.currentDataIndex = 0;
- data = autoRunning["auto0"];
- }
- _vehicleGlobalVars.timeCurrent = timeStamp;
+ if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
+ throw new DeviceApiError(errorcode.IO_ERR);
+ }
- if (!isFill) {
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label">Time</td>' +
- '<td class="vehicle-property-value" id="vehicle-time-show">' + timeStamp + '</td></tr>';
+ if (_readOnly || _mode === "r") {
+ throw new DeviceApiError(errorcode.SECURITY_ERR);
+ }
- for (property in data) {
- html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';
+ dbfs.touch(_entry.fullPath + "/" + _name,
+ function (entry) {
+ _file = new File(entry, _mode);
+ },
+ function () {});
+
+ return _file;
+ },
+ resolve: function (filePath) {
+ var _fullPath = _self.fullPath + "/" + String(filePath),
+ _file = null;
+
+ if (!_entry.isDirectory) {
+ throw new DeviceApiError(errorcode.IO_ERR);
+ }
- for (propertyItem in data[property]) {
- value = data[property][propertyItem].value;
- unit = vehiclePanelEngine.getPropertyUnit(property, propertyItem);
+ _resolveSync(_fullPath,
+ function (file) {
+ _file = file;
+ },
+ function (e) {
+ throw (e);
+ },
+ _mode);
- if (Object.prototype.toString.call(value) === '[object Array]') {
- value = value.join(",");
+ return _file;
+ },
+ deleteDirectory: function (onSuccess, onError, directory, recursive) {
+ function _deleteDirectory() {
+ var _dir = null,
+ _dirName = String(directory);
+ _resolveSync(_dirName,
+ function (file) {
+ _dir = file;
+ },
+ function (e) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
+ },
+ _mode);
+
+ if (_dir) {
+ if (_dir.isDirectory &&
+ _dir.parent.fullPath === _self.fullPath &&
+ (!recursive && _dir.length === 0)) {
+ if (!_readOnly && _mode !== "r") {
+ dbfs.rmdir(_v2r(_dirName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
+ }
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
+ }
+ }
}
- if (data[property][propertyItem].type === "radio" || data[property][propertyItem].type === "select") {
- valueField = "";
- options = data[property][propertyItem].options;
- for (i = 0; i < options.length; i++) {
- option = options[i];
- for (optionName in option) {
- if (option[optionName].toString() === data[property][propertyItem].value) {
- valueField += '<option value="' + option[optionName] + '" selected>' +
- optionName + '</option>';
+ return undefined;
+ }
+
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
+ },
+ deleteFile: function (onSuccess, onError, fileName) {
+ function _deleteFile() {
+ var _file = null;
+ _resolveSync(String(fileName),
+ function (file) {
+ _file = file;
+ },
+ function (e) {
+ if (onError) {
+ setTimeout(function () {
+ onError(e);
+ }, 1);
}
- else {
- valueField += '<option value="' + option[optionName] + '">' +
- optionName + '</option>';
+ },
+ _mode);
+
+ if (_file) {
+ if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
+ if (!_readOnly && _mode !== "r") {
+ dbfs.rm(_v2r(fileName),
+ function () {
+ setTimeout(function () {
+ onSuccess();
+ }, 1);
+ },
+ function () {});
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.SECURITY_ERR));
+ }, 1);
}
- break;
+ }
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.IO_ERR));
+ }, 1);
}
}
-
- valueField = '<select id="' + property + '-' + propertyItem + '-set">' + valueField + '</select>';
- }
- else if (data[property][propertyItem].type === "range") {
- range = vehiclePanelEngine.getPropertyRange(property, propertyItem);
-
- valueField = '<label id="' + property + '-' + propertyItem + '-num">' + value + '</label>' +
- '<input id="' + property + '-' + propertyItem + '-set" type="range" value="' + value + '"' +
- ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />';
- }
- else if (data[property][propertyItem].type === "text") {
- valueField = '<input type="text" value="' + value +'" id="' + property + '-' + propertyItem + '-set" disabled />';
}
- enums = vehiclePanelEngine.getPropertyConstant(property, propertyItem);
- if (enums) {
- showValue = enums["val" + value];
- }
+ return undefined;
+ }
- html += '<tr class="vehicle-property-content">' +
- '<td class="vehicle-property-label" title="' + propertyItem + unit + '">' + _interceptString(propertyItem + unit, 18) + '</td>' +
- '<td class="vehicle-property-value vehicle-property-value-auto" id="' + property + '-' + propertyItem + '-show">' + showValue + '</td>' +
- '<td class="vehicle-property-value vehicle-property-value-manual">' +
- valueField +
- '</td></tr>';
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
+ }
+ };
- if (data[property][propertyItem].type === "text") {
- html += _addArrayValueEnter(property, propertyItem, value);
- }
+ _self.__defineGetter__("parent", function () {
+ var _parts = _self.fullPath.split("/");
- if (_vehicleGlobalVars.registerListeners[property]) {
- event.trigger("vehicle-subscribe-request", [property, false, 0]);
- }
+ if (_parent === undefined) {
+ if (_parts.length === 1) {
+ // virtual root's parent is null
+ _parent = null;
+ } else {
+ _resolveSync(_parts.splice(0, _parts.length - 1).join("/"),
+ function (file) {
+ _parent = file;
+ },
+ function () {},
+ _mode);
}
+ return _parent;
+ } else {
+ return _parent;
}
+ });
- autoContainer.html(html);
- _switchAutoManual(false);
- }
- else {
- if (_vehicleGlobalVars.currentAutoStatus) {
- for (property in data) {
-
- for (propertyItem in data[property]) {
- value = data[property][propertyItem].value;
+ _self.__defineGetter__("readOnly", function () {
+ return false;
+ });
- showContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-show");
- setContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-set");
+ _self.__defineGetter__("isFile", function () {
+ return !_entry.isDirectory;
+ });
- if (Object.prototype.toString.call(value) === '[object Array]') {
- value = value.join(",");
- }
+ _self.__defineGetter__("isDirectory", function () {
+ return _entry.isDirectory;
+ });
- if (data[property][propertyItem].type === "text") {
- _addArrayValueEnter(property, propertyItem, value);
- }
+ _self.__defineGetter__("created", function () {
+ return undefined;
+ });
- if (showContainer && setContainer) {
- showContainer.html(value);
- setContainer.val(value);
- }
- }
- }
- }
- else {
+ _self.__defineGetter__("modified", function () {
+ if (_entry.isDirectory) {
+ return undefined;
+ } else {
+ return _entry.lastModifiedDate;
}
- jQuery("#vehicle-container #vehicle-running-show #vehicle-time-show").html(timeStamp);
- }
+ });
- for (property in _vehicleGlobalVars.registerListeners) {
- event.trigger("vehicle-subscribe-request", [property, false, 0]);
- }
+ _self.__defineGetter__("path", function () {
+ var _parts = _self.fullPath.split("/");
- _saveVehicleData();
- _vehicleGlobalVars.currentDataIndex++;
-}
+ if (_parts.length === 1) {
+ // virtual root
+ return _parts.join("");
+ } else {
+ return _parts.splice(0, _parts.length - 1).join("/") + "/";
+ }
+ });
-function _formatHistory (historyData, time, zone, source) {
- var format = {}, property, name, item, value;
+ _self.__defineGetter__("name", function () {
+ return _entry.name;
+ });
- for (property in historyData) {
- name = property.split("-")[0];
- item = property.split("-")[1];
+ _self.__defineGetter__("fullPath", function () {
+ return _r2v(_entry.fullPath);
+ });
- if (!format[name]) {
- format[name] = {};
- format[name].time = time;
- format[name].zone = zone;
- format[name].source = source;
+ _self.__defineGetter__("fileSize", function () {
+ if (_entry.isDirectory) {
+ return undefined;
+ } else {
+ return _entry.data.length;
}
+ });
- value = historyData[property];
- if (value.indexOf(",") > -1) {
- value = value.split(",");
+ _self.__defineGetter__("length", function () {
+ var _l = 0;
+ if (_entry.isDirectory) {
+ utils.forEach(_entry.children, function () {
+ _l++;
+ });
+ return _l;
+ } else {
+ return undefined;
}
- if (value === "true") value = true;
- if (value === "false") value = false;
-
- format[name][item] = value;
- }
-
- return format;
-}
+ });
-function _saveVehicleData () {
- var configurationContainer = jQuery("#vehicle-container #vehicle-configuration-show *[id$='-set']"),
- currentConfigContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
- settingContainer = jQuery("#vehicle-container #vehicle-setting-show *[id$='-set']"),
- autoContainer = jQuery("#vehicle-container #vehicle-running-show *[id$='-set']"),
- supportedContainer = jQuery("#vehicle-container #vehicle-supported-hide *[id$='-supported']:checked"),
- supported = [], currentConfig, configuration = [], setting = [], autoRunning = [],
- history = {}, itemKey, format, delTime, time, zone, source;
+ return _self;
+};
- supportedContainer.each(function (index, item) {
- supported.push(item.value);
- });
+FileStream = function (entry, mode, encoding) {
+ var _entry = entry,
+ _data = entry.data,
+ _mode = mode,
+ _position = (_mode === "a" ? _data.length : 0),
+ _self;
- currentConfig = currentConfigContainer.val().replace("configuration", "");
+ _self = {
+ close: function () {
+ var _element;
+ if (mode === "a" || mode === "w") {
+ dbfs.write(_entry.fullPath, _data, function () {}, function () {});
+ }
+ for (_element in _self) {
+ delete _self[_element];
+ }
+ },
+ read: function (charCount) {
+ var _count = charCount | 0,
+ _substr = _data.substring(_position, _position + _count);
- configurationContainer.each(function (index, item) {
- itemKey = item.id.replace("-set", "");
- history[itemKey] = item.value;
+ if (_position + _count > _data.length) {
+ _position = _data.length;
+ } else {
+ _position += _count;
+ }
- configuration.push(item.value);
- });
+ return _substr;
+ },
+ readBytes: function (byteCount) {
+ var _substr = _self.read(byteCount),
+ _bytes = [],
+ _i;
- settingContainer.each(function (index, item) {
- itemKey = item.id.replace("-set", "");
- history[itemKey] = item.value;
+ for (_i = 0; _i < _substr.length; _i++) {
+ _bytes.push(_substr.charCodeAt(_i));
+ }
- setting.push(item.value);
- });
+ return _bytes;
+ },
+ readBase64: function (byteCount) {
+ var _substr = _self.read(byteCount);
- autoContainer.each(function (index, item) {
- var value;
+ return window.atob(_substr);
+ },
+ write: function (stringData) {
+ var _stringData = String(stringData),
+ _substr = _data.substring(0, _position);
- value = item.value;
- if (item.id.indexOf("TripMeter") > -1) {
- value = item.value.split(",");
+ _data = _substr.concat(_stringData);
+ _position = _data.length;
+ },
+ writeBytes: function (byteData) {
+ _self.write(String.fromCharCode.apply(String, byteData));
+ },
+ writeBase64: function (base64Data) {
+ _self.write(window.btoa(String(base64Data)));
}
+ };
- itemKey = item.id.replace("-set", "");
- history[itemKey] = value;
-
- autoRunning.push(value);
+ _self.__defineGetter__("eof", function () {
+ return _position === _data.length;
});
- _vehicleGlobalVars.timeHistoryArray.push(_vehicleGlobalVars.timeCurrent);
- if (_vehicleGlobalVars.timeHistoryArray.length > _vehicleGlobalVars.timeHistoryLimit) {
- delTime = _vehicleGlobalVars.timeHistoryArray.shift();
- delete _vehicleGlobalVars.history[delTime];
- }
-
- time = _vehicleGlobalVars.timeCurrent;
- source = "";
- zone = 0;
-
- format = _formatHistory(history, time, zone, source);
- _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent] = format;
- event.trigger("vehicle-cache-refresh", [supported, format]);
+ _self.__defineGetter__("position", function () {
+ return _position;
+ });
- vehiclePanelEngine.saveData(supported, currentConfig, configuration, setting, autoRunning);
-}
+ _self.__defineSetter__("position", function (value) {
+ var _value = value | 0;
-function _switchAutoManual (isAuto) {
- var autoContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-auto"),
- manualContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-manual"),
- arrayContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-array"),
- autoBtnContainer = jQuery("#vehicle-container #vehicle-running-auto");
+ if (_value >= 0 && _value <= _data.length) {
+ _position = _value;
+ } else {
+ throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
+ }
+ });
- if (isAuto) {
- autoBtnContainer.addClass("vehicle-property-supported");
- autoBtnContainer.removeClass("vehicle-property-unsupported");
- autoContainer.show();
- manualContainer.hide();
- arrayContainer.hide();
- }
- else {
- autoBtnContainer.addClass("vehicle-property-unsupported");
- autoBtnContainer.removeClass("vehicle-property-supported");
- autoContainer.hide();
- manualContainer.show();
- arrayContainer.show();
- }
-}
+ _self.__defineGetter__("bytesAvailable", function () {
+ return (_data.length - _position) || -1;
+ });
-function _addVehicleDomEventListener () {
- var configSelection = jQuery("#vehicle-container #vehicle-configuration-types"),
- supportedSelection = jQuery("#vehicle-container #vehicle-supported-show td"),
- autoSelection = jQuery("#vehicle-container #vehicle-running-auto"),
- arraySelection = jQuery("#vehicle-container .vehicle-property-array"),
- arrayOKSelection = jQuery("#vehicle-container .vehicle-property-arrayOk"),
- rangeSelection = jQuery("#vehicle-container input[type='range']");
+ return _self;
+};
- arraySelection.delegate("button", "click", function () {
- var els = jQuery(this), appHtml;
+module.exports = function () {
+ return {
+ maxPathLength: _maxPathLength,
+ resolve: function (onSuccess, onError, srcLocation, accessMode) {
+ function _resolve() {
+ var _mode = accessMode ? String(accessMode) : _defaultMode;
- appHtml = '<div class="vehicle-property-arrayItem">' +
- '<button style="margin-left: -60px;">add</button>' +
- '<input type="text" value="0" />' +
- '<button >del</button>' +
- '</div>';
+ if (_mode === "r" || _mode === "rw") {
+ _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
+ return null;
+ } else {
+ if (onError) {
+ setTimeout(function () {
+ onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
+ }, 1);
+ }
+ }
+ return undefined;
+ }
- if (els.html() === "add") {
- jQuery(appHtml).insertAfter(els.parent());
- els.hide();
- }
- else if (els.html() === "del") {
- if (els.parent().prev().length === 0 && els.parent().next().length === 0)
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
+ },
+ handleSubFeatures: function (subFeatures) {
+ if (wac2_utils.isEmptyObject(subFeatures) ||
+ subFeatures["http://wacapps.net/api/filesystem"] ||
+ (subFeatures["http://wacapps.net/api/filesystem.read"] &&
+ subFeatures["http://wacapps.net/api/filesystem.write"])) {
return;
- els.parent().prev().find("button")[0].style.marginLeft = "-60px";
- els.parent().prev().find("button")[0].style.display = "";
- els.parent().remove();
+ }
+ if (subFeatures["http://wacapps.net/api/filesystem.read"]) {
+ _readOnly = true;
+ return;
+ }
+ if (subFeatures["http://wacapps.net/api/filesystem.write"]) {
+ _writeOnly = true;
+ return;
+ }
+ _console.warn("WAC-2.0-Filesystem: something wrong in handleSubFeatures");
}
- });
+ };
+};
- arrayOKSelection.click("click", function () {
- var els = jQuery(this), inputEls, i, trEls,
- setElsId, value = [];
- trEls = els.parent().parent();
- setElsId = trEls.attr("id").replace("OK", "");
+});
+define('ripple/platform/wac/2.0/accelerometer', function (require, exports, module) {
+/*
+ * Copyright 2011 Intel Corporation.
+ *
+ * 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.
+ */
- inputEls = trEls.prev().find("input");
- for (i = 0; i < inputEls.length; i++) {
- value.push(inputEls[i].value);
+var utils = require('ripple/utils'),
+ event = require('ripple/event'),
+ Acceleration = function (x, y, z) {
+ return {
+ xAxis: x || 0,
+ yAxis: y || 0,
+ zAxis: z || 0
+ };
+ },
+ wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
+ _accelerometerInfo = new Acceleration(),
+ _defaultInterval = 100,
+ _watches = {},
+ _self;
+
+module.exports = _self = {
+ getCurrentAcceleration: function (onSuccess, onError) {
+ function _getCurrentAcceleration() {
+ setTimeout(function () {
+ onSuccess(utils.copy(_accelerometerInfo));
+ }, 1);
+ return null;
}
- jQuery("#vehicle-container #" + setElsId).val(value.join(","));
- });
+ return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentAcceleration", _getCurrentAcceleration);
+ },
- rangeSelection.bind("change", function () {
- var domJQuery = jQuery(this);
+ watchAcceleration: function (accelerometerSuccess, accelerometerError, options) {
+ function _watchAcceleration() {
+ var watchId = (new Date()).getTime() | 0,
+ watchObj = {},
+ opt = Object(options),
+ minNotificationInterval = opt.minNotificationInterval | 0,
+ accelerometerInterval = _defaultInterval;
- domJQuery.prev().html(domJQuery.val());
- });
+ if (minNotificationInterval > 0) {
+ accelerometerInterval = minNotificationInterval;
+ }
- configSelection.bind("change", function () {
- var configuration, current,
- domJQuery = jQuery(this);
+ watchObj = {
+ onSuccess: accelerometerSuccess,
+ onError: accelerometerError,
+ interval: accelerometerInterval
+ };
- configuration = _vehicleGlobalVars.vehicleCache.configurationData;
- current = domJQuery.val();
- _setVehicleConfiguration(configuration, current);
- });
+ _watches[watchId] = watchObj;
- //add vehicle supported click event
- supportedSelection.bind("click", function () {
- var domJQuery = jQuery(this), vehicleChecked,
- propertiesSelector = "#vehicle-container #vehicle-supported-hide",
- content, supportedId, inputJQuery;
+ _watches[watchId].intervalId = setInterval(function () {
+ _self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
+ }, _watches[watchId].interval);
- content = domJQuery.html();
- supportedId = content + "-supported";
- inputJQuery = jQuery(propertiesSelector + " #" + supportedId);
- if (domJQuery.hasClass("vehicle-property-unsupported")) {
- inputJQuery.attr("checked", "checked");
- domJQuery.removeClass("vehicle-property-unsupported");
- domJQuery.addClass("vehicle-property-supported");
- }
- else {
- inputJQuery.removeAttr("checked");
- domJQuery.removeClass("vehicle-property-supported");
- domJQuery.addClass("vehicle-property-unsupported");
+ return watchId;
}
- vehicleChecked = jQuery("#vehicle-container #vehicle-supported-hide input:checked");
- _vehicleGlobalVars.vehicleCache.supported.length = 0;
- vehicleChecked.each(function (index, els) {
- _vehicleGlobalVars.vehicleCache.supported.push(els.value);
- });
- });
-
- //add vehicle auto click event
- autoSelection.bind("click", function () {
- if (_vehicleGlobalVars.currentAutoStatus) {
- _vehicleGlobalVars.currentAutoStatus = false;
- jQuery("#vehicle-container #vehicle-configuration-noOperation").hide();
- jQuery("#vehicle-container #vehicle-supported-noOperation").hide();
- }
- else {
- _vehicleGlobalVars.currentAutoStatus = true;
- jQuery("#vehicle-container #vehicle-configuration-noOperation").show();
- jQuery("#vehicle-container #vehicle-supported-noOperation").show();
- }
- _switchAutoManual(_vehicleGlobalVars.currentAutoStatus);
+ return wac2_utils.validateTypeMismatch(accelerometerSuccess, accelerometerError, "watchAcceleration", _watchAcceleration);
+ },
- _vehicleGlobalVars.timeFlag = setInterval(function () {
- _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
- }, _vehicleGlobalVars.timeInterval);
- });
-}
+ clearWatch: function (watchId) {
-function _addVehicleEventListener () {
- event.once("vehicle-cache-request", function (data) {
- data.supported = _vehicleGlobalVars.vehicleCache.supported;
- data.data = _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent];
- });
+ var id = watchId | 0;
- event.on("vehicle-subscribe-request", function (property, isRegister, zone) {
- if (isRegister) {
- _vehicleGlobalVars.registerListeners[property] = true;
- return;
+ if (_watches[id]) {
+ clearInterval(_watches[id].intervalId);
+ delete(_watches[id]);
+ return null;
}
- var value, status, time, history,
- propertyObj = {};
+ return undefined;
+ }
+};
- if (_vehicleGlobalVars.vehicleCache.supported.indexOf(property) === -1) {
- propertyObj.val = null;
- propertyObj.supported = false;
- propertyObj.type = property;
- }
- else {
- history = _vehicleGlobalVars.history;
- time = _vehicleGlobalVars.timeCurrent;
+event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
+ _accelerometerInfo.xAxis = accelerometerInfo.accelerationIncludingGravity.x;
+ _accelerometerInfo.yAxis = accelerometerInfo.accelerationIncludingGravity.y;
+ _accelerometerInfo.zAxis = accelerometerInfo.accelerationIncludingGravity.z;
+});
- value = history[time][property];
- value.time = time;
- status = true;
- propertyObj.val = value;
- propertyObj.supported = status;
- propertyObj.type = property;
- }
+});
+define('ripple/platform/wac/2.0/typecoerce', function (require, exports, module) {
+/*\r
+ * Copyright 2011 Intel Corporation.\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+var utils = require('ripple/utils'),\r
+ _self;\r
+\r
+_self = function (pattern) {\r
+ var typeCoerce,\r
+ typeOfPattern = Object.prototype.toString.call(pattern);\r
+\r
+ typeCoerce = {\r
+ cast: function (obj) {\r
+ var validObj,\r
+ validValue,\r
+ elementType,\r
+ typeOfObj = Object.prototype.toString.call(obj);\r
+\r
+ switch (typeOfPattern) {\r
+ case "[object String]":\r
+ validObj = (typeOfObj !== typeOfPattern) ? String(obj) : obj;\r
+ break;\r
+\r
+ case "[object Number]":\r
+ validObj = (typeOfObj !== typeOfPattern) ? (Number(obj) | 0) : obj;\r
+ break;\r
+\r
+ case "[object Object]":\r
+ if (typeOfObj !== typeOfPattern) {\r
+ validObj = {};\r
+ } else {\r
+ validObj = obj;\r
+ utils.forEach(validObj, function (value, key) {\r
+ if (pattern[key] === undefined) {\r
+ delete validObj[key];\r
+ } else {\r
+ validValue = _self(pattern[key]).cast(value);\r
+ if (validObj[key] !== validValue)\r
+ validObj[key] = validValue;\r
+ }\r
+ });\r
+ }\r
+ break;\r
+\r
+ case "[object Array]":\r
+ if (typeOfObj !== typeOfPattern) {\r
+ validObj = [];\r
+ } else {\r
+ validObj = obj;\r
+ elementType = _self(pattern[0]);\r
+ utils.forEach(validObj, function (element, index) {\r
+ validObj[index] = elementType.cast(element);\r
+ });\r
+ }\r
+ break;\r
+ }\r
+\r
+ return validObj;\r
+ }\r
+ };\r
+\r
+ return typeCoerce;\r
+};\r
+\r
+module.exports = _self;\r
- event.trigger("vehicle-subscribe-response", [propertyObj]);
- });
+});
+define('ripple/platform/cordova/2.0.0/JavaPluginManager', function (require, exports, module) {
+module.exports = {
+ exec: function () {
+ throw "this really shouldn't be called. like ever!";
+ },
+ resume: function () {
+ throw "this shouldn't be called";
+ },
+ pause: function () {
+ throw "this shouldn't be called";
+ },
+ destroy: function () {
+ throw "this shouldn't be called";
+ }
+};
- event.on("vehicle-set-request", function (property, value) {
- var status = true, enums, showValue;
+});
+define('ripple/platform/cordova/2.0.0/spec', function (require, exports, module) {
+function loadWebworks(win, device) {
+ var builder = require('ripple/platform/builder'),
+ platform = device.id === "Playbook" || device.id === "Colt" ? "tablet" : "handset",
+ webworks = require('ripple/platform/webworks.' + platform + '/2.0.0/spec');
- for (var item in value) {
- var enterID = property + "-" + item + "-set";
- var showID = property + "-" + item + "-show";
- var enterContainer = jQuery("#vehicle-container #" + enterID);
- var showContainer = jQuery("#vehicle-container #" + showID);
+ builder.build(webworks.objects).into(win);
+ builder.build(webworks.objects).into(window);
+}
- if (Object.prototype.toString.call(value[item]) === '[object Array]') {
- enterContainer.val(value[item].join(","));
- }
- else {
- enterContainer.val(value[item].toString());
- }
- if (showContainer) {
- enums = vehiclePanelEngine.getPropertyConstant(property, item);
- showValue = value[item];
- if (enums) {
- showValue = enums["val" + value[item]];
+module.exports = {
+ id: "cordova",
+ version: "2.0.0",
+ name: "Apache Cordova",
+ type: "platform",
+ nativeMethods: {},
+
+ config: require('ripple/platform/cordova/2.0.0/spec/config'),
+ device: require('ripple/platform/cordova/2.0.0/spec/device'),
+ ui: require('ripple/platform/cordova/2.0.0/spec/ui'),
+ events: require('ripple/platform/cordova/2.0.0/spec/events'),
+
+ initialize: function (win) {
+ var honeypot = require('ripple/honeypot'),
+ devices = require('ripple/devices'),
+ device = devices.getCurrentDevice(),
+ bridge = require('ripple/platform/cordova/2.0.0/bridge'),
+ cordova,
+ topCordova = window.top.require('ripple/platform/cordova/2.0.0/spec'),
+ get = function () {
+ return cordova;
+ },
+ set = function (orig) {
+ if (cordova) {
+ return;
}
- showContainer.html(showValue);
- }
- }
- event.trigger("vehicle-set-response", [status]);
- });
+ cordova = orig;
- event.on("vehicle-history-request", function (property, zone, startTime, endTime) {
- var history, historyResponse = [], obj, status, time;
+ cordova.define.remove("cordova/exec");
+ cordova.define("cordova/exec", function (require, exports, module) {
+ module.exports = bridge.exec;
+ });
- history = _vehicleGlobalVars.history;
+ cordova.UsePolling = true;
- for (time in history) {
- if (time >= startTime && time <= endTime &&
- history[time].hasOwnProperty(property)) {
- obj = history[time][property];
- obj.time = time;
- historyResponse.push(obj);
- }
- }
- status = true;
+ //do nothing here as we will just call the callbacks ourselves
+ cordova.define.remove("cordova/plugin/android/polling");
+ cordova.define("cordova/plugin/android/polling", function (require, exports, module) {
+ module.exports = function () {};
+ });
- event.trigger("vehicle-history-response", [historyResponse, status]);
- });
-}
+ var builder = cordova.require('cordova/builder'),
+ allTheThings = window,
+ base = cordova.require('cordova/common'),
+ iosPlugin;
-function _initializeVehiclePanel () {
- try {
- var stop = false,
- configuration, current, properties, supported, settings,
- autoRunning;
+ //HACK: Overwrite all the things, handles when cordova.js executes before we start booting
+ builder.build(base.objects).intoAndClobber(allTheThings);
+ cordova.require('cordova/channel').onNativeReady.fire();
+ // DIRTY HACK: once cordova is cleaned up, we do not
+ // need this.
+ // reference issue: https://issues.apache.org/jira/browse/CB-1013
+ try {
+ iosPlugin = cordova.require('cordova/plugin/ios/device');
+ bridge.exec(function (info) {
+ iosPlugin.setInfo(info);
+ }, null, 'Device', 'getDeviceInfo', []);
+ } catch (e) {
+ cordova.require('cordova/channel').onCordovaInfoReady.fire();
+ }
+ };
- _vehicleGlobalVars.timeHistoryArray = [];
+ if (window.FileReader && !topCordova.nativeMethods.FileReader) {
+ topCordova.nativeMethods.FileReader = window.FileReader;
+ }
- configuration = vehiclePanelEngine.getConfiguration();
- current = vehiclePanelEngine.getCurrentConfiguration();
- _setVehicleConfigurationSel(configuration);
- _vehicleGlobalVars.vehicleCache.configurationData = configuration;
- _vehicleGlobalVars.vehicleCache.currentConfiguration = current;
- _setVehicleConfiguration(configuration, current);
+ if (device.manufacturer === "Research In Motion") {
+ loadWebworks(win, device);
+ }
- properties = vehiclePanelEngine.getProperties();
- supported = vehiclePanelEngine.getSupported();
- _vehicleGlobalVars.vehicleCache.properties = properties;
- _vehicleGlobalVars.vehicleCache.supported = supported;
- _setVehicleSupported(properties, supported);
+ honeypot.monitor(win, "cordova").andRun(get, set);
+ },
- settings = vehiclePanelEngine.getSettings();
- _vehicleGlobalVars.vehicleCache.settingData = settings;
- _setVehicleSetting(settings);
+ objects: {
+ MediaError: {
+ path: "cordova/2.0.0/MediaError"
+ },
+ org: {
+ children: {
+ apache: {
+ children: {
+ cordova: {
+ children: {
+ Logger: {
+ path: "cordova/2.0.0/logger"
+ },
+ JavaPluginManager: {
+ path: "cordova/2.0.0/JavaPluginManager"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+};
- autoRunning = vehiclePanelEngine.getAutoRunning();
- _vehicleGlobalVars.vehicleCache.autoRunningData = autoRunning;
- _setVehicleAutoRunning(autoRunning, false);
- _vehicleGlobalVars.currentDataIndex = 0;
+});
+define('ripple/platform/cordova/2.0.0/logger', function (require, exports, module) {
+module.exports = {
+ log: function (msg) {
+ console.log(msg);
+ }
+};
- _vehicleGlobalVars.timeFlag = setInterval(function () {
- _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
- }, _vehicleGlobalVars.timeInterval);
+});
+define('ripple/platform/cordova/2.0.0/spec/config', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants');
- _addVehicleDomEventListener();
+module.exports = {
+ fileName: "config.xml",
+ validateVersion: function (configValidationObject) {
+ var valid = true;
+ valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
+ (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));
- _addVehicleEventListener();
+ return valid;
+ },
+ extractInfo: function (configValidationObject) {
+ if (!configValidationObject) {
+ return null;
+ }
- jQuery("#vehicle-properties h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
+ var widgetInfo = {};
+
+ widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
+ widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
+ widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
+ widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
+
+ return widgetInfo;
+ },
+ schema: {
+ rootElement: "widget",
+ widget: {
+ nodeName: "widget",
+ required: true,
+ occurrence: 1,
+ attributes: {
+ xmlns: {
+ attributeName: "xmlns",
+ required: true,
+ type: "list",
+ listValues: ["http://www.w3.org/ns/widgets"]
+ },
+ "xmlns:gap": {
+ attributeName: "xmlns:gap",
+ required: true,
+ type: "list",
+ listValues: ["http://phonegap.com/ns/1.0"]
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ required: false,
+ type: "iso-language"
+ },
+ dir: {
+ attributeName: "dir",
+ required: false,
+ type: "list",
+ listValues: ["ltr", "rtl", "lro", "rlo"]
+ },
+ id: {
+ attributeName: "id",
+ required: false,
+ type: "string"
+ },
+ version: {
+ attributeName: "version",
+ required: false,
+ type: "string"
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ },
+ viewmodes: {
+ attributeName: "viewmodes",
+ required: false,
+ type: "list",
+ listValues: ["floating", "fullscreen"]
+ }
+ },
+ children: {
+ name: {
+ nodeName: "name",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "short": {
+ attributeName: "short",
+ type: "string",
+ required: false
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ description: {
+ nodeName: "description",
+ required: false,
+ occurrence: 0,
+ type: "string",
+ attributes: {
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ author: {
+ nodeName: "author",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ email: {
+ attributeName: "email",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.EMAIL
+ },
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ }
+ }
+ },
+ license: {
+ nodeName: "license",
+ required: false,
+ occurrence: 1,
+ type: "string",
+ attributes: {
+ href: {
+ attributeName: "href",
+ type: "regex",
+ required: false,
+ regex: constants.REGEX.URL
+ },
+ "xml:lang": {
+ attributeName: "xml:lang",
+ type: "string",
+ required: false,
+ unique: true
+ }
+ }
+ },
+ icon: {
+ nodeName: "icon",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ height: {
+ attributeName: "height",
+ required: false,
+ type: "integer"
+ },
+ width: {
+ attributeName: "width",
+ required: false,
+ type: "integer"
+ }
+ }
+ },
+ content: {
+ nodeName: "content",
+ required: false,
+ occurrence: 1,
+ attributes: {
+ src: {
+ attributeName: "src",
+ type: "string",
+ required: true
+ },
+ encoding: {
+ attributeName: "encoding",
+ type: "string",
+ required: false
+ },
+ type: {
+ attributeName: "type",
+ type: "string",
+ required: false
+ }
+ }
+ },
+ feature: {
+ nodeName: "feature",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "list",
+ required: true,
+ listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
+ "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
+ "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
+ "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
+ "http://api.phonegap.com/1.0/storage"]
+ },
+ required: {
+ attributeName: "required",
+ type: "boolean",
+ required: false
+ }
+ }
+ },
+ preference: {
+ nodeName: "preference",
+ required: false,
+ occurrence: 0,
+ attributes: {
+ name: {
+ attributeName: "name",
+ type: "string",
+ required: true
+ },
+ value: {
+ type: "string",
+ attributeName: "value",
+ required: false
+ },
+ readonly: {
+ attributeName: "readonly",
+ type: "boolean",
+ required: false
+ }
+ }
+ }
}
- });
- jQuery("#vehicle-properties").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
- });
- } catch (e) {
- exception.handle(e, true);
+ }
}
-}
+};
+
+});
+define('ripple/platform/cordova/2.0.0/spec/device', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event');
module.exports = {
- panel: {
- domId: "vehicle-container",
- collapsed: true,
- pane: "right",
- titleName: "Vehicle Information",
- display: true
- },
- initialize: function () {
- _initializeVehiclePanel();
+ "NetworkStatus": {
+ "connectionType": {
+ "name": "Connection Type",
+ "control": {
+ "type": "select",
+ "value": "ethernet"
+ },
+ "options": {
+ "unknown": "UNKNOWN",
+ "ethernet": "ETHERNET",
+ "wifi": "WIFI",
+ "2g": "CELL_2G",
+ "3g": "CELL_3G",
+ "4g": "CELL_4G",
+ "none": "none"
+ },
+ "callback": function (setting) {
+ var connected = setting !== "none";
+ require('ripple/bus').send("network", connected);
+ }
+ },
+ "lag": {
+ "name": "Lag the network",
+ "control": {
+ type: "checkbox",
+ value: false
+ },
+ "callback": function (setting) {
+ require('ripple/bus').send("lag", setting);
+ }
+ },
}
};
});
-define('ripple/ui/plugins/videoPlayer', function (require, exports, module) {
+define('ripple/platform/cordova/2.0.0/spec/events', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- event = require('ripple/event');
+function _fires(name, data) {
+ return function () {
+ cordova.fireDocumentEvent(name, data);
+ };
+}
module.exports = {
- initialize: function () {
- var videoObj,
- videoProgress = document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_PROGRESS_ID);
-
- event.on("MultimediaAppVideoPlayerCreated", function (videoDOMObj) {
- videoObj = videoDOMObj;
-
- videoObj.addEventListener("timeupdate", function () {
- var s = parseInt(videoObj.currentTime % 60, 10),
- m = parseInt((videoObj.currentTime / 60) % 60, 10);
-
- videoProgress.innerText = ((m > 9) ? m : "0" + m) + ':' + ((s > 9) ? s : "0" + s);
- }, false);
- });
-
- event.on("MultimediaVolumeChanged", function (volume) {
- if (videoObj) {
- videoObj.volume = parseFloat(volume / 10);
- }
- });
-
- event.on("MultimediaVideoStateChanged", function (state) {
- document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_STATE_FIELD_ID).innerText = state;
- document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_FILE_FIELD_ID).innerText = videoObj.getAttribute("src");
- });
+ "deviceready": {
+ callback: _fires("deviceready")
+ },
+ "backbutton": {
+ callback: _fires("backbutton")
+ },
+ "menubutton": {
+ callback: _fires("menubutton")
+ },
+ "pause": {
+ callback: _fires("pause")
+ },
+ "resume": {
+ callback: _fires("resume")
+ },
+ "searchbutton": {
+ callback: _fires("searchbutton")
+ },
+ "online": {
+ callback: _fires("online")
+ },
+ "offline": {
+ callback: _fires("offline")
}
};
});
-define('ripple/ui/plugins/widgetConfig', function (require, exports, module) {
+define('ripple/platform/cordova/2.0.0/spec/ui', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- event = require('ripple/event'),
- utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- tooltip = require('ripple/ui/plugins/tooltip'),
- platform = require('ripple/platform'),
- widgetConfig = require('ripple/widgetConfig');
+module.exports = {
+ plugins: [
+ "accelerometer",
+ "deviceSettings",
+ "geoView",
+ "widgetConfig",
+ "platformEvents"
+ ]
+};
-function _buildConfigAccordionNode(node, accordionContainer, counter) {
- var nodeDiv, nodeTitleH3, nodeContentDiv, tableString, attribute, child, result,
- tableClass, nameClass, attributeNameClass, messageClass, nameId, messageId, attributeName, attributeValue, attributeMessage,
- helpText = {},
- nodeCounter = 0,
- attributeCounter = 0,
- moreNodes = node.validationResult,
- createTooltip = function (value, index) {
- tooltip.create("#" + index, value);
- };
+});
+define('ripple/platform/cordova/2.0.0/bridge/file', function (require, exports, module) {
+// HACK: fs keeps a reference to the last-used FileSystem requested via requestFileSystem
+// this is a hack because if you keep switching between TEMPORARY vs. PERSISTENT file systems requested,
+// and run Cordova File API methods, no parameter is passed into exec specifying the underlying File System.
+// This should be fixed in Cordova!
+var fs,
+ topCordova = require('ripple/platform/cordova/2.0.0/spec'),
+ rlfsu;
- while (moreNodes) {
- result = node.validationResult[nodeCounter];
+function cleanPath(path) {
+ while (path[0] && path[0] === '/') {
+ path = path.substr(1);
+ }
+ return path;
+}
- if (!result) {
- // this should never happen
- return;
+module.exports = {
+ requestFileSystem: function (win, fail, args) {
+ // HACK: may not be webkit
+ var rfs = window.webkitRequestFileSystem,
+ type = args[0],
+ size = args[1];
+
+ // HACK: assume any FS requested over a gig in size will throw an error
+ if (size > (1024 * 1024 * 1024 /* gigabyte */)) {
+ if (fail) fail(FileError.QUOTA_EXCEEDED_ERR);
+ } else {
+ return rfs(type, size, function (effes) {
+ fs = effes;
+ win(effes);
+ }, fail);
}
+ },
+ resolveLocalFileSystemURI: function (win, fail, args) {
+ var uri = args[0],
+ fulluri = fs.root.toURL();
- // the container of the entire accordion block
- nodeDiv = utils.createElement("div", {
- "id": "config-accordion-node-content-" + counter + "-" + nodeCounter,
- "class": "ui-corner-all"
- });
+ // HACK: iOS-specific bs right here. See lib/ios/plugin/ios/Entry.js in cordova.js for details
+ // Cordova badly needs a unified File System abstraction.
+ if (uri.indexOf("file://localhost") === 0) {
+ uri = uri.substr(16);
+ }
+ uri = cleanPath(uri);
- // the header bar of the accordion block
- nodeTitleH3 = utils.createElement("h3", {
- "id": "config-accordion-node-title-" + counter + "-" + nodeCounter,
- "class": "config-accordion-node-title"
+ fulluri += uri;
+
+ return window.webkitResolveLocalFileSystemURL(fulluri, function (entry) {
+ if (win) win(entry);
+ }, function (error) {
+ if (fail) fail(error.code);
});
+ },
+ getFile: function (win, fail, args) {
+ var path = args[0],
+ filename = args[1],
+ options = args[2],
+ file = '';
- nodeTitleH3.appendChild(utils.createElement("a", {
- href: "#",
- innerText: node.nodeName,
- "class": constants.CONFIG.SUCCESS_CSS[(result.valid === undefined) ? "missing" : result.valid.toString()]
- }));
- nodeDiv.appendChild(nodeTitleH3);
+ path = cleanPath(path);
+ filename = cleanPath(filename);
- if (node.helpText) {
- helpText[nodeTitleH3.id] = node.helpText;
+ if (path) {
+ file = path + '/';
}
+ file += filename;
- nodeContentDiv = utils.createElement("div");
-
- // display node value (add tool tip if exists)
- if (node.type || (!node.type && result && result.value)) {
- nodeContentDiv.appendChild(utils.createElement("div", {
- "id": "config-accordion-node-content-value-" + counter + "-" + nodeCounter,
- "class": "config-accordion-node-content-value",
- "innerHTML": "<span>Value:</span>" + (result.value || "")
- }));
+ fs.root.getFile(file, options, function (entry) {
+ if (win) win(entry);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ remove: function (win, fail, args) {
+ var file = args[0];
+ window.webkitResolveLocalFileSystemURL(fs.root.toURL() + file, function (entry) {
+ entry.remove(function () {
+ if (win) win();
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, fail);
+ },
+ readEntries: function (win, fail, args) {
+ var root = fs.root.toURL(),
+ path = args[0],
+ reader;
- if (node.helpValueText) {
- helpText["config-accordion-node-content-value-" + counter + "-" + nodeCounter] = node.helpValueText;
- }
- }
+ path = cleanPath(path);
+ path = root + path;
- // display node message if failed validation
- if (result && result.message) {
- nodeContentDiv.appendChild(utils.createElement("div", {
- "id": "config-accordion-node-content-value-message-" + counter + "-" + nodeCounter,
- "class": "config-accordion-node-content-value-message ui-text-fail",
- "innerHTML": "<span>Message:</span>" + result.message
- }));
- }
+ window.webkitResolveLocalFileSystemURL(path, function (entry) {
+ reader = entry.createReader();
+ reader.readEntries(function (entries) {
+ if (win) win(entries);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ getDirectory: function (win, fail, args) {
+ var path = args[0],
+ filename = args[1],
+ options = args[2],
+ file = '';
- // display node attributes with name, value, message if failed validation
- if (result.attributes) {
- nodeContentDiv.appendChild(utils.createElement("div", {
- "id": "config-accordion-node-content-attributes-title-" + counter + "-" + nodeCounter,
- "class": "config-accordion-node-content-attributes-title",
- "innerHTML": "Attributes..."
- }));
+ path = cleanPath(path);
+ filename = cleanPath(filename);
- tableClass = "preferences-table";
- nameClass = "config-attributes-name-value";
- attributeNameClass = "ui-text-label";
- messageClass = "config-attributes-message";
+ if (path) {
+ file = path + '/';
+ }
+ file += filename;
- tableString = '<table class="' + tableClass + ' ui-widget-content">';
- for (attribute in result.attributes) {
- if (result.attributes.hasOwnProperty(attribute)) {
- nameId = "config-accordion-node-content-attributes-table-name-" + counter + "-" + nodeCounter + "-" + attributeCounter;
- messageId = "config-accordion-node-content-attributes-table-message-" + counter + "-" + nodeCounter + "-" + attributeCounter;
- attributeName = result.attributes[attribute].attributeName;
- attributeValue = result.attributes[attribute].value || " ";
- attributeMessage = result.attributes[attribute].message || null;
+ fs.root.getDirectory(file, options, function (entry) {
+ if (win) win(entry);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ removeRecursively: function (win, fail, args) {
+ var root = fs.root.toURL(),
+ path = args[0];
- tableString += '<tr class="' + nameClass + '" id="' + nameId + '">' +
- '<td class="' + attributeNameClass + '">' + attributeName + '</td>' +
- '<td>' + attributeValue + '</td></tr>';
+ path = cleanPath(path);
- if (node.attributes[attributeName].helpText) {
- helpText[nameId] = node.attributes[attributeName].helpText;
- }
+ window.webkitResolveLocalFileSystemURL(root + path, function (dirEntry) {
+ dirEntry.removeRecursively(function () {
+ if (win) win();
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ getFileMetadata: function (win, fail, args) {
+ var path = args[0],
+ root = fs.root.toURL();
- if (attributeMessage !== null) {
- tableString += "<tr class=" + messageClass + " id=" + messageId + "><td colspan=\"2\">" +
- attributeMessage + "</td></tr>";
- }
- attributeCounter++;
- }
- }
- tableString += "</table>";
+ path = cleanPath(path);
- nodeContentDiv.innerHTML += tableString;
- }
+ window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
+ entry.file(function (file) {
+ if (win) win(file);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ getMetadata: function (win, fail, args) {
+ var path = args[0],
+ root = fs.root.toURL();
+ path = cleanPath(path);
+
+ window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
+ entry.getMetadata(function (data) {
+ if (win) win(data);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ getParent: function (win, fail, args) {
+ var path = args[0],
+ root = fs.root.toURL();
- nodeDiv.appendChild(nodeContentDiv);
- accordionContainer.appendChild(nodeDiv);
+ path = cleanPath(path);
- utils.forEach(helpText, createTooltip);
+ window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
+ entry.getParent(function (dirEntry) {
+ if (win) win(dirEntry);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ copyTo: function (win, fail, args) {
+ var src = args[0],
+ parent = args[1],
+ name = args[2],
+ root = fs.root.toURL();
- nodeCounter ++;
+ parent = cleanPath(parent);
+ src = cleanPath(src);
- if (!node.validationResult[nodeCounter]) {
- nodeCounter = 0;
- moreNodes = false;
- }
- }
+ rlfsu = window.webkitResolveLocalFileSystemURL;
+ // get the directoryentry that we will copy TO
+ rlfsu(root + parent, function (parentDirToCopyTo) {
+ rlfsu(root + src, function (sourceDir) {
+ sourceDir.copyTo(parentDirToCopyTo, name, function (newEntry) {
+ if (win) win(newEntry);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ moveTo: function (win, fail, args) {
+ var src = args[0],
+ parent = args[1],
+ name = args[2],
+ root = fs.root.toURL();
- if (node.children) {
- for (child in node.children) {
- if (node.children.hasOwnProperty(child)) {
- counter ++;
- _buildConfigAccordionNode(node.children[child], accordionContainer, counter);
- }
- }
- }
-}
+ parent = cleanPath(parent);
+ src = cleanPath(src);
-function _initializeConfigResultsView(results) {
- try {
- var rootNode,
- accordionContainer = document.getElementById("widget-config");
+ rlfsu = window.webkitResolveLocalFileSystemURL;
+ // get the directoryentry that we will move TO
+ rlfsu(root + parent, function (parentDirToMoveTo) {
+ rlfsu(root + src, function (sourceDir) {
+ sourceDir.moveTo(parentDirToMoveTo, name, function (newEntry) {
+ if (win) win(newEntry);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ write: function (win, fail, args) {
+ var file = args[0],
+ text = args[1],
+ position = args[2],
+ sourcepath,
+ BB = window.BlobBuilder || window.WebKitBlobBuilder,
+ bb = new BB();
- accordionContainer.innerHTML = "";
- if (!results) {
- accordionContainer.appendChild(utils.createElement("div", {
- "class": "config-accordion-node-title " + constants.CONFIG.SUCCESS_CSS["false"],
- "innerHTML": "Expected to find a configuration file for your application, but none is present. Please create" +
- " a configuration file with the following name in the root directory of your application: " +
- platform.current().fileName
- }));
- return;
- }
+ // Format source path
+ sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
+ sourcepath = cleanPath(sourcepath);
- rootNode = results[results.rootElement];
+ // Create a blob for the text to be written
+ bb.append(text);
- _buildConfigAccordionNode(rootNode, accordionContainer, 0);
+ // Get the FileEntry, create if necessary
+ fs.root.getFile(sourcepath, {create: true}, function (entry) {
+ // Create a FileWriter for this entry
+ entry.createWriter(function (writer) {
+ writer.onwriteend = function (progressEvt) {
+ if (win) win(progressEvt.total);
+ };
+ writer.onerror = function (err) {
+ if (fail) fail(err.code);
+ };
- jQuery(function () {
- var stop = false;
- jQuery("#widget-config h3").click(function (event) {
- if (stop) {
- event.stopImmediatePropagation();
- event.preventDefault();
- stop = false;
+ if (position && position > 0) {
+ writer.seek(position);
}
+ writer.write(bb.getBlob('text/plain'));
+ }, function (err) {
+ if (fail) fail(err.code);
});
- jQuery("#widget-config").accordion("destroy").accordion({
- header: "> div > h3",
- autoHeight: false
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ },
+ readAsText: function (win, fail, args) {
+ var path = args[0],
+ encoding = args[1],
+ FileReader = topCordova.nativeMethods.FileReader,
+ fr = new window.FileReader();
+
+ // Set up FileReader events
+ fr.onerror = function (err) {
+ if (fail) fail(err.code);
+ };
+ fr.onload = function (evt) {
+ if (win) win(evt.target.result);
+ };
+
+ path = cleanPath(path);
+
+ fs.root.getFile(path, {create: false}, function (entry) {
+ entry.file(function (blob) {
+ fr.readAsText(blob, encoding);
+ }, function (err) {
+ if (fail) fail(err.code);
});
+ }, function (err) {
+ if (fail) fail(err.code);
});
- } catch (e) {
- exception.handle(e, true);
- }
-}
+ },
+ readAsDataURL: function (win, fail, args) {
+ var path = args[0],
+ FileReader = topCordova.nativeMethods.FileReader,
+ fr = new window.FileReader();
-event.on("FrameHistoryChange", function () {
- module.exports.initialize();
-});
+ // Set up FileReader events
+ fr.onerror = function (err) {
+ if (fail) fail(err.code);
+ };
+ fr.onload = function (evt) {
+ if (win) win(evt.target.result);
+ };
-module.exports = {
- panel: {
- domId: "config-container",
- collapsed: true,
- pane: "right",
- titleName: "Application Configuration",
- display: true
+ path = cleanPath(path);
+
+ fs.root.getFile(path, {create: false}, function (entry) {
+ entry.file(function (blob) {
+ fr.readAsDataURL(blob);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
},
- initialize: function () {
- var results = widgetConfig.getValidationResults();
- _initializeConfigResultsView(results);
+ truncate: function (win, fail, args) {
+ var file = args[0],
+ position = args[1],
+ sourcepath;
+
+ // Format source path
+ sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
+ sourcepath = cleanPath(sourcepath);
+
+ // Get the FileEntry, create if necessary
+ fs.root.getFile(sourcepath, {create: false}, function (entry) {
+ // Create a FileWriter for this entry
+ entry.createWriter(function (writer) {
+ writer.onwriteend = function (progressEvt) {
+ if (win) win(progressEvt.target.length);
+ };
+ writer.onerror = function (err) {
+ if (fail) fail(err.code);
+ };
+
+ writer.truncate(position);
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
+ }, function (err) {
+ if (fail) fail(err.code);
+ });
}
};
});
-define('ripple/ui/themes', function (require, exports, module) {
-/*
- * Copyright 2011 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 = ["dark", "light"];
-module.exports = ["light"];
-
-});
-define('ripple/ui', function (require, exports, module) {
+define('ripple/platform/cordova/2.0.0/bridge/media', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var _self,
- db = require('ripple/db'),
- platform = require('ripple/platform'),
- constants = require('ripple/constants'),
- utils = require('ripple/utils'),
- exception = require('ripple/exception'),
- event = require('ripple/event'),
- themes = require('ripple/ui/themes'),
- _applicationStateId,
- _applicationState,
- _availablePanels,
- _applicationStateTmp,
- _systemPlugins = [
- "options",
- "about-dialog",
- "settings-dialog",
- "exec-dialog",
- "firstRunCheck",
- "eulaCheck",
- "devices",
- "goodVibrations",
- "panelCollapse",
- "platform",
- "information",
- "layout",
- "themeSwitcher",
- "settings-menu",
- "configWindow",
- "HWKeys"
- //"launchingHistory"
- ],
- _overlay = {
- getOrCreate: function (id) {
- var _container = document.getElementById(constants.COMMON.HTML_CONTAINER),
- _overlays = document.getElementById("overlay-views"),
- _overlay = _overlays.children[id],
- _hide = function (node) {
- node.setAttribute("style", "display: none");
- },
- _show = function (node) {
- node.setAttribute("style", "display: block");
- },
- _trigger = function (callback) {
- if (callback) {
- callback.apply(null, [_overlay]);
- }
- };
+var audioObjects = {},
+ noop = function () {};
+function createAudio(id, src, error) {
+ var a = new Audio();
+ a.addEventListener("error", function (e) {
+ error(new window.MediaError(1, e.toString()));
+ });
+ a.addEventListener("durationchange", function () {
+ //HACK: I don't like this but best way for us to update the duration
+ cordova.require("cordova/plugin/Media").onStatus(id, 2, this.duration);
+ });
+ a.src = src;
- if (!_overlay) {
- _overlay = utils.createElement("section", {id: id, "class": "overlay"});
- _overlays.appendChild(_overlay);
- }
+ return a;
+}
- return {
- hide: function (callback) {
- _hide(_overlay);
- _show(_container);
- _trigger(callback);
- },
- show: function (callback, showContainer) {
- _show(_overlay);
- if (!showContainer) {
- _hide(_container);
- }
- _trigger(callback);
- }
- };
+module.exports = {
+ create: function (success, error, args) {
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
}
- };
-function _addUIPaneItemsToApplicationState(arrayObj, pane) {
- utils.forEach(arrayObj, function (domId) {
- var collapsed = jQuery("#" + domId + " .info")[0];
- collapsed = (collapsed.style && collapsed.style.display === "none") ? true : false;
- utils.forEach(_applicationStateTmp, function (obj) {
- if (obj.domId === domId) {
- _applicationState.push({
- "domId": domId,
- "collapsed": collapsed,
- "pane": pane,
- "titleName" : obj.titleName,
- "display" : obj.display
- });
- _applicationStateTmp.splice(_applicationStateTmp.indexOf(obj), 1);
- return;
- }
- }, this);
- }, this);
+ var id = args[0],
+ src = args[1];
- utils.forEach(_applicationStateTmp, function (obj) {
- _applicationState.push({
- "domId": obj.domId,
- "collapsed": obj.collapsed,
- "pane": obj.pane,
- "titleName" : obj.titleName,
- "display" : obj.display
- });
- });
-}
+ error = error || noop;
+ success = success || noop;
-function _currentlyEnabledTheme() {
- var qsSet = utils.queryString().theme,
- current = db.retrieve("ui-theme") || themes[0];
+ audioObjects[id] = createAudio(id, src, error);
+ success();
+ },
+ startPlayingAudio: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
+ }
- function matches(something) {
- return function (item) {
- return something === item;
- };
- }
+ var id = args[0],
+ audio = audioObjects[id];
- if (qsSet && themes.some(matches(qsSet))) {
- current = qsSet;
- db.save("ui-theme", qsSet);
- }
+ if (args.length === 1) {
+ error("Media source argument not found");
+ return;
+ }
- return current;
-}
+ if (audio) {
+ audio.pause();
+ audioObjects[id] = undefined;
+ }
-function _insertStyleSheets() {
- var uiTheme = db.retrieve("ui-theme") || require('ripple/ui/themes')[0],
- extensionURL = jQuery("#extension-url").text(),
- uiThemeURL = extensionURL + "themes/" + uiTheme + "/theme.css",
- head = document.getElementsByTagName('head')[0];
+ audio = audioObjects[id] = createAudio(id, args[1], error);
+ audio.play();
- function stylesheet(src) {
- var scriptElement = document.createElement("link");
- scriptElement.setAttribute("href", src);
- scriptElement.setAttribute("type", "text/css");
- scriptElement.setAttribute("rel", "stylesheet");
- return scriptElement;
- }
+ success();
+ },
+ stopPlayingAudio: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
+ }
- head.appendChild(stylesheet(uiThemeURL));
-}
+ var id = args[0],
+ audio = audioObjects[id];
-function _collapsePannels(side) {
- var collapseNode = [],
- event = document.createEvent("UIEvent");
+ if (!audio) {
+ error("Audio Object has not been initialized");
+ return;
+ }
- collapseNode = side === "left" ? document.getElementsByClassName("left-panel-collapse") :
- document.getElementsByClassName("right-panel-collapse");
-
- if (collapseNode.length > 0) {
- event.initEvent("click", true, true);
- collapseNode[0].dispatchEvent(event);
- }
-}
+ audio.pause();
+ audioObjects[id] = undefined;
-function _initializeUI() {
- _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;
- _applicationState = db.retrieveObject(_applicationStateId) || [];
- _insertStyleSheets();
+ success();
+ },
+ seekToAudio: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
+ }
- var leftPanelSection = jQuery(".left"),
- uiBoxToggleEngaged = false;
+ var id = args[0],
+ audio = audioObjects[id];
- //clean up
- db.remove("ui-application-state");
- utils.forEach(_availablePanels, function (obj) {
- var matchingDomId = function (panel) {
- return panel.domId === obj.domId;
- };
- if (!utils.some(_applicationState, matchingDomId)) {
- _applicationState.push({
- "domId": obj.domId,
- "collapsed": obj.collapsed,
- "pane": obj.pane,
- "titleName" : obj.titleName,
- "display" : obj.display
- });
+ if (!audio) {
+ error("Audio Object has not been initialized");
+ return;
+ } else if (args.length === 1) {
+ error("Media seek time argument not found");
+ return;
+ } else {
+ try {
+ audio.currentTime = args[1];
+ } catch (e) {
+ error("Error seeking audio: " + e);
+ }
}
- });
- utils.forEach(_applicationState, function (obj) {
- var node = jQuery("#" + obj.domId),
- imgNode = node.find(".ui-box-TitleImage"),
- matchingDomId = function (panel) {
- return panel.domId === obj.domId;
- };
+ success();
+ },
+ pausePlayingAudio: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
+ }
- if (node.length > 0) {
- if (!utils.some(_availablePanels, matchingDomId)) {
- node.parent()[0].removeChild(node[0]);
- }
- else {
- if (obj.display !== false) {
- leftPanelSection.append(node.parent()[0].removeChild(node[0]));
- if (!obj.collapsed) {
- node.find(".info")
- .css({
- "display": "block"
- })
- .end()
- .addClass("ui-box-open");
- imgNode.addClass("ui-box-TitleImageOpen");
- }
- }
- }
+ var id = args[0],
+ audio = audioObjects[id];
+
+ if (!audio) {
+ error("Audio Object has not been initialized");
+ return;
}
- });
- db.saveObject(_applicationStateId, _applicationState);
+ audio.pause();
+ success();
+ },
+ getCurrentPositionAudio: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
+ }
- event.on("ApplicationState", function () {
- try {
- var leftArray = jQuery(".left").sortable('toArray');
- _applicationStateTmp = [];
- _applicationStateTmp = utils.copy(_applicationState);
- _applicationState = [];
- _addUIPaneItemsToApplicationState(leftArray, "left");
+ var id = args[0],
+ audio = audioObjects[id];
- if (leftArray.length === 0) {
- _collapsePannels("left");
- }
+ if (!audio) {
+ error("Audio Object has not been initialized");
+ return;
+ }
- db.saveObject(_applicationStateId, _applicationState);
+ success(audio.currentTime);
+ },
+ getDuration: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
}
- catch (e) {
- exception.handle(e);
+
+ var id = args[0],
+ audio = audioObjects[id];
+
+ if (!audio) {
+ error("Audio Object has not been initialized");
+ return;
}
- });
- jQuery(".left").sortable({
- handle: ".drag-handle",
- revert: true,
- placeholder: 'ui-sortable-highlight ui-corner-all',
- connectWith: [".left"],
- scroll: true,
- update: function (uiEvent, ui) {
- event.trigger("ApplicationState");
+ success(audio.duration);
+ },
+ startRecordingAudio: function (success, error, args) {
+ error = error || noop;
+ error("Not supported");
+ },
+ stopRecordingAudio: function (success, error, args) {
+ error = error || noop;
+ error("Not supported");
+ },
+ release: function (success, error, args) {
+ error = error || noop;
+ success = success || noop;
+ if (!args.length) {
+ error("Media Object id was not sent in arguments");
+ return;
}
- });
-
- jQuery(".left").sortable({ axis: 'y' });
-
- jQuery(".collapse-handle").bind("click", function () {
- if (!uiBoxToggleEngaged) {
-
- uiBoxToggleEngaged = true;
- var jNode = jQuery(this).parentsUntil(".ui-box"),
- pNode = jNode.parent(),
- isOpen = pNode.hasClass("ui-box-open"),
- imgNode = jQuery(this).find(".ui-box-TitleImage");
-
- if (!isOpen) {
- pNode.addClass("ui-box-open");
- imgNode.removeClass("ui-box-TitleImageClosed");
- imgNode.addClass("ui-box-TitleImageOpen");
- }
+ var id = args[0],
+ audio = audioObjects[id];
- jQuery(this).parent().next().toggle("blind", {}, 300, function () {
- if (isOpen) {
- pNode.removeClass("ui-box-open");
- imgNode.removeClass("ui-box-TitleImageOpen");
- imgNode.addClass("ui-box-TitleImageClosed");
- }
- event.trigger("ApplicationState", [pNode]);
- uiBoxToggleEngaged = false;
- });
+ if (audio) {
+ audioObjects[id] = undefined;
+ audio.src = undefined;
+ //delete audio;
}
- });
-}
-
-function _db_upgrade_for_release() {
- var version = db.retrieve(constants.RELEASE_VERSION);
- // version: 20121115 is the first release version
- if (version === null || version === undefined || Number(version) < 20130722) {
- db.remove(constants.COMMON.APPLICATION_STATE + "tizen");
- db.remove(constants.COMMON.APPLICATION_STATE + "cordova");
- db.remove("tizen1-db-application");
- db.remove("tizen-db-package");
- version = 20130722;
- db.save(constants.RELEASE_VERSION, version);
+ success();
}
-}
-
-_self = module.exports = {
- initialize: function () {
- var plugins = _systemPlugins.concat(platform.current().ui.plugins || []).map(function (name) {
- return require('ripple/ui/plugins/' + name);
- }),
- boot = jWorkflow.order(_initializeUI);
+};
- _db_upgrade_for_release();
- _availablePanels = [];
+});
+define('ripple/platform/cordova/2.0.0/bridge/device', function (require, exports, module) {
+/*
+ * Copyright 2011 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 devices = require('ripple/devices');
- plugins.forEach(function (plugin) {
- if (plugin.initialize) {
- boot.andThen(plugin.initialize);
- }
+module.exports = {
+ getDeviceInfo: function (success, fail, args) {
+ var device = devices.getCurrentDevice();
- if (plugin.panel) {
- _availablePanels.push(plugin.panel);
- }
+ success({
+ available: true,
+ platform: device.osName,
+ version: device.osVersion,
+ name: device.name,
+ uuid: device.uuid,
+ cordova: "2.0.0"
});
+ }
+};
- boot.start();
+});
+define('ripple/platform/cordova/2.0.0/bridge/notification', function (require, exports, module) {
+/*
+ * Copyright 2011 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 notifications = require('ripple/notifications'),
+ _console = require('ripple/console'),
+ goodVibrations = require('ripple/ui/plugins/goodVibrations');
+
+module.exports = {
+ alert: function (success, error, args) {
+ notifications.openNotification("normal", args[0]);
+ return success && success();
},
- getSystemPlugins: function () {
- return utils.copy(_systemPlugins);
+ confirm: function (success, error, args) {
+ throw "Not Implemented";
},
- register: function (plugin) {
- _systemPlugins.push(plugin);
+ activityStart: function (success, error, args) {
},
- registered: function (plugin) {
- return _systemPlugins.indexOf(plugin) >= 0;
+ activityStop: function (success, error, args) {
},
- getExtensionURL: function () {
- return jQuery("#" + constants.COMMON.EXTENSION_URL_CONTAINER).text();
+ progressStart: function (success, error, args) {
},
- showOverlay: function (id, callback, showContainer) {
- _overlay.getOrCreate(id).show(callback, showContainer);
+ vibrate: function (success, error, args) {
+ var ms = args[0] || 500;
+ goodVibrations.vibrateDevice(ms);
},
- hideOverlay: function (id, callback) {
- _overlay.getOrCreate(id).hide(callback);
+ beep: function (success, error, args) {
+ for (var i = args[0]; i > 0; i--) {
+ _console.log("beep!");
+ }
+ notifications.openNotification("normal", "BEEP x " + args[0]);
}
};
});
-define('ripple/utils', function (require, exports, module) {
+define('ripple/platform/cordova/2.0.0/bridge/contacts', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var self,
- exception = require('ripple/exception'),
- constants = require('ripple/constants'),
- _HtmlElements = ['header', 'footer', 'section', 'aside', 'nav', 'article'];
-
-self = module.exports = {
- validateNumberOfArguments: function (lowerBound, upperBound, numberOfArguments, customExceptionType, customExceptionMessage, customExceptionObject) {
-
- customExceptionMessage = customExceptionMessage || "";
-
- if (arguments.length < 3 || arguments.length > 6) {
- exception.raise(exception.types.Argument, "Wrong number of arguments when calling: validateNumberOfArguments()");
- }
-
- if (isNaN(lowerBound) && isNaN(upperBound) && isNaN(numberOfArguments)) {
- exception.raise(exception.types.ArgumentType, "(validateNumberOfArguments) Arguments are not numbers");
- }
-
- lowerBound = parseInt(lowerBound, 10);
- upperBound = parseInt(upperBound, 10);
- numberOfArguments = parseInt(numberOfArguments, 10);
+var db = require('ripple/db'),
+ utils = require('ripple/utils'),
+ _self;
- if (numberOfArguments < lowerBound || numberOfArguments > upperBound) {
- exception.raise((customExceptionType || exception.types.ArgumentLength), (customExceptionMessage + "\n\nWrong number of arguments"), customExceptionObject);
- }
+function _default() {
+ return [{
+ "name": {formatted: "Brent Lintner"},
+ "displayName": "Brent Lintner",
+ "emails": [{type: "work", value: "brent@tinyhippos.com", pref: false}]
+ }, {
+ "name": {formatted: "PJ Lowe"},
+ "displayName": "PJ Lowe",
+ "emails": [{type: "work", value: "pj@tinyhippos.com", pref: false}]
+ }, {
+ "name": {formatted: "Dan Silivestru"},
+ "displayName": "Dan Silivestru",
+ "emails": [{type: "work", value: "dan@tinyhippos.com", pref: false}]
+ }, {
+ "name": {formatted: "Gord Tanner"},
+ "displayName": "Gord Tanner",
+ "emails": [{type: "work", value: "gord@tinyhippos.com", pref: true}]
+ }, {
+ "name": {formatted: "Mark McArdle"},
+ "displayName": "Mark McArdle",
+ "emails": [{type: "work", value: "mark@tinyhippos.com", pref: false}]
+ }].map(function (obj) {
+ obj.id = Math.uuid(undefined, 16);
+ return navigator.contacts.create(obj);
+ });
+}
- },
+function _get() {
+ return db.retrieveObject("cordova-contacts") || _default();
+}
- validateArgumentType: function (arg, argType, customExceptionType, customExceptionMessage, customExceptionObject) {
- var invalidArg = false,
- msg;
+function _save(contacts) {
+ db.saveObject("cordova-contacts", contacts);
+}
- switch (argType) {
- case "array":
- if (!arg instanceof Array) {
- invalidArg = true;
- }
- break;
- case "date":
- if (!arg instanceof Date) {
- invalidArg = true;
- }
- break;
- case "integer":
- if (typeof arg === "number") {
- if (arg !== Math.floor(arg)) {
- invalidArg = true;
- }
- }
- else {
- invalidArg = true;
- }
- break;
- default:
- if (typeof arg !== argType) {
- invalidArg = true;
+function _filtered(compare, options) {
+ // this could be done a lot better..
+ var found = false;
+ if (!options.filter || options.filter === "") {
+ found = true;
+ } else if (typeof compare === "string" &&
+ compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
+ found = true;
+ } else if (typeof compare === "object" || compare instanceof Array) {
+ utils.forEach(compare, function (value) {
+ if (!found) {
+ found = _filtered(value, options);
}
- break;
- }
-
- if (invalidArg) {
- msg = customExceptionMessage + ("\n\nInvalid Argument type. argument: " + arg + " ==> was expected to be of type: " + argType);
- exception.raise((customExceptionType || exception.types.ArgumentType), msg, customExceptionObject);
- }
- },
-
- validateMultipleArgumentTypes: function (argArray, argTypeArray, customExceptionType, customExceptionMessage, customExceptionObject) {
- for (var i = 0; i < argArray.length; i++) {
- this.validateArgumentType(argArray[i], argTypeArray[i], customExceptionType, customExceptionMessage, customExceptionObject);
- }
- },
-
- createElement: function (elementType, attributes) {
- var d = document.createElement(elementType);
+ });
+ }
+ return found;
+}
- if (attributes) {
- this.forEach(attributes, function (attributeValue, attributeName) {
+_self = {
+ search: function (success, error, args) {
+ var fields = args[0],
+ options = args[1],
+ foundContacts = [],
+ tempContact = navigator.contacts.create(),
+ contacts = _get();
- switch (attributeName.toLowerCase()) {
+ options = options || {};
- case "innerhtml":
- d.innerHTML = attributeValue;
- break;
+ // handle special case of ["*"] to return all fields
+ if (fields.length === 1 && fields[0] === "*") {
+ fields = utils.map(tempContact, function (v, k) {
+ return k;
+ });
+ }
- case "innertext":
- d.innerText = attributeValue;
- break;
+ if (fields.length > 0) {
+ contacts.forEach(function (contact, index) {
+ var newContact = navigator.contacts.create(contact);
- default:
- d.setAttribute(attributeName, attributeValue);
+ if (options && (!_filtered(contact, options))) {
+ return;
}
+ utils.forEach(newContact, function (value, prop) {
+ if (typeof newContact[prop] !== "function" && prop !== "id" &&
+ !fields.some(function (field) {
+ return field === prop;
+ })) {
+ delete newContact[prop];
+ }
+ });
+
+ foundContacts.push(newContact);
});
}
- return d;
- },
-
-
- loadHTMLElements: function () {
- for (var i = 0; i < _HtmlElements.length; i += 1) {
- document.createElement(_HtmlElements[i]);
+ // TODO: don't loop over entire db just to slice the array
+ if (options.multiple === false) {
+ foundContacts = foundContacts.splice(0, 1);
}
+ success(foundContacts);
},
- getAllStylesheetRules: function getAllStylesheetRules(title) {
- this.validateNumberOfArguments(1, 1, arguments.length);
-
- var i, x, sheet, rules, styles_array = [];
-
- // get style sheet according to title
- for (i = 0; i < document.styleSheets.length; i += 1) {
+ save: function (success, error, args) {
+ var contacts = _get(),
+ contact = args[0],
+ index;
- sheet = document.styleSheets[i];
- rules = sheet.cssRules;
+ if (!contact.id) {
+ contact.id = Math.uuid(undefined, 16);
+ contacts.push(contact);
+ } else {
+ index = contacts.reduce(function (result, value, index) {
+ return value.id === contact.id ? index : result;
+ }, -1);
- if (rules) {
- for (x = 0; x < rules.length; x += 1) {
- if (rules[x].selectorText && rules[x].selectorText === (title.toString())) {
- styles_array.push(rules[x]);
- }
- }
+ if (index >= 0) {
+ utils.mixin(contact, contacts[index]);
+ contact = contacts[index];
+ } else {
+ contact = null;
}
}
- return (styles_array);
- },
-
- location: function () {
- return window.location;
+ _save(contacts);
+ if (success) {
+ success(contact);
+ }
},
- queryString: function () {
- // trim the leading ? and split each name=value
- var args = this.location().search.replace(/^\?/, '').split('&');
+ remove: function (success, error, args) {
+ var contacts = _get(),
+ id = args[0],
+ toDelete = contacts.reduce(function (result, current, index) {
+ return current.id === id ? index : result;
+ }, -1);
- return args.reduce(function (obj, value) {
- if (value) {
- value = value.toLowerCase().split("=");
- obj[value[0]] = value[1];
+ if (toDelete >= 0) {
+ contacts.splice(toDelete, 1);
+ _save(contacts);
+ if (success) {
+ success();
}
- return obj;
- }, {});
- },
-
- extensionUrl: function () {
- return document.getElementById("extension-url").innerText;
- },
-
- appLocation: function () {
- if (require('ripple/ui').registered("omnibar")) {
- /* rootURL can only get url saved from 'FrameHistoryChange' event
- it causes trouble when navigating directory through online
- version as index.html is automatically loaded.
- Need a way to get more updated URL */
+ } else {
+ error({code: 3, message: "could not find contact with id (" + id + ")"}); // PENDING_OPERATION_ERROR
+ }
+ }
+};
- var path = require('ripple/ui/plugins/omnibar').rootURL(),
- parts;
+module.exports = _self;
- if ((parts = path.match(/^((http[s]?|ftp|file):\/\/)(.+\/)?([^\/].+)$/i)) !== null && parts.length === 5) {
- // this is a path already.
- if (path.search(/\/$/, "") !== -1) {
- return path;
- }
- if (parts[4] === "about:blank") {
- path = "";
- }
- else if (parts[3]) {
- path = parts[1] + parts[3];
- if (parts[4].indexOf(".") === -1) {
- path += parts[4] + "/";
- }
- }
- else {
- path = parts[1] + parts[4] + "/";
- }
- }
- else {
- path = "";
- }
- return path;
- }
- return self.rippleLocation();
- },
+});
+define('ripple/platform/cordova/2.0.0/bridge/app', function (require, exports, module) {
+/*
+ * Copyright 2011 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 camera = require('ripple/ui/plugins/camera'),
+ event = require('ripple/event');
- rippleLocation: function () {
- var loc = self.location(),
- parts = loc.pathname.replace(/\/$/, "").split("/"),
- base = "",
- port = loc.port ? ":" + loc.port : "";
+module.exports = {
+ show: function (success, error, args) {
+ return success && success();
+ }
+};
- if (parts[parts.length - 1].indexOf(".") !== -1) {
- parts = parts.splice(0, parts.length - 1);
- }
- base = parts.join("/");
+});
+define('ripple/platform/cordova/2.0.0/bridge/camera', function (require, exports, module) {
+/*
+ * Copyright 2011 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 camera = require('ripple/ui/plugins/camera'),
+ event = require('ripple/event');
- return loc.protocol + "//" + loc.hostname + port + base + "/";
+module.exports = {
+ takePicture: function (success, error, args) {
+ event.once("captured-image", function (uri, file) {
+ success(uri);
+ });
+ camera.show();
},
+ cleanup: function (success, error, args) {
+ success();
+ }
+};
- arrayContains: function (array, obj) {
- var i = array.length;
- while (i--) {
- if (array[i] === obj) {
- return true;
- }
- }
- return false;
- },
+});
+define('ripple/platform/cordova/2.0.0/bridge/network', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- some: function (obj, predicate, scope) {
- if (obj instanceof Array) {
- return obj.some(predicate, scope);
- }
- else {
- var values = self.map(obj, predicate, scope);
+var deviceSettings = require('ripple/deviceSettings'),
+ event = require('ripple/event'),
+ _success;
- return self.reduce(values, function (some, value) {
- return value ? value : some;
- }, false);
- }
- },
+event.on("ConnectionChanged", function () {
+ return _success && _success(deviceSettings.retrieve("NetworkStatus.connectionType"));
+});
- count: function (obj) {
- return self.sum(obj, function (total) {
- return 1;
- });
- },
+module.exports = {
+ getConnectionInfo: function (success, fail, args) {
+ _success = success;
+ success(deviceSettings.retrieve("NetworkStatus.connectionType"));
+ }
+};
- sum: function (obj, selector, scope) {
- var values = self.map(obj, selector, scope);
- return self.reduce(values, function (total, value) {
- return total + value;
- });
- },
+});
+define('ripple/platform/cordova/2.0.0/bridge/compass', function (require, exports, module) {
+/*
+ * Copyright 2011 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 geo = require('ripple/geo');
- max: function (obj, selector, scope) {
- var values = self.map(obj, selector, scope);
- return self.reduce(values, function (max, value) {
- return max < value ? value : max;
- }, Number.MIN_VALUE);
+module.exports = {
+ getHeading: function (success, error, args) {
+ // TODO: build facility to trigger onError() from emulator
+ // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
+ success({
+ magneticHeading: geo.getPositionInfo().heading,
+ trueHeading: geo.getPositionInfo().heading,
+ headingAccuracy: 100,
+ timestamp: new Date().getSeconds()
+ });
},
- min: function (obj, selector, scope) {
- var values = self.map(obj, selector, scope);
- return self.reduce(values, function (min, value) {
- return min > value ? value : min;
- }, Number.MAX_VALUE);
- },
+ stopHeading: function () {
+ //do nothing
+ }
+};
- forEach: function (obj, action, scope) {
- if (obj instanceof Array) {
- return obj.forEach(action, scope);
- }
- else {
- self.map(obj, action, scope);
- }
+});
+define('ripple/platform/cordova/2.0.0/bridge/geolocation', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ geo = require('ripple/geo'),
+ utils = require('ripple/utils'),
+ PositionError = require('ripple/platform/w3c/1.0/PositionError'),
+ _watches = {},
+ _current = {
+ "latitude": 43.465187,
+ "longitude": -80.522372,
+ "altitude": 100,
+ "accuracy": 150,
+ "altitudeAccuracy": 80,
+ "heading": 0,
+ "velocity": 0,
},
+ _error;
- filter: function (obj, predicate, scope) {
- if (obj instanceof Array) {
- return obj.filter(predicate, scope);
- }
- else {
- var result = [];
- self.forEach(obj, function (value, index) {
- if (predicate.apply(scope, [value, index])) {
- result.push(value);
- }
-
- }, scope);
+function _getCurrentPosition(win, fail) {
+ if (geo.timeout) {
+ if (fail) {
+ var positionError = new PositionError();
- return result;
+ positionError.code = PositionError.TIMEOUT;
+ positionError.message = "postion timed out";
+ fail(positionError);
}
- },
-
- reduce: function (obj, func, init, scope) {
- var i,
- initial = init === undefined ? 0 : init,
- result = initial;
+ }
+ else {
+ win(geo.getPositionInfo());
+ }
+}
+event.on("PositionInfoUpdatedEvent", function (pi) {
+ _current.latitude = pi.latitude;
+ _current.longitude = pi.longitude;
+ _current.altitude = pi.altitude;
+ _current.accuracy = pi.accuracy;
+ _current.altitudeAccuracy = pi.altitudeAccuracy;
+ _current.heading = pi.heading;
+ _current.velocity = pi.speed;
- if (obj instanceof Array) {
- return obj.reduce(func, initial);
- }
- else if (obj instanceof NamedNodeMap) {
- for (i = 0; i < obj.length; i++) {
- result = func.apply(scope, [result, obj[i], i]);
- }
- }
- else {
- for (i in obj) {
- if (obj.hasOwnProperty(i)) {
- result = func.apply(scope, [result, obj[i], i]);
- }
- }
+ utils.forEach(_watches, function (watch) {
+ try {
+ _getCurrentPosition(watch.win, watch.fail);
+ } catch (e) {
+ console.log(e);
}
+ });
+});
- return result;
+module.exports = {
+ getLocation: function (success, error, args) {
+ _getCurrentPosition(success, error);
+ },
+ addWatch: function (success, error, args) {
+ _watches[args[0]] = {
+ win: success,
+ fail: error
+ };
+ _getCurrentPosition(success, error);
},
- map: function (obj, func, scope) {
- var i,
- returnVal = null,
- result = [];
+ clearWatch: function (id) {
+ delete _watches[id];
+ }
+};
- if (obj instanceof Array) {
- return obj.map(func, scope);
- }
- else if (obj instanceof NamedNodeMap) {
- for (i = 0; i < obj.length; i++) {
- returnVal = func.apply(scope, [obj[i], i]);
- result.push(returnVal);
- }
- }
- else {
- for (i in obj) {
- if (obj.hasOwnProperty(i)) {
- returnVal = func.apply(scope, [obj[i], i]);
- result.push(returnVal);
- }
- }
- }
+});
+define('ripple/platform/cordova/2.0.0/bridge/console', function (require, exports, module) {
+/*
+ * Copyright 2011 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.
+ */
- return result;
- },
+module.exports = {
+ log: function (win, fail, args) {
+ console.log(args[0]);
+ }
+};
- regexSanitize: function (regexString) {
- return regexString.replace("^", "\\^")
- .replace("$", "\\$")
- .replace("(", "\\(")
- .replace(")", "\\)")
- .replace("<", "\\<")
- .replace("[", "\\[")
- .replace("{", "\\{")
- .replace(/\\/, "\\\\")
- .replace("|", "\\|")
- .replace(">", "\\>")
- .replace(".", "\\.")
- .replace("*", "\\*")
- .replace("+", "\\+")
- .replace("?", "\\?");
- },
+});
+define('ripple/platform/cordova/2.0.0/bridge/accelerometer', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ _success,
+ _error,
+ _current = {x: 0, y: 0, z: 0, timestamp: (new Date()).getTime()},
+ _interval;
- bindAutoSaveEvent: function (node, saveCallback) {
- var oldSetTimeoutId,
- jNode = jQuery(node);
+event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
+ _current.x = accelerometerInfo.accelerationIncludingGravity.x;
+ _current.y = accelerometerInfo.accelerationIncludingGravity.y;
+ _current.z = accelerometerInfo.accelerationIncludingGravity.z;
+ _current.timestamp = (new Date()).getTime();
+});
- jNode.bind("keyup", function (event) {
- if (event.keyCode !== 9) {
- clearTimeout(oldSetTimeoutId);
- oldSetTimeoutId = window.setTimeout(function () {
- saveCallback();
- }, 500);
- }
- });
+module.exports = {
+ start: function (success, error, args) {
+ _success = success;
+ _error = error;
+ // Possible HACK? update the timestamp of the last data to something current
+ _interval = window.setInterval(function () {
+ _current.timestamp = (new Date()).getTime();
+ _success(_current);
+ }, 50);
},
- find: function (comparison, collection, startInx, endInx, callback) {
- var results = [],
- compare = function (s, pattern) {
+ stop: function () {
+ _success = null;
+ _error = null;
+ window.clearInterval(_interval);
+ }
+};
- if (typeof(s) !== "string" || pattern === null) {
- return s === pattern;
- }
+});
+define('ripple/platform/cordova/2.0.0/bridge/capture', function (require, exports, module) {
+/*
+ * Copyright 2011 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 regex = pattern.replace(/\./g, "\\.")
- .replace(/\^/g, "\\^")
- .replace(/\*/g, ".*")
- .replace(/\\\.\*/g, "\\*");
+var camera = require('ripple/ui/plugins/camera'),
+ event = require('ripple/event');
- regex = "^".concat(regex, "$");
+module.exports = {
+ captureImage: function (success, error, args) {
+ event.once("captured-image", function (uri, file) {
+ file.fullPath = uri;
+ success([file]);
+ });
+ camera.show();
+ }
+};
- return !!s.match(new RegExp(regex, "i"));
- };
+});
+define('ripple/platform/cordova/2.0.0/bridge', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _prompt = require('ripple/ui/plugins/exec-dialog');
- self.forEach(collection, function (c) {
- var match,
- fail = false;
+module.exports = {
+ exec: function (success, fail, service, action, args) {
+ var emulator = {
+ "App": require('ripple/platform/cordova/2.0.0/bridge/app'),
+ "Accelerometer": require('ripple/platform/cordova/2.0.0/bridge/accelerometer'),
+ "Compass": require('ripple/platform/cordova/2.0.0/bridge/compass'),
+ "Camera": require('ripple/platform/cordova/2.0.0/bridge/camera'),
+ "Capture": require('ripple/platform/cordova/2.0.0/bridge/capture'),
+ "Contacts": require('ripple/platform/cordova/2.0.0/bridge/contacts'),
+ "Debug Console": require('ripple/platform/cordova/2.0.0/bridge/console'),
+ "Device": require('ripple/platform/cordova/2.0.0/bridge/device'),
+ "File": require('ripple/platform/cordova/2.0.0/bridge/file'),
+ "Geolocation": require('ripple/platform/cordova/2.0.0/bridge/geolocation'),
+ "Media": require('ripple/platform/cordova/2.0.0/bridge/media'),
+ "Network Status": require('ripple/platform/cordova/2.0.0/bridge/network'),
+ "NetworkStatus": require('ripple/platform/cordova/2.0.0/bridge/network'),
+ "Notification": require('ripple/platform/cordova/2.0.0/bridge/notification')
+ };
- self.forEach(comparison, function (value, key) {
- if (!fail && value !== undefined) {
+ try {
+ emulator[service][action](success, fail, args);
+ }
+ catch (e) {
+ console.log("missing exec:" + service + "." + action);
+ console.log(args);
+ console.log(e);
+ console.log(e.stack);
+ //TODO: this should really not log the above lines, but they are very nice for development right now
+ _prompt.show(service, action, success, fail);
+ }
+ }
+};
- if (compare(c[key], value)) {
- match = c;
- }
- else {
- fail = true;
- match = null;
- }
- }
- });
+});
+define('ripple/platform/cordova/2.0.0/MediaError', function (require, exports, module) {
+/*
+ * Copyright 2011 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 MediaError = function (code, msg) {
+ this.code = (code !== undefined ? code : null);
+ this.message = msg || "";
+};
- if (match) {
- results.push(match);
- }
- });
+MediaError.MEDIA_ERR_NONE_ACTIVE = 0;
+MediaError.MEDIA_ERR_ABORTED = 1;
+MediaError.MEDIA_ERR_NETWORK = 2;
+MediaError.MEDIA_ERR_DECODE = 3;
+MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
- if (callback) {
- if (startInx === undefined) {
- startInx = 0;
- }
- if (endInx === undefined) {
- endInx = results.length;
- }
- if (startInx === endInx) {
- endInx = startInx + 1;
- }
+module.exports = MediaError;
- callback.apply(null, [results.slice(startInx, endInx)]);
- }
- },
+});
+define('ripple/accelerometer', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _self,
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ event = require('ripple/event'),
+ Rotation = require('ripple/platform/w3c/1.0/Rotation'),
+ Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
+ _motion = {
+ acceleration: new Acceleration(0, 0, 0),
+ accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
+ rotationRate: new Rotation(0, 0, 0),
+ orientation: new Rotation(0, 0, 0),
+ interval: 60000,
+ timestamp: new Date().getTime()
+ };
- mixin: function (mixin, to) {
- for (var prop in mixin) {
- if (Object.hasOwnProperty.call(mixin, prop)) {
- to[prop] = mixin[prop];
- }
- }
- return to;
- },
+function _validateAccelerometerInfo(x, y, z) {
+ return !(isNaN(x) || isNaN(y) || isNaN(z));
+}
- copy: function (obj) {
- var i,
- newObj = jQuery.isArray(obj) ? [] : {};
+_self = {
+ getInfo: function () {
+ return utils.copy(_motion);
+ },
- if (typeof obj === 'number' ||
- typeof obj === 'string' ||
- typeof obj === 'boolean' ||
- obj === null ||
- obj === undefined) {
- return obj;
- }
+ setInfo: function (e) {
+ var triggerDeviceMotion = false,
+ triggerDeviceOrientation = false;
- if (obj instanceof Date) {
- return new Date(obj);
+ if (e.x !== undefined && e.y !== undefined && e.z !== undefined) {
+ _motion = {
+ acceleration: new Acceleration(e.x, e.y, e.z),
+ accelerationIncludingGravity: new Acceleration(e.x, e.y, e.z),
+ rotationRate: new Rotation(0, 0, 0),
+ orientation: new Rotation(e.alpha, e.beta, e.gamma),
+ timestamp: new Date().getTime()
+ };
+ triggerDeviceMotion = true;
+ triggerDeviceOrientation = true;
+ }
+ else {
+ _motion = {
+ acceleration: new Acceleration(0, 0, 0),
+ accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
+ rotationRate: new Rotation(0, 0, 0),
+ orientation: new Rotation(0, 0, 0),
+ timestamp: new Date().getTime()
+ };
}
- if (obj instanceof RegExp) {
- return new RegExp(obj);
+ if (triggerDeviceMotion) {
+ event.trigger("DeviceMotionEvent", [_motion]);
}
- for (i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (obj[i] && typeof obj[i] === "object") {
- if (obj[i] instanceof Date) {
- newObj[i] = obj[i];
- }
- else {
- newObj[i] = self.copy(obj[i]);
- }
- }
- else {
- newObj[i] = obj[i];
- }
- }
+ if (triggerDeviceOrientation) {
+ event.trigger("DeviceOrientationEvent", [_motion]);
}
- return newObj;
+ event.trigger("AccelerometerInfoChangedEvent", [_motion]);
},
- navHelper: function () {
- return {
- getHeading: function (lat1, lon1, lat2, lon2) {
- var dLon = this.rad(lon2 - lon1),
- llat1 = this.rad(lat1),
- llat2 = this.rad(lat2),
- y = Math.sin(dLon) * Math.cos(llat2),
- x = Math.cos(llat1) * Math.sin(llat2) - Math.sin(llat1) * Math.cos(llat2) * Math.cos(dLon);
- return (this.deg(Math.atan2(y, x)) + 360) % 360;
- },
+ triggerEvent: function() {
+ event.trigger("DeviceMotionEvent", [_motion]);
+ event.trigger("DeviceOrientationEvent", [_motion]);
+ event.trigger("AccelerometerInfoChangedEvent", [_motion]);
+ },
- getDistance: function (lat1, lon1, lat2, lon2) {
- var dLat = this.rad(lat2 - lat1),
- dLon = this.rad(lon2 - lon1),
- a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.rad(lat1)) * Math.cos(this.rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2),
- c = 2 * Math.asin(Math.sqrt(a)),
- d = 6378100 * c;
- return d;
- },
+ shake: function (shakeXtimes) {
+ var id,
+ count = 1,
+ stopCount = shakeXtimes || 17,
+ oldX = _motion.accelerationIncludingGravity.x;
- simulateTravel: function (lat, lon, hdg, dist) {
- var lat1 = this.rad(lat),
- lon1 = this.rad(lon),
- brng = this.rad(hdg),
- angularDistance = dist / 6378100,
- lat2 = Math.asin(Math.sin(lat1) * Math.cos(angularDistance) + Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(brng)),
- lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angularDistance) * Math.cos(lat1), Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2));
- lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // Normalise to -180..+180
+ id = setInterval(function () {
+ var freq = 1,
+ amp = 30,
+ value = Math.round(amp * Math.sin(freq * count * (180 / Math.PI)) * 100) / 100;
- return {
- latitude: this.deg(lat2),
- longitude: this.deg(lon2)
- };
- },
+ if (count > stopCount) {
+ _motion.acceleration.x = oldX;
+ _motion.accelerationIncludingGravity.x = oldX;
+ event.trigger("AccelerometerInfoChangedEvent", [_motion]);
+ clearInterval(id);
+ return;
+ }
- deg: function (num) {
- return num * 180 / Math.PI;
- },
+ _motion.acceleration.x = value;
+ _motion.accelerationIncludingGravity.x = value;
- rad: function (num) {
- return num * Math.PI / 180;
- }
- };
- },
+ event.trigger("AccelerometerInfoChangedEvent", [_motion]);
- getURIParams: function (uriString) {
- var params = {};
+ count++;
- uriString.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
- params[key] = value;
- });
+ }, 80);
+ },
- return params;
+ init: function () {
+ event.on("DeviceMotionEventAddedEvent", function () {
+ _self.triggerEvent();
+ });
+ event.on("DeviceOrientationEventAddedEvent", function () {
+ _self.triggerEvent();
+ });
}
};
+module.exports = _self;
+
});
-define('ripple/widgetConfig', function (require, exports, module) {
+define('ripple/bus', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var exception = require('ripple/exception'),
- event = require('ripple/event'),
- app = require('ripple/app'),
- _console = require('ripple/console'),
- utils = require('ripple/utils'),
- platform = require('ripple/platform'),
- _validationResult = {
- valid: false,
- message: "",
- value: null
- },
- _configValidationResults = null;
-
-function _failNodeValidation(schemaNode, message, value, node) {
- var validationResult = utils.copy(_validationResult);
-
- if (!schemaNode.validationResult) {
- schemaNode.validationResult = [];
- }
- validationResult.valid = false;
- if (value) {
- validationResult.value = value;
- }
- else {
- delete(validationResult.value);
- }
- validationResult.message = schemaNode.nodeName + message;
- validationResult.node = node;
-
- schemaNode.validationResult.push(validationResult);
-}
-
-function _createEmptyNodeValidation(node) {
-
- var validationResult = utils.copy(_validationResult),
- attributeValidationResult, attribute;
-
- if (!node.validationResult) {
- node.validationResult = [];
- }
-
- validationResult.value = "";
- delete(validationResult.valid);
- delete(validationResult.message);
- if (node.attributes) {
- for (attribute in node.attributes) {
- if (node.attributes.hasOwnProperty(attribute)) {
- if (!validationResult.attributes) {
- validationResult.attributes = {};
- }
+var _send = document.getElementById("bus-send"),
+ _receive = document.getElementById("bus-receive"),
+ _evt = document.createEvent("Events");
- attributeValidationResult = utils.copy(_validationResult);
+_evt.initEvent('bus-init', true, true);
+document.dispatchEvent(_evt);
- attributeValidationResult.attributeName = node.attributes[attribute].attributeName;
- delete(attributeValidationResult.value);
- delete(attributeValidationResult.valid);
- delete(attributeValidationResult.message);
+module.exports = {
+ send: function (msg, data, callback) {
+ var m = document.createElement("span");
+ m.dataset.msg = msg;
+ m.innerHTML = JSON.stringify(data);
- validationResult.attributes[attributeValidationResult.attributeName] = attributeValidationResult;
- }
+ if (callback) {
+ m.dataset.callback = Math.uuid();
+ this.receive(m.dataset.callback, callback);
}
- }
-
- node.validationResult.push(validationResult);
-}
-function _validateValue(valueToTest, schemaNode) {
- var failMessage = "",
- nodeValue,
- numbers,
- numberRangeIndex,
- numberRange,
- range1,
- range2;
+ _send.appendChild(m);
+ },
- switch (schemaNode.type) {
- case "string":
- if (typeof valueToTest !== "string") {
- failMessage = " value was expected to be of type string but was typeof: " + typeof(valueToTest);
- }
- break;
- case "number":
- nodeValue = parseFloat(valueToTest);
- if (isNaN(nodeValue)) {
- failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
- }
- break;
- case "integer":
- nodeValue = parseInt(valueToTest, 10);
- if (isNaN(nodeValue)) {
- failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
- }
- break;
- case "boolean":
- if (valueToTest !== "false" && valueToTest !== "true") {
- failMessage = " value was expected to be of type boolean (i.e. 'true' or 'false' but was: " + valueToTest;
- }
- break;
- case "list":
- if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
- failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
- "</span><br/><br/>Valid values are:<p class=\"ui-text-pass\">" + schemaNode.listValues.join(" <br/> ") + "</p>";
- }
- break;
- case "listBoolean":
- case "listDefault":
- if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
- failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
- "</span><br/><br/>The framework will assume the value to be:<p class=\"ui-text-pass\">" + schemaNode.defaultValue + "</p>";
+ receive: function (msg, handler) {
+ if (!handler) {
+ return;
}
- break;
- case "listNumbers":
- numbers = valueToTest.split(",");
- for (numberRangeIndex = 0; numberRangeIndex < numbers.length; numberRangeIndex++) {
- numberRange = valueToTest.split("-");
- if (numberRange.length > 1) {
- range1 = parseInt(numberRange[0], 10);
- range2 = parseInt(numberRange[1], 10);
- if (isNaN(range1) || isNaN(range2)) {
- failMessage = " range values where not recognized as being valid, they was: " + range1 +
- " and " + range2 + " :: valid values should be of type 'integer'";
- break;
- }
+ _receive.addEventListener("DOMNodeInserted", function (evt) {
+ if (evt.target.dataset.msg === msg) {
+ handler(JSON.parse(evt.target.innerHTML));
}
- else if (numberRange.length === 1) {
- range1 = parseInt(numberRange[0], 10);
- if (isNaN(range1)) {
- failMessage = " value was not recognized as being valid, it was: " + range1 +
- " :: valid values should be of type 'integer'";
- break;
- }
+ });
+ },
+
+ ajax: function (method, url, data, success, fail) {
+ this.send("xhr", {
+ method: method,
+ url: url,
+ data: data
+ }, function (result) {
+ if (result.code === 200) {
+ success(result.data);
}
- }
- break;
- case "regex":
- if (!valueToTest.match(schemaNode.regex)) {
- failMessage = " value does not match expected format. Value should pass this regular expression validation: " + schemaNode.regex;
- }
- break;
- case "iso-language":
- break;
- default:
- exception.raise(exception.types.Application, "Schema node with value type of: " + schemaNode.type + " is not known");
+ else {
+ fail(result);
+ }
+ });
}
+};
- return failMessage;
-}
-
-function _passNodeValidation(schemaNode, value, node) {
- var validationResult = utils.copy(_validationResult);
-
- if (!schemaNode.validationResult) {
- schemaNode.validationResult = [];
- }
- validationResult.valid = true;
- validationResult.node = node;
- if (value) {
- validationResult.value = value;
- }
- else {
- delete(validationResult.value);
- }
- delete(validationResult.message);
+});
+define('ripple/ui', function (require, exports, module) {
+/*
+ * Copyright 2011 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 _self,
+ db = require('ripple/db'),
+ platform = require('ripple/platform'),
+ constants = require('ripple/constants'),
+ utils = require('ripple/utils'),
+ exception = require('ripple/exception'),
+ event = require('ripple/event'),
+ themes = require('ripple/ui/themes'),
+ _applicationStateId,
+ _applicationState,
+ _availablePanels,
+ _applicationStateTmp,
+ _systemPlugins = [
+ "options",
+ "about-dialog",
+ "settings-dialog",
+ "exec-dialog",
+ "firstRunCheck",
+ "eulaCheck",
+ "devices",
+ "goodVibrations",
+ "panelCollapse",
+ "platform",
+ "information",
+ "layout",
+ "themeSwitcher",
+ "settings-menu",
+ "configWindow",
+ "HWKeys"
+ //"launchingHistory"
+ ],
+ _overlay = {
+ getOrCreate: function (id) {
+ var _container = document.getElementById(constants.COMMON.HTML_CONTAINER),
+ _overlays = document.getElementById("overlay-views"),
+ _overlay = _overlays.children[id],
+ _hide = function (node) {
+ node.setAttribute("style", "display: none");
+ },
+ _show = function (node) {
+ node.setAttribute("style", "display: block");
+ },
+ _trigger = function (callback) {
+ if (callback) {
+ callback.apply(null, [_overlay]);
+ }
+ };
- schemaNode.validationResult.push(validationResult);
-}
-function _validateNodeValue(schemaNode, node) {
- var failMessage,
- valueToTest = node && node.nodeValue ? node.nodeValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;
+ if (!_overlay) {
+ _overlay = utils.createElement("section", {id: id, "class": "overlay"});
+ _overlays.appendChild(_overlay);
+ }
- if (schemaNode.type && valueToTest) {
+ return {
+ hide: function (callback) {
+ _hide(_overlay);
+ _show(_container);
+ _trigger(callback);
+ },
+ show: function (callback, showContainer) {
+ _show(_overlay);
+ if (!showContainer) {
+ _hide(_container);
+ }
+ _trigger(callback);
+ }
+ };
+ }
+ };
- failMessage = _validateValue(valueToTest, schemaNode);
+function _addUIPaneItemsToApplicationState(arrayObj, pane) {
+ utils.forEach(arrayObj, function (domId) {
+ var collapsed = jQuery("#" + domId + " .info")[0];
+ collapsed = (collapsed.style && collapsed.style.display === "none") ? true : false;
+ utils.forEach(_applicationStateTmp, function (obj) {
+ if (obj.domId === domId) {
+ _applicationState.push({
+ "domId": domId,
+ "collapsed": collapsed,
+ "pane": pane,
+ "titleName" : obj.titleName,
+ "display" : obj.display
+ });
+ _applicationStateTmp.splice(_applicationStateTmp.indexOf(obj), 1);
+ return;
+ }
+ }, this);
+ }, this);
- if (failMessage !== "") {
- _failNodeValidation(schemaNode, failMessage, valueToTest, node);
- return;
- }
- }
- _passNodeValidation(schemaNode, valueToTest, node);
+ utils.forEach(_applicationStateTmp, function (obj) {
+ _applicationState.push({
+ "domId": obj.domId,
+ "collapsed": obj.collapsed,
+ "pane": obj.pane,
+ "titleName" : obj.titleName,
+ "display" : obj.display
+ });
+ });
}
-function _failNodeAttributeValidation(node, attribute, message, value) {
- var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
- attributeValidationResult = utils.copy(_validationResult);
+function _currentlyEnabledTheme() {
+ var qsSet = utils.queryString().theme,
+ current = db.retrieve("ui-theme") || themes[0];
- if (!nodeValidationResult.attributes) {
- nodeValidationResult.attributes = {};
+ function matches(something) {
+ return function (item) {
+ return something === item;
+ };
}
- nodeValidationResult.valid = false;
- nodeValidationResult.message = "One or more attributes failed validation";
-
- attributeValidationResult.attributeName = attribute.attributeName;
- attributeValidationResult.valid = false;
- if (value) {
- attributeValidationResult.value = value;
- }
- else {
- delete(attributeValidationResult.value);
+ if (qsSet && themes.some(matches(qsSet))) {
+ current = qsSet;
+ db.save("ui-theme", qsSet);
}
- attributeValidationResult.message = node.nodeName + "." + attribute.attributeName + message;
- nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
- node.validationResult.push(nodeValidationResult);
+ return current;
}
-function _passNodeAttributeValidation(node, attribute, value) {
- var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
- attributeValidationResult = utils.copy(_validationResult);
-
- if (!nodeValidationResult.attributes) {
- nodeValidationResult.attributes = {};
- }
+function _insertStyleSheets() {
+ var uiTheme = db.retrieve("ui-theme") || require('ripple/ui/themes')[0],
+ extensionURL = jQuery("#extension-url").text(),
+ uiThemeURL = extensionURL + "themes/" + uiTheme + "/theme.css",
+ head = document.getElementsByTagName('head')[0];
- attributeValidationResult.attributeName = attribute.attributeName;
- attributeValidationResult.valid = true;
- if (value) {
- attributeValidationResult.value = value;
- }
- else {
- delete(attributeValidationResult.value);
+ function stylesheet(src) {
+ var scriptElement = document.createElement("link");
+ scriptElement.setAttribute("href", src);
+ scriptElement.setAttribute("type", "text/css");
+ scriptElement.setAttribute("rel", "stylesheet");
+ return scriptElement;
}
- delete(attributeValidationResult.message);
- nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
- node.validationResult.push(nodeValidationResult);
+ head.appendChild(stylesheet(uiThemeURL));
}
-function _validateNodeAttributeValue(schemaNode, schemaNodeAttribute, attribute) {
- var failMessage,
- valueToTest = attribute ? attribute.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;
-
- if (schemaNodeAttribute.type && valueToTest) {
-
- failMessage = _validateValue(valueToTest, schemaNodeAttribute);
+function _collapsePannels(side) {
+ var collapseNode = [],
+ event = document.createEvent("UIEvent");
- if (failMessage !== "") {
- _failNodeAttributeValidation(schemaNode, schemaNodeAttribute, failMessage, valueToTest);
- return;
- }
+ collapseNode = side === "left" ? document.getElementsByClassName("left-panel-collapse") :
+ document.getElementsByClassName("right-panel-collapse");
+
+ if (collapseNode.length > 0) {
+ event.initEvent("click", true, true);
+ collapseNode[0].dispatchEvent(event);
}
- _passNodeAttributeValidation(schemaNode, schemaNodeAttribute, valueToTest);
}
-function _validateNodeAttributes(schemaNode, node, children) {
+function _initializeUI() {
+ _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;
+ _applicationState = db.retrieveObject(_applicationStateId) || [];
+ _insertStyleSheets();
- var siblings = utils.filter(children, function (child) {
- return child !== node;
- }),
- attributeConverter = function (attribute) {
- var _self = {
- toValue: function (n) {
- var obj = _self.toNode(n);
- return obj ? obj.value : null;
- },
- toNode: function (n) {
- return n.attributes.getNamedItem(attribute.attributeName);
- }
- };
+ var leftPanelSection = jQuery(".left"),
+ uiBoxToggleEngaged = false;
- return _self;
+ //clean up
+ db.remove("ui-application-state");
+ utils.forEach(_availablePanels, function (obj) {
+ var matchingDomId = function (panel) {
+ return panel.domId === obj.domId;
};
-
- utils.forEach(schemaNode.attributes, function (attribute) {
-
- var convert = attributeConverter(attribute),
- dupe = false;
-
- if (attribute.unique) {
- // this means we need to check and see if there are other node with the same name
- // and ensure that they have a different value for this attributes, if not... fail
-
- dupe = siblings.some(function (sibling) {
- return convert.toValue(sibling) === convert.toValue(node);
+ if (!utils.some(_applicationState, matchingDomId)) {
+ _applicationState.push({
+ "domId": obj.domId,
+ "collapsed": obj.collapsed,
+ "pane": obj.pane,
+ "titleName" : obj.titleName,
+ "display" : obj.display
});
-
- if (dupe) {
- _failNodeAttributeValidation(schemaNode,
- attribute,
- " node is allowed to appear multiple times, however it must be unique based on this attribute and in this case another node with an identical attribute vale was found",
- convert.toValue(node));
- return;
- }
}
+ });
- if (attribute.required && !convert.toValue(node)) {
- _failNodeAttributeValidation(schemaNode, attribute, " attribute was expected but not found", null);
- }
- else {
- _validateNodeAttributeValue(schemaNode, attribute, convert.toNode(node));
+ utils.forEach(_applicationState, function (obj) {
+ var node = jQuery("#" + obj.domId),
+ imgNode = node.find(".ui-box-TitleImage"),
+ matchingDomId = function (panel) {
+ return panel.domId === obj.domId;
+ };
+
+ if (node.length > 0) {
+ if (!utils.some(_availablePanels, matchingDomId)) {
+ node.parent()[0].removeChild(node[0]);
+ }
+ else {
+ if (obj.display !== false) {
+ leftPanelSection.append(node.parent()[0].removeChild(node[0]));
+ if (!obj.collapsed) {
+ node.find(".info")
+ .css({
+ "display": "block"
+ })
+ .end()
+ .addClass("ui-box-open");
+ imgNode.addClass("ui-box-TitleImageOpen");
+ }
+ }
+ }
}
});
-}
+ db.saveObject(_applicationStateId, _applicationState);
-function _validateNode(schemaNode, parentNode) {
- var children = utils.filter(parentNode.childNodes, function (child) {
- return child && child.nodeName === schemaNode.nodeName;
- });
+ event.on("ApplicationState", function () {
+ try {
+ var leftArray = jQuery(".left").sortable('toArray');
+ _applicationStateTmp = [];
+ _applicationStateTmp = utils.copy(_applicationState);
+ _applicationState = [];
+ _addUIPaneItemsToApplicationState(leftArray, "left");
- if (children.length === 0) {
- if (schemaNode.required) {
- _failNodeValidation(schemaNode, " node expected, but not found", null, null);
- }
- }
+ if (leftArray.length === 0) {
+ _collapsePannels("left");
+ }
- utils.forEach(children, function (child) {
- if (schemaNode.occurrence !== 0 && schemaNode.occurrence < children.length) {
- _failNodeValidation(schemaNode, " node: more then " + schemaNode.occurrence + " node(s) found", null, child);
+ db.saveObject(_applicationStateId, _applicationState);
}
- else {
- _validateNodeValue(schemaNode, child.childNodes[0] || child);
-
- _validateNodeAttributes(schemaNode, child, children);
+ catch (e) {
+ exception.handle(e);
}
+ });
- utils.forEach(schemaNode.children, function (schema) {
- _validateNode(schema, child);
- });
+ jQuery(".left").sortable({
+ handle: ".drag-handle",
+ revert: true,
+ placeholder: 'ui-sortable-highlight ui-corner-all',
+ connectWith: [".left"],
+ scroll: true,
+ update: function (uiEvent, ui) {
+ event.trigger("ApplicationState");
+ }
});
-}
-function _validateAgainstSchemaNode(configSchema, configXML) {
- var results = utils.copy(configSchema);
- try {
- _validateNode(results[configSchema.rootElement], configXML);
- }
- catch (e) {
- exception.handle(e, true);
- }
+ jQuery(".left").sortable({ axis: 'y' });
- return results;
-}
+ jQuery(".collapse-handle").bind("click", function () {
+ if (!uiBoxToggleEngaged) {
-function _validate(configXML) {
- // traverse the config schema JSON object
- // TODO: update to get platform.getPlatformConfigSpec().schema
- return _validateAgainstSchemaNode(platform.current().config.schema, configXML);
-}
+ uiBoxToggleEngaged = true;
-function _process(results) {
- // Check to make sure that widget is the correct version (i.e. config.xml needs to match selected platform)
- var validVersion = app.validateVersion(results);
+ var jNode = jQuery(this).parentsUntil(".ui-box"),
+ pNode = jNode.parent(),
+ isOpen = pNode.hasClass("ui-box-open"),
+ imgNode = jQuery(this).find(".ui-box-TitleImage");
- if (!validVersion) {
- _console.warn("Your application does not appear to match" +
- " the platform you have selected. The version number in your configuration might not " +
- "match the selected platform version or your configuration file has errors in it.");
- }
+ if (!isOpen) {
+ pNode.addClass("ui-box-open");
+ imgNode.removeClass("ui-box-TitleImageClosed");
+ imgNode.addClass("ui-box-TitleImageOpen");
+ }
- // save widget info
- app.saveInfo(results);
- event.trigger("WidgetInformationUpdated");
+ jQuery(this).parent().next().toggle("blind", {}, 300, function () {
+ if (isOpen) {
+ pNode.removeClass("ui-box-open");
+ imgNode.removeClass("ui-box-TitleImageOpen");
+ imgNode.addClass("ui-box-TitleImageClosed");
+ }
+ event.trigger("ApplicationState", [pNode]);
+ uiBoxToggleEngaged = false;
+ });
+ }
+ });
+}
- // Check for readonly preferences (WAC only?)
+function _db_upgrade_for_release() {
+ var version = db.retrieve(constants.RELEASE_VERSION);
- if (app.getInfo().preferences !== {}) {
- event.trigger("StorageUpdatedEvent");
+ // version: 20121115 is the first release version
+ if (version === null || version === undefined || Number(version) < 20130722) {
+ db.remove(constants.COMMON.APPLICATION_STATE + "tizen");
+ db.remove(constants.COMMON.APPLICATION_STATE + "cordova");
+ db.remove("tizen1-db-application");
+ db.remove("tizen-db-package");
+ version = 20130722;
+ db.save(constants.RELEASE_VERSION, version);
}
}
-function _xmlToJson(xml) {
- var obj = {};
+_self = module.exports = {
+ initialize: function () {
+ var plugins = _systemPlugins.concat(platform.current().ui.plugins || []).map(function (name) {
+ return require('ripple/ui/plugins/' + name);
+ }),
+ boot = jWorkflow.order(_initializeUI);
- if (xml.nodeType === 1) { // element
- if (xml.attributes.length > 0) {
- obj["@attributes"] = {};
- utils.forEach(xml.attributes, function (attribute) {
- obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
- });
- }
- }
- else if (xml.nodeType === 3) { // text node
- obj = xml.nodeValue;
- }
+ _db_upgrade_for_release();
+ _availablePanels = [];
- if (xml.hasChildNodes && xml.hasChildNodes()) {
- utils.forEach(xml.childNodes, function (child) {
- if (!child.nodeName) {
- return;
+ plugins.forEach(function (plugin) {
+ if (plugin.initialize) {
+ boot.andThen(plugin.initialize);
}
- if (!obj[child.nodeName]) {
- obj[child.nodeName] = [];
+
+ if (plugin.panel) {
+ _availablePanels.push(plugin.panel);
}
- obj[child.nodeName].push(_xmlToJson(child));
});
- }
- return obj;
-}
+ boot.start();
+ },
-module.exports = {
+ getSystemPlugins: function () {
+ return utils.copy(_systemPlugins);
+ },
- validate: function (configXML) {
- utils.validateNumberOfArguments(1, 1, arguments.length);
- return _validate(configXML);
+ register: function (plugin) {
+ _systemPlugins.push(plugin);
},
- initialize: function (previous, baton) {
- var xmlHttp = new XMLHttpRequest(),
- config = platform.current().config,
- fileName = config ? config.fileName : null,
- results;
+ registered: function (plugin) {
+ return _systemPlugins.indexOf(plugin) >= 0;
+ },
- if (!fileName) {
- return;
- }
+ getExtensionURL: function () {
+ return jQuery("#" + constants.COMMON.EXTENSION_URL_CONTAINER).text();
+ },
- try {
- xmlHttp.open("GET", utils.appLocation() + fileName, false);
- xmlHttp.send();
- if (xmlHttp.responseXML) {
- results = _validate(xmlHttp.responseXML);
- results.rawJSON = _xmlToJson(xmlHttp.responseXML);
- _process(results);
- _configValidationResults = results;
- }
- else {
- _process();
- _configValidationResults = null;
- require('ripple/ui/plugins/widgetConfig').initialize();
- }
- }
- catch (e) {
- exception.handle(e);
- }
+ showOverlay: function (id, callback, showContainer) {
+ _overlay.getOrCreate(id).show(callback, showContainer);
},
- getValidationResults: function () {
- return _configValidationResults;
+ hideOverlay: function (id, callback) {
+ _overlay.getOrCreate(id).hide(callback);
+ }
+};
+
+});
+define('ripple/xhr/helpers', function (require, exports, module) {
+/*
+ * Copyright 2011 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 constants = require('ripple/constants'),
+ db = require('ripple/db');
+
+module.exports = {
+ isLocalRequest: function (url) {
+ return (!!(url.match(constants.REGEX.LOCAL_URI)) || !url.match(constants.REGEX.EXTERNAL_URI)) ||
+ !!(location.host && url.match(location.host));
+ },
+
+ proxyEnabled: function () {
+ var isDisabled = db.retrieve(constants.XHR.PROXY_DISABLED_BUTTON);
+ return !isDisabled || isDisabled === "false" ? true : false;
}
};
module.exports = _XMLHttpRequest;
});
-define('ripple/xhr/cors', function (require, exports, module) {
-/*
- * Copyright 2011 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 helpers = require('ripple/xhr/helpers'),
- constants = require('ripple/constants'),
- XHR = require('ripple/xhr/base');
-
-function _XMLHttpRequest() {
- var xhr = new XHR(),
- origMethods = {
- setRequestHeader: xhr.setRequestHeader,
- open: xhr.open
- };
-
- xhr.setRequestHeader = function (header, value) {
- // This is done to get around jQuery 1.3.2 setting a header that it shouldn't
- if (header && header.toUpperCase() !== "X-REQUESTED-WITH") {
- origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
- }
- };
-
- xhr.open = function (method, url, async, user, password) {
- if (!helpers.isLocalRequest(url)) {
- url = constants.API_URL + "/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=" + escape(url);
- }
-
- origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
- };
-
- return xhr;
-}
-
-module.exports = _XMLHttpRequest;
-
-});
-define('ripple/xhr/helpers', function (require, exports, module) {
-/*
- * Copyright 2011 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 constants = require('ripple/constants'),
- db = require('ripple/db');
-
-module.exports = {
- isLocalRequest: function (url) {
- return (!!(url.match(constants.REGEX.LOCAL_URI)) || !url.match(constants.REGEX.EXTERNAL_URI)) ||
- !!(location.host && url.match(location.host));
- },
-
- proxyEnabled: function () {
- var isDisabled = db.retrieve(constants.XHR.PROXY_DISABLED_BUTTON);
- return !isDisabled || isDisabled === "false" ? true : false;
- }
-};
-
-});
define('ripple/xhr/jsonp', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
module.exports = _XMLHttpRequest;
});
-define('ripple/xhr', function (require, exports, module) {
+define('ripple/xhr/cors', function (require, exports, module) {
/*
* Copyright 2011 Research In Motion Limited.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var constants = require('ripple/constants'),
- utils = require('ripple/utils'),
- ui = require('ripple/ui'),
- helpers = require('ripple/xhr/helpers'),
- XHR = window.XMLHttpRequest;
+var helpers = require('ripple/xhr/helpers'),
+ constants = require('ripple/constants'),
+ XHR = require('ripple/xhr/base');
-module.exports = {
- initialize: function (previous, baton) {
- window.XMLHttpRequest = require('ripple/xhr/base');
+function _XMLHttpRequest() {
+ var xhr = new XHR(),
+ origMethods = {
+ setRequestHeader: xhr.setRequestHeader,
+ open: xhr.open
+ };
- if (helpers.proxyEnabled() && !ui.registered("omnibar")) {
- var isFileScheme = utils.location().protocol.match(/^file:/);
- window.XMLHttpRequest = require(isFileScheme ? 'ripple/xhr/jsonp' : 'ripple/xhr/cors');
+ xhr.setRequestHeader = function (header, value) {
+ // This is done to get around jQuery 1.3.2 setting a header that it shouldn't
+ if (header && header.toUpperCase() !== "X-REQUESTED-WITH") {
+ origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
}
- }
+ };
+
+ xhr.open = function (method, url, async, user, password) {
+ if (!helpers.isLocalRequest(url)) {
+ url = constants.API_URL + "/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=" + escape(url);
+ }
+
+ origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
+ };
+
+ return xhr;
+}
+
+module.exports = _XMLHttpRequest;
+
+});
+define('ripple/omgwtf', function (require, exports, module) {
+/*
+ * Copyright 2011 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 event = require('ripple/event'),
+ db = require('ripple/db'),
+ _loaded = false,
+ _self;
+
+function _delay(action) {
+ window.setTimeout(function () {
+ if (!_loaded) {
+ if (jQuery(".first-run-window").is(":visible")) {
+ _delay(action);
+ } else {
+ action();
+ }
+ }
+ }, 10000);
+}
+
+function _hide() {
+ jQuery(".error-window").css({display: 'none'});
+ jQuery(".error-dialog").css({display: 'none'});
+}
+
+function _show() {
+ jQuery(".error-window").css({display: 'block'});
+
+ jQuery(".error-dialog").css({
+ display: 'block',
+ left: (jQuery(document).width() / 2) - 277 + "px"
+ });
+
+ jQuery("#error-wait").click(function () {
+ _hide();
+ _delay(_show);
+ });
+
+ jQuery("#error-panic").click(function () {
+ db.removeAll(null, function () {
+ window.tinyHipposReload = true;
+ localStorage.clear();
+ location.reload();
+ });
+ });
+}
+
+_delay(_show);
+
+_self = {
+ initialize: function (previous, baton) {
+ event.on("TinyHipposLoaded", function () {
+ _loaded = true;
+ });
+ },
+ show: _show,
+ hide: _hide
};
+module.exports = _self;
+
});
define('ripple', function (require, exports, module) {
/*