incubator-xap-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mtu...@apache.org
Subject svn commit: r518313 [22/43] - in /incubator/xap/trunk/codebase/src/dojo: ./ src/ src/animation/ src/cal/ src/charting/ src/charting/svg/ src/charting/vml/ src/collections/ src/crypto/ src/data/ src/data/core/ src/data/old/ src/data/old/format/ src/data...
Date Wed, 14 Mar 2007 20:37:27 GMT
Added: incubator/xap/trunk/codebase/src/dojo/src/loader.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/loader.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/loader.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/loader.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,768 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+/*
+ * loader.js - A bootstrap module.  Runs before the hostenv_*.js file. Contains all of the package loading methods.
+ */
+
+//A semi-colon is at the start of the line because after doing a build, this function definition
+//get compressed onto the same line as the last line in bootstrap1.js. That list line is just a
+//curly bracket, and the browser complains about that syntax. The semicolon fixes it. Putting it
+//here instead of at the end of bootstrap1.js, since it is more of an issue for this file, (using
+//the closure), and bootstrap1.js could change in the future.
+;(function(){
+	//Additional properties for dojo.hostenv
+	var _addHostEnv = {
+		pkgFileName: "__package__",
+	
+		// for recursion protection
+		loading_modules_: {},
+		loaded_modules_: {},
+		addedToLoadingCount: [],
+		removedFromLoadingCount: [],
+	
+		inFlightCount: 0,
+	
+		// FIXME: it should be possible to pull module prefixes in from djConfig
+		modulePrefixes_: {
+			dojo: {name: "dojo", value: "src"}
+		},
+
+		setModulePrefix: function(/*String*/module, /*String*/prefix){
+			// summary: establishes module/prefix pair
+			this.modulePrefixes_[module] = {name: module, value: prefix};
+		},
+
+		moduleHasPrefix: function(/*String*/module){
+			// summary: checks to see if module has been established
+			var mp = this.modulePrefixes_;
+			return Boolean(mp[module] && mp[module].value); // Boolean
+		},
+
+		getModulePrefix: function(/*String*/module){
+			// summary: gets the prefix associated with module
+			if(this.moduleHasPrefix(module)){
+				return this.modulePrefixes_[module].value; // String
+			}
+			return module; // String
+		},
+
+		getTextStack: [],
+		loadUriStack: [],
+		loadedUris: [],
+	
+		//WARNING: This variable is referenced by packages outside of bootstrap: FloatingPane.js and undo/browser.js
+		post_load_: false,
+		
+		//Egad! Lots of test files push on this directly instead of using dojo.addOnLoad.
+		modulesLoadedListeners: [],
+		unloadListeners: [],
+		loadNotifying: false
+	};
+	
+	//Add all of these properties to dojo.hostenv
+	for(var param in _addHostEnv){
+		dojo.hostenv[param] = _addHostEnv[param];
+	}
+})();
+
+dojo.hostenv.loadPath = function(/*String*/relpath, /*String?*/module, /*Function?*/cb){
+// summary:
+//	Load a Javascript module given a relative path
+//
+// description:
+//	Loads and interprets the script located at relpath, which is relative to the
+//	script root directory.  If the script is found but its interpretation causes
+//	a runtime exception, that exception is not caught by us, so the caller will
+//	see it.  We return a true value if and only if the script is found.
+//
+//	For now, we do not have an implementation of a true search path.  We
+//	consider only the single base script uri, as returned by getBaseScriptUri().
+//
+// relpath: A relative path to a script (no leading '/', and typically
+// 	ending in '.js').
+// module: A module whose existance to check for after loading a path.
+//	Can be used to determine success or failure of the load.
+// cb: a callback function to pass the result of evaluating the script
+
+	var uri;
+	if(relpath.charAt(0) == '/' || relpath.match(/^\w+:/)){
+		// dojo.raise("relpath '" + relpath + "'; must be relative");
+		uri = relpath;
+	}else{
+		uri = this.getBaseScriptUri() + relpath;
+	}
+	if(djConfig.cacheBust && dojo.render.html.capable){
+		uri += "?" + String(djConfig.cacheBust).replace(/\W+/g,"");
+	}
+	try{
+		return !module ? this.loadUri(uri, cb) : this.loadUriAndCheck(uri, module, cb); // Boolean
+	}catch(e){
+		dojo.debug(e);
+		return false; // Boolean
+	}
+}
+
+dojo.hostenv.loadUri = function(/*String (URL)*/uri, /*Function?*/cb){
+// summary:
+//	Loads JavaScript from a URI
+//
+// description:
+//	Reads the contents of the URI, and evaluates the contents.  This is used to load modules as well
+//	as resource bundles.  Returns true if it succeeded. Returns false if the URI reading failed.
+//	Throws if the evaluation throws.
+//
+// uri: a uri which points at the script to be loaded
+// cb: a callback function to process the result of evaluating the script as an expression, typically
+//	used by the resource bundle loader to load JSON-style resources
+
+	if(this.loadedUris[uri]){
+		return true; // Boolean
+	}
+	var contents = this.getText(uri, null, true);
+	if(!contents){ return false; } // Boolean
+	this.loadedUris[uri] = true;
+	if(cb){ contents = '('+contents+')'; }
+	var value = dj_eval(contents);
+	if(cb){ cb(value); }
+	return true; // Boolean
+}
+
+// FIXME: probably need to add logging to this method
+dojo.hostenv.loadUriAndCheck = function(/*String (URL)*/uri, /*String*/moduleName, /*Function?*/cb){
+	// summary: calls loadUri then findModule and returns true if both succeed
+	var ok = true;
+	try{
+		ok = this.loadUri(uri, cb);
+	}catch(e){
+		dojo.debug("failed loading ", uri, " with error: ", e);
+	}
+	return Boolean(ok && this.findModule(moduleName, false)); // Boolean
+}
+
+dojo.loaded = function(){ }
+dojo.unloaded = function(){ }
+
+dojo.hostenv.loaded = function(){
+	this.loadNotifying = true;
+	this.post_load_ = true;
+	var mll = this.modulesLoadedListeners;
+	for(var x=0; x<mll.length; x++){
+		mll[x]();
+	}
+
+	//Clear listeners so new ones can be added
+	//For other xdomain package loads after the initial load.
+	this.modulesLoadedListeners = [];
+	this.loadNotifying = false;
+
+	dojo.loaded();
+}
+
+dojo.hostenv.unloaded = function(){
+	var mll = this.unloadListeners;
+	while(mll.length){
+		(mll.pop())();
+	}
+	dojo.unloaded();
+}
+
+dojo.addOnLoad = function(/*Object?*/obj, /*String|Function*/functionName) {
+// summary:
+//	Registers a function to be triggered after the DOM has finished loading 
+//	and widgets declared in markup have been instantiated.  Images and CSS files
+//	may or may not have finished downloading when the specified function is called.
+//	(Note that widgets' CSS and HTML code is guaranteed to be downloaded before said
+//	widgets are instantiated.)
+//
+// usage:
+//	dojo.addOnLoad(functionPointer)
+//	dojo.addOnLoad(object, "functionName")
+
+	var dh = dojo.hostenv;
+	if(arguments.length == 1) {
+		dh.modulesLoadedListeners.push(obj);
+	} else if(arguments.length > 1) {
+		dh.modulesLoadedListeners.push(function() {
+			obj[functionName]();
+		});
+	}
+
+	//Added for xdomain loading. dojo.addOnLoad is used to
+	//indicate callbacks after doing some dojo.require() statements.
+	//In the xdomain case, if all the requires are loaded (after initial
+	//page load), then immediately call any listeners.
+	if(dh.post_load_ && dh.inFlightCount == 0 && !dh.loadNotifying){
+		dh.callLoaded();
+	}
+}
+
+dojo.addOnUnload = function(/*Object?*/obj, /*String|Function?*/functionName){
+// summary: registers a function to be triggered when the page unloads
+//
+// usage:
+//	dojo.addOnLoad(functionPointer)
+//	dojo.addOnLoad(object, "functionName")
+	var dh = dojo.hostenv;
+	if(arguments.length == 1){
+		dh.unloadListeners.push(obj);
+	} else if(arguments.length > 1) {
+		dh.unloadListeners.push(function() {
+			obj[functionName]();
+		});
+	}
+}
+
+dojo.hostenv.modulesLoaded = function(){
+	if(this.post_load_){ return; }
+	if(this.loadUriStack.length==0 && this.getTextStack.length==0){
+		if(this.inFlightCount > 0){ 
+			dojo.debug("files still in flight!");
+			return;
+		}
+		dojo.hostenv.callLoaded();
+	}
+}
+
+dojo.hostenv.callLoaded = function(){
+	if(typeof setTimeout == "object"){
+		setTimeout("dojo.hostenv.loaded();", 0);
+	}else{
+		dojo.hostenv.loaded();
+	}
+}
+
+dojo.hostenv.getModuleSymbols = function(/*String*/modulename){
+// summary:
+//	Converts a module name in dotted JS notation to an array representing the path in the source tree
+	var syms = modulename.split(".");
+	for(var i = syms.length; i>0; i--){
+		var parentModule = syms.slice(0, i).join(".");
+		if((i==1) && !this.moduleHasPrefix(parentModule)){		
+			// Support default module directory (sibling of dojo) for top-level modules 
+			syms[0] = "../" + syms[0];
+		}else{
+			var parentModulePath = this.getModulePrefix(parentModule);
+			if(parentModulePath != parentModule){
+				syms.splice(0, i, parentModulePath);
+				break;
+			}
+		}
+	}
+	return syms; // Array
+}
+
+dojo.hostenv._global_omit_module_check = false;
+dojo.hostenv.loadModule = function(/*String*/moduleName, /*Boolean?*/exactOnly, /*Boolean?*/omitModuleCheck){
+// summary:
+//	loads a Javascript module from the appropriate URI
+//
+// description:
+//	loadModule("A.B") first checks to see if symbol A.B is defined. 
+//	If it is, it is simply returned (nothing to do).
+//	
+//	If it is not defined, it will look for "A/B.js" in the script root directory,
+//	followed by "A.js".
+//	
+//	It throws if it cannot find a file to load, or if the symbol A.B is not
+//	defined after loading.
+//	
+//	It returns the object A.B.
+//	
+//	This does nothing about importing symbols into the current package.
+//	It is presumed that the caller will take care of that. For example, to import
+//	all symbols:
+//	
+//	   with (dojo.hostenv.loadModule("A.B")) {
+//	      ...
+//	   }
+//	
+//	And to import just the leaf symbol:
+//	
+//	   var B = dojo.hostenv.loadModule("A.B");
+//	   ...
+//	
+//	dj_load is an alias for dojo.hostenv.loadModule
+
+	if(!moduleName){ return; }
+	omitModuleCheck = this._global_omit_module_check || omitModuleCheck;
+	var module = this.findModule(moduleName, false);
+	if(module){
+		return module;
+	}
+
+	// protect against infinite recursion from mutual dependencies
+	if(dj_undef(moduleName, this.loading_modules_)){
+		this.addedToLoadingCount.push(moduleName);
+	}
+	this.loading_modules_[moduleName] = 1;
+
+	// convert periods to slashes
+	var relpath = moduleName.replace(/\./g, '/') + '.js';
+
+	var nsyms = moduleName.split(".");
+	
+	// this line allowed loading of a module manifest as if it were a namespace
+	// it's an interesting idea, but shouldn't be combined with 'namespaces' proper
+	// and leads to unwanted dependencies
+	// the effect can be achieved in other (albeit less-flexible) ways now, so I am
+	// removing this pending further design work
+	// perhaps we can explicitly define this idea of a 'module manifest', and subclass
+	// 'namespace manifest' from that
+	//dojo.getNamespace(nsyms[0]);
+
+	var syms = this.getModuleSymbols(moduleName);
+	var startedRelative = ((syms[0].charAt(0) != '/') && !syms[0].match(/^\w+:/));
+	var last = syms[syms.length - 1];
+	var ok;
+	// figure out if we're looking for a full package, if so, we want to do
+	// things slightly diffrently
+	if(last=="*"){
+		moduleName = nsyms.slice(0, -1).join('.');
+		while(syms.length){
+			syms.pop();
+			syms.push(this.pkgFileName);
+			relpath = syms.join("/") + '.js';
+			if(startedRelative && relpath.charAt(0)=="/"){
+				relpath = relpath.slice(1);
+			}
+			ok = this.loadPath(relpath, !omitModuleCheck ? moduleName : null);
+			if(ok){ break; }
+			syms.pop();
+		}
+	}else{
+		relpath = syms.join("/") + '.js';
+		moduleName = nsyms.join('.');
+		var modArg = !omitModuleCheck ? moduleName : null;
+		ok = this.loadPath(relpath, modArg);
+		if(!ok && !exactOnly){
+			syms.pop();
+			while(syms.length){
+				relpath = syms.join('/') + '.js';
+				ok = this.loadPath(relpath, modArg);
+				if(ok){ break; }
+				syms.pop();
+				relpath = syms.join('/') + '/'+this.pkgFileName+'.js';
+				if(startedRelative && relpath.charAt(0)=="/"){
+					relpath = relpath.slice(1);
+				}
+				ok = this.loadPath(relpath, modArg);
+				if(ok){ break; }
+			}
+		}
+
+		if(!ok && !omitModuleCheck){
+			dojo.raise("Could not load '" + moduleName + "'; last tried '" + relpath + "'");
+		}
+	}
+
+	// check that the symbol was defined
+	//Don't bother if we're doing xdomain (asynchronous) loading.
+	if(!omitModuleCheck && !this["isXDomain"]){
+		// pass in false so we can give better error
+		module = this.findModule(moduleName, false);
+		if(!module){
+			dojo.raise("symbol '" + moduleName + "' is not defined after loading '" + relpath + "'"); 
+		}
+	}
+
+	return module;
+}
+
+dojo.hostenv.startPackage = function(/*String*/packageName){
+// summary:
+//	Creates a JavaScript package
+//
+// description:
+//	startPackage("A.B") follows the path, and at each level creates a new empty
+//	object or uses what already exists. It returns the result.
+//
+// packageName: the package to be created as a String in dot notation
+
+	//Make sure we have a string.
+	var fullPkgName = String(packageName);
+	var strippedPkgName = fullPkgName;
+
+	var syms = packageName.split(/\./);
+	if(syms[syms.length-1]=="*"){
+		syms.pop();
+		strippedPkgName = syms.join(".");
+	}
+	var evaledPkg = dojo.evalObjPath(strippedPkgName, true);
+	this.loaded_modules_[fullPkgName] = evaledPkg;
+	this.loaded_modules_[strippedPkgName] = evaledPkg;
+	
+	return evaledPkg; // Object
+}
+
+dojo.hostenv.findModule = function(/*String*/moduleName, /*Boolean?*/mustExist){
+// summary:
+//	Returns the Object representing the module, if it exists, otherwise null.
+//
+// moduleName A fully qualified module including package name, like 'A.B'.
+// mustExist Optional, default false. throw instead of returning null
+//	if the module does not currently exist.
+
+	var lmn = String(moduleName);
+
+	if(this.loaded_modules_[lmn]){
+		return this.loaded_modules_[lmn]; // Object
+	}
+
+	if(mustExist){
+		dojo.raise("no loaded module named '" + moduleName + "'");
+	}
+	return null; // null
+}
+
+//Start of old bootstrap2:
+
+dojo.kwCompoundRequire = function(/*Object containing Arrays*/modMap){
+// description:
+//	This method taks a "map" of arrays which one can use to optionally load dojo
+//	modules. The map is indexed by the possible dojo.hostenv.name_ values, with
+//	two additional values: "default" and "common". The items in the "default"
+//	array will be loaded if none of the other items have been choosen based on
+//	the hostenv.name_ item. The items in the "common" array will _always_ be
+//	loaded, regardless of which list is chosen.  Here's how it's normally
+//	called:
+//	
+//	dojo.kwCompoundRequire({
+//		browser: [
+//			["foo.bar.baz", true, true], // an example that passes multiple args to loadModule()
+//			"foo.sample.*",
+//			"foo.test,
+//		],
+//		default: [ "foo.sample.*" ],
+//		common: [ "really.important.module.*" ]
+//	});
+
+	var common = modMap["common"]||[];
+	var result = modMap[dojo.hostenv.name_] ? common.concat(modMap[dojo.hostenv.name_]||[]) : common.concat(modMap["default"]||[]);
+
+	for(var x=0; x<result.length; x++){
+		var curr = result[x];
+		if(curr.constructor == Array){
+			dojo.hostenv.loadModule.apply(dojo.hostenv, curr);
+		}else{
+			dojo.hostenv.loadModule(curr);
+		}
+	}
+}
+
+dojo.require = function(/*String*/ resourceName){
+	// summary
+	//	Ensure that the given resource (ie, javascript
+	//	source file) has been loaded.
+	// description
+	//	dojo.require() is similar to C's #include command or java's "import" command.
+	//	You call dojo.require() to pull in the resources (ie, javascript source files)
+	//	that define the functions you are using. 
+	//
+	//	Note that in the case of a build, many resources have already been included
+	//	into dojo.js (ie, many of the javascript source files have been compressed and
+	//	concatened into dojo.js), so many dojo.require() calls will simply return
+	//	without downloading anything.
+	dojo.hostenv.loadModule.apply(dojo.hostenv, arguments);
+}
+
+dojo.requireIf = function(/*Boolean*/ condition, /*String*/ resourceName){
+	// summary
+	//	If the condition is true then call dojo.require() for the specified resource
+	var arg0 = arguments[0];
+	if((arg0 === true)||(arg0=="common")||(arg0 && dojo.render[arg0].capable)){
+		var args = [];
+		for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); }
+		dojo.require.apply(dojo, args);
+	}
+}
+
+dojo.requireAfterIf = dojo.requireIf;
+
+dojo.provide = function(/*String*/ resourceName){
+	// summary
+	//	Each javascript source file must have (exactly) one dojo.provide()
+	//	call at the top of the file, corresponding to the file name.
+	//	For example, dojo/src/foo.js must have dojo.provide("dojo.foo"); at the top of the file.
+	//
+	// description
+	//	Each javascript source file is called a resource.  When a resource
+	//	is loaded by the browser, dojo.provide() registers that it has
+	//	been loaded.
+	//	
+	//	For backwards compatibility reasons, in addition to registering the resource,
+	//	dojo.provide() also ensures that the javascript object for the module exists.  For
+	//	example, dojo.provide("dojo.html.common"), in addition to registering that common.js
+	//	is a resource for the dojo.html module, will ensure that the dojo.html javascript object
+	//	exists, so that calls like dojo.html.foo = function(){ ... } don't fail.
+	//
+	//	In the case of a build (or in the future, a rollup), where multiple javascript source
+	//	files are combined into one bigger file (similar to a .lib or .jar file), that file
+	//	will contain multiple dojo.provide() calls, to note that it includes
+	//	multiple resources.
+	return dojo.hostenv.startPackage.apply(dojo.hostenv, arguments);
+}
+
+dojo.registerModulePath = function(/*String*/module, /*String*/prefix){
+	// summary: maps a module name to a path
+	// description: An unregistered module is given the default path of ../<module>,
+	//	relative to Dojo root. For example, module acme is mapped to ../acme.
+	//	If you want to use a different module name, use dojo.registerModulePath. 
+	return dojo.hostenv.setModulePrefix(module, prefix);
+}
+
+dojo.setModulePrefix = function(/*String*/module, /*String*/prefix){
+	// summary: maps a module name to a path
+	dojo.deprecated('dojo.setModulePrefix("' + module + '", "' + prefix + '")', "replaced by dojo.registerModulePath", "0.5");
+	return dojo.registerModulePath(module, prefix);
+}
+
+dojo.exists = function(/*Object*/obj, /*String*/name){
+	// summary: determine if an object supports a given method
+	// description: useful for longer api chains where you have to test each object in the chain
+	var p = name.split(".");
+	for(var i = 0; i < p.length; i++){
+		if(!obj[p[i]]){ return false; } // Boolean
+		obj = obj[p[i]];
+	}
+	return true; // Boolean
+}
+
+// Localization routines
+
+dojo.hostenv.normalizeLocale = function(/*String?*/locale){
+//	summary:
+//		Returns canonical form of locale, as used by Dojo.  All variants are case-insensitive and are separated by '-'
+//		as specified in RFC 3066. If no locale is specified, the user agent's default is returned.
+
+	var result = locale ? locale.toLowerCase() : dojo.locale;
+	if(result == "root"){
+		result = "ROOT";
+	}
+	return result;// String
+};
+
+dojo.hostenv.searchLocalePath = function(/*String*/locale, /*Boolean*/down, /*Function*/searchFunc){
+//	summary:
+//		A helper method to assist in searching for locale-based resources.  Will iterate through
+//		the variants of a particular locale, either up or down, executing a callback function.
+//		For example, "en-us" and true will try "en-us" followed by "en" and finally "ROOT".
+
+	locale = dojo.hostenv.normalizeLocale(locale);
+
+	var elements = locale.split('-');
+	var searchlist = [];
+	for(var i = elements.length; i > 0; i--){
+		searchlist.push(elements.slice(0, i).join('-'));
+	}
+	searchlist.push(false);
+	if(down){searchlist.reverse();}
+
+	for(var j = searchlist.length - 1; j >= 0; j--){
+		var loc = searchlist[j] || "ROOT";
+		var stop = searchFunc(loc);
+		if(stop){ break; }
+	}
+}
+
+//These two functions are placed outside of preloadLocalizations
+//So that the xd loading can use/override them.
+dojo.hostenv.localesGenerated /***BUILD:localesGenerated***/; // value will be inserted here at build time, if necessary
+
+dojo.hostenv.registerNlsPrefix = function(){
+// summary:
+//	Register module "nls" to point where Dojo can find pre-built localization files
+	dojo.registerModulePath("nls","nls");	
+}
+
+dojo.hostenv.preloadLocalizations = function(){
+// summary:
+//	Load built, flattened resource bundles, if available for all locales used in the page.
+//	Execute only once.  Note that this is a no-op unless there is a build.
+
+	if(dojo.hostenv.localesGenerated){
+		dojo.hostenv.registerNlsPrefix();
+
+		function preload(locale){
+			locale = dojo.hostenv.normalizeLocale(locale);
+			dojo.hostenv.searchLocalePath(locale, true, function(loc){
+				for(var i=0; i<dojo.hostenv.localesGenerated.length;i++){
+					if(dojo.hostenv.localesGenerated[i] == loc){
+						dojo["require"]("nls.dojo_"+loc);
+						return true; // Boolean
+					}
+				}
+				return false; // Boolean
+			});
+		}
+		preload();
+		var extra = djConfig.extraLocale||[];
+		for(var i=0; i<extra.length; i++){
+			preload(extra[i]);
+		}
+	}
+	dojo.hostenv.preloadLocalizations = function(){};
+}
+
+dojo.requireLocalization = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale, /*String?*/availableFlatLocales){
+// summary:
+//	Declares translated resources and loads them if necessary, in the same style as dojo.require.
+//	Contents of the resource bundle are typically strings, but may be any name/value pair,
+//	represented in JSON format.  See also dojo.i18n.getLocalization.
+//
+// moduleName: name of the package containing the "nls" directory in which the bundle is found
+// bundleName: bundle name, i.e. the filename without the '.js' suffix
+// locale: the locale to load (optional)  By default, the browser's user locale as defined by dojo.locale
+// availableFlatLocales: A comma-separated list of the available, flattened locales for this bundle.
+// This argument should only be set by the build process.
+//
+// description:
+//	Load translated resource bundles provided underneath the "nls" directory within a package.
+//	Translated resources may be located in different packages throughout the source tree.  For example,
+//	a particular widget may define one or more resource bundles, structured in a program as follows,
+//	where moduleName is mycode.mywidget and bundleNames available include bundleone and bundletwo:
+//	...
+//	mycode/
+//	 mywidget/
+//	  nls/
+//	   bundleone.js (the fallback translation, English in this example)
+//	   bundletwo.js (also a fallback translation)
+//	   de/
+//	    bundleone.js
+//	    bundletwo.js
+//	   de-at/
+//	    bundleone.js
+//	   en/
+//	    (empty; use the fallback translation)
+//	   en-us/
+//	    bundleone.js
+//	   en-gb/
+//	    bundleone.js
+//	   es/
+//	    bundleone.js
+//	    bundletwo.js
+//	  ...etc
+//	...
+//	Each directory is named for a locale as specified by RFC 3066, (http://www.ietf.org/rfc/rfc3066.txt),
+//	normalized in lowercase.  Note that the two bundles in the example do not define all the same variants.
+//	For a given locale, bundles will be loaded for that locale and all more general locales above it, including
+//	a fallback at the root directory.  For example, a declaration for the "de-at" locale will first
+//	load nls/de-at/bundleone.js, then nls/de/bundleone.js and finally nls/bundleone.js.  The data will
+//	be flattened into a single Object so that lookups will follow this cascading pattern.  An optional build
+//	step can preload the bundles to avoid data redundancy and the multiple network hits normally required to
+//	load these resources.
+
+	dojo.hostenv.preloadLocalizations();
+	var targetLocale = dojo.hostenv.normalizeLocale(locale);
+ 	var bundlePackage = [moduleName, "nls", bundleName].join(".");
+//NOTE: When loading these resources, the packaging does not match what is on disk.  This is an
+// implementation detail, as this is just a private data structure to hold the loaded resources.
+// e.g. tests/hello/nls/en-us/salutations.js is loaded as the object tests.hello.nls.salutations.en_us={...}
+// The structure on disk is intended to be most convenient for developers and translators, but in memory
+// it is more logical and efficient to store in a different order.  Locales cannot use dashes, since the
+// resulting path will not evaluate as valid JS, so we translate them to underscores.
+	
+	//Find the best-match locale to load if we have available flat locales.
+	var bestLocale = "";
+	if(availableFlatLocales){
+		var flatLocales = availableFlatLocales.split(",");
+		for(var i = 0; i < flatLocales.length; i++){
+			//Locale must match from start of string.
+			if(targetLocale.indexOf(flatLocales[i]) == 0){
+				if(flatLocales[i].length > bestLocale.length){
+					bestLocale = flatLocales[i];
+				}
+			}
+		}
+		if(!bestLocale){
+			bestLocale = "ROOT";
+		}		
+	}
+
+	//See if the desired locale is already loaded.
+	var tempLocale = availableFlatLocales ? bestLocale : targetLocale;
+	var bundle = dojo.hostenv.findModule(bundlePackage);
+	var localizedBundle = null;
+	if(bundle){
+		if(djConfig.localizationComplete && bundle._built){return;}
+		var jsLoc = tempLocale.replace('-', '_');
+		var translationPackage = bundlePackage+"."+jsLoc;
+		localizedBundle = dojo.hostenv.findModule(translationPackage);
+	}
+
+	if(!localizedBundle){
+		bundle = dojo.hostenv.startPackage(bundlePackage);
+		var syms = dojo.hostenv.getModuleSymbols(moduleName);
+		var modpath = syms.concat("nls").join("/");
+		var parent;
+
+		dojo.hostenv.searchLocalePath(tempLocale, availableFlatLocales, function(loc){
+			var jsLoc = loc.replace('-', '_');
+			var translationPackage = bundlePackage + "." + jsLoc;
+			var loaded = false;
+			if(!dojo.hostenv.findModule(translationPackage)){
+				// Mark loaded whether it's found or not, so that further load attempts will not be made
+				dojo.hostenv.startPackage(translationPackage);
+				var module = [modpath];
+				if(loc != "ROOT"){module.push(loc);}
+				module.push(bundleName);
+				var filespec = module.join("/") + '.js';
+				loaded = dojo.hostenv.loadPath(filespec, null, function(hash){
+					// Use singleton with prototype to point to parent bundle, then mix-in result from loadPath
+					var clazz = function(){};
+					clazz.prototype = parent;
+					bundle[jsLoc] = new clazz();
+					for(var j in hash){ bundle[jsLoc][j] = hash[j]; }
+				});
+			}else{
+				loaded = true;
+			}
+			if(loaded && bundle[jsLoc]){
+				parent = bundle[jsLoc];
+			}else{
+				bundle[jsLoc] = parent;
+			}
+			
+			if(availableFlatLocales){
+				//Stop the locale path searching if we know the availableFlatLocales, since
+				//the first call to this function will load the only bundle that is needed.
+				return true;
+			}
+		});
+	}
+
+	//Save the best locale bundle as the target locale bundle when we know the
+	//the available bundles.
+	if(availableFlatLocales && targetLocale != bestLocale){
+		bundle[targetLocale.replace('-', '_')] = bundle[bestLocale.replace('-', '_')];
+	}
+};
+
+(function(){
+	// If other locales are used, dojo.requireLocalization should load them as well, by default.
+	// Override dojo.requireLocalization to do load the default bundle, then iterate through the
+	// extraLocale list and load those translations as well, unless a particular locale was requested.
+
+	var extra = djConfig.extraLocale;
+	if(extra){
+		if(!extra instanceof Array){
+			extra = [extra];
+		}
+
+		var req = dojo.requireLocalization;
+		dojo.requireLocalization = function(m, b, locale, availableFlatLocales){
+			req(m,b,locale, availableFlatLocales);
+			if(locale){return;}
+			for(var i=0; i<extra.length; i++){
+				req(m,b,extra[i], availableFlatLocales);
+			}
+		};
+	}
+})();

