Merge branch 'jake' of git@github.com:280north/cappuccino into jake

This commit is contained in:
Ross Boucher committed 2009-12-01 09:14:45 -08:00
commit f1d4794dd1
21 files changed
+47 -2313

No files matched your search

-12
View File
@@ -1,12 +0,0 @@
[submodule "External/narwhal"]
path = External/narwhal
url = git://github.com/tlrobinson/narwhal.git
[submodule "External/jack"]
path = External/jack
url = git://github.com/tlrobinson/jack.git
[submodule "External/browserjs"]
path = External/browserjs
url = git://github.com/tlrobinson/browserjs.git
[submodule "External/ojunit"]
path = External/ojunit
url = git://github.com/280north/ojunit.git
-63
View File
@@ -1,63 +0,0 @@
#!/usr/bin/env narwhal
var FILE = require("file"),
ENV = require("system").env,
OS = require("os"),
Jake = require("jake");
/*,
Clean = require("jake/clean");
*/
require(FILE.absolute("../common.jake"));
$ENVIRONMENT_NARWHAL_PRODUCT = $ENVIRONMENT_DIR
$ENVIRONMENT_PACKAGES_PRODUCT = FILE.join($ENVIRONMENT_NARWHAL_PRODUCT, 'packages')
$EXTERNALS = ['browserjs', 'jack', 'narwhal', 'ojunit'];
$PACKAGES = ['browserjs', 'jack'];
function git_export(source, destination)
{
destination = FILE.join(FILE.absolute(destination), '');
OS.system("cd " + source + " && git checkout-index -a -f \"--prefix=" + destination + "\"");
};
filedir ($ENVIRONMENT_DIR, function()
{
FILE.mkdirs($ENVIRONMENT_DIR);
});
task ("update_submodules", function()
{
if (ENV['NOSUBUP'])
return;
if (executableExists("git"))
OS.system("cd .. && git submodule init && git submodule update");
else
throw "Git not installed";
});
task ("build", ["update_submodules", $ENVIRONMENT_DIR], function()
{
rm_rf($ENVIRONMENT_NARWHAL_PRODUCT);
git_export('narwhal', $ENVIRONMENT_NARWHAL_PRODUCT);
$PACKAGES.forEach(function(aPackage)
{
git_export(aPackage, FILE.join($ENVIRONMENT_PACKAGES_PRODUCT, aPackage));
});
symlink_executable(FILE.join($ENVIRONMENT_PACKAGES_PRODUCT, 'jack', 'bin', 'jackup'))
});
//CLOBBER.include($ENVIRONMENT_NARWHAL_PRODUCT)
task ("pull", function()
{
$EXTERNALS.forEach(function(external)
{
OS.system("cd " + external + " && git pull origin master");
});
});
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env ruby
require '../common'
require 'objective-j'
require 'rake'
require 'rake/clean'
require 'fileutils'
$ENVIRONMENT_NARWHAL_PRODUCT = $ENVIRONMENT_DIR
$ENVIRONMENT_PACKAGES_PRODUCT = File.join($ENVIRONMENT_NARWHAL_PRODUCT, 'packages')
$EXTERNALS = ['browserjs', 'jack', 'narwhal', 'ojunit']
$PACKAGES = ['browserjs', 'jack']
def git_export(source, dest)
dest = File.join(File.expand_path(dest), '');
system %{cd "#{source}" && git checkout-index -a -f "--prefix=#{dest}"}
end
file_d $ENVIRONMENT_DIR do
mkdir_p $ENVIRONMENT_DIR
end
task :update_submodules do
if !ENV['NOSUBUP'] then
if executable_exists? "git"
system %{cd .. && git submodule init && git submodule update}
else
puts "Git not installed"
rake abort
end
end
end
task :build => [:update_submodules, $ENVIRONMENT_DIR] do
rm_rf($ENVIRONMENT_NARWHAL_PRODUCT)
git_export('narwhal', $ENVIRONMENT_NARWHAL_PRODUCT)
$PACKAGES.each do |package|
git_export(package, File.join($ENVIRONMENT_PACKAGES_PRODUCT, package))
end
symlink_executable(File.join($ENVIRONMENT_PACKAGES_PRODUCT, 'jack', 'bin', 'jackup'))
end
CLOBBER.include($ENVIRONMENT_NARWHAL_PRODUCT)
task :pull do
$EXTERNALS.each do |external|
system "cd #{external} && git pull origin master"
end
end
Submodule External/browserjs deleted from 98a71a4122.
-1
Submodule External/jack deleted from 3ee7b56812.
-1
Submodule External/narwhal deleted from cd6e4b02ab.
-1
Submodule External/ojunit deleted from 352b7e8c61.
+12 -11
View File
@@ -8,12 +8,12 @@ function printUsage()
print("this is where you say the usage");
}
function main()
exports.main = function(args)
{
// FIXME: ARGS
system.args.shift();
// TODO: args parser
args.shift();
if (system.args.length < 1)
if (args.length < 1)
return printUsage();
var allFiles = NO,
@@ -23,11 +23,11 @@ function main()
outExtension = nil;
index = 0,
count = system.args.length;
count = args.length;
for (; index < count; ++index)
{
var argument = system.args[index];
var argument = args[index];
if (argument.charAt(0) === '-' && !allFiles)
{
@@ -35,13 +35,13 @@ function main()
return printUsage();
else if (argument === "-convert")
format = system.args[++index];
format = args[++index];
else if (argument === "-o")
outPath = system.args[++index];
outPath = args[++index];
else if (argument === "-e")
outExtension = system.args[++index];
outExtension = args[++index];
else if (argument === "--")
allFiles = YES;
@@ -50,7 +50,7 @@ function main()
return printUsage();
}
else
filePaths.push(system.args[index]);
filePaths.push(args[index]);
}
index = 0;
@@ -76,4 +76,5 @@ function main()
}
}
main();
if (require.main == module.id)
exports.main(system.args);
+13 -26
View File
@@ -1,6 +1,6 @@
var FILE = require("file");
var window = require("browser/window");
var window = exports.window = require("browser/window");
if (system.engine === "rhino")
{
@@ -104,37 +104,26 @@ with (window)
exports.IS_FILE = function(aFragment) { return (aFragment.type & FRAGMENT_FILE); }
exports.IS_LOCAL = function(aFragment) { return (aFragment.type & FRAGMENT_LOCAL); }
exports.IS_IMPORT = function(aFragment) { return (aFragment.type & FRAGMENT_IMPORT); }
/*
objj_set_evaluator(function(code) {
return function(OBJJ_CURRENT_BUNDLE) {
with (window) {
return eval("function(OBJJ_CURRENT_BUNDLE){"+code+"}");
}
}
});
*/
// runs the objj repl or file provided in args
exports.run = function(args)
{
args = args || [];
window.args = args;
// FIXME: ARGS
args.shift();
if (args.length > 0)
if (args && args.length > 1)
{
while (args.length && args[0].indexOf('-I') === 0)
OBJJ_INCLUDE_PATHS = args.shift().substr(2).split(':').concat(OBJJ_INCLUDE_PATHS);
var mainFilePath = FILE.canonical(args.shift());
var arg0 = args.slice(0,1),
argv = args.slice(1);
while (argv.length && argv[0].indexOf('-I') === 0)
OBJJ_INCLUDE_PATHS = argv.shift().substr(2).split(':').concat(OBJJ_INCLUDE_PATHS);
var mainFilePath = FILE.canonical(argv.shift());
objj_import(mainFilePath, YES, function() {
if (typeof main === "function")
main.apply(main, args);
main(arg0.concat(argv));
});
require("browser/timeout").serviceTimeouts();
}
else
{
@@ -155,8 +144,6 @@ exports.run = function(args)
require("browser/timeout").serviceTimeouts();
}
}
require("browser/timeout").serviceTimeouts();
}
// synchronously evals Objective-J code
@@ -183,7 +183,7 @@ exports.compile = function(aFilePath, flags)
exports.main = function(args)
{
// FIXME: ARGS
// TODO: args parser
args.shift();
var resolved = resolveFlags(args),
@@ -200,4 +200,4 @@ exports.main = function(args)
}
if (require.main == module.id)
exports.main(system.args);
exports.main(system.args);
-676
View File
@@ -1,676 +0,0 @@
if (typeof debug == "undefined")
debug = false;
//window
if (!this.window)
this.window = this;
// DOMParser
/*function DOMParser() {};
DOMParser.prototype.parseFromString = function(text, contentType) {
return new DOMDocument(
new Packages.org.xml.sax.InputSource(
new Packages.java.io.StringReader(text)));
};*/
// Image
function Image() { }
// print, alert, prompt, confirm
if (!this.print)
{
if (this.Packages)
{
this.print = function(object)
{
Packages.java.lang.System.out.println(String(object));
}
}
}
window.alert = function(obj)
{
if (this.print)
print(String(obj));
}
// FIXME: prompt user for response?
window.confirm = function(obj)
{
window.alert(obj);
return true;
}
window.prompt = function(obj)
{
window.alert(obj);
return "";
}
// setTimeout, setInterval, clearTimeout, clearInterval
// This implementation is single-threaded (like browsers) but requires a call to serviceTimeouts()
// Also includes beginning of a multithreaded implementation (commented out)
window.setNativeTimeout = function(callback, delay)
{
return _scheduleTimeout(callback, delay, false);
}
window.setTimeout = window.setNativeTimeout;
window.setNativeInterval = function(callback, delay)
{
return _scheduleTimeout(callback, delay, true);
}
window.setInterval = window.setInterval;
window.clearTimeout = function(id)
{
if (_timeouts[id])
_timeouts[id] = null;
}
window.clearInterval = window.clearTimeout;
var _nextId = 0,
_timeouts = {},
_pendingTimeouts = [];
var _scheduleTimeout = function(callback, delay, repeat)
{
var date = new Date(new Date().getTime() + delay);
if (typeof callback == "function")
var func = callback;
else if (typeof callback == "string")
var func = new Function(callback);
else
return;
var timeout = {
callback: func,
date: date,
repeat: repeat,
interval: delay,
id : _nextId++
}
_timeouts[timeout.id] = timeout;
_pendingTimeouts.push(timeout);
// if (!_timersBlock)
// serviceTimeouts();
return timeout.id;
}
var _sortTimeouts = function()
{
}
//var _timersBlock = false,
// _timerThread = null,
// _nextTimeout = null;
function serviceTimeouts()
{
while (_pendingTimeouts.length > 0)
{
_pendingTimeouts = _pendingTimeouts.sort(function (a,b) { return a.date - b.date; });
var timeout = _pendingTimeouts.shift();
if (_timeouts[timeout.id])
{
var wait = timeout.date - new Date();
if (wait > 0)
{
//if (_timersBlock)
//{
Packages.java.lang.Thread.sleep(wait);
//}
//else
//{
// _pendingTimeouts.splice(0, 0, timeout);
//
// if (!_nextTimeout || _nextTimeout > timeout.date)
// {
// _nextTimeout = timeout.date;
//
//
// _timerThread = new java.lang.Thread(new java.lang.Runnable({
// run: function() {
// Packages.java.lang.Thread.sleep(wait);
// _nextTimeout = null;
// serviceTimeouts();
// }
// }));
//
// _timerThread.start();
// }
//
// return;
//}
}
// perform the callback
timeout.callback();
// if its an interval, reschedule it, otherwise clear it
if (timeout.repeat)
{
var now = new Date(),
proposed = new Date(timeout.date.getTime() + timeout.interval);
timeout.date = (proposed < now) ? now : proposed;
_pendingTimeouts.push(timeout);
}
else
_timeouts[timeout.id] = null;
}
}
}
// load
if (!this.load)
{
if (debug)
alert("Setting up 'load()'");
this.load = function(path)
{
var contents = readFile(path);
if (typeof Packages !== "undefined")
return Packages.org.mozilla.javascript.Context.getCurrentContext().evaluateString(window, contents, path, 0, null);
else
return eval(contents);
}
}
// readFile
if (!this.readFile)
{
if (this.File)
{
if (debug)
alert("Setting up 'readFile()' for SpiderMonkey");
this.readFile = function(path)
{
var f = new File(path);
if (!f.canRead)
{
if (debug)
alert("can't read: " + f.path);
return "";
}
if (debug)
alert("reading: " + f.path);
f.open("read", "text");
var result = f.readAll().join("\n");
f.close();
return result;
}
}
else if (this.Packages)
{
if (debug)
alert("Setting up 'readFile()' for Rhino");
this.readFile = function(path, characterCoding)
{
var f = new Packages.java.io.File(path);
if (!f.canRead())
{
if (debug)
alert("can't read: " + f.path);
return "";
}
if (debug)
alert("reading: " + f.getAbsolutePath());
var fis = new Packages.java.io.FileInputStream(f),
b = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, fis.available());
fis.read(b);
fis.close();
if (characterCoding)
return String(new Packages.java.lang.String(b, characterCoding));
else
return String(new Packages.java.lang.String(b));
}
}
else
{
alert("Warning: No 'readFile' implementation available.")
}
}
var hex_lookup = "0123456789abcdef";
function bytesToHexString(buf)
{
var buffer = "";
for (var i = 0 ; i < buf.length; i++)
buffer += hex_lookup[(buf[i] >> 4) & 0x0F] + hex_lookup[buf[i] & 0x0F];
return buffer;
}
// Rhino utilities
if (this.Packages) {
if (debug)
alert("Setting up Rhino utilties");
jsArrayToJavaArray = function(js_array, type)
{
var java_class = null;
var java_converter = null;
switch (type || ((js_array && js_array.length > 0) && typeof js_array[0]))
{
case "string":
case "String":
java_class = Packages.java.lang.String;
java_converter = Packages.java.lang.String.valueOf;
break;
case "Boolean":
java_class = Packages.java.lang.Boolean;
java_converter = Packages.java.lang.Boolean.valueOf;
break;
case "boolean":
java_class = Packages.java.lang.Boolean.TYPE;
java_converter = function(input) { return Packages.java.lang.Boolean.valueOf(input).booleanValue(); };
break;
default:
return null;
}
if (js_array && js_array.length > 0)
{
var java_array = Packages.java.lang.reflect.Array.newInstance(java_class, js_array.length);
for (var i = 0; i < js_array.length; i++)
java_array[i] = java_converter ? java_converter(js_array[i]) : js_array[i];
return java_array;
}
return Packages.java.lang.reflect.Array.newInstance(java_class, 0);
}
jsObjectToJavaHashMap = function(js_object)
{
var map = Packages.java.util.HashMap();
for (var i in js_object)
map.put(i, js_object[i]);
return map;
}
objj_console = function()
{
var br = new Packages.java.io.BufferedReader(new Packages.java.io.InputStreamReader(Packages.java.lang.System["in"], "UTF-8"));
keepgoing = true;
while (keepgoing)
{
try {
Packages.java.lang.System.out.print("objj> ");
var input = String(br.readLine()),
fragments = objj_preprocess(input, new objj_bundle(), new objj_file(), OBJJ_PREPROCESSOR_DEBUG_SYMBOLS),
count = fragments.length,
ctx = (new objj_context);
if (count == 1 && (fragments[0].type & FRAGMENT_CODE))
{
var fragment = fragments[0];
var result = eval(fragment.info);
if (result != undefined)
print(result);
}
else if (count > 0)
{
while (count--)
{
var fragment = fragments[count];
if (fragment.type & FRAGMENT_FILE)
objj_request_file(fragment.info, (fragment.type & FRAGMENT_LOCAL), NULL);
ctx.pushFragment(fragment);
}
ctx.schedule();
}
serviceTimeouts();
} catch (e) {
print(e);
}
}
};
var _documentBuilderFactory = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance();
// setValidating to false doesn't seem to prevent it from downloading the DTD, but lets do it anyway
_documentBuilderFactory.setValidating(false);
_documentBuilder = _documentBuilderFactory.newDocumentBuilder();
// prevent the Java XML parser from downloading the plist DTD from Apple every time we parse a plist
_documentBuilder.setEntityResolver(new Packages.org.xml.sax.EntityResolver({
resolveEntity: function(publicId, systemId) {
//Packages.java.lang.System.out.println("publicId=" + publicId + " systemId=" + systemId);
// TODO: return a local copy of the DTD?
if (String(systemId) == "http://www.apple.com/DTDs/PropertyList-1.0.dtd")
return new Packages.org.xml.sax.InputSource(new Packages.java.io.StringReader(""));
return null;
}
}));
// throw an exception on error
_documentBuilder.setErrorHandler(function(exception, methodName) {
throw exception;
});
copyInputStreamToOutputStream = function(is, os)
{
var buf = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, 1024*10);
var len = 0;
while ((len = is.read(buf)) != -1)
{
os.write(buf, 0, len);
}
}
var lineEnd = "\r\n";
var twoHyphens = "--";
var boundary = "----------------------------b453b5d52446";
//var boundary = "----CappuccinoBoundary" + (new Date().getTime());
multipartRequest = function(method, url, headers, parts)
{
var bufferSize = 1024*10,
buffer = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, bufferSize);
var url = new Packages.java.net.URL(url),
connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method);
for (var i in headers)
{
print(i+":"+headers[i]);
connection.setRequestProperty(i, headers[i]);
}
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ boundary);
var output = new Packages.java.io.DataOutputStream(connection.getOutputStream());
for (var i = 0; parts && i < parts.length; i++)
{
var part = parts[i];
output.writeBytes(twoHyphens + boundary + lineEnd);
if (part.headers)
{
for (var header in part.headers)
{
output.writeBytes(header +": " + part.headers[header] + lineEnd);
}
}
output.writeBytes(lineEnd);
if (part.data)
{
output.writeBytes(part.data);
}
else if (part.stream)
{
var n;
while ((n = part.stream.read(buffer, 0, bufferSize)) > 0)
{
output.write(buffer, 0, n)
}
}
output.writeBytes(lineEnd);
}
output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
output.flush();
output.close();
var buffer,
input = new Packages.java.io.DataInputStream(connection.getInputStream()),
result = new Packages.java.lang.StringBuffer();
while (null != (buffer = input.readLine()))
result.append(buffer);
input.close();
return String(result.toString());
}
parseXMLString = function(string) {
return (_documentBuilder.parse(
new Packages.org.xml.sax.InputSource(
new Packages.java.io.StringReader(string))).getDocumentElement());
}
}
// Environment variables
function getenv(variable)
{
if (this.Packages)
return String(Packages.java.lang.System.getenv().get(variable) || "") || null;
else if (this.environment)
return environment[variable] || null;
return null;
}
// XMLHttpRequest
function XMLHttpRequest()
{
this.readyState = 0;
this.responseText = "";
this.responseXML = null;
this.status = null;
this.statusText = null;
this.onreadystatechange = null;
this.method = null;
this.url = null;
this.async = null;
this.username = null;
this.password = null;
}
XMLHttpRequest.prototype.abort = function()
{
this.readyState = 0;
}
XMLHttpRequest.prototype.open = function(method, url, async, username, password)
{
this.readyState = 1;
this.method = method;
this.url = url;
this.async = async;
this.username = username;
this.password = password;
}
XMLHttpRequest.prototype.send = function(body)
{
this.readyState = 3;
this.responseText = "";
this.responseXML = null;
try
{
this.responseText = readFile(this.url, "UTF-8"); // FIXME: should we really assume this is UTF-8?
if (debug)
alert("xhr response: " + this.url + " (length="+this.responseText.length+")");
}
catch (e)
{
if (debug)
alert("xhr exception: " + this.url);
this.responseText = "";
this.responseXML = null;
}
if (this.responseText.length > 0)
{
try
{
this.responseXML = _documentBuilder.parse(new Packages.org.xml.sax.InputSource(new Packages.java.io.StringReader(this.responseText)));
}
catch (e)
{
this.responseXML = null;
}
this.status = 200;
}
else {
if (debug)
alert("xhr empty: " + this.url);
this.status = 404;
}
this.readyState = 4;
if (this.onreadystatechange)
{
if (this.async)
setNativeTimeout(this.onreadystatechange, 0);
else
this.onreadystatechange();
}
}
XMLHttpRequest.prototype.getResponseHeader = function(header)
{
return (this.readyState < 3) ? "" : "";
}
XMLHttpRequest.prototype.getAllResponseHeaders = function()
{
return (this.readyState < 3) ? null : "";
}
XMLHttpRequest.prototype.setRequestHeader = function(name, value)
{
}
objj_request_xmlhttp = function()
{
return new XMLHttpRequest();
}
OBJJ_HOME = getenv("OBJJ_HOME");
if (!OBJJ_HOME)
{
OBJJ_HOME = "/usr/local/share/objj";
alert("OBJJ_HOME environment variable not set, defaulting to " + OBJJ_HOME);
}
function exec(/*Array*/ command, /*Boolean*/ showOutput)
{
var line = "",
output = "",
process = Packages.java.lang.Runtime.getRuntime().exec(command),//jsArrayToJavaArray(command));
reader = new Packages.java.io.BufferedReader(new Packages.java.io.InputStreamReader(process.getInputStream()));
while (line = reader.readLine())
{
if (showOutput)
Packages.java.lang.System.out.println(line);
output += line + '\n';
}
reader = new Packages.java.io.BufferedReader(new Packages.java.io.InputStreamReader(process.getErrorStream()));
while (line = reader.readLine())
Packages.java.lang.System.out.println(line);
try
{
if (process.waitFor() != 0)
Packages.java.lang.System.err.println("exit value = " + process.exitValue());
}
catch (anException)
{
Packages.java.lang.System.err.println(anException);
}
return output;
}
function getFiles(/*File*/ sourceDirectory, /*nil|String|Array<String>*/ extensions, /*Array*/ exclusions)
{
var matches = [],
files = sourceDirectory.listFiles(),
hasMultipleExtensions = typeof extensions !== "string";
if (files)
{
var index = 0,
count = files.length;
for (; index < count; ++index)
{
var file = files[index].getCanonicalFile(),
name = String(file.getName()),
isValidExtension = !extensions;
if (exclusions && fileArrayContainsFile(exclusions, file))
continue;
if (!isValidExtension)
if (hasMultipleExtensions)
{
var extensionCount = extensions.length;
while (extensionCount-- && !isValidExtension)
{
var extension = extensions[extensionCount];
if (name.substring(name.length - extension.length - 1) === ("." + extension))
isValidExtension = true;
}
}
else if (name.substring(name.length - extensions.length - 1) === ("." + extensions))
isValidExtension = true;
if (isValidExtension)
matches.push(file);
if (file.isDirectory())
matches = matches.concat(getFiles(file, extensions, exclusions));
}
}
return matches;
}
-131
View File
@@ -1,131 +0,0 @@
function readContentsOfFile(/*File*/ aFile)
{
var reader = new BufferedReader(new FileReader(aFile)),
fileContents = "";
// Get contents of the file
while (reader.ready())
fileContents += reader.readLine() + '\n';
reader.close();
return fileContents;
}
function writeContentsToFile(/*String*/ contents, /*File*/ aFile)
{
var writer = new BufferedWriter(new FileWriter(aFile));
writer.write(contents);
writer.close();
}
function readPlist(/*File*/ aFile)
{
var fileContents = readFile(aFile);
var data = new objj_data();
data.string = fileContents;
return new CPPropertyListCreateFromData(data);
}
function readBundle(/*File*/ aFile, /*Boolean*/ shouldDecompile)
{
var bundlePath = typeof aFile === "string" ? new File(aFile).getCanonicalPath() : aFile.getCanonicalPath(),
infoPath = bundlePath + "/Info.plist";
//err
var bundle = new objj_bundle();
bundle.path = infoPath;
bundle.info = readPlist(infoPath);
bundle._staticFilePaths = dictionary_getValue(bundle.info, "CPBundleReplacedFiles");
if (bundle._staticFilePaths.length)
{
bundle._staticContentPath = staticContentPath = bundlePath + '/' + dictionary_getValue(bundle.info, "CPBundleExecutable");
//err
bundle._staticContent = readFile(staticContentPath);
if (shouldDecompile)
bundle.files = objj_decompile(bundle._staticContent, bundle);
}
else
bundle._staticContent = "";
return bundle;
}
function importFiles(files, aCallback)
{
if (files.length === 0)
aCallback();
else
{
var file = files.shift();
if (typeof file === "string")
file = new File(file);
objj_import(file.getCanonicalPath(), YES, function() { importFiles(files, aCallback) });
}
return;
var context = new objj_context();
if (aCallback)
context.didCompleteCallback = aCallback;
var count = files.length;
while (count--)
{
var file = files[count];
if (typeof file === "string")
file = new File(file);
context.pushFragment(fragment_create_file(file, new objj_bundle(""), YES, NULL));
}
context.evaluate();
}
function loadFrameworks(frameworkPaths, aCallback)
{
if (frameworkPaths.length === 0)
return aCallback();
var frameworkPath = frameworkPaths.shift(),
infoPlist = new File(frameworkPath + "/Info.plist");
if (!infoPlist.exists())
{
java.lang.System.out.println("'" + frameworkPath + "' is not a framework or could not be found.");
java.lang.System.exit(1);
}
var infoDictionary = readPlist(new File(frameworkPath + "/Info.plist"));
if (dictionary_getValue(infoDictionary, "CPBundlePackageType") !== "FMWK")
{
java.lang.System.out.println("'" + frameworkPath + "' is not a framework .");
java.lang.System.exit(1);
}
var files = dictionary_getValue(infoDictionary, "CPBundleReplacedFiles"),
index = 0,
count = files.length;
for (; index < count; ++index)
files[index] = String(frameworkPath + '/' + files[index]);
importFiles(files, function() { loadFrameworks(frameworkPaths, aCallback) });
}
-99
View File
@@ -1,99 +0,0 @@
function readFile(/*File*/ aFile)
{
var reader = new BufferedReader(new FileReader(aFile)),
fileContents = "";
// Get contents of the file
while (reader.ready())
fileContents += reader.readLine() + '\n';
reader.close();
return fileContents;
}
function writeContentsToFile(/*String*/ contents, /*File*/ aFile)
{
}
function readPlist(/*File*/ aFile)
{
var fileContents = readFile(aFile);
var data = new objj_data();
data.string = fileContents;
return new CPPropertyListCreateFromData(data);
}
function importFiles(files, aCallback)
{
if (files.length === 0)
aCallback();
else
{
var file = files.shift();
if (typeof file === "string")
file = new File(file);
objj_import(String(file.getCanonicalPath()), YES, function() { importFiles(files, aCallback) });
}
return;
var context = new objj_context();
if (aCallback)
context.didCompleteCallback = aCallback;
var count = files.length;
while (count--)
{
var file = files[count];
if (typeof file === "string")
file = new File(file);
context.pushFragment(fragment_create_file(file, new objj_bundle(""), YES, NULL));
}
context.evaluate();
}
function loadFrameworks(frameworkPaths, aCallback)
{
if (frameworkPaths.length === 0)
return aCallback();
var frameworkPath = frameworkPaths.shift(),
infoPlist = new File(frameworkPath + "/Info.plist");
if (!infoPlist.exists())
{
java.lang.System.out.println("'" + frameworkPath + "' is not a framework or could not be found.");
java.lang.System.exit(1);
}
var infoDictionary = readPlist(new File(frameworkPath + "/Info.plist"));
if (dictionary_getValue(infoDictionary, "CPBundlePackageType") !== "FMWK")
{
java.lang.System.out.println("'" + frameworkPath + "' is not a framework .");
java.lang.System.exit(1);
}
var files = dictionary_getValue(infoDictionary, "CPBundleReplacedFiles"),
index = 0,
count = files.length;
for (; index < count; ++index)
files[index] = String(frameworkPath + '/' + files[index]);
importFiles(files, function() { loadFrameworks(frameworkPaths, aCallback) });
}
Binary file not shown.
-41
View File
@@ -1,41 +0,0 @@
#!/usr/bin/env ruby
require 'rake'
require '../../common'
require 'objective-j'
require 'objective-j/bundletask'
$PRODUCT = :bake
$BUILD_PATH = File.join($BUILD_DIR, $CONFIGURATION, 'bake')
$ENVIRONMENT_BIN_PRODUCT = File.join($ENVIRONMENT_BIN_DIR, 'bake')
$ENVIRONMENT_LIB_PRODUCT = File.join($ENVIRONMENT_LIB_DIR, 'bake')
# Debug Framework
ObjectiveJ::BundleTask.new(:bake) do |t|
t.name = 'bake'
t.identifier = 'com.280n.bake'
t.version = '0.7.1'
t.author = '280 North, Inc.'
t.email = 'feedback @nospam@ 280north.com'
t.summary = 'Deployment tool for Cappuccino applications'
t.sources = FileList['*.j']
t.resources = FileList['Resources/*']
t.license = ObjectiveJ::License::LGPL_v2_1
t.build_path = $BUILD_PATH
t.flag = '-DDEBUG' if $CONFIGURATION == 'Debug'
t.flag = '-O' if $CONFIGURATION == 'Release'
end
#executable in environment directory
file_d $ENVIRONMENT_BIN_PRODUCT do
make_objj_executable($ENVIRONMENT_BIN_PRODUCT)
end
file_d $ENVIRONMENT_LIB_PRODUCT => [:bake] do
cp_r(File.join($BUILD_PATH, '.'), $ENVIRONMENT_LIB_PRODUCT)
end
task :build => [:bake, $ENVIRONMENT_BIN_PRODUCT, $ENVIRONMENT_LIB_PRODUCT]
CLOBBER.include($ENVIRONMENT_BIN_PRODUCT, $ENVIRONMENT_LIB_PRODUCT)
-57
View File
@@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en">
<!--
//
// index.html
//
// $APPLICATION_NAME
//
// Copyright 2005 - 2008, 280 North, Inc. All rights reserved.
//
-->
<head>
<title>$APPLICATION_NAME</title>
<script type = "text/javascript" charset = "utf-8" >
//create a new timestamp to monitor launch time
_LAUNCH_TIME = new Date();
OBJJ_MAIN_FILE = "main.j";
window.files_total = $FILES_TOTAL;
window.update_progress = function(percent)
{
var value = Math.max(Math.min(Math.round(percent*100), 100), 0);
var progress = document.getElementById("progress");
if (progress)
progress.style.width = value + "%";
window.title = "Loading $APPLICATION_NAME... " + value + "%";
}
var path = document.location.href;
path = path.substr(0, path.lastIndexOf('/') + 1);
document.write("<base href=\"" + path + "$VERSION/" + "\"><!--[if IE]><"+"/base><![endif]-->");
</script>
<script src = "Frameworks/Objective-J/Objective-J.js" type = "text/javascript" charset = "utf-8"></script>
</head>
<body style="background-color: $BACKGROUND_COLOR;">
<div style="position: absolute; top: 50%; left: 50%; min-height: 100px; width: 250px; margin-top: -50px; margin-left: -125px; padding: 10px; background-color: white; text-align: center; -moz-border-radius: 5px; -webkit-border-radius: 5px;">
<img src="Resources/spinner.gif" />
<div style="height: 3px; width: 100%; left: 0px; top: 0px; background-color: lightgrey; overflow: hidden;">
<div id="progress" style="height: 100%; width: 0%; left: 0px; top: 0px; background-color: black; margin-right: auto;"></div>
</div>
<h3 style="font-size: 18px; font-family: 'Lucida Grande', Lucida, Verdana, Helvetica, Arial, sans-serif; color: $TEXT_COLOR;">Loading $APPLICATION_NAME...</h3>
</div>
</body>
</html>
-56
View File
@@ -1,56 +0,0 @@
{
"sources" : [
{
"type" : "git",
"path" : "git://github.com/280north/cappuccino.git",
"parts" : [
{
"src" : "Objective-J",
"dst" : "Frameworks/Objective-J",
"build" : "ant -DBuild=BUILD_PATH",
"copyFrom" : "Release/Objective-J"
},
{
"src" : "Foundation",
"dst" : "Frameworks/Foundation",
"build" : "steam build -c Release -b BUILD_PATH",
"copyFrom" : "Release/Foundation"
},
{
"src" : "AppKit",
"dst" : "Frameworks/AppKit",
"build" : "steam build -c Release -b BUILD_PATH",
"copyFrom" : "Release/AppKit"
}
]
},
{
"type" : "rsync",
"path" : "/Users/username/projects/NewApplication",
"parts" : [
{
"src" : "",
"dst" : "Blah"
}
]
},
{
"type" : "svn",
"path" : "https://svn.youserver.com/Project/trunk",
"parts" : [
{
"src" : "subdirectory",
"dst" : "Something"
}
]
}
],
"deployments" : [
{ "host" : "deploy@myserver.com", "path" : "/var/www/mysite/public" }
],
"templateVars" : {
"APPLICATION_NAME" : "My Application",
"BACKGROUND_COLOR" : "black",
"TEXT_COLOR" : "black"
}
}
-299
View File
@@ -1,299 +0,0 @@
@import <Foundation/Foundation.j>
importPackage(Packages.java.io);
var options = {
base : "trunk",
clean : false,
deploy : false,
deployHost : null,
deployPath : null,
skipUpdate : false,
tag : false,
archive : false,
message : null,
templatePath : OBJJ_HOME + "/lib/bake/Resources/bake_template.html"
}
var targetPath,
checkoutsPath,
buildsPath,
productsPath,
version = ROUND(new Date().getTime() / 1000);
CPLogRegister(CPLogPrint);
function readConfig(configFile)
{
var fileData = String(readFile(configFile));
if (!fileData)
throw new Error("Couldn't read file: " + configFile);
var configs = JSON.parse(fileData);
return configs;
}
function update()
{
for (var i = 0; i < options.sources.length; i++)
{
var source = options.sources[i];
source.localSourcePath = checkoutsPath + "/" + source.path.replace(/\W+/g, "_");
switch (source.type)
{
case "git":
if (new File(source.localSourcePath).isDirectory())
{
CPLog.debug("git pull (" + source.localSourcePath + ")");
exec("git pull", null, new File(source.localSourcePath));
}
else
{
CPLog.debug("git clone (" + source.path + ")");
exec(["git", "clone", source.path, source.localSourcePath]);
}
break;
case "svn":
if (new File(source.localSourcePath).isDirectory())
{
CPLog.debug("svn up (" + source.localSourcePath + ")");
exec("svn up", null, new File(source.localSourcePath));
}
else
{
CPLog.debug("svn co (" + source.path + ")");
exec(["svn", "co", source.path, source.localSourcePath]);
}
break;
case "rsync":
CPLog.debug("rsync (" + source.localSourcePath + ")");
exec(["rsync", "-avz", source.path + "/", source.localSourcePath]);
break;
default :
CPLog.error("Unimplemented: " + source.type);
}
}
}
function build()
{
var versionedPath = productsPath + "/" + version + "/" + version;
for (var i = 0; i < options.sources.length; i++)
{
var source = options.sources[i];
for (var j = 0; j < source.parts.length; j++)
{
var part = source.parts[j];
var fromPath = source.localSourcePath + "/" + part.src;
var toPath = versionedPath + "/" + part.dst;
if (part.build)
{
var buildCommand = part.build.replace("$BUILD_PATH", buildsPath);
CPLog.debug("Building: " + buildCommand);
exec(buildCommand, null, new File(fromPath));
fromPath = buildsPath + "/" + part.copyFrom;
}
mkdirs(toPath);
var rsyncCommand = "rsync -aC " + fromPath + "/. " + toPath;
CPLog.debug("Rsyncing: " + rsyncCommand);
exec(rsyncCommand);
}
}
if (options.press)
{
var tempPath = versionedPath+"-Stripped";
var pressCommand = ["press", versionedPath, tempPath];
if (options.png)
pressCommand.push("--png");
var result = exec(pressCommand);
if (result.code)
throw new Error("press failed");
exec(["rm", "-rf", versionedPath]);
exec(["mv", tempPath, versionedPath]);
}
var results = exec(["bash", "-c", "find "+versionedPath+" \\( -name \"*.sj\" -or -name \"*.j\" \\) -exec cat {} \\; | wc -c | tr -d \" \""]);
var filesTotal = parseInt(results.stdout);
if (isNaN(filesTotal))
filesTotal = 0;
CPLog.debug("FILES_TOTAL=["+filesTotal+"]");
var substitutions = options.templateVars;
substitutions.VERSION = version;
substitutions.FILES_TOTAL = filesTotal;
var template = readFile(options.templatePath);
if (!template)
throw new Error("Couldn't get template");
for (var variable in substitutions)
template = template.replace(new RegExp("\\$" + variable, "g"), substitutions[variable]);
templateBytes = new java.lang.String(template).getBytes();
templateOutput = new FileOutputStream(productsPath + "/" + version + "/index.html");
templateOutput.write(templateBytes, 0, templateBytes.length);
templateOutput.close();
exec(["tar", "czf", version+".tar.gz", version], null, new File(productsPath));
}
function deploy()
{
for (var i = 0; i < options.deployments.length; i++)
{
var dep = options.deployments[i];
exec(["scp", productsPath + "/" + version + ".tar.gz", dep.host + ":~/" + version + ".tar.gz"]);
exec(["ssh", dep.host,
"tar xzf " + version + ".tar.gz; " +
"mkdir -p " + dep.path + "; " +
"mv " + version + "/" + version + "/ " + dep.path + "/" + version + "; " +
"mv " + version + "/index.html " + dep.path + "/index.html; " +
"rm " + version + ".tar.gz; " +
"rmdir " + version + "; " +
"cd " + dep.path + "; " +
"ln -nsf " + version + " Current"]);
}
}
function main()
{
var bakefile = "bakefile",
commandOpts = {};
while (args.length)
{
var arg = args.shift();
switch (arg)
{
case "--base":
commandOpts.base = args.shift();
break;
case "--tag":
commandOpts.tag = true;
break;
case "--archive":
commandOpts.archive = true;
break;
case "--clean":
commandOpts.clean = true;
break;
case "--deploy":
commandOpts.deploy = true;
break;
case "--press":
commandOpts.press = true;
break;
case "--png":
commandOpts.png = true;
break;
case "--host":
commandOpts.deployHost = args.shift();
break;
case "--path":
commandOpts.deployPath = args.shift();
break;
case "--skip-update":
commandOpts.skipUpdate = true
break;
case "--message":
commandOpts.message = args.shift();
break;
default:
bakefile = arg;
}
}
try
{
var configOpts = readConfig(bakefile);
for (var i in configOpts) options[i] = configOpts[i];
for (var i in commandOpts) options[i] = commandOpts[i];
targetPath = pwd() + "/" + bakefile.match(/^[^\.]+/)[0] + ".oven";
mkdirs(targetPath);
checkoutsPath = targetPath + "/Checkouts"
mkdirs(checkoutsPath);
buildsPath = targetPath + "/Build"
mkdirs(buildsPath);
productsPath = targetPath + "/Products"
mkdirs(productsPath);
if (!options.skipUpdate)
{
CPLog.info("Updating");
update();
}
CPLog.info("Building");
build();
if (options.deploy)
{
CPLog.info("Deploying");
deploy();
}
}
catch (e)
{
CPLog.error(e);
}
}
function exec()
{
var runtime = Packages.java.lang.Runtime.getRuntime()
var p = runtime.exec.apply(runtime, arguments);
var stdout = "";
var reader = new Packages.java.io.BufferedReader(new Packages.java.io.InputStreamReader(p.getInputStream()));
while (s = reader.readLine())
{
stdout += s;
CPLog.info("exec: " + s);
}
var stderr = "";
var reader = new Packages.java.io.BufferedReader(new Packages.java.io.InputStreamReader(p.getErrorStream()));
while (s = reader.readLine())
{
stdout += s;
CPLog.warn("exec: " + s);
}
var code = p.waitFor();
return { code : code, stdout : stdout, stderr : stderr };
}
function pwd()
{
return String(new File("").getAbsolutePath());
}
function mkdirs(path)
{
return new File(path).mkdirs();
}
+8 -6
View File
@@ -5,17 +5,19 @@
@import "Generate.j"
function main()
function main(args)
{
if (system.args.length < 1)
args.shift();
if (args.length < 1)
return printUsage();
var index = 0,
count = system.args.length;
count = args.length;
for (; index < count; ++index)
{
var argument = system.args[index];
var argument = args[index];
switch (argument)
{
@@ -25,9 +27,9 @@ function main()
case "-h":
case "--help": return printUsage();
case "config": return config.apply(this, system.args.slice(index + 1));
case "config": return config.apply(this, args.slice(index + 1));
case "gen": return gen.apply(this, system.args.slice(index + 1));
case "gen": return gen.apply(this, args.slice(index + 1));
default: print("unknown command " + argument);
}
+12 -9
View File
@@ -69,21 +69,24 @@ function loadFrameworks(frameworkPaths, aCallback)
aCallback();
}
function main()
function main(args)
{
var count = arguments.length;
// TODO: args parser
args.shift();
var count = args.length;
if (count < 1)
if (count < 2)
return printUsage();
var index = 0,
var index = 1,
frameworkPaths = [],
converter = [[Converter alloc] init];
for (; index < count; ++index)
{
switch(arguments[index])
switch(args[index])
{
case "-help":
case "--help": printUsage();
@@ -92,16 +95,16 @@ function main()
case "--mac": [converter setFormat:NibFormatMac];
break;
case "-F": frameworkPaths.push(arguments[++index]);
case "-F": frameworkPaths.push(args[++index]);
break;
case "-R": [converter setResourcesPath:arguments[++index]];
case "-R": [converter setResourcesPath:args[++index]];
break;
default: if ([converter inputPath])
[converter setOutputPath:arguments[index]];
[converter setOutputPath:args[index]];
else
[converter setInputPath:arguments[index]];
[converter setInputPath:args[index]];
}
}
-767
View File
@@ -1,767 +0,0 @@
/*
* Pure JavaScript Browser Environment
* By John Resig <http://ejohn.org/>
* Copyright 2008 John Resig, under the MIT License
*/
// The window Object
var window = this;
(function(){
// Browser Navigator
window.navigator = {
get userAgent(){
return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
}
};
var curLocation = (new java.io.File("./")).toURL();
window.__defineSetter__("location", function(url){
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function(){
curLocation = new java.net.URL( curLocation, url );
window.document = xhr.responseXML;
var event = document.createEvent();
event.initEvent("load");
window.dispatchEvent( event );
};
xhr.send();
});
window.__defineGetter__("location", function(url){
return {
get protocol(){
return curLocation.getProtocol() + ":";
},
get href(){
return curLocation.toString();
},
toString: function(){
return this.href;
}
};
});
// Timers
var timers = [];
window.setTimeout = function(fn, time){
var num;
return num = setInterval(function(){
fn();
clearInterval(num);
}, time);
};
window.setInterval = function(fn, time){
var num = timers.length;
timers[num] = new java.lang.Thread(new java.lang.Runnable({
run: function(){
while (true){
java.lang.Thread.currentThread().sleep(time);
fn();
}
}
}));
timers[num].start();
return num;
};
window.clearInterval = function(num){
if ( timers[num] ) {
timers[num].stop();
delete timers[num];
}
};
// Window Events
var events = [{}];
window.addEventListener = function(type, fn){
if ( !this.uuid || this == window ) {
this.uuid = events.length;
events[this.uuid] = {};
}
if ( !events[this.uuid][type] )
events[this.uuid][type] = [];
if ( events[this.uuid][type].indexOf( fn ) < 0 )
events[this.uuid][type].push( fn );
};
window.removeEventListener = function(type, fn){
if ( !this.uuid || this == window ) {
this.uuid = events.length;
events[this.uuid] = {};
}
if ( !events[this.uuid][type] )
events[this.uuid][type] = [];
events[this.uuid][type] =
events[this.uuid][type].filter(function(f){
return f != fn;
});
};
window.dispatchEvent = function(event){
if ( event.type ) {
if ( this.uuid && events[this.uuid][event.type] ) {
var self = this;
events[this.uuid][event.type].forEach(function(fn){
fn.call( self, event );
});
}
if ( this["on" + event.type] )
this["on" + event.type].call( self, event );
}
};
// DOM Document
window.DOMDocument = function(file){
this._file = file;
this._dom = Packages.javax.xml.parsers.
DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(file);
if ( !obj_nodes.containsKey( this._dom ) )
obj_nodes.put( this._dom, this );
};
DOMDocument.prototype = {
get nodeType(){
return 9;
},
createTextNode: function(text){
return makeNode( this._dom.createTextNode(
text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")) );
},
createElement: function(name){
return makeNode( this._dom.createElement(name.toLowerCase()) );
},
getElementsByTagName: function(name){
return new DOMNodeList( this._dom.getElementsByTagName(
name.toLowerCase()) );
},
getElementsByName: function(name){
var elems = this._dom.getElementsByTagName("*"), ret = [];
ret.item = function(i){ return this[i]; };
ret.getLength = function(){ return this.length; };
for ( var i = 0; i < elems.length; i++ ) {
var elem = elems.item(i);
if ( elem.getAttribute("name") == name )
ret.push( elem );
}
return new DOMNodeList( ret );
},
getElementById: function(id){
var elems = this._dom.getElementsByTagName("*");
for ( var i = 0; i < elems.length; i++ ) {
var elem = elems.item(i);
if ( elem.getAttribute("id") == id )
return makeNode(elem);
}
return null;
},
get body(){
return this.getElementsByTagName("body")[0];
},
get documentElement(){
return makeNode( this._dom.getDocumentElement() );
},
get ownerDocument(){
return null;
},
addEventListener: window.addEventListener,
removeEventListener: window.removeEventListener,
dispatchEvent: window.dispatchEvent,
get nodeName() {
return "#document";
},
importNode: function(node, deep){
return makeNode( this._dom.importNode(node._dom, deep) );
},
toString: function(){
return "Document" + (typeof this._file == "string" ?
": " + this._file : "");
},
get innerHTML(){
return this.documentElement.outerHTML;
},
get defaultView(){
return {
getComputedStyle: function(elem){
return {
getPropertyValue: function(prop){
prop = prop.replace(/\-(\w)/g,function(m,c){
return c.toUpperCase();
});
var val = elem.style[prop];
if ( prop == "opacity" && val == "" )
val = "1";
return val;
}
};
}
};
},
createEvent: function(){
return {
type: "",
initEvent: function(type){
this.type = type;
}
};
}
};
function getDocument(node){
return obj_nodes.get(node);
}
// DOM NodeList
window.DOMNodeList = function(list){
this._dom = list;
this.length = list.getLength();
for ( var i = 0; i < this.length; i++ ) {
var node = list.item(i);
this[i] = makeNode( node );
}
};
DOMNodeList.prototype = {
toString: function(){
return "[ " +
Array.prototype.join.call( this, ", " ) + " ]";
},
get outerHTML(){
return Array.prototype.map.call(
this, function(node){return node.outerHTML;}).join('');
}
};
// DOM Node
window.DOMNode = function(node){
this._dom = node;
};
DOMNode.prototype = {
get nodeType(){
return this._dom.getNodeType();
},
get nodeValue(){
return this._dom.getNodeValue();
},
get nodeName() {
return this._dom.getNodeName();
},
get childNodes(){
return new DOMNodeList( this._dom.getChildNodes() );
},
cloneNode: function(deep){
return makeNode( this._dom.cloneNode(deep) );
},
get ownerDocument(){
return getDocument( this._dom.ownerDocument );
},
get documentElement(){
return makeNode( this._dom.documentElement );
},
get parentNode() {
return makeNode( this._dom.getParentNode() );
},
get nextSibling() {
return makeNode( this._dom.getNextSibling() );
},
get previousSibling() {
return makeNode( this._dom.getPreviousSibling() );
},
toString: function(){
return '"' + this.nodeValue + '"';
},
get outerHTML(){
return this.nodeValue;
}
};
window.DOMComment = function(node){
this._dom = node;
};
DOMComment.prototype = extend(new DOMNode(), {
get nodeType(){
return 8;
},
get outerHTML(){
return "<!--" + this.nodeValue + "-->";
}
});
// DOM Element
window.DOMElement = function(elem){
this._dom = elem;
this.style = {
get opacity(){ return this._opacity; },
set opacity(val){ this._opacity = val + ""; }
};
// Load CSS info
var styles = (this.getAttribute("style") || "").split(/\s*;\s*/);
for ( var i = 0; i < styles.length; i++ ) {
var style = styles[i].split(/\s*:\s*/);
if ( style.length == 2 )
this.style[ style[0] ] = style[1];
}
if ( this.nodeName == "FORM" ) {
this.__defineGetter__("elements", function(){
return this.getElementsByTagName("*");
});
this.__defineGetter__("length", function(){
var elems = this.elements;
for ( var i = 0; i < elems.length; i++ ) {
this[i] = elems[i];
}
return elems.length;
});
}
if ( this.nodeName == "SELECT" ) {
this.__defineGetter__("options", function(){
return this.getElementsByTagName("option");
});
}
this.defaultValue = this.value;
};
DOMElement.prototype = extend( new DOMNode(), {
get nodeName(){
return this.tagName;
},
get tagName(){
return this._dom.getTagName().toUpperCase();
},
toString: function(){
return "<" + this.tagName + (this.id ? "#" + this.id : "" ) + ">";
},
get outerHTML(){
var ret = "<" + this.tagName, attr = this.attributes;
for ( var i in attr )
ret += " " + i + "='" + attr[i] + "'";
if ( this.childNodes.length || this.nodeName == "SCRIPT" )
ret += ">" + this.childNodes.outerHTML +
"</" + this.tagName + ">";
else
ret += "/>";
return ret;
},
get attributes(){
var attr = {}, attrs = this._dom.getAttributes();
for ( var i = 0; i < attrs.getLength(); i++ )
attr[ attrs.item(i).nodeName ] = attrs.item(i).nodeValue;
return attr;
},
get innerHTML(){
return this.childNodes.outerHTML;
},
set innerHTML(html){
html = html.replace(/<\/?([A-Z]+)/g, function(m){
return m.toLowerCase();
}).replace(/&nbsp;/g, " ");
var nodes = this.ownerDocument.importNode(
new DOMDocument( new java.io.ByteArrayInputStream(
(new java.lang.String("<wrap>" + html + "</wrap>"))
.getBytes("UTF8"))).documentElement, true).childNodes;
while (this.firstChild)
this.removeChild( this.firstChild );
for ( var i = 0; i < nodes.length; i++ )
this.appendChild( nodes[i] );
},
get textContent(){
return nav(this.childNodes);
function nav(nodes){
var str = "";
for ( var i = 0; i < nodes.length; i++ )
if ( nodes[i].nodeType == 3 )
str += nodes[i].nodeValue;
else if ( nodes[i].nodeType == 1 )
str += nav(nodes[i].childNodes);
return str;
}
},
set textContent(text){
while (this.firstChild)
this.removeChild( this.firstChild );
this.appendChild( this.ownerDocument.createTextNode(text));
},
style: {},
clientHeight: 0,
clientWidth: 0,
offsetHeight: 0,
offsetWidth: 0,
get disabled() {
var val = this.getAttribute("disabled");
return val != "false" && !!val;
},
set disabled(val) { return this.setAttribute("disabled",val); },
get checked() {
var val = this.getAttribute("checked");
return val != "false" && !!val;
},
set checked(val) { return this.setAttribute("checked",val); },
get selected() {
if ( !this._selectDone ) {
this._selectDone = true;
if ( this.nodeName == "OPTION" && !this.parentNode.getAttribute("multiple") ) {
var opt = this.parentNode.getElementsByTagName("option");
if ( this == opt[0] ) {
var select = true;
for ( var i = 1; i < opt.length; i++ )
if ( opt[i].selected ) {
select = false;
break;
}
if ( select )
this.selected = true;
}
}
}
var val = this.getAttribute("selected");
return val != "false" && !!val;
},
set selected(val) { return this.setAttribute("selected",val); },
get className() { return this.getAttribute("class") || ""; },
set className(val) {
return this.setAttribute("class",
val.replace(/(^\s*|\s*$)/g,""));
},
get type() { return this.getAttribute("type") || ""; },
set type(val) { return this.setAttribute("type",val); },
get defaultValue() { return this.getAttribute("defaultValue") || ""; },
set defaultValue(val) { return this.setAttribute("defaultValue",val); },
get value() { return this.getAttribute("value") || ""; },
set value(val) { return this.setAttribute("value",val); },
get src() { return this.getAttribute("src") || ""; },
set src(val) { return this.setAttribute("src",val); },
get id() { return this.getAttribute("id") || ""; },
set id(val) { return this.setAttribute("id",val); },
getAttribute: function(name){
return this._dom.hasAttribute(name) ?
new String( this._dom.getAttribute(name) ) :
null;
},
setAttribute: function(name,value){
this._dom.setAttribute(name,value);
},
removeAttribute: function(name){
this._dom.removeAttribute(name);
},
get childNodes(){
return new DOMNodeList( this._dom.getChildNodes() );
},
get firstChild(){
return makeNode( this._dom.getFirstChild() );
},
get lastChild(){
return makeNode( this._dom.getLastChild() );
},
appendChild: function(node){
this._dom.appendChild( node._dom );
},
insertBefore: function(node,before){
this._dom.insertBefore( node._dom, before ? before._dom : before );
execScripts( node );
function execScripts( node ) {
if ( node.nodeName == "SCRIPT" ) {
if ( !node.getAttribute("src") ) {
eval.call( window, node.textContent );
}
} else {
var scripts = node.getElementsByTagName("script");
for ( var i = 0; i < scripts.length; i++ ) {
execScripts( node );
}
}
}
},
removeChild: function(node){
this._dom.removeChild( node._dom );
},
getElementsByTagName: DOMDocument.prototype.getElementsByTagName,
addEventListener: window.addEventListener,
removeEventListener: window.removeEventListener,
dispatchEvent: window.dispatchEvent,
click: function(){
var event = document.createEvent();
event.initEvent("click");
this.dispatchEvent(event);
},
submit: function(){
var event = document.createEvent();
event.initEvent("submit");
this.dispatchEvent(event);
},
focus: function(){
var event = document.createEvent();
event.initEvent("focus");
this.dispatchEvent(event);
},
blur: function(){
var event = document.createEvent();
event.initEvent("blur");
this.dispatchEvent(event);
},
get contentWindow(){
return this.nodeName == "IFRAME" ? {
document: this.contentDocument
} : null;
},
get contentDocument(){
if ( this.nodeName == "IFRAME" ) {
if ( !this._doc )
this._doc = new DOMDocument(
new java.io.ByteArrayInputStream((new java.lang.String(
"<html><head><title></title></head><body></body></html>"))
.getBytes("UTF8")));
return this._doc;
} else
return null;
}
});
// Helper method for extending one object with another
function extend(a,b) {
for ( var i in b ) {
var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);
if ( g || s ) {
if ( g )
a.__defineGetter__(i, g);
if ( s )
a.__defineSetter__(i, s);
} else
a[i] = b[i];
}
return a;
}
// Helper method for generating the right
// DOM objects based upon the type
var obj_nodes = new java.util.HashMap();
function makeNode(node){
if ( node ) {
if ( !obj_nodes.containsKey( node ) )
obj_nodes.put( node, node.getNodeType() == 1?
new DOMElement( node ) :
node.getNodeType() == 8 ?
new DOMComment( node ) :
new DOMNode( node ) );
return obj_nodes.get(node);
} else
return null;
}
// XMLHttpRequest
// Originally implemented by Yehuda Katz
window.XMLHttpRequest = function(){
this.headers = {};
this.responseHeaders = {};
};
XMLHttpRequest.prototype = {
open: function(method, url, async, user, password){
this.readyState = 1;
if (async)
this.async = true;
this.method = method || "GET";
this.url = url;
this.onreadystatechange();
},
setRequestHeader: function(header, value){
this.headers[header] = value;
},
getResponseHeader: function(header){ },
send: function(data){
var self = this;
function makeRequest(){
var url = new java.net.URL(curLocation, self.url);
if ( url.getProtocol() == "file" ) {
if ( self.method == "PUT" ) {
var out = new java.io.FileWriter(
new java.io.File( new java.net.URI( url.toString() ) ) ),
text = new java.lang.String( data || "" );
out.write( text, 0, text.length() );
out.flush();
out.close();
} else if ( self.method == "DELETE" ) {
var file = new java.io.File( new java.net.URI( url.toString() ) );
file["delete"]();
} else {
var connection = url.openConnection();
connection.connect();
handleResponse();
}
} else {
var connection = url.openConnection();
connection.setRequestMethod( self.method );
// Add headers to Java connection
for (var header in self.headers)
connection.addRequestProperty(header, self.headers[header]);
connection.connect();
// Stick the response headers into responseHeaders
for (var i = 0; ; i++) {
var headerName = connection.getHeaderFieldKey(i);
var headerValue = connection.getHeaderField(i);
if (!headerName && !headerValue) break;
if (headerName)
self.responseHeaders[headerName] = headerValue;
}
handleResponse();
}
function handleResponse(){
self.readyState = 4;
self.status = parseInt(connection.responseCode) || undefined;
self.statusText = connection.responseMessage || "";
var stream = new java.io.InputStreamReader(connection.getInputStream()),
buffer = new java.io.BufferedReader(stream), line;
while ((line = buffer.readLine()) != null)
self.responseText += line;
self.responseXML = null;
if ( self.responseText.match(/^\s*</) ) {
try {
self.responseXML = new DOMDocument(
new java.io.ByteArrayInputStream(
(new java.lang.String(
self.responseText)).getBytes("UTF8")));
} catch(e) {}
}
}
self.onreadystatechange();
}
if (this.async)
(new java.lang.Thread(new java.lang.Runnable({
run: makeRequest
}))).start();
else
makeRequest();
},
abort: function(){},
onreadystatechange: function(){},
getResponseHeader: function(header){
if (this.readyState < 3)
throw new Error("INVALID_STATE_ERR");
else {
var returnedHeaders = [];
for (var rHeader in this.responseHeaders) {
if (rHeader.match(new Regexp(header, "i")))
returnedHeaders.push(this.responseHeaders[rHeader]);
}
if (returnedHeaders.length)
return returnedHeaders.join(", ");
}
return null;
},
getAllResponseHeaders: function(header){
if (this.readyState < 3)
throw new Error("INVALID_STATE_ERR");
else {
var returnedHeaders = [];
for (var header in this.responseHeaders)
returnedHeaders.push( header + ": " + this.responseHeaders[header] );
return returnedHeaders.join("\r\n");
}
},
async: true,
readyState: 0,
responseText: "",
status: 0
};
})();