Added: incubator/xap/trunk/codebase/src/dojo/src/loader_xd.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/loader_xd.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/loader_xd.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/loader_xd.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,548 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+//Cross-domain package loader.
+
+//FIXME: How will xd loading work with debugAtAllCosts? Any bad interactions?
+//FIXME: widgets won't work fully (HTML/CSS) and also because of the requireIf() thing.
+
+dojo.hostenv.resetXd = function(){
+	//summary: Internal xd loader function. Resets the xd state.
+
+	//This flag indicates where or not we have crossed into xdomain territory. Once any package says
+	//it is cross domain, then the rest of the packages have to be treated as xdomain because we need
+	//to evaluate packages in order. If there is a xdomain package followed by a xhr package, we can't load
+	//the xhr package until the one before it finishes loading. The text of the xhr package will be converted
+	//to match the format for a xd package and put in the xd load queue.
+	//You can force all packages to be treated as xd by setting the djConfig.forceXDomain.
+	this.isXDomain = djConfig.forceXDomain || false;
+
+	this.xdTimer = 0;
+	this.xdInFlight = {};
+	this.xdOrderedReqs = [];
+	this.xdDepMap = {};
+	this.xdContents = [];
+}
+
+//Call reset immediately to set the state.
+dojo.hostenv.resetXd();
+
+dojo.hostenv.createXdPackage = function(/*String*/contents){
+	//summary: Internal xd loader function. Creates an xd module source given an
+	//non-xd module contents.
+
+	//Find dependencies.
+	var deps = [];
+    var depRegExp = /dojo.(require|requireIf|requireAll|provide|requireAfterIf|requireAfter|kwCompoundRequire|conditionalRequire|hostenv\.conditionalLoadModule|.hostenv\.loadModule|hostenv\.moduleLoaded)\(([\w\W]*?)\)/mg;
+    var match;
+	while((match = depRegExp.exec(contents)) != null){
+		deps.push("\"" + match[1] + "\", " + match[2]);
+	}
+
+	//Create package object and the call to packageLoaded.
+	var output = [];
+	output.push("dojo.hostenv.packageLoaded({\n");
+
+	//Add dependencies
+	if(deps.length > 0){
+		output.push("depends: [");
+		for(var i = 0; i < deps.length; i++){
+			if(i > 0){
+				output.push(",\n");
+			}
+			output.push("[" + deps[i] + "]");
+		}
+		output.push("],");
+	}
+
+	//Add the contents of the file inside a function.
+	//Pass in dojo as an argument to the function to help with
+	//allowing multiple versions of dojo in a page.
+	output.push("\ndefinePackage: function(dojo){");
+	output.push(contents);
+	output.push("\n}});");
+	
+	return output.join(""); //String
+}
+
+dojo.hostenv.loadPath = function(/*String*/relpath, /*String?*/module, /*Function?*/cb){
+	//summary: Internal xd loader function. Overrides loadPath() from loader.js.
+	//xd loading requires slightly different behavior from loadPath().
+
+
+	//Only do getBaseScriptUri if path does not start with a URL with a protocol.
+	//If there is a colon before the first / then, we have a URL with a protocol.
+	var colonIndex = relpath.indexOf(":");
+	var slashIndex = relpath.indexOf("/");
+	var uri;
+	var currentIsXDomain = false;
+	if(colonIndex > 0 && colonIndex < slashIndex){
+		uri = relpath;
+		this.isXDomain = currentIsXDomain = true;
+	}else{
+		uri = this.getBaseScriptUri() + relpath;
+
+		//Is ithe base script URI-based URL a cross domain URL?
+		colonIndex = uri.indexOf(":");
+		slashIndex = uri.indexOf("/");
+		if(colonIndex > 0 && colonIndex < slashIndex && (!location.host || uri.indexOf("http://" + location.host) != 0)){
+			this.isXDomain = currentIsXDomain = true;
+		}
+	}
+
+	if(djConfig.cacheBust && dojo.render.html.capable) { uri += "?" + String(djConfig.cacheBust).replace(/\W+/g,""); }
+	try{
+		return ((!module || this.isXDomain) ? this.loadUri(uri, cb, currentIsXDomain, module) : this.loadUriAndCheck(uri, module, cb)); //boolean
+	}catch(e){
+		dojo.debug(e);
+		return false; //boolean
+	}
+}
+
+dojo.hostenv.loadUri = function(/*String*/uri, /*Function?*/cb, /*boolean*/currentIsXDomain, /*String?*/module){
+	//summary: Internal xd loader function. Overrides loadUri() from loader.js.
+	//		xd loading requires slightly different behavior from loadPath().
+	//description: Wanted to override getText(), but it is used by
+	//		the widget code in too many, synchronous ways right now.
+	if(this.loadedUris[uri]){
+		return 1; //boolean
+	}
+
+	//Add the module (package) to the list of modules.
+	if(this.isXDomain){
+		//Curious: is this array going to get whacked with multiple access since scripts
+		//load asynchronously and may be accessing the array at the same time?
+		//JS is single-threaded supposedly, so it should be ok. And we don't need
+		//a precise ordering.
+		this.xdOrderedReqs.push(module);
+
+		//Add to waiting packages.
+		//If this is a __package__.js file, then this must be
+		//a package.* request (since xdomain can only work with the first
+		//path in a package search list. However, .* module names are not
+		//passed to this function, so do an adjustment here.
+		if(uri.indexOf("__package__") != -1){
+			module += ".*";
+		}
+
+		this.xdInFlight[module] = true;
+
+		//Increment inFlightCount
+		//This will stop the modulesLoaded from firing all the way.
+		this.inFlightCount++;
+				
+		//Start timer
+		if(!this.xdTimer){
+			this.xdTimer = setInterval("dojo.hostenv.watchInFlightXDomain();", 100);
+		}
+		this.xdStartTime = (new Date()).getTime();
+	}
+
+	if (currentIsXDomain){
+		//Fix name to be a .xd.fileextension name.
+		var lastIndex = uri.lastIndexOf('.');
+		if(lastIndex <= 0){
+			lastIndex = uri.length - 1;
+		}
+
+		var xdUri = uri.substring(0, lastIndex) + ".xd";
+		if(lastIndex != uri.length - 1){
+			xdUri += uri.substring(lastIndex, uri.length);
+		}
+
+		//Add to script src
+		var element = document.createElement("script");
+		element.type = "text/javascript";
+		element.src = xdUri;
+		if(!this.headElement){
+			this.headElement = document.getElementsByTagName("head")[0];
+		}
+		this.headElement.appendChild(element);
+	}else{
+		var contents = this.getText(uri, null, true);
+		if(contents == null){ return 0; /*boolean*/}
+		
+		if(this.isXDomain){
+			var pkg = this.createXdPackage(contents);
+			dj_eval(pkg);
+		}else{
+			if(cb){ contents = '('+contents+')'; }
+			var value = dj_eval(contents);
+			if(cb){
+				cb(value);
+			}
+		}
+	}
+
+	//These steps are done in the non-xd loader version of this function.
+	//Maintain these steps to fit in with the existing system.
+	this.loadedUris[uri] = true;
+	return 1; //boolean
+}
+
+dojo.hostenv.packageLoaded = function(/*Object*/pkg){
+	//summary: Internal xd loader function. Called by an xd module when
+	//it has been loaded via a script tag.
+	var deps = pkg.depends;
+	var requireList = null;
+	var requireAfterList = null;
+	var provideList = [];
+	if(deps && deps.length > 0){
+		var dep = null;
+		var insertHint = 0;
+		var attachedPackage = false;
+		for(var i = 0; i < deps.length; i++){
+			dep = deps[i];
+
+			//Look for specific dependency indicators.
+			if (dep[0] == "provide" || dep[0] == "hostenv.moduleLoaded"){
+				provideList.push(dep[1]);
+			}else{
+				if(!requireList){
+					requireList = [];
+				}
+				if(!requireAfterList){
+					requireAfterList = [];
+				}
+
+				var unpackedDeps = this.unpackXdDependency(dep);
+				if(unpackedDeps.requires){
+					requireList = requireList.concat(unpackedDeps.requires);
+				}
+				if(unpackedDeps.requiresAfter){
+					requireAfterList = requireAfterList.concat(unpackedDeps.requiresAfter);
+				}
+			}
+
+			//Call the dependency indicator to allow for the normal dojo setup.
+			//Only allow for one dot reference, for the hostenv.* type calls.
+			var depType = dep[0];
+			var objPath = depType.split(".");
+			if(objPath.length == 2){
+				dojo[objPath[0]][objPath[1]].apply(dojo[objPath[0]], dep.slice(1));
+			}else{
+				dojo[depType].apply(dojo, dep.slice(1));
+			}
+		}
+
+		//Save off the package contents for definition later.
+		var contentIndex = this.xdContents.push({content: pkg.definePackage, isDefined: false}) - 1;
+
+		//Add provide/requires to dependency map.
+		for(var i = 0; i < provideList.length; i++){
+			this.xdDepMap[provideList[i]] = { requires: requireList, requiresAfter: requireAfterList, contentIndex: contentIndex };
+		}
+
+		//Now update the inflight status for any provided packages in this loaded package.
+		//Do this at the very end (in a *separate* for loop) to avoid shutting down the 
+		//inflight timer check too soon.
+		for(var i = 0; i < provideList.length; i++){
+			this.xdInFlight[provideList[i]] = false;
+		}
+	}
+}
+
+dojo.hostenv.xdLoadFlattenedBundle = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale, /*Object*/bundleData){
+	//summary: Internal xd loader function. Used when loading
+	//a flattened localized bundle via a script tag.
+	locale = locale || "root";
+	var jsLoc = dojo.hostenv.normalizeLocale(locale).replace('-', '_');
+ 	var bundlePackage = [moduleName, "nls", bundleName].join(".");
+	var bundle = dojo.hostenv.startPackage(bundlePackage);
+	bundle[jsLoc] = bundleData;
+	
+	//Assign the bundle for the original locale(s) we wanted.
+	var mapName = [moduleName, jsLoc, bundleName].join(".");
+	var bundleMap = dojo.hostenv.xdBundleMap[mapName];
+	if(bundleMap){
+		for(var param in bundleMap){
+			bundle[param] = bundleData;
+		}
+	}
+};
+
+
+dojo.hostenv.xdBundleMap = {};
+
+dojo.xdRequireLocalization = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale, /*String*/availableFlatLocales){
+	//summary: Internal xd loader function. The xd version of dojo.requireLocalization.
+	var locales = availableFlatLocales.split(",");
+	
+	//Find the best-match locale to load.
+	var jsLoc = dojo.hostenv.normalizeLocale(locale);
+
+	var bestLocale = "";
+	for(var i = 0; i < locales.length; i++){
+		//Locale must match from start of string.
+		if(jsLoc.indexOf(locales[i]) == 0){
+			if(locales[i].length > bestLocale.length){
+				bestLocale = locales[i];
+			}
+		}
+	}
+
+	var fixedBestLocale = bestLocale.replace('-', '_');
+	//See if the bundle we are going to use is already loaded.
+ 	var bundlePackage = dojo.evalObjPath([moduleName, "nls", bundleName].join("."));
+	if(bundlePackage && bundlePackage[fixedBestLocale]){
+		bundle[jsLoc.replace('-', '_')] = bundlePackage[fixedBestLocale];
+	}else{
+		//Need to remember what locale we wanted and which one we actually use.
+		//Then when we load the one we are actually using, use that bundle for the one
+		//we originally wanted.
+		var mapName = [moduleName, (fixedBestLocale||"root"), bundleName].join(".");
+		var bundleMap = dojo.hostenv.xdBundleMap[mapName];
+		if(!bundleMap){
+			bundleMap = dojo.hostenv.xdBundleMap[mapName] = {};
+		}
+		bundleMap[jsLoc.replace('-', '_')] = true;
+		
+		//Do just a normal dojo.require so the package tracking stuff works as usual.
+		dojo.require(moduleName + ".nls" + (bestLocale ? "." + bestLocale : "") + "." + bundleName);
+	}
+}
+
+;(function(){
+	// Simulate the extra locale work that dojo.requireLocalization does.
+
+	var extra = djConfig.extraLocale;
+	if(extra){
+		if(!extra instanceof Array){
+			extra = [extra];
+		}
+
+		dojo._xdReqLoc = dojo.xdRequireLocalization;
+		dojo.xdRequireLocalization = function(m, b, locale, fLocales){
+			dojo._xdReqLoc(m,b,locale, fLocales);
+			if(locale){return;}
+			for(var i=0; i<extra.length; i++){
+				dojo._xdReqLoc(m,b,extra[i], fLocales);
+			}
+		};
+	}
+})();
+
+
+//This is a bit brittle: it has to know about the dojo methods that deal with dependencies
+//It would be ideal to intercept the actual methods and do something fancy at that point,
+//but I have concern about knowing which provide to match to the dependency in that case,
+//since scripts can load whenever they want, and trigger new calls to dojo.hostenv.packageLoaded().
+dojo.hostenv.unpackXdDependency = function(dep){
+	//summary: Internal xd loader function. Determines what to do with a dependency
+	//that was listed in an xd version of a module contents.
+
+	//Extract the dependency(ies).
+	var newDeps = null;
+	var newAfterDeps = null;
+	switch(dep[0]){
+		case "requireIf":
+		case "requireAfterIf":
+		case "conditionalRequire":
+			//First arg (dep[1]) is the test. Depedency is dep[2].
+			if((dep[1] === true)||(dep[1]=="common")||(dep[1] && dojo.render[dep[1]].capable)){
+				newDeps = [{name: dep[2], content: null}];
+			}
+			break;
+		case "requireAll":
+			//the arguments are an array, each element a call to require.
+			//Get rid of first item, which is "requireAll".
+			dep.shift();
+			newDeps = dep;
+			dojo.hostenv.flattenRequireArray(newDeps);
+			break;
+		case "kwCompoundRequire":
+		case "hostenv.conditionalLoadModule":
+			var modMap = dep[1];
+			var common = modMap["common"]||[];
+			var newDeps = (modMap[dojo.hostenv.name_]) ? common.concat(modMap[dojo.hostenv.name_]||[]) : common.concat(modMap["default"]||[]);	
+			dojo.hostenv.flattenRequireArray(newDeps);
+			break;
+		case "require":
+		case "requireAfter":
+		case "hostenv.loadModule":
+			//Just worry about dep[1]
+			newDeps = [{name: dep[1], content: null}];
+			break;
+	}
+
+	//The requireAfterIf or requireAfter needs to be evaluated after the current package is evaluated.
+	if(dep[0] == "requireAfterIf"){
+		newAfterDeps = newDeps;
+		newDeps = null;
+	}
+	return {requires: newDeps, requiresAfter: newAfterDeps}; //Object
+}
+
+dojo.hostenv.xdWalkReqs = function(){
+	//summary: Internal xd loader function. 
+	//Walks the requires and evaluates package contents in
+	//the right order.
+	var reqChain = null;
+	var req;
+	for(var i = 0; i < this.xdOrderedReqs.length; i++){
+		req = this.xdOrderedReqs[i];
+		if(this.xdDepMap[req]){
+			reqChain = [req];
+			reqChain[req] = true; //Allow for fast lookup of the req in the array
+			this.xdEvalReqs(reqChain);
+		}
+	}
+}
+
+dojo.hostenv.xdTraceReqs = function(/*Object*/reqs, /*Array*/reqChain){
+	//summary: Internal xd loader function. 
+	//Trace the requires to chain the correct order of required modules.
+	if(reqs && reqs.length > 0){
+		var nextReq;
+		for(var i = 0; i < reqs.length; i++){
+			nextReq = reqs[i].name;
+			if(nextReq && !reqChain[nextReq]){
+				//New req depedency. Follow it down.
+				reqChain.push(nextReq);
+				reqChain[nextReq] = true;
+				this.xdEvalReqs(reqChain);
+			}
+		}
+	}
+}
+
+dojo.hostenv.xdEvalReqs = function(/*Array*/reqChain){
+	//summary: Internal xd loader function. 
+	//Does a depth first, breadth second search and eval of required modules.
+	if(reqChain.length > 0){
+		var req = reqChain[reqChain.length - 1];
+		var pkg = this.xdDepMap[req];
+		if(pkg){
+			//Trace down any requires for this package.
+			this.xdTraceReqs(pkg.requires, reqChain);
+
+			//Evaluate the package.
+			var contents = this.xdContents[pkg.contentIndex];
+			if(!contents.isDefined){
+				//Evaluate the package to bring it into being.
+				//Pass dojo in so that later, to support multiple versions of dojo
+				//in a page, we can pass which version of dojo to use.
+				contents.content(dojo);
+				contents.isDefined = true;
+			}
+			this.xdDepMap[req] = null;
+
+			//Trace down any requireAfters for this package..
+			this.xdTraceReqs(pkg.requiresAfter, reqChain);
+		}
+
+		//Done with that require. Remove it and go to the next one.
+		reqChain.pop();
+		this.xdEvalReqs(reqChain);
+	}
+}
+
+dojo.hostenv.clearXdInterval = function(){
+	//summary: Internal xd loader function.
+	//Clears the interval timer used to check on the
+	//status of in-flight xd module resource requests.
+	clearInterval(this.xdTimer);
+	this.xdTimer = 0;
+}
+
+dojo.hostenv.watchInFlightXDomain = function(){
+	//summary: Internal xd loader function.
+	//Monitors in-flight requests for xd module resources.
+
+	//Make sure we haven't waited timed out.
+	var waitInterval = (djConfig.xdWaitSeconds || 30) * 1000;
+
+	if(this.xdStartTime + waitInterval < (new Date()).getTime()){
+		this.clearXdInterval();
+		var noLoads = "";
+		for(var param in this.xdInFlight){
+			if(this.xdInFlight[param]){
+				noLoads += param + " ";
+			}
+		}
+		dojo.raise("Could not load cross-domain packages: " + noLoads);
+	}
+
+	//If any are true, then still waiting.
+	//Come back later.	
+	for(var param in this.xdInFlight){
+		if(this.xdInFlight[param]){
+			return;
+		}
+	}
+
+	//All done loading. Clean up and notify that we are loaded.
+	this.clearXdInterval();
+
+	this.xdWalkReqs();
+
+	//Evaluate any packages that were not evaled before.
+	//This normally shouldn't happen with proper dojo.provide and dojo.require
+	//usage, but providing it just in case. Note that these may not be executed
+	//in the original order that the developer intended.
+	//Pass dojo in so that later, to support multiple versions of dojo
+	//in a page, we can pass which version of dojo to use.
+	for(var i = 0; i < this.xdContents.length; i++){
+		var current = this.xdContents[i];
+		if(current.content && !current.isDefined){
+			current.content(dojo);
+		}
+	}
+
+	//Clean up for the next round of xd loading.
+	this.resetXd();
+
+	//Clear inflight count so we will finally do finish work.
+	this.inFlightCount = 0; 
+	this.callLoaded();
+}
+
+dojo.hostenv.flattenRequireArray = function(/*Array*/target){
+	//summary: Internal xd loader function.
+	//Flattens an array of arrays into a one-level deep array.
+
+	//Each result could be an array of 3 elements  (the 3 arguments to dojo.require).
+	//We only need the first one.
+	if(target){
+		for(var i = 0; i < target.length; i++){
+			if(target[i] instanceof Array){
+				target[i] = {name: target[i][0], content: null};
+			}else{
+				target[i] = {name: target[i], content: null};
+			}
+		}
+	}
+}
+
+
+dojo.hostenv.xdHasCalledPreload = false;
+dojo.hostenv.xdRealCallLoaded = dojo.hostenv.callLoaded;
+dojo.hostenv.callLoaded = function(){
+	//summary: Internal xd loader function. Overrides callLoaded() from loader.js
+	//description: The method is overridden because xd loading needs to preload 
+	//any flattened i18n bundles before dojo starts executing code, 
+	//since xd loading cannot do it synchronously, as the i18n code normally expects.
+
+	//If getModulePrefix for dojo returns anything other than "src", that means
+	//there is a path registered for dojo, with implies that dojo was xdomain loaded.
+	if(this.xdHasCalledPreload || dojo.hostenv.getModulePrefix("dojo") == "src" || !this.localesGenerated){
+		this.xdRealCallLoaded();
+		this.xdHasCalledPreload = true;
+	}else{
+		if(this.localesGenerated){
+			this.registerNlsPrefix = function(){
+				//Need to set the nls prefix to be the xd location.
+				dojo.registerModulePath("nls", dojo.hostenv.getModulePrefix("dojo") + "/../nls");	
+			};
+			this.preloadLocalizations();
+		}
+		this.xdHasCalledPreload = true;
+	}
+}

Added: incubator/xap/trunk/codebase/src/dojo/src/logging/ConsoleLogger.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/logging/ConsoleLogger.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/logging/ConsoleLogger.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/logging/ConsoleLogger.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,108 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.provide("dojo.logging.ConsoleLogger");
+dojo.require("dojo.logging.Logger");
+
+dojo.lang.extend(dojo.logging.MemoryLogHandler,{
+	
+	debug:function(){
+		dojo.hostenv.println.apply(this,arguments);
+	},
+	info:function(){
+		dojo.hostenv.println.apply(this,arguments);
+	},
+	warn:function(){
+		dojo.hostenv.println.apply(this,arguments);
+	},
+	error:function(){
+		dojo.hostenv.println.apply(this,arguments);
+	},
+	critical:function(){
+		dojo.hostenv.println.apply(this,arguments);
+	},
+	
+	emit:function(record){
+		if (!djConfig.isDebug) { return; }
+		
+		var funcName=null;
+		switch(record.level){
+			case 1:
+				funcName="debug";
+				break;
+			case 2:
+				funcName="info";
+				break;
+			case 3:
+				funcName="warn";
+				break;
+			case 4:
+				funcName="error";
+				break;
+			case 5:
+				funcName="critical";
+				break;
+			default:
+				funcName="debug";
+		}
+		
+		var logStr = String(dojo.log.getLevelName(record.level)+": "
+					+record.time.toLocaleTimeString())+": "+record.message;
+		if(record.msgArgs && record.msgArgs.length > 0){
+			this[funcName].call(this, logStr, record.msgArgs);
+		} else {
+			this[funcName].call(this, logStr);
+		}
+		
+		this.data.push(record);
+		if(this.numRecords != -1){
+			while(this.data.length>this.numRecords){
+				this.data.shift();
+			}
+		}
+	}
+});
+
+if(!dj_undef("console") && !dj_undef("info", console)){
+	dojo.lang.extend(dojo.logging.MemoryLogHandler,{
+		debug:function(){
+			console.debug.apply(this, arguments);
+		},
+		info:function(){
+			console.info.apply(this, arguments);
+		},
+		warn:function(){
+			console.warn.apply(this, arguments);
+		},
+		error:function(){
+			console.error.apply(this, arguments);
+		},
+		critical:function(){
+			console.error.apply(this, arguments);
+		}
+	});
+
+	dojo.lang.extend(dojo.logging.Logger,{
+		exception: function(msg, e, squelch){
+			var args=[msg];
+			
+			if(e){
+				msg+=" : "+ e.name + " " + (e.description||e.message);
+				args.push(e);
+			}
+			
+			this.logType("ERROR", args);
+			if(!squelch){
+				throw e;
+			}
+		}
+	});
+
+}

Added: incubator/xap/trunk/codebase/src/dojo/src/logging/Logger.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/logging/Logger.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/logging/Logger.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/logging/Logger.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,474 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.provide("dojo.logging.Logger");
+dojo.provide("dojo.logging.LogFilter");
+dojo.provide("dojo.logging.Record");
+dojo.provide("dojo.log");
+dojo.require("dojo.lang.common");
+dojo.require("dojo.lang.declare");
+
+/*		This is the dojo logging facility, which is imported from nWidgets
+		(written by Alex Russell, CLA on file), which is patterned on the
+		Python logging module, which in turn has been heavily influenced by
+		log4j (execpt with some more pythonic choices, which we adopt as well).
+
+		While the dojo logging facilities do provide a set of familiar
+		interfaces, many of the details are changed to reflect the constraints
+		of the browser environment. Mainly, file and syslog-style logging
+		facilites are not provided, with HTTP POST and GET requests being the
+		only ways of getting data from the browser back to a server. Minimal
+		support for this (and XML serialization of logs) is provided, but may
+		not be of practical use in a deployment environment.
+
+		The Dojo logging classes are agnostic of any environment, and while
+		default loggers are provided for browser-based interpreter
+		environments, this file and the classes it define are explicitly
+		designed to be portable to command-line interpreters and other
+		ECMA-262v3 envrionments.
+
+	the logger needs to accomidate:
+		log "levels"
+		type identifiers
+		file?
+		message
+		tic/toc?
+
+	The logger should ALWAYS record:
+		time/date logged
+		message
+		type
+		level
+*/
+// TODO: define DTD for XML-formatted log messages
+// TODO: write XML Formatter class
+// TODO: write HTTP Handler which uses POST to send log lines/sections
+
+
+dojo.logging.Record = function(/*Integer*/logLevel, /*String||Array*/message){
+	// summary:
+	//		A simple data structure class that stores information for and about
+	//		a logged event. Objects of this type are created automatically when
+	//		an event is logged and are the internal format in which information
+	//		about log events is kept.
+	// logLevel:
+	//		Integer mapped via the dojo.logging.log.levels object from a
+	//		string. This mapping also corresponds to an instance of
+	//		dojo.logging.Logger
+	// message:
+	//		The contents of the message represented by this log record.
+	this.level = logLevel;
+	this.message = "";
+	this.msgArgs = [];
+	this.time = new Date();
+	
+	if(dojo.lang.isArray(message)){
+		if(message.length > 0 && dojo.lang.isString(message[0])){
+			this.message=message.shift();
+		}
+		this.msgArgs = message;
+	}else{
+		this.message = message;
+	}
+	// FIXME: what other information can we receive/discover here?
+}
+
+dojo.logging.LogFilter = function(loggerChain){
+	// summary:
+	//		An empty parent (abstract) class which concrete filters should
+	//		inherit from. Filters should have only a single method, filter(),
+	//		which processes a record and returns true or false to denote
+	//		whether or not it should be handled by the next step in a filter
+	//		chain.
+	this.passChain = loggerChain || "";
+	this.filter = function(record){
+		// FIXME: need to figure out a way to enforce the loggerChain
+		// restriction
+		return true; // pass all records
+	}
+}
+
+dojo.logging.Logger = function(){
+	this.cutOffLevel = 0;
+	this.propagate = true;
+	this.parent = null;
+	// storage for dojo.logging.Record objects seen and accepted by this logger
+	this.data = [];
+	this.filters = [];
+	this.handlers = [];
+}
+
+dojo.extend(dojo.logging.Logger,{
+	_argsToArr: function(args){
+		var ret = [];
+		for(var x=0; x<args.length; x++){
+			ret.push(args[x]);
+		}
+		return ret;
+	},
+
+	setLevel: function(/*Integer*/lvl){
+		// summary: 
+		//		set the logging level for this logger.
+		// lvl:
+		//		the logging level to set the cutoff for, as derived from the
+		//		dojo.logging.log.levels object. Any messages below the
+		//		specified level are dropped on the floor
+		this.cutOffLevel = parseInt(lvl);
+	},
+
+	isEnabledFor: function(/*Integer*/lvl){
+		// summary:
+		//		will a message at the specified level be emitted?
+		return parseInt(lvl) >= this.cutOffLevel; // boolean
+	},
+
+	getEffectiveLevel: function(){
+		// summary:
+		//		gets the effective cutoff level, including that of any
+		//		potential parent loggers in the chain.
+		if((this.cutOffLevel==0)&&(this.parent)){
+			return this.parent.getEffectiveLevel(); // Integer
+		}
+		return this.cutOffLevel; // Integer
+	},
+
+	addFilter: function(/*dojo.logging.LogFilter*/flt){
+		// summary:
+		//		registers a new LogFilter object. All records will be passed
+		//		through this filter from now on.
+		this.filters.push(flt);
+		return this.filters.length-1; // Integer
+	},
+
+	removeFilterByIndex: function(/*Integer*/fltIndex){
+		// summary:
+		//		removes the filter at the specified index from the filter
+		//		chain. Returns whether or not removal was successful.
+		if(this.filters[fltIndex]){
+			delete this.filters[fltIndex];
+			return true; // boolean
+		}
+		return false; // boolean
+	},
+
+	removeFilter: function(/*dojo.logging.LogFilter*/fltRef){
+		// summary:
+		//		removes the passed LogFilter. Returns whether or not removal
+		//		was successful.
+		for(var x=0; x<this.filters.length; x++){
+			if(this.filters[x]===fltRef){
+				delete this.filters[x];
+				return true;
+			}
+		}
+		return false;
+	},
+
+	removeAllFilters: function(){
+		// summary: clobbers all the registered filters.
+		this.filters = []; // clobber all of them
+	},
+
+	filter: function(/*dojo.logging.Record*/rec){
+		// summary:
+		//		runs the passed Record through the chain of registered filters.
+		//		Returns a boolean indicating whether or not the Record should
+		//		be emitted.
+		for(var x=0; x<this.filters.length; x++){
+			if((this.filters[x]["filter"])&&
+			   (!this.filters[x].filter(rec))||
+			   (rec.level<this.cutOffLevel)){
+				return false; // boolean
+			}
+		}
+		return true; // boolean
+	},
+
+	addHandler: function(/*dojo.logging.LogHandler*/hdlr){
+		// summary: adds as LogHandler to the chain
+		this.handlers.push(hdlr);
+		return this.handlers.length-1;
+	},
+
+	handle: function(/*dojo.logging.Record*/rec){
+		// summary:
+		//		if the Record survives filtering, pass it down to the
+		//		registered handlers. Returns a boolean indicating whether or
+		//		not the record was successfully handled. If the message is
+		//		culled for some reason, returns false.
+		if((!this.filter(rec))||(rec.level<this.cutOffLevel)){ return false; } // boolean
+		for(var x=0; x<this.handlers.length; x++){
+			if(this.handlers[x]["handle"]){
+			   this.handlers[x].handle(rec);
+			}
+		}
+		// FIXME: not sure what to do about records to be propagated that may have
+		// been modified by the handlers or the filters at this logger. Should
+		// parents always have pristine copies? or is passing the modified record
+		// OK?
+		// if((this.propagate)&&(this.parent)){ this.parent.handle(rec); }
+		return true; // boolean
+	},
+
+	// the heart and soul of the logging system
+	log: function(/*integer*/lvl, /*string*/msg){
+		// summary:
+		//		log a message at the specified log level
+		if(	(this.propagate)&&(this.parent)&&
+			(this.parent.rec.level>=this.cutOffLevel)){
+			this.parent.log(lvl, msg);
+			return false;
+		}
+		// FIXME: need to call logging providers here!
+		this.handle(new dojo.logging.Record(lvl, msg));
+		return true;
+	},
+
+	// logger helpers
+	debug:function(/*string*/msg){
+		// summary:
+		//		log the msg and any other arguments at the "debug" logging
+		//		level.
+		return this.logType("DEBUG", this._argsToArr(arguments));
+	},
+
+	info: function(msg){
+		// summary:
+		//		log the msg and any other arguments at the "info" logging
+		//		level.
+		return this.logType("INFO", this._argsToArr(arguments));
+	},
+
+	warning: function(msg){
+		// summary:
+		//		log the msg and any other arguments at the "warning" logging
+		//		level.
+		return this.logType("WARNING", this._argsToArr(arguments));
+	},
+
+	error: function(msg){
+		// summary:
+		//		log the msg and any other arguments at the "error" logging
+		//		level.
+		return this.logType("ERROR", this._argsToArr(arguments));
+	},
+
+	critical: function(msg){
+		// summary:
+		//		log the msg and any other arguments at the "critical" logging
+		//		level.
+		return this.logType("CRITICAL", this._argsToArr(arguments));
+	},
+
+	exception: function(/*string*/msg, /*Error*/e, /*boolean*/squelch){
+		// summary:
+		//		logs the error and the message at the "exception" logging
+		//		level. If squelch is true, also prevent bubbling of the
+		//		exception.
+
+		// FIXME: this needs to be modified to put the exception in the msg
+		// if we're on Moz, we can get the following from the exception object:
+		//		lineNumber
+		//		message
+		//		fileName
+		//		stack
+		//		name
+		// on IE, we get:
+		//		name
+		//		message (from MDA?)
+		//		number
+		//		description (same as message!)
+		if(e){
+			var eparts = [e.name, (e.description||e.message)];
+			if(e.fileName){
+				eparts.push(e.fileName);
+				eparts.push("line "+e.lineNumber);
+				// eparts.push(e.stack);
+			}
+			msg += " "+eparts.join(" : ");
+		}
+
+		this.logType("ERROR", msg);
+		if(!squelch){
+			throw e;
+		}
+	},
+
+	logType: function(/*string*/type, /*array*/args){
+		// summary:
+		//		a more "user friendly" version of the log() function. Takes the
+		//		named log level instead of the corresponding integer.
+		return this.log.apply(this, [dojo.logging.log.getLevel(type), 
+			args]);
+	},
+	
+	warn:function(){
+		// summary: shorthand for warning()
+		this.warning.apply(this,arguments);
+	},
+	err:function(){
+		// summary: shorthand for error()
+		this.error.apply(this,arguments);
+	},
+	crit:function(){
+		// summary: shorthand for critical()
+		this.critical.apply(this,arguments);
+	}
+});
+
+// the Handler class
+dojo.logging.LogHandler = function(level){
+	this.cutOffLevel = (level) ? level : 0;
+	this.formatter = null; // FIXME: default formatter?
+	this.data = [];
+	this.filters = [];
+}
+dojo.lang.extend(dojo.logging.LogHandler,{
+	
+	setFormatter:function(formatter){
+		dojo.unimplemented("setFormatter");
+	},
+	
+	flush:function(){
+		// summary:
+		//		Unimplemented. Should be implemented by subclasses to handle
+		//		finishing a transaction or otherwise comitting pending log
+		//		messages to whatevery underlying transport or storage system is
+		//		available.
+	},
+	close:function(){
+		// summary:
+		//		Unimplemented. Should be implemented by subclasses to handle
+		//		shutting down the logger, including a call to flush()
+	},
+	handleError:function(){
+		// summary:
+		//		Unimplemented. Should be implemented by subclasses.
+		dojo.deprecated("dojo.logging.LogHandler.handleError", "use handle()", "0.6");
+	},
+	
+	handle:function(/*dojo.logging.Record*/record){
+		// summary:
+		//		Emits the record object passed in should the record meet the
+		//		current logging level cuttof, as specified in cutOffLevel.
+		if((this.filter(record))&&(record.level>=this.cutOffLevel)){
+			this.emit(record);
+		}
+	},
+	
+	emit:function(/*dojo.logging.Record*/record){
+		// summary:
+		//		Unimplemented. Should be implemented by subclasses to handle
+		//		an individual record. Subclasses may batch records and send
+		//		them to their "substrate" only when flush() is called, but this
+		//		is generally not a good idea as losing logging messages may
+		//		make debugging significantly more difficult. Tuning the volume
+		//		of logging messages written to storage should be accomplished
+		//		with log levels instead.
+		dojo.unimplemented("emit");
+	}
+});
+
+// set aliases since we don't want to inherit from dojo.logging.Logger
+void(function(){ // begin globals protection closure
+	var names = [
+		"setLevel", "addFilter", "removeFilterByIndex", "removeFilter",
+		"removeAllFilters", "filter"
+	];
+	var tgt = dojo.logging.LogHandler.prototype;
+	var src = dojo.logging.Logger.prototype;
+	for(var x=0; x<names.length; x++){
+		tgt[names[x]] = src[names[x]];
+	}
+})(); // end globals protection closure
+
+dojo.logging.log = new dojo.logging.Logger();
+
+// an associative array of logger objects. This object inherits from
+// a list of level names with their associated numeric levels
+dojo.logging.log.levels = [ {"name": "DEBUG", "level": 1},
+						   {"name": "INFO", "level": 2},
+						   {"name": "WARNING", "level": 3},
+						   {"name": "ERROR", "level": 4},
+						   {"name": "CRITICAL", "level": 5} ];
+
+dojo.logging.log.loggers = {};
+
+dojo.logging.log.getLogger = function(/*string*/name){
+	// summary:
+	//		returns a named dojo.logging.Logger instance. If one is not already
+	//		available with that name in the global map, one is created and
+	//		returne.
+	if(!this.loggers[name]){
+		this.loggers[name] = new dojo.logging.Logger();
+		this.loggers[name].parent = this;
+	}
+	return this.loggers[name]; // dojo.logging.Logger
+}
+
+dojo.logging.log.getLevelName = function(/*integer*/lvl){
+	// summary: turns integer logging level into a human-friendly name
+	for(var x=0; x<this.levels.length; x++){
+		if(this.levels[x].level == lvl){
+			return this.levels[x].name; // string
+		}
+	}
+	return null;
+}
+
+dojo.logging.log.getLevel = function(/*string*/name){
+	// summary: name->integer conversion for log levels
+	for(var x=0; x<this.levels.length; x++){
+		if(this.levels[x].name.toUpperCase() == name.toUpperCase()){
+			return this.levels[x].level; // integer
+		}
+	}
+	return null;
+}
+
+// a default handler class, it simply saves all of the handle()'d records in
+// memory. Useful for attaching to with dojo.event.connect()
+
+dojo.declare("dojo.logging.MemoryLogHandler", 
+	dojo.logging.LogHandler,
+	{
+		initializer: function(level, recordsToKeep, postType, postInterval){
+			// mixin style inheritance
+			dojo.logging.LogHandler.call(this, level);
+			// default is unlimited
+			this.numRecords = (typeof djConfig['loggingNumRecords'] != 'undefined') ? djConfig['loggingNumRecords'] : ((recordsToKeep) ? recordsToKeep : -1);
+			// 0=count, 1=time, -1=don't post TODO: move this to a better location for prefs
+			this.postType = (typeof djConfig['loggingPostType'] != 'undefined') ? djConfig['loggingPostType'] : ( postType || -1);
+			// milliseconds for time, interger for number of records, -1 for non-posting,
+			this.postInterval = (typeof djConfig['loggingPostInterval'] != 'undefined') ? djConfig['loggingPostInterval'] : ( postType || -1);
+		},
+		emit: function(record){
+			if(!djConfig.isDebug){ return; }
+			var logStr = String(dojo.log.getLevelName(record.level)+": "
+						+record.time.toLocaleTimeString())+": "+record.message;
+			if(!dj_undef("println", dojo.hostenv)){
+				dojo.hostenv.println(logStr, record.msgArgs);
+			}
+			
+			this.data.push(record);
+			if(this.numRecords != -1){
+				while(this.data.length>this.numRecords){
+					this.data.shift();
+				}
+			}
+		}
+	}
+);
+
+dojo.logging.logQueueHandler = new dojo.logging.MemoryLogHandler(0,50,0,10000);
+
+dojo.logging.log.addHandler(dojo.logging.logQueueHandler);
+dojo.log = dojo.logging.log;

Added: incubator/xap/trunk/codebase/src/dojo/src/logging/__package__.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/logging/__package__.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/logging/__package__.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/logging/__package__.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,15 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.kwCompoundRequire({
+	common: [["dojo.logging.Logger", false, false]],
+	rhino: ["dojo.logging.RhinoLogger"]
+});
+dojo.provide("dojo.logging.*");

Added: incubator/xap/trunk/codebase/src/dojo/src/math.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/math.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/math.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/math.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,127 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.provide("dojo.math");
+
+dojo.math.degToRad = function(/* float */x) {
+	//	summary
+	//	Converts degrees to radians.
+	return (x*Math.PI) / 180; 	//	float
+}
+dojo.math.radToDeg = function(/* float */x) { 
+	//	summary
+	//	Converts radians to degrees.
+	return (x*180) / Math.PI; 	//	float
+}
+
+dojo.math.factorial = function(/* integer */n){
+	//	summary
+	//	Returns n!
+	if(n<1){ return 0; }
+	var retVal = 1;
+	for(var i=1;i<=n;i++){ retVal *= i; }
+	return retVal;	//	integer
+}
+
+dojo.math.permutations = function(/* integer */n, /* integer */k) {
+	//	summary
+	//	The number of ways of obtaining an ordered subset of k elements from a set of n elements
+	if(n==0 || k==0) return 1;
+	return (dojo.math.factorial(n) / dojo.math.factorial(n-k));	//	float
+}
+
+dojo.math.combinations = function (/* integer */n, /* integer */r) {
+	//	summary
+	//	The number of ways of picking n unordered outcomes from r possibilities
+	if(n==0 || r==0) return 1;
+	return (dojo.math.factorial(n) / (dojo.math.factorial(n-r) * dojo.math.factorial(r)));	//	float
+}
+
+dojo.math.bernstein = function(/* float */t, /* float */n, /* float */i) {
+	//	summary
+	//	Calculates a weighted average based on the Bernstein theorem.
+	return (dojo.math.combinations(n,i) * Math.pow(t,i) * Math.pow(1-t,n-i));	//	float
+}
+
+dojo.math.gaussianRandom = function(){
+	//	summary
+	//	Returns random numbers with a Gaussian distribution, with the mean set at 0 and the variance set at 1.
+	var k = 2;
+	do {
+		var i = 2 * Math.random() - 1;
+		var j = 2 * Math.random() - 1;
+		k = i * i + j * j;
+	} while (k >= 1);
+	k = Math.sqrt((-2 * Math.log(k)) / k);
+	return i * k;	//	float
+}
+
+dojo.math.mean = function() {
+	//	summary
+	//	Calculates the mean of an Array of numbers.
+	var array = dojo.lang.isArray(arguments[0]) ? arguments[0] : arguments;
+	var mean = 0;
+	for (var i = 0; i < array.length; i++) { mean += array[i]; }
+	return mean / array.length;	//	float
+}
+
+dojo.math.round = function(/* float */number, /* integer */places) {
+	//	summary
+	//	Extends Math.round by adding a second argument specifying the number of decimal places to round to.
+	// TODO: add support for significant figures
+	if (!places) { var shift = 1; }
+	else { var shift = Math.pow(10, places); }
+	return Math.round(number * shift) / shift;	//	float
+}
+
+dojo.math.sd = dojo.math.standardDeviation = function(/* array */){
+	//	summary
+	//	Calculates the standard deviation of an Array of numbers
+	var array = dojo.lang.isArray(arguments[0]) ? arguments[0] : arguments;
+	return Math.sqrt(dojo.math.variance(array));	//	float
+}
+
+dojo.math.variance = function(/* array */) {
+	//	summary
+	//	Calculates the variance of an Array of numbers
+	var array = dojo.lang.isArray(arguments[0]) ? arguments[0] : arguments;
+	var mean = 0, squares = 0;
+	for (var i = 0; i < array.length; i++) {
+		mean += array[i];
+		squares += Math.pow(array[i], 2);
+	}
+	return (squares / array.length) - Math.pow(mean / array.length, 2);	//	float
+}
+
+dojo.math.range = function(/* integer */a, /* integer */b, /* integer */step) {
+	//	summary
+	//	implementation of Python's range()
+    if(arguments.length < 2) {
+        b = a;
+        a = 0;
+    }
+    if(arguments.length < 3) {
+        step = 1;
+    }
+
+    var range = [];
+    if(step > 0) {
+        for(var i = a; i < b; i += step) {
+            range.push(i);
+        }
+    } else if(step < 0) {
+        for(var i = a; i > b; i += step) {
+            range.push(i);
+        }
+    } else {
+        throw new Error("dojo.math.range: step must be non-zero");
+    }
+    return range;	//	array
+}

Added: incubator/xap/trunk/codebase/src/dojo/src/math/__package__.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/math/__package__.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/math/__package__.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/math/__package__.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,18 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.kwCompoundRequire({
+	common: [
+		["dojo.math", false, false],
+		["dojo.math.curves", false, false],
+		["dojo.math.points", false, false]
+	]
+});
+dojo.provide("dojo.math.*");

Added: incubator/xap/trunk/codebase/src/dojo/src/math/curves.js
URL: http://svn.apache.org/viewvc/incubator/xap/trunk/codebase/src/dojo/src/math/curves.js?view=auto&rev=518313
==============================================================================
--- incubator/xap/trunk/codebase/src/dojo/src/math/curves.js (added)
+++ incubator/xap/trunk/codebase/src/dojo/src/math/curves.js Wed Mar 14 13:36:44 2007
@@ -0,0 +1,242 @@
+/*
+	Copyright (c) 2004-2006, The Dojo Foundation
+	All Rights Reserved.
+
+	Licensed under the Academic Free License version 2.1 or above OR the
+	modified BSD license. For more information on Dojo licensing, see:
+
+		http://dojotoolkit.org/community/licensing.shtml
+*/
+
+dojo.provide("dojo.math.curves");
+dojo.require("dojo.math");
+
+/* Curves from Dan's 13th lib stuff.
+ * See: http://pupius.co.uk/js/Toolkit.Drawing.js
+ *      http://pupius.co.uk/dump/dojo/Dojo.Math.js
+ */
+
+dojo.math.curves = {
+	Line: function(/* array */start, /* array */end) {
+		//	summary
+		//	Creates a straight line object
+		this.start = start;
+		this.end = end;
+		this.dimensions = start.length;
+
+		for(var i = 0; i < start.length; i++) {
+			start[i] = Number(start[i]);
+		}
+
+		for(var i = 0; i < end.length; i++) {
+			end[i] = Number(end[i]);
+		}
+
+		//simple function to find point on an n-dimensional, straight line
+		this.getValue = function(/* float */n){
+			//	summary
+			//	Returns the point at point N (in terms of percentage) on this line.
+			var retVal = new Array(this.dimensions);
+			for(var i=0;i<this.dimensions;i++)
+				retVal[i] = ((this.end[i] - this.start[i]) * n) + this.start[i];
+			return retVal;	//	array
+		}
+		return this;	//	dojo.math.curves.Line
+	},
+
+	Bezier: function(/* array */pnts) {
+		//	summary
+		//	Creates a bezier curve
+		//	Takes an array of points, the first is the start point, the last is end point and the ones in
+		//	between are the Bezier control points.
+		this.getValue = function(/* float */step) {
+			//	summary
+			//	Returns the point at point N (in terms of percentage) on this curve.
+			if(step >= 1) return this.p[this.p.length-1];	// if step>=1 we must be at the end of the curve
+			if(step <= 0) return this.p[0];					// if step<=0 we must be at the start of the curve
+			var retVal = new Array(this.p[0].length);
+			for(var k=0;j<this.p[0].length;k++) { retVal[k]=0; }
+			for(var j=0;j<this.p[0].length;j++) {
+				var C=0; var D=0;
+				for(var i=0;i<this.p.length;i++) {
+					C += this.p[i][j] * this.p[this.p.length-1][0]
+						* dojo.math.bernstein(step,this.p.length,i);
+				}
+				for(var l=0;l<this.p.length;l++) {
+					D += this.p[this.p.length-1][0] * dojo.math.bernstein(step,this.p.length,l);
+				}
+				retVal[j] = C/D;
+			}
+			return retVal;	//	array
+		}
+		this.p = pnts;
+		return this;	//	dojo.math.curves.Bezier
+	},
+
+	CatmullRom : function(/* array */pnts, /* float */c) {
+		//	summary
+		//	Creates a catmull-rom spline curve with c tension.
+		this.getValue = function(/* float */step) {
+			//	summary
+			//	Returns the point at point N (in terms of percentage) on this curve.
+			var percent = step * (this.p.length-1);
+			var node = Math.floor(percent);
+			var progress = percent - node;
+
+			var i0 = node-1; if(i0 < 0) i0 = 0;
+			var i = node;
+			var i1 = node+1; if(i1 >= this.p.length) i1 = this.p.length-1;
+			var i2 = node+2; if(i2 >= this.p.length) i2 = this.p.length-1;
+
+			var u = progress;
+			var u2 = progress*progress;
+			var u3 = progress*progress*progress;
+
+			var retVal = new Array(this.p[0].length);
+			for(var k=0;k<this.p[0].length;k++) {
+				var x1 = ( -this.c * this.p[i0][k] ) + ( (2 - this.c) * this.p[i][k] ) + ( (this.c-2) * this.p[i1][k] ) + ( this.c * this.p[i2][k] );
+				var x2 = ( 2 * this.c * this.p[i0][k] ) + ( (this.c-3) * this.p[i][k] ) + ( (3 - 2 * this.c) * this.p[i1][k] ) + ( -this.c * this.p[i2][k] );
+				var x3 = ( -this.c * this.p[i0][k] ) + ( this.c * this.p[i1][k] );
+				var x4 = this.p[i][k];
+
+				retVal[k] = x1*u3 + x2*u2 + x3*u + x4;
+			}
+			return retVal;	//	array
+		}
+
+		if(!c) this.c = 0.7;
+		else this.c = c;
+		this.p = pnts;
+
+		return this;	//	dojo.math.curves.CatmullRom
+	},
+
+	// FIXME: This is the bad way to do a partial-arc with 2 points. We need to have the user
+	// supply the radius, otherwise we always get a half-circle between the two points.
+	Arc : function(/* array */start, /* array */end, /* boolean? */ccw) {
+		//	summary
+		//	Creates an arc with a counter clockwise switch
+		var center = dojo.math.points.midpoint(start, end);
+		var sides = dojo.math.points.translate(dojo.math.points.invert(center), start);
+		var rad = Math.sqrt(Math.pow(sides[0], 2) + Math.pow(sides[1], 2));
+		var theta = dojo.math.radToDeg(Math.atan(sides[1]/sides[0]));
+		if( sides[0] < 0 ) {
+			theta -= 90;
+		} else {
+			theta += 90;
+		}
+		dojo.math.curves.CenteredArc.call(this, center, rad, theta, theta+(ccw?-180:180));
+	},
+
+	CenteredArc : function(/* array */center, /* float */radius, /* array */start, /* array */end) {
+		//	summary
+		// 	Creates an arc object, with center and radius (Top of arc = 0 degrees, increments clockwise)
+		//  center => 2D point for center of arc
+		//  radius => scalar quantity for radius of arc
+		//  start  => to define an arc specify start angle (default: 0)
+		//  end    => to define an arc specify start angle
+		this.center = center;
+		this.radius = radius;
+		this.start = start || 0;
+		this.end = end;
+
+		this.getValue = function(/* float */n) {
+			//	summary
+			//	Returns the point at point N (in terms of percentage) on this curve.
+			var retVal = new Array(2);
+			var theta = dojo.math.degToRad(this.start+((this.end-this.start)*n));
+
+			retVal[0] = this.center[0] + this.radius*Math.sin(theta);
+			retVal[1] = this.center[1] - this.radius*Math.cos(theta);
+	
+			return retVal;	//	array
+		}
+
+		return this;	//	dojo.math.curves.CenteredArc
+	},
+
+	Circle : function(/* array */center, /* float */radius) {
+		//	summary
+		// Special case of Arc (start = 0, end = 360)
+		dojo.math.curves.CenteredArc.call(this, center, radius, 0, 360);
+		return this;	//	dojo.math.curves.Circle
+	},
+
+	Path : function() {
+		//	summary
+		// 	Generic path shape, created from curve segments
+		var curves = [];
+		var weights = [];
+		var ranges = [];
+		var totalWeight = 0;
+
+		this.add = function(/* dojo.math.curves.* */curve, /* float */weight) {
+			//	summary
+			//	Add a curve segment to this path
+			if( weight < 0 ) { dojo.raise("dojo.math.curves.Path.add: weight cannot be less than 0"); }
+			curves.push(curve);
+			weights.push(weight);
+			totalWeight += weight;
+			computeRanges();
+		}
+
+		this.remove = function(/* dojo.math.curves.* */curve) {
+			//	summary
+			//	Remove a curve segment from this path
+			for(var i = 0; i < curves.length; i++) {
+				if( curves[i] == curve ) {
+					curves.splice(i, 1);
+					totalWeight -= weights.splice(i, 1)[0];
+					break;
+				}
+			}
+			computeRanges();
+		}
+
+		this.removeAll = function() {
+			//	summary
+			//	Remove all curve segments
+			curves = [];
+			weights = [];
+			totalWeight = 0;
+		}
+
+		this.getValue = function(/* float */n) {
+			//	summary
+			//	Returns the point at point N (in terms of percentage) on this curve.
+			var found = false, value = 0;
+			for(var i = 0; i < ranges.length; i++) {
+				var r = ranges[i];
+				//w(r.join(" ... "));
+				if( n >= r[0] && n < r[1] ) {
+					var subN = (n - r[0]) / r[2];
+					value = curves[i].getValue(subN);
+					found = true;
+					break;
+				}
+			}
+
+			// FIXME: Do we want to assume we're at the end?
+			if( !found ) {
+				value = curves[curves.length-1].getValue(1);
+			}
+
+			for(var j = 0; j < i; j++) {
+				value = dojo.math.points.translate(value, curves[j].getValue(1));
+			}
+			return value;	//	array
+		}
+
+		function computeRanges() {
+			var start = 0;
+			for(var i = 0; i < weights.length; i++) {
+				var end = start + weights[i] / totalWeight;
+				var len = end - start;
+				ranges[i] = [start, end, len];
+				start = end;
+			}
+		}
+
+		return this;	//	dojo.math.curves.Path
+	}
+};



Mime
View raw message