public final boolean webkit = isWebkit();
protected abstract boolean isIe6();
+
protected abstract boolean isIe8();
+
protected abstract boolean isIe9();
+
protected abstract boolean isIe10();
+
protected abstract boolean isIe11();
+
protected abstract boolean isMozilla();
+
protected abstract boolean isMsie();
+
protected abstract boolean isOpera();
+
protected abstract boolean isWebkit();
}
private String dumpArguments(Object[] arguments, String sep) {
StringBuilder b = new StringBuilder();
- for (int i = 0, l = arguments.length; i < l; i++ ) {
+ for (int i = 0, l = arguments.length; i < l; i++) {
b.append("[").append(i).append("]");
Object o = arguments[i];
if (o == null) {
b.append(" null");
} else if (o.getClass().isArray()) {
- b.append(dumpArguments((Object[])o, sep + " "));
+ b.append(dumpArguments((Object[]) o, sep + " "));
} else if (o instanceof JavaScriptObject) {
- JavaScriptObject jso = (JavaScriptObject)o;
+ JavaScriptObject jso = (JavaScriptObject) o;
if (JsUtils.isElement(jso)) {
b.append("(Element) ").append(jso.toString());
} else {
- b.append("(JSO) ").append(jso.<Properties>cast().toJsonString());
+ b.append("(JSO) ").append(jso.<Properties> cast().toJsonString());
}
} else {
b.append("(").append(o.getClass().getName()).append(") ").append(o);
}
- if (i < l-1) b.append(sep);
+ if (i < l - 1)
+ b.append(sep);
}
return b.toString();
}
public <T extends com.google.gwt.dom.client.Element> T getElement() {
- return element.<T>cast();
+ return element.<T> cast();
}
public <T extends com.google.gwt.dom.client.Element> Function setElement(T e) {
public Function setEvent(Event e) {
event = e;
- element = e != null ? e.getCurrentEventTarget().<com.google.gwt.dom.client.Element>cast() : null;
+ element =
+ e != null ? e.getCurrentEventTarget().<com.google.gwt.dom.client.Element> cast() : null;
return this;
}
/**
* Set the list of arguments to be passed to the function.
*/
- public Function setArguments(Object...arguments) {
+ public Function setArguments(Object... arguments) {
this.arguments = arguments;
return this;
}
*/
@SuppressWarnings("unchecked")
public <T extends JavaScriptObject> T getArgumentJSO(int argIdx, int pos) {
- return (T)getArgument(argIdx, pos, JavaScriptObject.class);
+ return (T) getArgument(argIdx, pos, JavaScriptObject.class);
}
/**
* Always returns an array.
*/
public Object[] getArgumentArray(int idx) {
- Object o = idx < 0 ? arguments: getArgument(idx);
+ Object o = idx < 0 ? arguments : getArgument(idx);
if (o != null) {
- return o.getClass().isArray() ? (Object[])o : new Object[]{o};
+ return o.getClass().isArray() ? (Object[]) o : new Object[] {o};
} else if (idx == 0) {
return arguments;
}
Object[] objs = getArgumentArray(argIdx);
Object o = objs.length > pos ? objs[pos] : null;
if (o != null && (
- // When type is null we don't safety check
- type == null ||
- // The object is an instance of the type requested
- o.getClass() == type ||
- // Overlay types
- type == JavaScriptObject.class && o instanceof JavaScriptObject
- )) {
- return (T)o;
+ // When type is null we don't safety check
+ type == null ||
+ // The object is an instance of the type requested
+ o.getClass() == type ||
+ // Overlay types
+ type == JavaScriptObject.class && o instanceof JavaScriptObject
+ )) {
+ return (T) o;
}
return null;
}
* @deprecated use use setArguments instead.
*/
@Deprecated
- public void setData(Object...arguments) {
+ public void setData(Object... arguments) {
setArguments(arguments);
}
*/
public void cancel(com.google.gwt.dom.client.Element e) {
setElement(e);
- // This has to be the order of calls
- cancel(e.<com.google.gwt.user.client.Element>cast());
+ // This has to be the order of calls
+ cancel(e.<com.google.gwt.user.client.Element> cast());
}
/**
setElement(e);
setIndex(i);
// This has to be the order of calls
- return f(e.<com.google.gwt.user.client.Element>cast(), i);
+ return f(e.<com.google.gwt.user.client.Element> cast(), i);
}
/**
setElement(e);
setIndex(i);
Widget w = GQuery.getAssociatedWidget(e);
- if (w != null){
+ if (w != null) {
f(w, i);
} else {
- f(e.<com.google.gwt.dom.client.Element>cast());
+ f(e.<com.google.gwt.dom.client.Element> cast());
}
return null;
}
* Override this method for bound callbacks.
*/
public void f(int i, Object arg) {
- f(i, new Object[]{arg});
+ f(i, new Object[] {arg});
}
/**
setIndex(i);
setArguments(args);
if (args.length == 1 && args[0] instanceof JavaScriptObject) {
- if (JsUtils.isElement((JavaScriptObject)args[0])) {
- setElement((com.google.gwt.dom.client.Element)args[0]);
+ if (JsUtils.isElement((JavaScriptObject) args[0])) {
+ setElement((com.google.gwt.dom.client.Element) args[0]);
f(getElement(), i);
- } else if (JsUtils.isEvent((JavaScriptObject)args[0])) {
- setEvent((Event)args[0]);
+ } else if (JsUtils.isEvent((JavaScriptObject) args[0])) {
+ setEvent((Event) args[0]);
f(getEvent());
} else {
f();
*/
public void f(com.google.gwt.dom.client.Element e) {
setElement(e);
- // This has to be the order of calls
- f(e.<com.google.gwt.user.client.Element>cast());
+ // This has to be the order of calls
+ f(e.<com.google.gwt.user.client.Element> cast());
}
/**
* @param elem takes a com.google.gwt.user.client.Element
*/
private boolean loop = false;
+
@Deprecated
public void f(com.google.gwt.user.client.Element e) {
setElement(e);
Widget w = e != null ? GQuery.getAssociatedWidget(e) : null;
- if (w != null){
+ if (w != null) {
loop = true;
f(w);
} else {
* 'public void f()' or 'public void f(Element e)' to handle these elements and
* avoid a runtime exception.
*/
- public void f(Widget w){
+ public void f(Widget w) {
setElement(w.getElement());
if (loop) {
loop = false;
f();
} else {
- f(w.getElement().<com.google.gwt.dom.client.Element>cast());
+ f(w.getElement().<com.google.gwt.dom.client.Element> cast());
}
}
* They are intentionally final to avoid override them.
*/
public final void fe(Object arg) {
- fe(new Object[]{arg});
+ fe(new Object[] {arg});
}
/**
public final void fe(com.google.gwt.dom.client.Element elem) {
if (GWT.getUncaughtExceptionHandler() != null) {
try {
- f(elem.<com.google.gwt.dom.client.Element>cast());
+ f(elem.<com.google.gwt.dom.client.Element> cast());
} catch (Exception e) {
GWT.getUncaughtExceptionHandler().onUncaughtException(e);
}
return;
}
- f(elem.<com.google.gwt.dom.client.Element>cast());
+ f(elem.<com.google.gwt.dom.client.Element> cast());
}
}
// We are running DevMode, so create Js versions of the factories
method = gwt.getMethod("create", Class.class);
ret = method.invoke(null,
- new Object[] {JsonFactory.class});
+ new Object[] {JsonFactory.class});
jsonFactory = (JsonFactory) ret;
ajaxTransport = new AjaxTransportJs();
return;
/**
* A Browser object with a set of browser-specific flags.
*/
- public static final Browser browser = GWT.isClient() ? GWT.<Browser>create(Browser.class) : null;
+ public static final Browser browser = GWT.isClient() ? GWT.<Browser> create(Browser.class) : null;
/**
* An object with the same methods than window.console.
*/
- public static final Console console = GWT.isClient() ? GWT.<Console>create(Console.class) : null;
+ public static final Console console = GWT.isClient() ? GWT.<Console> create(Console.class) : null;
/**
* Object to store element data (public so as we can access to it from tests).
// Sizzle POS regex : usefull in some methods
// TODO: Share this static with SelectorEngineSizzle
- private static RegExp posRegex = RegExp.compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$");
+ private static RegExp posRegex = RegExp
+ .compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$");
/**
* Implementation class used for style manipulations.
/**
* The window object.
*/
- public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element>cast() : null;
+ public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element> cast()
+ : null;
private static Element windowData = null;
}
return JsUtils.isWindow(jso) ? $(jso.<Element> cast()) :
- JsUtils.isElement(jso) ? $(jso.<Element> cast()) :
- JsUtils.isEvent(jso) ? $(jso.<Event> cast()) :
- JsUtils.isNodeList(jso) ? $(jso.<NodeList<Element>> cast()) :
- $(jso.<Element> cast());
+ JsUtils.isElement(jso) ? $(jso.<Element> cast()) :
+ JsUtils.isEvent(jso) ? $(jso.<Event> cast()) :
+ JsUtils.isNodeList(jso) ? $(jso.<NodeList<Element>> cast()) :
+ $(jso.<Element> cast());
}
/**
public static GQuery $(Object o) {
if (o != null) {
if (o instanceof String) {
- return $((String)o);
+ return $((String) o);
}
if (o instanceof GQuery) {
- return (GQuery)o;
+ return (GQuery) o;
}
if (o instanceof Function) {
- return $((Function)o);
+ return $((Function) o);
}
if (JsUtils.isElement(o)) {
- return $(JsUtils.<Element>cast(o));
+ return $(JsUtils.<Element> cast(o));
}
if (o instanceof JavaScriptObject) {
- return $((JavaScriptObject)o);
+ return $((JavaScriptObject) o);
}
if (o instanceof IsWidget) {
return $(Arrays.asList(o));
}
- console.log("Error: GQuery.$(Object o) could not wrap the type : ", o.getClass().getName(), o);
+ console
+ .log("Error: GQuery.$(Object o) could not wrap the type : ", o.getClass().getName(), o);
}
return $();
}
if (o instanceof Node) {
elms.addNode((Node) o);
} else if (o instanceof IsWidget) {
- elms.addNode(((IsWidget)o).asWidget().getElement());
+ elms.addNode(((IsWidget) o).asWidget().getElement());
}
}
}
return
// return all nodes added to the wrapper
$(n.getChildNodes())
- // detach nodes from their temporary parent
- .remove(null, false);
+ // detach nodes from their temporary parent
+ .remove(null, false);
}
/**
wrapperMap.put("td", trWrapper);
wrapperMap.put("th", trWrapper);
wrapperMap.put("col", new TagWrapper(2, "<table><tbody></tbody><colgroup>",
- "</colgroup></table>"));
+ "</colgroup></table>"));
wrapperMap.put("area", new TagWrapper(1, "<map>", "</map>"));
}
return engine;
}
- private static native void scrollIntoViewImpl(Node n)
- /*-{
+ private static native void scrollIntoViewImpl(Node n) /*-{
if (n)
n.scrollIntoView()
}-*/;
- private static native void setElementValue(Element e, String value)
- /*-{
+ private static native void setElementValue(Element e, String value) /*-{
e.value = value;
}-*/;
public <T extends GQuery> T as(Class<T> plugin) {
// GQuery is not a plugin for itself
if (plugin == GQUERY) {
- return (T)this;
+ return (T) this;
} else if (plugins != null) {
Plugin<?> p = plugins.get(plugin);
if (p != null) {
- return (T)p.init(this);
+ return (T) p.init(this);
}
}
throw new RuntimeException("No plugin registered for class " + plugin.getName());
*/
@SuppressWarnings("unchecked")
public <T> T data(String name) {
- return isEmpty() ? null : (T)data(get(0), name, null);
+ return isEmpty() ? null : (T) data(get(0), name, null);
}
/**
return end();
}
- private native Element getPreviousSiblingElement(Element elem)
- /*-{
-
+ private native Element getPreviousSiblingElement(Element elem) /*-{
var sib = elem.previousSibling;
while (sib && sib.nodeType != 1)
sib = sib.previousSibling;
* Set the current coordinates of every element in the set of matched elements, relative to the document.
*/
public GQuery offset(int top, int left) {
- for (Element element : elements()){
+ for (Element element : elements()) {
GQuery g = $(element);
String position = g.css("position", true);
long curTop = 0;
long curLeft = 0;
- if (("absolute".equals(position) || "fixed".equals(position)) && ("auto".equals(curCSSTop) || "auto".equals(curCSSLeft))) {
+ if (("absolute".equals(position) || "fixed".equals(position))
+ && ("auto".equals(curCSSTop) || "auto".equals(curCSSLeft))) {
Offset curPosition = g.position();
curTop = curPosition.top;
curLeft = curPosition.left;
return 0;
}
// height including padding and border
- int outerHeight = (int)cur("offsetHeight", true);
+ int outerHeight = (int) cur("offsetHeight", true);
if (includeMargin) {
outerHeight += cur("marginTop", true) + cur("marginBottom", true);
}
return 0;
}
// width including padding and border
- int outerWidth = (int)cur("offsetWidth", true);
+ int outerWidth = (int) cur("offsetWidth", true);
if (includeMargin) {
outerWidth += cur("marginRight", true) + cur("marginLeft", true);
}
* including the element matched by the selector.
*/
public GQuery parentsUntil(final String selector) {
- return parentsUntil(new Predicate(){
+ return parentsUntil(new Predicate() {
@Override
public <T> boolean f(T e, int index) {
return selector != null && $(e).is(selector);
*/
public <T> T prop(String key) {
assert key != null : "Key is null";
- return isEmpty() ? null : JsUtils.<T>prop(get(0), key);
+ return isEmpty() ? null : JsUtils.<T> prop(get(0), key);
}
/**
*/
public <T> T prop(String key, Class<? extends T> clz) {
assert key != null : "Key is null";
- return isEmpty() ? null : JsUtils.<T>prop(get(0), key, clz);
+ return isEmpty() ? null : JsUtils.<T> prop(get(0), key, clz);
}
/**
*/
public GQuery removeProp(String name) {
for (Element e : elements) {
- e.<JsCache>cast().delete(name);
+ e.<JsCache> cast().delete(name);
}
return this;
}
elStr = JsUtils.isXML(e) ? JsUtils.XML2String(e) : e.getString();
} catch (Exception e2) {
elStr =
- "< " + (e == null ? "null" : e.getNodeName())
- + "(gquery, error getting the element string representation: " + e2.getMessage()
- + ")/>";
+ "< " + (e == null ? "null" : e.getNodeName())
+ + "(gquery, error getting the element string representation: " + e2.getMessage()
+ + ")/>";
}
r += (pretty && r.length() > 0 ? "\n " : "") + elStr;
}
* converts a JsonBuilder instance into another JsonBuilder type but
* preserving the underlying data object.
*/
- <T extends JsonBuilder> T as (Class<T> clz);
+ <T extends JsonBuilder> T as(Class<T> clz);
}
* @param index
* the element position in the gquery elements array.
*/
- public boolean f(Element e, int index) {
- return f((Object)e, index);
+ public boolean f(Element e, int index) {
+ return f((Object) e, index);
}
public <T> boolean f(T e, int index) {
return JsUtils.parseJSON(p);
} catch (Exception e) {
if (!GWT.isProdMode()) {
- System.err.println("Error creating Properties: \n> " + properties + "\n< " + p + "\n" + e.getMessage());
+ System.err.println("Error creating Properties: \n> " + properties + "\n< " + p + "\n"
+ + e.getMessage());
}
}
}
public static String wrapPropertiesString(String s) {
String ret = s //
.replaceAll("\\s*/\\*[\\s\\S]*?\\*/\\s*", "") // Remove comments
- .replaceAll("([:\\)\\(,;}{'\"])\\s+" , "$1") // Remove spaces
- .replaceAll("\\s+([:\\)\\(,;}{'\"])" , "$1") // Remove spaces
+ .replaceAll("([:\\)\\(,;}{'\"])\\s+", "$1") // Remove spaces
+ .replaceAll("\\s+([:\\)\\(,;}{'\"])", "$1") // Remove spaces
.replaceFirst("^[\\(]+(.*)[\\)]+$", "$1") // Remove ()
- .replaceAll("\\([\"']([^\\)]+)[\"']\\)" , "($1)") // Remove quotes
+ .replaceAll("\\([\"']([^\\)]+)[\"']\\)", "($1)") // Remove quotes
.replaceAll("[;,]+([\\w-\\$]+:|$)", ";$1") // Change comma by semicolon
.replaceAll("([^,;])([\\]}])", "$1;$2") // Put control semicolon used below
.replaceAll(":\\s*[\"']?([^;\\{\\}\\[\\]\"']*)[\"']?\\s*([;,]+|$)", ":\"$1\";") // put quotes to all values (even empty)
}
private JsCache c() {
- return this.<JsCache>cast();
+ return this.<JsCache> cast();
}
public final native Properties cloneProps() /*-{
@SuppressWarnings("unchecked")
public final <T> T get(Object name) {
// Casting because of issue_135
- return (T)c().get(String.valueOf(name));
+ return (T) c().get(String.valueOf(name));
}
public final boolean getBoolean(Object name) {
final Object o = c().get(String.valueOf(name));
if (o != null) {
if (o instanceof Function) {
- return (Function)o;
+ return (Function) o;
} else if (o instanceof JavaScriptObject) {
- Object f = ((JavaScriptObject)o).<Properties>cast().getObject("__f");
+ Object f = ((JavaScriptObject) o).<Properties> cast().getObject("__f");
if (f != null && f instanceof Function) {
return (Function) f;
}
- return new JsUtils.JsFunction((JavaScriptObject)o);
+ return new JsUtils.JsFunction((JavaScriptObject) o);
}
}
return null;
@SuppressWarnings("unchecked")
public final <T extends JavaScriptObject> T getJavaScriptObject(Object name) {
// Casting because of issue_135
- return (T)c().getJavaScriptObject(String.valueOf(name));
+ return (T) c().getJavaScriptObject(String.valueOf(name));
}
public final JsArrayMixed getArray(Object name) {
return JsUtils.param(JsCache.checkNull(this));
}
- public final boolean isEmpty(){
+ public final boolean isEmpty() {
return c().length() == 0;
}
public final <J extends IsProperties> J load(Object prp) {
c().clear();
if (prp instanceof JsCache) {
- c().copy((JsCache)prp);
+ c().copy((JsCache) prp);
}
return getDataImpl();
}
@SuppressWarnings("unchecked")
public final <J> J getDataImpl() {
- return (J)this;
+ return (J) this;
}
public final String getJsonName() {
public J load(Object prp) {
assert prp == null || prp instanceof JavaScriptObject || prp instanceof String;
if (prp != null && prp instanceof String) {
- return parse((String)prp);
+ return parse((String) prp);
}
if (prp != null) {
- p = (Properties)prp;
+ p = (Properties) prp;
}
- return (J)this;
+ return (J) this;
}
protected <T> void setArrayBase(String n, T[] r) {
if (r.length > 0 && r[0] instanceof JsonBuilder) {
JsArray<JavaScriptObject> a = JavaScriptObject.createArray().cast();
for (T o : r) {
- a.push(((JsonBuilder)o).<Properties>getDataImpl());
+ a.push(((JsonBuilder) o).<Properties> getDataImpl());
}
p.set(n, a);
} else {
protected <T> T[] getArrayBase(String n, T[] r, Class<T> clazz) {
JsObjectArray<?> a = p.getArray(n).cast();
int l = r.length;
- for (int i = 0 ; i < l ; i++) {
+ for (int i = 0; i < l; i++) {
Object w = a.get(i);
Class<?> c = w.getClass();
do {
if (c.equals(clazz)) {
- r[i] = (T)w;
+ r[i] = (T) w;
break;
}
c = c.getSuperclass();
@SuppressWarnings("unchecked")
public <T extends IsProperties> T set(Object key, Object val) {
if (val instanceof IsProperties) {
- p.set(key, ((IsProperties)val).getDataImpl());
+ p.set(key, ((IsProperties) val).getDataImpl());
} else {
p.set(key, val);
}
- return (T)this;
+ return (T) this;
}
public <T extends JsonBuilder> T as(Class<T> clz) {
*/
public interface JsonFactory {
<T extends JsonBuilder> T create(Class<T> clz);
+
IsProperties create(String s);
+
IsProperties create();
}
public abstract class XmlBuilderBase<J extends XmlBuilderBase<?>> implements XmlBuilder {
// TODO empty document
- protected GQuery g = $((Element)JsUtils.parseXML("<root/>"));
+ protected GQuery g = $((Element) JsUtils.parseXML("<root/>"));
public void append(String xml) {
g.append(JsUtils.parseXML(xml));
}
public double getTextAsNumber() {
- String t = g.text().replaceAll("[^\\d\\.\\-]", "");
+ String t = g.text().replaceAll("[^\\d\\.\\-]", "");
return t.isEmpty() ? 0 : Double.parseDouble(t);
}
public Date getTextAsDate() {
- String t = g.text().trim();
+ String t = g.text().trim();
if (t.matches("\\d+")) {
return new Date(Long.parseLong(t));
} else {
- return new Date((long)JsDate.parse(t));
+ return new Date((long) JsDate.parse(t));
}
}
public boolean getTextAsBoolean() {
- String t = g.text().trim().toLowerCase();
+ String t = g.text().trim().toLowerCase();
return !t.matches("^(|false|off|0)$");
}
public <T extends Enum<T>> T getTextAsEnum(Class<T> clazz) {
- String t = g.text().trim();
+ String t = g.text().trim();
return Enum.valueOf(clazz, t);
}
@SuppressWarnings("unchecked")
public J load(Object o) {
- assert o == null || o instanceof JavaScriptObject && JsUtils.isElement((JavaScriptObject)o) || o instanceof String;
+ assert o == null || o instanceof JavaScriptObject && JsUtils.isElement((JavaScriptObject) o)
+ || o instanceof String;
if (o != null && o instanceof String) {
- return parse((String)o);
+ return parse((String) o);
}
if (o != null) {
- g=$((Element)o);
+ g = $((Element) o);
}
- return (J)this;
+ return (J) this;
}
@SuppressWarnings("unchecked")
protected <T> void setArrayBase(String n, T[] r) {
String v = "";
- for (T t: r) {
+ for (T t : r) {
v += String.valueOf(t);
}
setBase(n, v);
@SuppressWarnings("unchecked")
public <T> T setText(String t) {
g.text(t);
- return (T)this;
+ return (T) this;
}
public String toString() {
*/
REPEAT_Y;
- public String getCssName(){
+ public String getCssName() {
return name().toLowerCase().replace('_', '-');
}
}
private static native boolean setAttributeNode(Element e, String name,
Object value) /*-{
- var attrNode = e.getAttributeNode(name);
- if (attrNode) {
- attrNode.nodeValue = value;
- return true;
- }
- return false;
+ var attrNode = e.getAttributeNode(name);
+ if (attrNode) {
+ attrNode.nodeValue = value;
+ return true;
+ }
+ return false;
}-*/;
@Override
private boolean initialized = false;
- public ConsoleIe9(){
+ public ConsoleIe9() {
init();
}
super.clear();
}
}
+
@Override
public void dir(Object arg) {
if (initialized) {
super.dir(arg);
}
}
+
@Override
public void error(JavaScriptObject arg) {
if (initialized) {
super.error(arg);
}
}
+
@Override
public void info(JavaScriptObject arg) {
if (initialized) {
super.info(arg);
}
}
+
@Override
public void profile(String title) {
if (initialized) {
super.profile(title);
}
}
+
@Override
public void profileEnd(String title) {
if (initialized) {
super.profileEnd(title);
}
}
+
@Override
public void warn(JavaScriptObject arg) {
if (initialized) {
super.warn(arg);
}
}
+
@Override
- public void group(Object arg) {}
+ public void group(Object arg) {
+ }
+
@Override
- public void groupCollapsed(Object arg) {}
+ public void groupCollapsed(Object arg) {
+ }
+
@Override
- public void groupEnd() {}
+ public void groupEnd() {
+ }
+
@Override
- public void time(String title) {}
+ public void time(String title) {
+ }
+
@Override
- public void timeStamp(Object arg) {}
+ public void timeStamp(Object arg) {
+ }
+
@Override
- public void timeEnd(String title) {}
+ public void timeEnd(String title) {
+ }
}
/**
private ConsoleImpl impl;
public ConsoleBrowser() {
- impl = GQuery.browser.ie8? new ConsoleIe8(): GQuery.browser.ie9? new ConsoleIe9(): new ConsoleImpl();
+ impl =
+ GQuery.browser.ie8 ? new ConsoleIe8() : GQuery.browser.ie9 ? new ConsoleIe9()
+ : new ConsoleImpl();
}
@Override
*/
public class DocumentStyleImpl {
- private static final RegExp cssNumberRegex = RegExp.compile("^(fillOpacity|fontWeight|lineHeight|opacity|orphans|widows|zIndex|zoom)$", "i");
+ private static final RegExp cssNumberRegex = RegExp.compile(
+ "^(fillOpacity|fontWeight|lineHeight|opacity|orphans|widows|zIndex|zoom)$", "i");
private static final RegExp sizeRegex = RegExp.compile("^(client|offset|)(width|height)$", "i");
/**
}
private Element attachTemporary(Element elem) {
- Element lastParent = $(elem).parents().last().get(0);
+ Element lastParent = $(elem).parents().last().get(0);
- if (lastParent == null){
+ if (lastParent == null) {
// the element itself is detached
lastParent = elem;
}
// inline elements do not have width nor height unless we set it to inline-block
private void fixInlineElement(Element e) {
- if (e.getClientHeight() == 0 && e.getClientWidth() == 0 && "inline".equals(curCSS(e, "display", true))) {
+ if (e.getClientHeight() == 0 && e.getClientWidth() == 0
+ && "inline".equals(curCSS(e, "display", true))) {
setStyleProperty(e, "display", "inline-block");
setStyleProperty(e, "width", "auto");
setStyleProperty(e, "height", "auto");
public int getHeight(Element e) {
fixInlineElement(e);
- return (int) (e.getClientHeight() - num(curCSS(e, "paddingTop", true)) - num(curCSS(e, "paddingBottom", true)));
+ return (int) (e.getClientHeight() - num(curCSS(e, "paddingTop", true)) - num(curCSS(e,
+ "paddingBottom", true)));
}
public double getOpacity(Element e) {
public int getWidth(Element e) {
fixInlineElement(e);
- return (int) (e.getClientWidth() - num(curCSS(e, "paddingLeft", true)) - num(curCSS(e, "paddingRight", true)));
+ return (int) (e.getClientWidth() - num(curCSS(e, "paddingLeft", true)) - num(curCSS(e,
+ "paddingRight", true)));
}
/**
protected native String getComputedStyle(Element elem, String hyphenName,
String camelName, String pseudo) /*-{
try {
- var cStyle = $doc.defaultView.getComputedStyle(elem, pseudo);
- return cStyle && cStyle.getPropertyValue ? cStyle.getPropertyValue(hyphenName) : null;
+ var cStyle = $doc.defaultView.getComputedStyle(elem, pseudo);
+ return cStyle && cStyle.getPropertyValue ? cStyle.getPropertyValue(hyphenName) : null;
} catch(e) {return null;}
}-*/;
@Override
public int getHeight(Element e) {
- return (int) (e.getOffsetHeight() - num(curCSS(e, "paddingTop", true)) - num(curCSS(e, "paddingBottom", true))
+ return (int) (e.getOffsetHeight() - num(curCSS(e, "paddingTop", true))
+ - num(curCSS(e, "paddingBottom", true))
- num(curCSS(e, "borderTopWidth", true)) - num(curCSS(e, "borderBottomWidth", true)));
}
@Override
public int getWidth(Element e) {
- return (int) (e.getOffsetWidth() - num(curCSS(e, "paddingLeft", true)) - num(curCSS(e, "paddingRight", true))
+ return (int) (e.getOffsetWidth() - num(curCSS(e, "paddingLeft", true))
+ - num(curCSS(e, "paddingRight", true))
- num(curCSS(e, "borderRightWidth", true)) - num(curCSS(e, "borderRightWidth", true)));
}
public static native NodeList<Element> getElementsByClassName(String clazz,
Node ctx) /*-{
- return ctx.getElementsByClassName(clazz);
+ return ctx.getElementsByClassName(clazz);
}-*/;
public static native Node getNextSibling(Node n) /*-{
- return n.nextSibling || null;
+ return n.nextSibling || null;
}-*/;
public static native Node getPreviousSibling(Node n) /*-{
- return n.previousSibling || null;
+ return n.previousSibling || null;
}-*/;
public NodeList<Element> querySelectorAll(String selector, Node ctx) {
public static native NodeList<Element> querySelectorAllImpl(String selector,
Node ctx) /*-{
- return ctx.querySelectorAll(selector);
+ return ctx.querySelectorAll(selector);
}-*/;
public static native NodeList<Element> elementsByTagName(String selector,
Node ctx) /*-{
- return ctx.getElementsByTagName(selector);
+ return ctx.getElementsByTagName(selector);
}-*/;
public static native NodeList<Element> elementsByClassName(String selector,
Node ctx) /*-{
- return ctx.getElementsByClassName(selector);
+ return ctx.getElementsByClassName(selector);
}-*/;
public static NodeList<Element> veryQuickId(String id, Node ctx) {
public static native NodeList<Element> xpathEvaluate(String selector,
Node ctx, JsNodeArray r) /*-{
- var node;
- var ownerDoc = ctx && (ctx.ownerDocument || ctx );
- var evalDoc = ownerDoc ? ownerDoc : $doc;
- var result = evalDoc.evaluate(selector, ctx, null, 0, null);
- while ((node = result.iterateNext())) {
- r.push(node);
- }
- return r;
+ var node;
+ var ownerDoc = ctx && (ctx.ownerDocument || ctx );
+ var evalDoc = ownerDoc ? ownerDoc : $doc;
+ var result = evalDoc.evaluate(selector, ctx, null, 0, null);
+ while ((node = result.iterateNext())) {
+ r.push(node);
+ }
+ return r;
}-*/;
public final SelectorEngineImpl impl;
static {
filters = JsMap.create();
- filters.put("visible", new Predicate(){
+ filters.put("visible", new Predicate() {
public boolean f(Element e, int index) {
return (e.getOffsetWidth() + e.getOffsetHeight()) > 0 &&
- !"none".equalsIgnoreCase(styleImpl.curCSS(e, "display", true));
+ !"none".equalsIgnoreCase(styleImpl.curCSS(e, "display", true));
}
});
filters.put("hidden", new Predicate() {
return e.getPropertyBoolean("selected");
}
});
- filters.put("input", new Predicate(){
+ filters.put("input", new Predicate() {
public boolean f(Element e, int index) {
return e.getNodeName().toLowerCase().matches("input|select|textarea|button");
}
});
- filters.put("header", new Predicate(){
+ filters.put("header", new Predicate() {
public boolean f(Element e, int index) {
return e.getNodeName().toLowerCase().matches("h\\d");
}
public NodeList<Element> filter(NodeList<Element> nodes, String selector, boolean filterDetached) {
JsNodeArray res = JsNodeArray.create();
- if (selector.isEmpty()){
+ if (selector.isEmpty()) {
return res;
}
Element ghostParent = null;
HashSet<Node> elmList = new HashSet<Node>();
for (int i = 0, l = nodes.getLength(); i < l; i++) {
Node e = nodes.getItem(i);
- if (e == window || e == document || e.getNodeName() == null || "html".equalsIgnoreCase(e.getNodeName())) {
+ if (e == window || e == document || e.getNodeName() == null
+ || "html".equalsIgnoreCase(e.getNodeName())) {
continue;
}
elmList.add(e);
parents.add(p);
}
} else if (parents.isEmpty()) {
- parents.add(document);
+ parents.add(document);
}
}
for (Node e : parents) {
- NodeList<Element> n = select(selector, e);
+ NodeList<Element> n = select(selector, e);
for (int i = 0, l = n.getLength(); i < l; i++) {
Element el = n.getItem(i);
if (elmList.remove(el)) {
}
// pseudo selectors which are computed by gquery in runtime
- RegExp gQueryPseudo = RegExp.compile("(.*):((visible|hidden|selected|input|header)|((button|checkbox|file|hidden|image|password|radio|reset|submit|text)\\s*(,|$)))(.*)", "i");
+ RegExp gQueryPseudo =
+ RegExp.compile(
+ "(.*):((visible|hidden|selected|input|header)|((button|checkbox|file|hidden|image|password|radio|reset|submit|text)\\s*(,|$)))(.*)", "i");
// pseudo selectors which work in engine
- RegExp nativePseudo = RegExp.compile("(.*):([\\w]+):(disabled|checked|enabled|empty|focus)\\s*([:,].*|$)", "i");
+ RegExp nativePseudo = RegExp.compile(
+ "(.*):([\\w]+):(disabled|checked|enabled|empty|focus)\\s*([:,].*|$)", "i");
public NodeList<Element> select(String selector, Node ctx) {
if (pred != null) {
nodes = filter(select(select, ctx), pred);
} else if (nativePseudo.test(pseudo)) {
- nodes = select(select, ctx);
+ nodes = select(select, ctx);
} else {
nodes = select(select + "[type=" + pseudo + "]", ctx);
}
private static ReplaceCallback rc_scp = new ReplaceCallback() {
public String foundMatch(ArrayList<String> s) {
return s.get(1) + s.get(2) +
- (s.get(3).startsWith(" ") ? "%S%" : s.get(3).startsWith("#") ? "%H%" : "%P%") +
- s.get(4) + s.get(5);
+ (s.get(3).startsWith(" ") ? "%S%" : s.get(3).startsWith("#") ? "%H%" : "%P%") +
+ s.get(4) + s.get(5);
}
};
private static ReplaceCallback rc_$Attr = new ReplaceCallback() {
public String foundMatch(ArrayList<String> s) {
- return "[substring(@" + s.get(1) + ",string-length(@" + s.get(1) + ")-" + (s.get(2).replaceAll("'", "").length() - 1) + ")=" + s.get(2) + "]";
+ return "[substring(@" + s.get(1) + ",string-length(@" + s.get(1) + ")-"
+ + (s.get(2).replaceAll("'", "").length() - 1) + ")=" + s.get(2) + "]";
}
};
private static ReplaceCallback rc_Not = new ReplaceCallback() {
public String foundMatch(ArrayList<String> s) {
- return s.get(1) + "[not(" + getInstance().css2Xpath(s.get(2)).replaceAll("^[^\\[]+\\[([^\\]]*)\\].*$", "$1" + ")]");
+ return s.get(1) + "[not("
+ + getInstance().css2Xpath(s.get(2)).replaceAll("^[^\\[]+\\[([^\\]]*)\\].*$", "$1" + ")]");
}
};
boolean afterAttr = "]".equals(s1);
String prefix = afterAttr ? s1 : "*";
- boolean noPrefix = afterAttr || s1 == null || s1.length() == 0 ;
+ boolean noPrefix = afterAttr || s1 == null || s1.length() == 0;
if ("n".equals(s2)) {
return s1;
return prefix + "[(count(preceding-sibling::*) + 1) mod 2=1]";
}
- if (!s2.contains("n")){
- return prefix + "[position() = "+s2+"]" + (noPrefix ? "" : "/self::" + s1);
+ if (!s2.contains("n")) {
+ return prefix + "[position() = " + s2 + "]" + (noPrefix ? "" : "/self::" + s1);
}
String[] t = s2.replaceAll("^([0-9]*)n.*?([0-9]*)?$", "$1+$2").split("\\+");
String t0 = t[0];
String t1 = t.length > 1 ? t[1] : "0";
- return prefix + "[(position()-" + t1 + ") mod " + t0 + "=0 and position()>=" + t1 + "]" + (noPrefix ? "" : "/self::" + s1);
+ return prefix + "[(position()-" + t1 + ") mod " + t0 + "=0 and position()>=" + t1 + "]"
+ + (noPrefix ? "" : "/self::" + s1);
}
};
- public static Object[] regs = new Object[]{
- // scape some dots and spaces
- "(['\\[])([^'\\]]*)([\\s\\.#])([^'\\]]*)(['\\]])", rc_scp,
- // add @ for attrib
- "\\[([^@\\]~\\$\\*\\^\\|\\!]+)(=[^\\]]+)?\\]", "[@$1$2]",
- // multiple queries
- "\\s*,\\s*", "|.//",
- // , + ~ >
- "\\s*(\\+|~|>)\\s*", "$1",
- // * ~ + >
- "([\\w\\-\\*])~([\\w\\-\\*])", "$1/following-sibling::$2",
- "([\\w\\-\\*])\\+([\\w\\-\\*])", "$1/following-sibling::*[1]/self::$2",
- "([\\w\\-\\*])>([\\w\\-\\*])", "$1/$2",
- // all unescaped stuff escaped
- "\\[([^=]+)=([^'|\"][^\\]]*)\\]", "[$1='$2']",
- // all descendant or self to
- "(^|[^\\w\\-\\*])(#|\\.)([\\w\\-]+)", "$1*$2$3",
- "([\\>\\+\\|\\~\\,\\s])([a-zA-Z\\*]+)", "$1//$2",
- "\\s+//", "//",
- // :first-child
- "([\\w\\-\\*]+):first-child", "*[1]/self::$1",
- // :last-child
- "([\\w\\-\\*]+):last-child", "$1[not(following-sibling::*)]",
- // :only-child
- "([\\w\\-\\*]+):only-child", "*[last()=1]/self::$1",
- // :empty
- "([\\w\\-\\*]+):empty", "$1[not(*) and not(normalize-space())]",
- // :odd :even, this is intentional since sizzle behaves so
- ":odd" , ":nth-child(even)",
- ":even" , ":nth-child(odd)",
- // :not
- "(.+):not\\(([^\\)]*)\\)", rc_Not,
- // :nth-child
- "([a-zA-Z0-9\\_\\-\\*]*|\\]):nth-child\\(([^\\)]*)\\)", rc_nth_child,
- // :contains(selectors)
- ":contains\\(([^\\)]*)\\)", "[contains(string(.),'$1')]",
- // |= attrib
- "\\[([\\w\\-]+)\\|=([^\\]]+)\\]", "[@$1=$2 or starts-with(@$1,concat($2,'-'))]",
- // *= attrib
- "\\[([\\w\\-]+)\\*=([^\\]]+)\\]", "[contains(@$1,$2)]",
- // ~= attrib
- "\\[([\\w\\-]+)~=([^\\]]+)\\]", "[contains(concat(' ',normalize-space(@$1),' '),concat(' ',$2,' '))]",
- // ^= attrib
- "\\[([\\w\\-]+)\\^=([^\\]]+)\\]", "[starts-with(@$1,$2)]",
- // $= attrib
- "\\[([\\w\\-]+)\\$=([^\\]]+)\\]", rc_$Attr,
- // != attrib
- "\\[([\\w\\-]+)\\!=([^\\]]+)\\]", "[not(@$1) or @$1!=$2]",
- // ids and classes
- "#([\\w\\-]+)", "[@id='$1']",
- "\\.([\\w\\-]+)", "[contains(concat(' ',normalize-space(@class),' '),' $1 ')]",
- // normalize multiple filters
- "\\]\\[([^\\]]+)", " and ($1)",
- // tag:pseudo
- ":(enabled)", "[not(@disabled)]",
- ":(checked)", "[@$1='$1']",
- ":(disabled)", "[@$1]",
- ":(first)", "[1]",
- ":(last)", "[last()]",
- // put '*' when tag is omitted
- "(^|\\|[\\./]*)(\\[)", "$1*$2",
- // Replace escaped dots and spaces
- "%S%"," ",
- "%P%",".",
- "%H%","#",
- // Duplicated quotes
- "'+","'",
- };
+ public static Object[] regs = new Object[] {
+ // scape some dots and spaces
+ "(['\\[])([^'\\]]*)([\\s\\.#])([^'\\]]*)(['\\]])", rc_scp,
+ // add @ for attrib
+ "\\[([^@\\]~\\$\\*\\^\\|\\!]+)(=[^\\]]+)?\\]", "[@$1$2]",
+ // multiple queries
+ "\\s*,\\s*", "|.//",
+ // , + ~ >
+ "\\s*(\\+|~|>)\\s*", "$1",
+ // * ~ + >
+ "([\\w\\-\\*])~([\\w\\-\\*])", "$1/following-sibling::$2",
+ "([\\w\\-\\*])\\+([\\w\\-\\*])", "$1/following-sibling::*[1]/self::$2",
+ "([\\w\\-\\*])>([\\w\\-\\*])", "$1/$2",
+ // all unescaped stuff escaped
+ "\\[([^=]+)=([^'|\"][^\\]]*)\\]", "[$1='$2']",
+ // all descendant or self to
+ "(^|[^\\w\\-\\*])(#|\\.)([\\w\\-]+)", "$1*$2$3",
+ "([\\>\\+\\|\\~\\,\\s])([a-zA-Z\\*]+)", "$1//$2",
+ "\\s+//", "//",
+ // :first-child
+ "([\\w\\-\\*]+):first-child", "*[1]/self::$1",
+ // :last-child
+ "([\\w\\-\\*]+):last-child", "$1[not(following-sibling::*)]",
+ // :only-child
+ "([\\w\\-\\*]+):only-child", "*[last()=1]/self::$1",
+ // :empty
+ "([\\w\\-\\*]+):empty", "$1[not(*) and not(normalize-space())]",
+ // :odd :even, this is intentional since sizzle behaves so
+ ":odd", ":nth-child(even)",
+ ":even", ":nth-child(odd)",
+ // :not
+ "(.+):not\\(([^\\)]*)\\)", rc_Not,
+ // :nth-child
+ "([a-zA-Z0-9\\_\\-\\*]*|\\]):nth-child\\(([^\\)]*)\\)", rc_nth_child,
+ // :contains(selectors)
+ ":contains\\(([^\\)]*)\\)", "[contains(string(.),'$1')]",
+ // |= attrib
+ "\\[([\\w\\-]+)\\|=([^\\]]+)\\]", "[@$1=$2 or starts-with(@$1,concat($2,'-'))]",
+ // *= attrib
+ "\\[([\\w\\-]+)\\*=([^\\]]+)\\]", "[contains(@$1,$2)]",
+ // ~= attrib
+ "\\[([\\w\\-]+)~=([^\\]]+)\\]",
+ "[contains(concat(' ',normalize-space(@$1),' '),concat(' ',$2,' '))]",
+ // ^= attrib
+ "\\[([\\w\\-]+)\\^=([^\\]]+)\\]", "[starts-with(@$1,$2)]",
+ // $= attrib
+ "\\[([\\w\\-]+)\\$=([^\\]]+)\\]", rc_$Attr,
+ // != attrib
+ "\\[([\\w\\-]+)\\!=([^\\]]+)\\]", "[not(@$1) or @$1!=$2]",
+ // ids and classes
+ "#([\\w\\-]+)", "[@id='$1']",
+ "\\.([\\w\\-]+)", "[contains(concat(' ',normalize-space(@class),' '),' $1 ')]",
+ // normalize multiple filters
+ "\\]\\[([^\\]]+)", " and ($1)",
+ // tag:pseudo
+ ":(enabled)", "[not(@disabled)]",
+ ":(checked)", "[@$1='$1']",
+ ":(disabled)", "[@$1]",
+ ":(first)", "[1]",
+ ":(last)", "[last()]",
+ // put '*' when tag is omitted
+ "(^|\\|[\\./]*)(\\[)", "$1*$2",
+ // Replace escaped dots and spaces
+ "%S%", " ",
+ "%P%", ".",
+ "%H%", "#",
+ // Duplicated quotes
+ "'+", "'",
+ };
public static SelectorEngineCssToXPath getInstance() {
if (instance == null) {
}
String xsel = cache.get(sel);
if (xsel == null) {
- xsel = sel.startsWith("./") || sel.startsWith("/") ? sel : css2Xpath(sel);
+ xsel = sel.startsWith("./") || sel.startsWith("/") ? sel : css2Xpath(sel);
cache.put(sel, xsel);
}
throw new RuntimeException("This Browser does not support Xpath selectors.", e);
}
console.error("ERROR: xpathEvaluate invalid xpath expression: "
- + xsel + " css-selector: " + sel + " " + e.getMessage() + "\n");
+ + xsel + " css-selector: " + sel + " " + e.getMessage() + "\n");
}
return elm;
}
public class SelectorEngineNative extends SelectorEngineImpl {
// querySelectorAll unsupported selectors
- public static String NATIVE_EXCEPTIONS_REGEXP = "(^[\\./]/.*)|(.*(:contains|:first([^-]|$)|:last([^-]|$)|:even|:odd)).*";
+ public static String NATIVE_EXCEPTIONS_REGEXP =
+ "(^[\\./]/.*)|(.*(:contains|:first([^-]|$)|:last([^-]|$)|:even|:odd)).*";
private static HasSelector impl;
public NodeList<Element> select(String selector, Node ctx) {
// querySelectorAllImpl does not support ids starting with a digit.
-// if (selector.matches("#[\\w\\-]+")) {
-// return SelectorEngine.veryQuickId(selector.substring(1), ctx);
-// } else
+ // if (selector.matches("#[\\w\\-]+")) {
+ // return SelectorEngine.veryQuickId(selector.substring(1), ctx);
+ // } else
if (selector.contains("!=")) {
if (cache == null) {
cache = JsNamedArray.create();
*/
public class SelectorEngineNativeIE8 extends SelectorEngineSizzleIE {
- public static String NATIVE_EXCEPTIONS_REGEXP = ".*(:contains|!=|:not|:nth-|:only-|:first|:last|:even|:odd).*";
+ public static String NATIVE_EXCEPTIONS_REGEXP =
+ ".*(:contains|!=|:not|:nth-|:only-|:first|:last|:even|:odd).*";
public NodeList<Element> select(String selector, Node ctx) {
if (!SelectorEngine.hasQuerySelector || selector.matches(NATIVE_EXCEPTIONS_REGEXP)) {
} catch (Exception e) {
console.error("GwtQuery: Selector '" + selector +
"' is unsupported in this SelectorEngineNativeMin engine."
- + " Do not use this syntax or configure your module to use a JS fallback. " + e.getMessage());
+ + " Do not use this syntax or configure your module to use a JS fallback. "
+ + e.getMessage());
return null;
}
}
try {
return SelectorEngine.querySelectorAllImpl(selector, ctx);
} catch (Exception e) {
- console.error("GwtQuery: Selector '" + selector + "' is unsupported in this SelectorEngineNativeMinIE8 engine,"
+ console.error("GwtQuery: Selector '" + selector
+ + "' is unsupported in this SelectorEngineNativeMinIE8 engine,"
+ " check that you are in 'standards mode' or configure your module to use JS fallback. "
+ e.getMessage());
return null;
protected static Sequence getSequence(String expression) {
int start = 0, add = 2, max = -1, modVal = -1;
- JsRegexp expressionRegExp = new JsRegexp(
- "^((odd|even)|([1-9]\\d*)|((([1-9]\\d*)?)n((\\+|\\-)(\\d+))?)|(\\-(([1-9]\\d*)?)n\\+(\\d+)))$");
+ JsRegexp expressionRegExp =
+ new JsRegexp(
+ "^((odd|even)|([1-9]\\d*)|((([1-9]\\d*)?)n((\\+|\\-)(\\d+))?)|(\\-(([1-9]\\d*)?)n\\+(\\d+)))$");
JsObjectArray<String> pseudoValue = expressionRegExp.exec(expression);
if (!truth(pseudoValue)) {
return null;
} else {
- if (truth(pseudoValue.get(2))) { // odd or even
+ if (truth(pseudoValue.get(2))) { // odd or even
start = (eq(pseudoValue.get(2), "odd")) ? 1 : 2;
modVal = (start == 1) ? 1 : 0;
} else if (JsUtils
- .truth(pseudoValue.get(3))) { // single digit
+ .truth(pseudoValue.get(3))) { // single digit
start = Integer.parseInt(pseudoValue.get(3), 10);
add = 0;
max = start;
- } else if (truth(pseudoValue.get(4))) { // an+b
+ } else if (truth(pseudoValue.get(4))) { // an+b
add = truth(pseudoValue.get(6)) ? Integer
.parseInt(pseudoValue.get(6), 10) : 1;
start = truth(pseudoValue.get(7)) ? Integer.parseInt(
}
modVal = (start > add) ? (start - add) % add
: ((start == add) ? 0 : start);
- } else if (truth(pseudoValue.get(10))) { // -an+b
+ } else if (truth(pseudoValue.get(10))) { // -an+b
add = truth(pseudoValue.get(12)) ? Integer
.parseInt(pseudoValue.get(12), 10) : 1;
start = max = Integer.parseInt(pseudoValue.get(13), 10);
public static native NodeList<Element> getElementsByClassName(String clazz,
Node ctx) /*-{
- return ctx.getElementsByClassName(clazz);
+ return ctx.getElementsByClassName(clazz);
}-*/;
public static native boolean isAdded(Node prevRef) /*-{
private static void getGeneralSiblingNodes(JsNodeArray matchingElms,
JsObjectArray<String> nextTag, JsRegexp nextRegExp, Node prevRef) {
- while (
- JsUtils.truth((prevRef = SelectorEngine.getNextSibling(prevRef)))
- && !isAdded(prevRef)) {
+ while (JsUtils.truth((prevRef = SelectorEngine.getNextSibling(prevRef)))
+ && !isAdded(prevRef)) {
if (!JsUtils.truth(nextTag) || nextRegExp
.test(prevRef.getNodeName())) {
setAdded(prevRef, true);
private static void getSiblingNodes(JsNodeArray matchingElms, JsObjectArray<String> nextTag,
JsRegexp nextRegExp, Node prevRef) {
- while (
- JsUtils.truth(prevRef = SelectorEngine.getNextSibling(prevRef))
- && prevRef.getNodeType() != Node.ELEMENT_NODE) {
+ while (JsUtils.truth(prevRef = SelectorEngine.getNextSibling(prevRef))
+ && prevRef.getNodeType() != Node.ELEMENT_NODE) {
}
if (JsUtils.truth(prevRef)) {
if (!JsUtils.truth(nextTag) || nextRegExp
private static native JsNodeArray subtractArray(JsNodeArray previousMatch,
JsNodeArray elementsByPseudo) /*-{
- for (var i=0, src1; (src1=arr1[i]); i++) {
- var found = false;
- for (var j=0, src2; (src2=arr2[j]); j++) {
- if (src2 === src1) {
- found = true;
- break;
- }
- }
- if (found) {
- arr1.splice(i--, 1);
- }
+ for (var i=0, src1; (src1=arr1[i]); i++) {
+ var found = false;
+ for (var j=0, src2; (src2=arr2[j]); j++) {
+ if (src2 === src1) {
+ found = true;
+ break;
}
- return arr;
- }-*/;
+ }
+ if (found) {
+ arr1.splice(i--, 1);
+ }
+ }
+ return arr;
+ }-*/;
private JsRegexp cssSelectorRegExp;
public SelectorEngineJS() {
selectorSplitRegExp = new JsRegexp("[^\\s]+", "g");
childOrSiblingRefRegExp = new JsRegexp("^(>|\\+|~)$");
- cssSelectorRegExp = new JsRegexp(
- "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\"']*[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+[\"']*)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?");
+ cssSelectorRegExp =
+ new JsRegexp(
+ "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\"']*[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+[\"']*)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?");
}
public NodeList<Element> select(String sel, Node ctx) {
for (int l = 0, ll = prevElem.size(); l < ll; l++) {
tagCollectionMatches = getElementsByTagName(splitRule.tag,
prevElem.getNode(l));
- for (int m = 0, mlen = tagCollectionMatches.getLength(); m < mlen;
- m++) {
+ for (int m = 0, mlen = tagCollectionMatches.getLength(); m < mlen; m++) {
Node tagMatch = tagCollectionMatches.getItem(m);
if (!isAdded(tagMatch)) {
for (int r = 0, rlen = matchingElms.size(); r < rlen; r++) {
Element current = matchingElms.getElement(r);
boolean addElm = false;
- for (int s = 0, sl = regExpAttributes.length;
- s < sl; s++) {
+ for (int s = 0, sl = regExpAttributes.length; s < sl; s++) {
addElm = false;
JsRegexp attributeRegexp = regExpAttributes[s];
String currentAttr = getAttr(current, regExpAttributesStr[s]);
elm.pushAll(prevElem);
}
- return JsUtils.unique(elm.<JsArray<Element>>cast()).cast();
+ return JsUtils.unique(elm.<JsArray<Element>> cast()).cast();
}
protected String getAttr(Element current, String name) {
&& next.getNodeType() != Node.ELEMENT_NODE) {
}
} else {
- while (
- JsUtils.truth((next = SelectorEngine.getNextSibling(next)))
- && next.getNodeType() != Node.ELEMENT_NODE) {
+ while (JsUtils.truth((next = SelectorEngine.getNextSibling(next)))
+ && next.getNodeType() != Node.ELEMENT_NODE) {
}
}
if (!JsUtils.truth(next)) {
next = previous = previousMatch.getNode(n);
if (previousDir) {
- while (
- JsUtils.truth(next = SelectorEngine.getPreviousSibling(next))
- && !JsUtils
+ while (JsUtils.truth(next = SelectorEngine.getPreviousSibling(next))
+ && !JsUtils
.eq(next.getNodeName(), previous.getNodeName())) {
}
} else {
.exec(pseudoValue);
JsRegexp notRegExp = new JsRegexp("(^|\\s)"
+ (JsUtils.truth(notTag) ? notTag.get(1)
- : JsUtils.truth(notClass) ? notClass.get(1) : "")
+ : JsUtils.truth(notClass) ? notClass.get(1) : "")
+ "(\\s|$)", "i");
if (JsUtils.truth(notAttr)) {
String notAttribute = JsUtils.truth(notAttr.get(3)) ? notAttr
prev = next = previous = previousMatch.getNode(k);
Node prevParent = previous.getParentNode();
if (prevParent != kParent) {
- while (
- JsUtils.truth(prev = SelectorEngine.getPreviousSibling(prev))
- && prev.getNodeType() != Node.ELEMENT_NODE) {
+ while (JsUtils.truth(prev = SelectorEngine.getPreviousSibling(prev))
+ && prev.getNodeType() != Node.ELEMENT_NODE) {
}
while (JsUtils.truth(next = SelectorEngine.getNextSibling(next))
&& next.getNodeType() != Node.ELEMENT_NODE) {
prev = next = previous = previousMatch.getNode(o);
Node prevParent = previous.getParentNode();
if (prevParent != oParent) {
- while (
- JsUtils.truth(prev = SelectorEngine.getPreviousSibling(prev))
- && !JsUtils
+ while (JsUtils.truth(prev = SelectorEngine.getPreviousSibling(prev))
+ && !JsUtils
.eq(prev.getNodeName(), previous.getNodeName())) {
}
while (JsUtils.truth(next = SelectorEngine.getNextSibling(next))
}
SelectorEngine.xpathEvaluate(xPathExpression, ctx, elm);
}
- return JsUtils.unique(elm.<JsArray<Element>>cast()).cast();
+ return JsUtils.unique(elm.<JsArray<Element>> cast()).cast();
}
private void init() {
if (cssSelectorRegExp == null) {
- cssSelectorRegExp = new JsRegexp(
- "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\"']*[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+[\"']*)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?(>|\\+|~)?");
+ cssSelectorRegExp =
+ new JsRegexp(
+ "^(\\w+)?(#[\\w\\u00C0-\\uFFFF\\-\\_]+|(\\*))?((\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[\"']*[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+[\"']*)?\\]+)*)?(((:\\w+[\\w\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[\\w\\u00C0-\\uFFFF\\-_]+|((\\w*\\.[\\w\\u00C0-\\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[\\w\\u00C0-\\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[\\w\\-]*))\\))?)*)?(>|\\+|~)?");
selectorSplitRegExp = new JsRegexp("[^\\s]+", "g");
combinator = new JsRegexp("(>|\\+|~)");
}
xpath = "(count(preceding-sibling::*) + 1) mod " + sequence.add
+ " = " + sequence.modVal
+ ((sequence.start > 1) ? " and count(preceding-sibling::*) >= "
- + (sequence.start - 1) : "") + ((sequence.max > 0) ?
- " and count(preceding-sibling::*) <= " + (sequence.max - 1)
- : "");
+ + (sequence.start - 1) : "") + ((sequence.max > 0) ?
+ " and count(preceding-sibling::*) <= " + (sequence.max - 1)
+ : "");
}
}
}
} else {
xpath = "position() mod " + sequence.add + " = " + sequence.modVal
+ ((sequence.start > 1) ? " and position() >= " + sequence.start
- : "") + ((sequence.max > 0) ? " and position() <= "
- + sequence.max : "");
+ : "") + ((sequence.max > 0) ? " and position() <= "
+ + sequence.max : "");
}
}
}
import com.google.gwt.core.client.JsArrayMixed;
import com.google.gwt.core.client.JsArrayString;
- /**
- * A Lightweight JSO class to store data.
- */
+/**
+ * A Lightweight JSO class to store data.
+ */
public class JsCache extends JavaScriptObject {
protected JsCache() {
Object o = get(id);
if (o != null && clz != null) {
if (o instanceof Double) {
- Double d = (Double)o;
- if (clz == Float.class) o = d.floatValue();
- else if (clz == Integer.class) o = d.intValue();
- else if (clz == Long.class) o = d.longValue();
- else if (clz == Short.class) o = d.shortValue();
- else if (clz == Byte.class) o = d.byteValue();
+ Double d = (Double) o;
+ if (clz == Float.class)
+ o = d.floatValue();
+ else if (clz == Integer.class)
+ o = d.intValue();
+ else if (clz == Long.class)
+ o = d.longValue();
+ else if (clz == Short.class)
+ o = d.shortValue();
+ else if (clz == Byte.class)
+ o = d.byteValue();
} else if (clz == Boolean.class && !(o instanceof Boolean)) {
o = Boolean.valueOf(String.valueOf(o));
} else if (clz == String.class && !(o instanceof String)) {
o = String.valueOf(o);
}
}
- return (T)o;
+ return (T) o;
}
public final native <T> T get(Object id) /*-{
}-*/;
public final JsCache getCache(int id) {
- return (JsCache)get(id);
+ return (JsCache) get(id);
}
public final boolean getBoolean(Object id) {
public final <T extends JavaScriptObject> T getJavaScriptObject(Object name) {
Object o = get(name);
- return (o != null && o instanceof JavaScriptObject) ? ((JavaScriptObject)o).<T>cast() : null;
+ return (o != null && o instanceof JavaScriptObject) ? ((JavaScriptObject) o).<T> cast() : null;
}
public final native boolean isEmpty() /*-{
return this;
}-*/;
- public final JsCache put(Object id, Object obj) {
+ public final JsCache put(Object id, Object obj) {
if (obj instanceof Boolean) {
- putBoolean(id, ((Boolean)obj).booleanValue());
+ putBoolean(id, ((Boolean) obj).booleanValue());
} else if (obj instanceof Number) {
- putNumber(id, ((Number)obj).doubleValue());
+ putNumber(id, ((Number) obj).doubleValue());
} else {
putObject(id, obj);
}
JsArrayString a = keysImpl();
String[] ret = new String[a.length()];
for (int i = 0; i < a.length(); i++) {
- ret[i] = a.get(i);
+ ret[i] = a.get(i);
}
return ret;
}
public final Object[] elements() {
String[] keys = keys();
Object[] ret = new Object[keys.length];
- int i=0;
- for (String s: keys) {
+ int i = 0;
+ for (String s : keys) {
ret[i++] = get(s);
}
return ret;
public final String tostring() {
String ret = getClass().getName() + "{ ";
- for (String k: keys()){
+ for (String k : keys()) {
ret += k + "=" + get(k) + " ";
}
return ret + "}";
@SuppressWarnings("unchecked")
public T get(int hashCode) {
- return (T)c().get(hashCode);
+ return (T) c().get(hashCode);
}
public T get(S key) {
c().put(key.hashCode(), val);
}
- public T remove(S key){
+ public T remove(S key) {
T old = get(key);
c().delete(key.hashCode());
return old;
}
- public T remove(int key){
+ public T remove(int key) {
T old = get(key);
c().delete(key);
return old;
@SuppressWarnings("unchecked")
public T get(String key) {
- return (T)c().get(key);
+ return (T) c().get(key);
}
public void put(String key, T val) {
return c().elements();
}
- public boolean exists(String key){
+ public boolean exists(String key) {
return c().exists(key);
}
- public void delete(String key){
+ public void delete(String key) {
c().delete(key);
}
public class JsNodeArray extends NodeList<Element> {
public static JsNodeArray create() {
- return create((Node)null);
+ return create((Node) null);
}
public static native JsNodeArray create(Node node) /*-{
}-*/;
public static JsNodeArray create(NodeList<?> nl) {
- JsNodeArray ret = create((Node)null);
+ JsNodeArray ret = create((Node) null);
ret.pushAll(nl);
return ret;
}
- protected JsNodeArray(){
+ protected JsNodeArray() {
}
- public final void addNode(Node n){
+ public final void addNode(Node n) {
c().add(n);
}
public final Element[] elements() {
Element[] ret = new Element[size()];
- for (int i=0 ; i<size(); i++) {
+ for (int i = 0; i < size(); i++) {
ret[i] = getElement(i);
}
return ret;
return cast();
}
- public JsObjectArray<T> add(T...vals) {
- for (T t: vals) {
+ public JsObjectArray<T> add(T... vals) {
+ for (T t : vals) {
if (t instanceof Number) {
- c().putNumber(length(), (((Number)t).doubleValue()));
+ c().putNumber(length(), (((Number) t).doubleValue()));
} else if (t instanceof Boolean) {
- c().putBoolean(length(), ((Boolean)t).booleanValue());
+ c().putBoolean(length(), ((Boolean) t).booleanValue());
} else {
c().put(length(), t);
}
@SuppressWarnings("unchecked")
public T get(int index) {
- return (T)c().get(index);
+ return (T) c().get(index);
}
public int length() {
return regexp.test(rule);
}-*/;
- public String getPattern(){
+ public String getPattern() {
return regexp.toString();
};
}
*/
public static class JsFunction extends Function implements Command {
private JavaScriptObject jso = null;
+
public JsFunction(JavaScriptObject f) {
if (JsUtils.isFunction(f)) {
jso = f;
// @see https://github.com/douglascrockford/JSON-js/blob/master/json2.js
Properties prop = js.cast();
String ret = "";
- for (String k : prop.keys()){
+ for (String k : prop.keys()) {
String ky = k.matches("\\d+") ? k : "\"" + k + "\"";
JsCache o = prop.getArray(k).cast();
if (o != null) {
ret += ky + ":[";
- for (int i = 0, l = o.length(); i < l ; i++) {
- Properties p = o.<JsCache>cast().getJavaScriptObject(i);
+ for (int i = 0, l = o.length(); i < l; i++) {
+ Properties p = o.<JsCache> cast().getJavaScriptObject(i);
if (p != null) {
ret += p.toJsonString() + ",";
} else {
}
}
}
- return "{" + ret.replaceAll(",\\s*([\\]}]|$)","$1")
- .replaceAll("([:,\\[])\"(-?[\\d\\.]+|null|false|true)\"", "$1$2")
- + "}";
+ return "{" + ret.replaceAll(",\\s*([\\]}]|$)", "$1")
+ .replaceAll("([:,\\[])\"(-?[\\d\\.]+|null|false|true)\"", "$1$2")
+ + "}";
}
@Override
* Returns a property present in a javascript object.
*/
public static <T> T prop(JavaScriptObject o, Object id, Class<? extends T> type) {
- return o == null ? null : o.<JsCache>cast().get(id, type);
+ return o == null ? null : o.<JsCache> cast().get(id, type);
}
/**
* Returns a property present in a javascript object.
*/
public static <T> T prop(JavaScriptObject o, Object id) {
- return o == null ? null : o.<JsCache>cast().<T>get(id);
+ return o == null ? null : o.<JsCache> cast().<T> get(id);
}
/**
*/
public static void prop(JavaScriptObject o, Object id, Object val) {
if (o != null) {
- o.<JsCache>cast().put(id, val);
+ o.<JsCache> cast().put(id, val);
}
}
public static boolean isDetached(Node n) {
assert n != null;
- if ("html".equalsIgnoreCase(n.getNodeName())){
+ if ("html".equalsIgnoreCase(n.getNodeName())) {
return false;
}
* @return the javascript object returned by the jsni method or null.
*/
public static <T> T runJavascriptFunction(JavaScriptObject o, String meth, Object... args) {
- return runJavascriptFunctionImpl(o, meth, JsObjectArray.create().add(args).<JsArrayMixed>cast());
+ return runJavascriptFunctionImpl(o, meth, JsObjectArray.create().add(args)
+ .<JsArrayMixed> cast());
}
- private static native <T> T runJavascriptFunctionImpl(JavaScriptObject o, String meth, JsArrayMixed args) /*-{
+ private static native <T> T runJavascriptFunctionImpl(JavaScriptObject o, String meth,
+ JsArrayMixed args) /*-{
return (f = o && o[meth])
&& @com.google.gwt.query.client.js.JsUtils::isFunction(*)(f)
&& @com.google.gwt.query.client.js.JsCache::gwtBox(*)([f.apply(o, args)]);
ret += ret.isEmpty() ? "" : "&";
JsCache o = prop.getArray(k).cast();
if (o != null) {
- for (int i = 0, l = o.length(); i < l ; i++) {
+ for (int i = 0, l = o.length(); i < l; i++) {
ret += i > 0 ? "&" : "";
- Properties p = o.<JsCache>cast().getJavaScriptObject(i);
+ Properties p = o.<JsCache> cast().getJavaScriptObject(i);
if (p != null) {
ret += k + "[]=" + p.toJsonString();
} else {
- ret += k + "[]=" + o.getString(i) ;
+ ret += k + "[]=" + o.getString(i);
}
}
} else {
/**
* Class to access protected methods in Animation.
*/
- public abstract static class GQAnimation extends Animation {
+ public abstract static class GQAnimation extends Animation {
private static final String ACTUAL_ANIMATION = "EffectsRunnning";
e = element;
return this;
}
+
protected GQAnimation setProperties(Properties properties) {
prps = properties == null ? Properties.create() : properties;
return this;
}
+
protected void onStart() {
// Mark this animation as actual, so as we can stop it in the GQuery.stop() method
$(e).data(ACTUAL_ANIMATION, this);
super.onStart();
}
+
protected void onComplete() {
// avoid memory leak (issue #132)
$(e).removeData(ACTUAL_ANIMATION);
super.onComplete();
}
+
public void cancel() {
// avoid memory leak (issue #132)
$(e).removeData(ACTUAL_ANIMATION);
anim.cancel();
}
}
+
public void f(Element e) {
anim.run(duration);
}
duration = Math.abs(duration);
- for (Element e: elements()) {
+ for (Element e : elements()) {
if (Fx.css3) {
new TransitionsClipAnimation(easing, e, p, funcs).run(duration);
} else {
* Don't apply events on text and comment nodes !!
*/
private static boolean isEventCapable(Node n) {
- return JsUtils.isWindow(n) || JsUtils.isElement(n) && n.getNodeType() != 3 && n.getNodeType() != 8;
+ return JsUtils.isWindow(n) || JsUtils.isElement(n) && n.getNodeType() != 3
+ && n.getNodeType() != 8;
}
public Events(GQuery gq) {
}
public GQuery die(int eventbits) {
- return die(eventbits, null);
+ return die(eventbits, null);
}
/**
GqEvent.setOriginalEventType(e, originalEventName);
}
- if ("submit".equals(htmlEvent)){
+ if ("submit".equals(htmlEvent)) {
Function submitFunction = new Function() {
public void f(Element e) {
// first submit the form then call the others functions
if (FormElement.is(e)) {
- e.<FormElement>cast().submit();
+ e.<FormElement> cast().submit();
}
callHandlers(e, getEvent(), functions);
}
// Ie6-8 don't dispatch bitless event
if ((browser.ie6 || browser.ie8) && Event.getTypeInt(evt.getType()) == -1) {
- bubbleEventForIE(e, evt.<Event>cast());
+ bubbleEventForIE(e, evt.<Event> cast());
} else {
e.dispatchEvent(evt);
}
*/
private boolean isEventPropagationStopped(Event event) {
// trick to avoid jnsi
- return event.<Element>cast().getPropertyBoolean("cancelBubble");
+ return event.<Element> cast().getPropertyBoolean("cancelBubble");
}
- private void callHandlers(Element e, NativeEvent evt, Function... functions){
+ private void callHandlers(Element e, NativeEvent evt, Function... functions) {
for (Function f : functions) {
f.setEvent(Event.as(evt));
f.f(e);
* the License.
*/
package com.google.gwt.query.client.plugins;
+
import com.google.gwt.query.client.Function;
import com.google.gwt.query.client.LazyBase;
import com.google.gwt.query.client.plugins.effects.PropertiesAnimation.Easing;
* LazyEffects.
* @param <T>
*/
-public interface LazyEffects<T> extends LazyBase<T>{
+public interface LazyEffects<T> extends LazyBase<T> {
/**
* The animate() method allows you to create animation effects on any numeric
* the License.
*/
package com.google.gwt.query.client.plugins;
+
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.query.client.Function;
import com.google.gwt.query.client.GQuery;
* LazyEvents.
* @param <T>
*/
-public interface LazyEvents<T> extends LazyBase<T>{
+public interface LazyEvents<T> extends LazyBase<T> {
/**
* Binds a set of handlers to a particular Event for each matched element.
* the License.
*/
package com.google.gwt.query.client.plugins;
+
import com.google.gwt.query.client.LazyBase;
import com.google.gwt.query.client.plugins.widgets.WidgetFactory;
import com.google.gwt.query.client.plugins.widgets.WidgetInitializer;
* LazyWidgets.
* @param <T>
*/
-public interface LazyWidgets<T> extends LazyBase<T>{
+public interface LazyWidgets<T> extends LazyBase<T> {
/**
* Try to create a widget using the given factory and the given options for
* each element of the query. Returns a new gquery set of elements with the
* new widgets created.
*/
- <W extends Widget> LazyWidgets<T> widgets(WidgetFactory<W> factory, WidgetInitializer<W> initializers);
+ <W extends Widget> LazyWidgets<T> widgets(WidgetFactory<W> factory,
+ WidgetInitializer<W> initializers);
/**
* Create a {@link Button} widget for each selected element.
protected void initDefault() {
delay = 0;
distance = 1; // by default, the mouse have to move one pixel !
- cancel = new String[] { "input", "option" };
+ cancel = new String[] {"input", "option"};
}
}
bindOtherEvents(element);
- if (!touchSupported){ // click event are not triggered if we call preventDefault on touchstart event.
+ if (!touchSupported) { // click event are not triggered if we call preventDefault on touchstart event.
event.getOriginalEvent().preventDefault();
}
return mouseDistance >= neededDistance;
}
- private native boolean isEventAlreadyHandled(GqEvent event)
- /*-{
-
+ private native boolean isEventAlreadyHandled(GqEvent event) /*-{
var result = event.mouseHandled ? event.mouseHandled : false;
return result;
}-*/;
- private native void markEventAsHandled(GqEvent event)
- /*-{
-
+ private native void markEventAsHandled(GqEvent event) /*-{
event.mouseHandled = true;
}-*/;
for (Element e : elements()) {
queue(e, name, new DelayFunction(e, name, milliseconds, funcs));
}
- return (T)this;
+ return (T) this;
}
/**
int count = 1;
// Inner functions don't have constructors, we use a block to initialize it
{
- for (Element elem: elements()) {
+ for (Element elem : elements()) {
// Add this resolve function only to those elements with active queue
if (queue(elem, name, null) != null) {
emptyHooks(elem, name).add(this);
*/
public int queue(String name) {
Queue<?> q = isEmpty() ? null : queue(get(0), name, null);
- return q == null? 0 : q.size();
+ return q == null ? 0 : q.size();
}
/**
queue(e, DEFAULT_NAME, f);
}
}
- return (T)this;
+ return (T) this;
}
/**
*/
@SuppressWarnings("unchecked")
public T queue(final String name, Function... funcs) {
- for (final Function f: funcs) {
- for (Element e: elements()) {
+ for (final Function f : funcs) {
+ for (Element e : elements()) {
queue(e, name, f);
}
}
- return (T)this;
+ return (T) this;
}
/**
private Callbacks emptyHooks(Element elem, String name) {
String key = name + EMPTY_HOOKS;
- Callbacks c = (Callbacks)data(elem, key, null);
+ Callbacks c = (Callbacks) data(elem, key, null);
if (c == null) {
- c = (Callbacks)data(elem, key, new Callbacks("once memory"));
+ c = (Callbacks) data(elem, key, new Callbacks("once memory"));
}
return c;
}
handlerManager.fireEvent(e);
}
if (callback != null) {
- callback.f(element.<com.google.gwt.dom.client.Element>cast());
+ callback.f(element.<com.google.gwt.dom.client.Element> cast());
}
}
*/
public interface Settings extends JsonBuilder {
String getContentType();
+
Element getContext();
+
IsProperties getData();
+
String getDataString();
+
String getDataType();
+
Function getError();
+
IsProperties getHeaders();
+
String getPassword();
+
Function getSuccess();
+
int getTimeout();
+
String getType();
+
String getUrl();
+
String getUsername();
+
boolean getWithCredentials();
+
Settings setContentType(String t);
+
Settings setContext(Element e);
+
Settings setData(Object p);
+
Settings setDataString(String d);
+
Settings setDataType(String t);
+
Settings setError(Function f);
+
Settings setHeaders(IsProperties p);
+
Settings setPassword(String p);
+
Settings setSuccess(Function f);
+
Settings setTimeout(int t);
+
Settings setType(String t);
+
Settings setUrl(String u);
+
Settings setUsername(String u);
+
Settings setWithCredentials(boolean b);
}
if ("jsonp".equalsIgnoreCase(dataType)) {
ret = GQ.getAjaxTransport().getJsonP(settings);
- } else if ("loadscript".equalsIgnoreCase(dataType)){
+ } else if ("loadscript".equalsIgnoreCase(dataType)) {
ret = GQ.getAjaxTransport().getLoadScript(settings);
} else {
ret = GQ.getAjaxTransport().getXhr(settings)
- .then(new Function() {
- public Object f(Object...args) {
- Response response = arguments(0);
- Request request = arguments(1);
- Object retData = response.getText();
- if (retData != null && !"".equals(retData)) {
- try {
- if ("xml".equalsIgnoreCase(dataType)) {
- retData = JsUtils.parseXML(response.getText());
- } else if ("json".equalsIgnoreCase(dataType)) {
- retData = GQ.create(response.getText());
- } else {
- retData = response.getText();
- if ("script".equalsIgnoreCase(dataType)) {
- ScriptInjector.fromString((String)retData).setWindow(window).inject();
+ .then(new Function() {
+ public Object f(Object... args) {
+ Response response = arguments(0);
+ Request request = arguments(1);
+ Object retData = response.getText();
+ if (retData != null && !"".equals(retData)) {
+ try {
+ if ("xml".equalsIgnoreCase(dataType)) {
+ retData = JsUtils.parseXML(response.getText());
+ } else if ("json".equalsIgnoreCase(dataType)) {
+ retData = GQ.create(response.getText());
+ } else {
+ retData = response.getText();
+ if ("script".equalsIgnoreCase(dataType)) {
+ ScriptInjector.fromString((String) retData).setWindow(window).inject();
+ }
+ }
+ } catch (Exception e) {
+ if (GWT.isClient() && GWT.getUncaughtExceptionHandler() != null) {
+ GWT.getUncaughtExceptionHandler().onUncaughtException(e);
+ } else {
+ e.printStackTrace();
}
- }
- } catch (Exception e) {
- if (GWT.isClient() && GWT.getUncaughtExceptionHandler() != null) {
- GWT.getUncaughtExceptionHandler().onUncaughtException(e);
- } else {
- e.printStackTrace();
}
}
+ return new Object[] {retData, "success", request, response};
}
- return new Object[]{retData, "success", request, response};
- }
- }, new Function() {
- public Object f(Object...args) {
- Throwable exception = arguments(0);
- Request request = getArgument(1, Request.class);
- String msg = String.valueOf(exception);
- return new Object[]{null, msg, request, null, exception};
- }
- });
+ }, new Function() {
+ public Object f(Object... args) {
+ Throwable exception = arguments(0);
+ Request request = getArgument(1, Request.class);
+ String msg = String.valueOf(exception);
+ return new Object[] {null, msg, request, null, exception};
+ }
+ });
}
if (onSuccess != null) {
ret.done(onSuccess);
private static void resolveSettings(Settings settings) {
String url = settings.getUrl();
- assert settings != null && settings.getUrl() != null: "no url found in settings";
+ assert settings != null && settings.getUrl() != null : "no url found in settings";
String type = "POST";
if (settings.getType() != null) {
IsProperties data = settings.getData();
if (data != null) {
String dataString = null, contentType = null;
- if (data.getDataImpl() instanceof JavaScriptObject && JsUtils.isFormData(data.<JavaScriptObject>getDataImpl())) {
+ if (data.getDataImpl() instanceof JavaScriptObject
+ && JsUtils.isFormData(data.<JavaScriptObject> getDataImpl())) {
dataString = null;
contentType = FormPanel.ENCODING_URLENCODED;
- } else if (settings.getType().matches("(POST|PUT)") && "json".equalsIgnoreCase(settings.getDataType())) {
+ } else if (settings.getType().matches("(POST|PUT)")
+ && "json".equalsIgnoreCase(settings.getDataType())) {
dataString = data.toJson();
contentType = JSON_CONTENT_TYPE_UTF8;
} else {
}
public static Promise get(String url, IsProperties data) {
- return get(url, (IsProperties)data, null);
+ return get(url, (IsProperties) data, null);
}
public static Promise get(String url, IsProperties data, Function onSuccess) {
}
public static Promise getJSONP(String url, IsProperties data) {
- return getJSONP(url, (IsProperties)data, null);
+ return getJSONP(url, (IsProperties) data, null);
}
public static Promise getJSONP(String url, IsProperties data, Function onSuccess) {
public static Promise getJSONP(String url, Function success, Function error, int timeout) {
return ajax(createSettings()
- .setUrl(url)
- .setDataType("jsonp")
- .setType("get")
- .setTimeout(timeout)
- .setSuccess(success)
- .setError(error)
- );
+ .setUrl(url)
+ .setDataType("jsonp")
+ .setType("get")
+ .setTimeout(timeout)
+ .setSuccess(success)
+ .setError(error));
}
/**
public static Promise getScript(final String url, Function success) {
return ajax(createSettings()
- .setUrl(url)
- .setType("get")
- .setDataType("script")
- .setSuccess(success)
- );
+ .setUrl(url)
+ .setType("get")
+ .setDataType("script")
+ .setSuccess(success));
}
/**
public static Promise loadScript(final String url, Function success) {
return ajax(createSettings()
- .setUrl(url)
- .setType("get")
- .setDataType("loadscript")
- .setSuccess(success)
- );
+ .setUrl(url)
+ .setType("get")
+ .setDataType("loadscript")
+ .setSuccess(success));
}
public static Promise post(String url, IsProperties data) {
- return post(url, (IsProperties)data, null);
+ return post(url, (IsProperties) data, null);
}
public static Promise post(String url, IsProperties data, final Function onSuccess) {
// not support java embedded flag expressions (?s) and javascript does
// not have multidot flag.
String s = arguments(0).toString().replaceAll("<![^>]+>\\s*", "")
- .replaceAll("</?html[\\s\\S]*?>\\s*", "")
- .replaceAll("<head[\\s\\S]*?</head>\\s*", "")
- .replaceAll("<script[\\s\\S]*?</script>\\s*", "")
- .replaceAll("</?body[\\s\\S]*?>\\s*", "");
+ .replaceAll("</?html[\\s\\S]*?>\\s*", "")
+ .replaceAll("<head[\\s\\S]*?</head>\\s*", "")
+ .replaceAll("<script[\\s\\S]*?</script>\\s*", "")
+ .replaceAll("</?body[\\s\\S]*?>\\s*", "");
// We wrap the results in a div
s = "<div>" + s + "</div>";
public Promise getLoadScript(final Settings settings) {
return new PromiseFunction() {
private ScriptElement scriptElement;
+
public void f(final Deferred dfd) {
scriptElement = ScriptInjector.fromUrl(settings.getUrl()).setWindow(GQuery.window)
- .setCallback(new Callback<Void, Exception>() {
- public void onSuccess(Void result) {
- GQuery.$(GQuery.window).delay(0, new Function(){
- public void f() {
- dfd.resolve(scriptElement);
+ .setCallback(new Callback<Void, Exception>() {
+ public void onSuccess(Void result) {
+ GQuery.$(GQuery.window).delay(0, new Function() {
+ public void f() {
+ dfd.resolve(scriptElement);
+ }
+ });
+ }
+
+ public void onFailure(Exception reason) {
+ dfd.reject(reason);
}
- });
- }
- public void onFailure(Exception reason) {
- dfd.reject(reason);
- }
- }).inject().cast();
+ }).inject().cast();
}
};
}
/**
* Return false to avoid executing the rest of functions.
*/
- boolean f(Object ...objects);
+ boolean f(Object... objects);
}
private List<Object> stack = new ArrayList<Object>();
*
*/
public Callbacks add(Callback... c) {
- addAll((Object[])c);
+ addAll((Object[]) c);
return this;
}
* Add a Callback or a collection of callbacks to a callback list.
*/
public Callbacks add(com.google.gwt.core.client.Callback<?, ?>... c) {
- addAll((Object[])c);
+ addAll((Object[]) c);
return this;
}
* Add a Function or a collection of Function to a callback list.
*/
public Callbacks add(Function... f) {
- addAll((Object[])f);
+ addAll((Object[]) f);
return this;
}
if (isMemory) {
memory = new ArrayList<Object>(Arrays.asList(o));
}
- if (stack != null) for (Object c : stack) {
- if (!run(c, o) && stopOnFalse) {
- break;
+ if (stack != null)
+ for (Object c : stack) {
+ if (!run(c, o) && stopOnFalse) {
+ break;
+ }
}
- }
}
return this;
}
return this;
}
- private void addAll(Object...o) {
+ private void addAll(Object... o) {
for (Object c : o) {
if (!done && stack != null && c != null && (!isUnique || !stack.contains(c))) {
stack.add(c);
}
@SuppressWarnings({"unchecked", "rawtypes"})
- private boolean run(Object c, Object...o) {
+ private boolean run(Object c, Object... o) {
// Unbox array inside array when there is only an element.
// It happens when running filters in Promise.then()
if (o != null && o.length == 1 && o[0] != null && o[0].getClass().isArray()) {
- o = (Object[])o[0];
+ o = (Object[]) o[0];
}
if (c instanceof Callback) {
- return ((Callback)c).f(o);
+ return ((Callback) c).f(o);
} else if (c instanceof Function) {
- Object r = ((Function)c).f(o);
- return (r instanceof Boolean) ? (Boolean)r : true;
+ Object r = ((Function) c).f(o);
+ return (r instanceof Boolean) ? (Boolean) r : true;
} else if (c instanceof com.google.gwt.core.client.Callback) {
- ((com.google.gwt.core.client.Callback)c).onSuccess(o);
+ ((com.google.gwt.core.client.Callback) c).onSuccess(o);
}
return true;
}
return "stack=" + (stack == null ? "null" : stack.size()) + " " + done;
}
}
-
// Whether break the flow if old deferred fails
boolean cont = false;
- public ThenFunction(Deferred newDfd, Function[] subordinates, int funcType, boolean continueFlow) {
+ public ThenFunction(Deferred newDfd, Function[] subordinates, int funcType,
+ boolean continueFlow) {
type = funcType;
filter = subordinates.length > type ? subordinates[type] : null;
dfd = newDfd;
// If filter function returns a promise we pipeline it.
final Promise p = (Promise) newArgs;
if (type == PROGRESS) {
- p.progress(new Function(){public void f() {
- settle(PROGRESS, getArguments());
- }});
+ p.progress(new Function() {
+ public void f() {
+ settle(PROGRESS, getArguments());
+ }
+ });
} else {
- p.always(new Function(){public void f() {
- settle((type == DONE || type == FAIL && cont) && p.isResolved() ? DONE : FAIL, getArguments());
- }});
+ p.always(new Function() {
+ public void f() {
+ settle((type == DONE || type == FAIL && cont) && p.isResolved() ? DONE : FAIL,
+ getArguments());
+ }
+ });
}
} else {
// Otherwise we change the arguments by the new ones
newArgs = Boolean.TRUE.equals(newArgs) ? oldArgs :
- newArgs != null && newArgs.getClass().isArray() ? (Object[])newArgs : newArgs;
+ newArgs != null && newArgs.getClass().isArray() ? (Object[]) newArgs : newArgs;
settle(type, newArgs);
}
} else {
}
private void settle(int action, Object... args) {
- if (action == DONE) dfd.resolve(args);
- if (action == FAIL) dfd.reject(args);
- if (action == PROGRESS) dfd.notify(args);
+ if (action == DONE)
+ dfd.resolve(args);
+ if (action == FAIL)
+ dfd.reject(args);
+ if (action == PROGRESS)
+ dfd.notify(args);
}
}
private static Promise makePromise(final Object o) {
if (o instanceof Promise) {
- return (Promise)o;
+ return (Promise) o;
} else if (o instanceof Function) {
- return makePromise(((Function)o).f(new Object[0]));
+ return makePromise(((Function) o).f(new Object[0]));
} else if (o instanceof GQuery) {
- return ((GQuery)o).promise();
+ return ((GQuery) o).promise();
} else {
return new PromiseFunction() {
public void f(Deferred dfd) {
* Call the progressCallbacks on a Deferred object with the given args.
*/
public Deferred notify(Object... o) {
- if (state == PENDING) notify.fire(o);
+ if (state == PENDING)
+ notify.fire(o);
return this;
}
* Reject a Deferred object and call any failCallbacks with the given args.
*/
public Deferred reject(Object... o) {
- if (state == PENDING) reject.fire(o);
+ if (state == PENDING)
+ reject.fire(o);
return this;
}
* Resolve a Deferred object and call any doneCallbacks with the given args.
*/
public Deferred resolve(Object... o) {
- if (state == PENDING) resolve.fire(o);
+ if (state == PENDING)
+ resolve.fire(o);
return this;
}
@Override
public String toString() {
- return "Deferred this=" + hashCode() + " promise=" + promise().hashCode() + " state=" + promise.state() + " restatus=" + resolve.status();
+ return "Deferred this=" + hashCode() + " promise=" + promise().hashCode() + " state="
+ + promise.state() + " restatus=" + resolve.status();
}
}
/**
* Cache types.
*/
- public static enum CacheType {NONE, ALL, RESOLVED, REJECTED};
+ public static enum CacheType {
+ NONE, ALL, RESOLVED, REJECTED
+ };
protected Deferred dfd;
public Function resolve, reject;
* is resolved.
*/
public final Object f(Object... args) {
- return dfd != null &&
+ return dfd != null &&
(cache == CacheType.ALL ||
- cache == CacheType.RESOLVED && dfd.promise().isResolved() ||
- cache == CacheType.REJECTED && dfd.promise().isRejected())
+ cache == CacheType.RESOLVED && dfd.promise().isResolved() ||
+ cache == CacheType.REJECTED && dfd.promise().isRejected())
? dfd.promise()
: new PromiseFunction() {
public void f(Deferred dfd) {
FunctionDeferred.this.dfd = dfd;
FunctionDeferred.this.f(dfd);
}
- };
+ };
}
/**
String url = settings.getUrl();
IsProperties data = settings.getData();
String ctype = settings.getContentType();
- Boolean isFormData = data != null && data.getDataImpl() instanceof JavaScriptObject && JsUtils.isFormData(data.<JavaScriptObject>getDataImpl());
+ Boolean isFormData =
+ data != null && data.getDataImpl() instanceof JavaScriptObject
+ && JsUtils.isFormData(data.<JavaScriptObject> getDataImpl());
XMLHttpRequest xmlHttpRequest = XMLHttpRequest.create();
try {
});
try {
- JsUtils.runJavascriptFunction(xmlHttpRequest, "send", isFormData ? data.getDataImpl() : settings.getDataString());
+ JsUtils.runJavascriptFunction(xmlHttpRequest, "send", isFormData ? data.getDataImpl()
+ : settings.getDataString());
} catch (JavaScriptException e) {
onError(null, e);
}
int status = response.getStatusCode();
if (status <= 0 || status >= 400) {
String statusText = status <= 0 ? "Bad CORS" : response.getStatusText();
- onError(request, new RequestException("HTTP ERROR: " + status + " " + statusText + "\n" + response.getText()));
+ onError(request, new RequestException("HTTP ERROR: " + status + " " + statusText + "\n"
+ + response.getText()));
} else {
dfd.resolve(response, request);
}
// jQuery allows a parameter callback=? to figure out the callback parameter
if (callbackParam == null) {
MatchResult tmp = callbackRegex.exec(url);
- if (tmp != null && tmp.getGroupCount() == 4) {
+ if (tmp != null && tmp.getGroupCount() == 4) {
callbackParam = tmp.getGroup(2);
url = tmp.getGroup(1) + tmp.getGroup(3);
}
*/
public class Bezier {
- private double x1, y1 , x2, y2;
+ private double x1, y1, x2, y2;
public Bezier(double x1, double y1, double x2, double y2) {
- this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
+ this.x1 = x1;
+ this.y1 = y1;
+ this.x2 = x2;
+ this.y2 = y2;
}
private double a(double a1, double a2) {
return 1.0 - 3.0 * a2 + 3.0 * a1;
}
+
private double b(double a1, double a2) {
return 3.0 * a2 - 6.0 * a1;
}
- private double c(double a1){
+
+ private double c(double a1) {
return 3.0 * a1;
}
private double calcBezier(double t, double a1, double a2) {
- return ((a(a1, a2)*t + b(a1, a2))*t + c(a1))*t;
+ return ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t;
}
private double calcSlope(double t, double a1, double a2) {
- return 3.0 * a(a1, a2)*t*t + 2.0 * b(a1, a2) * t + c(a1);
+ return 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1);
}
private double getTForX(double x) {
double t = x;
for (double i = 0; i < 4; ++i) {
double currentSlope = calcSlope(t, x1, x2);
- if (currentSlope == 0.0) return t;
+ if (currentSlope == 0.0)
+ return t;
double currentX = calcBezier(t, x1, x2) - x;
t -= currentX / currentSlope;
}
return t;
}
- public double f (double x) {
+ public double f(double x) {
return calcBezier(getTForX(x), y1, y2);
}
BIDIRECTIONAL, HORIZONTAL, VERTICAL
}
- private static final String[] attrsToSave = new String[]{
- "position", "overflow", "visibility", "white-space", "top", "left", "width", "height"};
+ private static final String[] attrsToSave = new String[] {
+ "position", "overflow", "visibility", "white-space", "top", "left", "width", "height"};
private Action action;
private Corner corner;
if (action == null) {
return;
}
- currentAction = action != Action.TOGGLE ? action : hidden ? Action.SHOW : Action.HIDE;
+ currentAction = action != Action.TOGGLE ? action : hidden ? Action.SHOW : Action.HIDE;
g.saveCssAttrs(attrsToSave);
}
// hexadecimal regex
- public static RegExp REGEX_HEX_COLOR_PATTERN = RegExp.compile("#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})");
+ public static RegExp REGEX_HEX_COLOR_PATTERN = RegExp
+ .compile("#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})");
private static JsNamedArray<int[]> htmlColorToRgb;
// rgb and rgba regex
public static RegExp REGEX_RGB_COLOR_PATTERN =
- RegExp.compile("rgba?\\(\\s*([0-9]{1,3}%?)\\s*,\\s*([0-9]{1,3}%?)\\s*,\\s*([0-9]{1,3}%?).*\\)$");
+ RegExp
+ .compile("rgba?\\(\\s*([0-9]{1,3}%?)\\s*,\\s*([0-9]{1,3}%?)\\s*,\\s*([0-9]{1,3}%?).*\\)$");
static {
htmlColorToRgb = JsNamedArray.create();
- htmlColorToRgb.put("white", new int[]{255, 255, 255});
- htmlColorToRgb.put("aqua", new int[]{0, 255, 255});
- htmlColorToRgb.put("azure", new int[]{240, 255, 255});
- htmlColorToRgb.put("beige", new int[]{245, 245, 220});
- htmlColorToRgb.put("black", new int[]{0, 0, 0});
- htmlColorToRgb.put("blue", new int[]{0, 0, 255});
- htmlColorToRgb.put("brown", new int[]{165, 42, 42});
- htmlColorToRgb.put("cyan", new int[]{0, 255, 255});
- htmlColorToRgb.put("darkblue", new int[]{0, 0, 139});
- htmlColorToRgb.put("darkcyan", new int[]{0, 139, 139});
- htmlColorToRgb.put("darkgrey", new int[]{169, 169, 169});
- htmlColorToRgb.put("darkgreen", new int[]{0, 100, 0});
- htmlColorToRgb.put("darkkhaki", new int[]{189, 183, 107});
- htmlColorToRgb.put("darkmagenta", new int[]{139, 0, 139});
- htmlColorToRgb.put("darkolivegreen", new int[]{85, 107, 47});
- htmlColorToRgb.put("darkorange", new int[]{255, 140, 0});
- htmlColorToRgb.put("darkorchid", new int[]{153, 50, 204});
- htmlColorToRgb.put("darkred", new int[]{139, 0, 0});
- htmlColorToRgb.put("darksalmon", new int[]{233, 150, 122});
- htmlColorToRgb.put("darkviolet", new int[]{148, 0, 211});
- htmlColorToRgb.put("fuchsia", new int[]{255, 0, 255});
- htmlColorToRgb.put("gold", new int[]{255, 215, 0});
- htmlColorToRgb.put("green", new int[]{0, 128, 0});
- htmlColorToRgb.put("indigo", new int[]{75, 0, 130});
- htmlColorToRgb.put("khaki", new int[]{240, 230, 140});
- htmlColorToRgb.put("lightblue", new int[]{173, 216, 230});
- htmlColorToRgb.put("lightcyan", new int[]{224, 255, 255});
- htmlColorToRgb.put("lightgreen", new int[]{144, 238, 144});
- htmlColorToRgb.put("lightgrey", new int[]{211, 211, 211});
- htmlColorToRgb.put("lightpink", new int[]{255, 182, 193});
- htmlColorToRgb.put("lightyellow", new int[]{255, 255, 224});
- htmlColorToRgb.put("lime", new int[]{0, 255, 0});
- htmlColorToRgb.put("magenta", new int[]{255, 0, 255});
- htmlColorToRgb.put("maroon", new int[]{128, 0, 0});
- htmlColorToRgb.put("navy", new int[]{0, 0, 128});
- htmlColorToRgb.put("olive", new int[]{128, 128, 0});
- htmlColorToRgb.put("orange", new int[]{255, 165, 0});
- htmlColorToRgb.put("pink", new int[]{255, 192, 203});
- htmlColorToRgb.put("purple", new int[]{128, 0, 128});
- htmlColorToRgb.put("violet", new int[]{128, 0, 128});
- htmlColorToRgb.put("red", new int[]{255, 0, 0});
- htmlColorToRgb.put("silver", new int[]{192, 192, 192});
- htmlColorToRgb.put("white", new int[]{255, 255, 255});
- htmlColorToRgb.put("yellow", new int[]{255, 255, 0});
+ htmlColorToRgb.put("white", new int[] {255, 255, 255});
+ htmlColorToRgb.put("aqua", new int[] {0, 255, 255});
+ htmlColorToRgb.put("azure", new int[] {240, 255, 255});
+ htmlColorToRgb.put("beige", new int[] {245, 245, 220});
+ htmlColorToRgb.put("black", new int[] {0, 0, 0});
+ htmlColorToRgb.put("blue", new int[] {0, 0, 255});
+ htmlColorToRgb.put("brown", new int[] {165, 42, 42});
+ htmlColorToRgb.put("cyan", new int[] {0, 255, 255});
+ htmlColorToRgb.put("darkblue", new int[] {0, 0, 139});
+ htmlColorToRgb.put("darkcyan", new int[] {0, 139, 139});
+ htmlColorToRgb.put("darkgrey", new int[] {169, 169, 169});
+ htmlColorToRgb.put("darkgreen", new int[] {0, 100, 0});
+ htmlColorToRgb.put("darkkhaki", new int[] {189, 183, 107});
+ htmlColorToRgb.put("darkmagenta", new int[] {139, 0, 139});
+ htmlColorToRgb.put("darkolivegreen", new int[] {85, 107, 47});
+ htmlColorToRgb.put("darkorange", new int[] {255, 140, 0});
+ htmlColorToRgb.put("darkorchid", new int[] {153, 50, 204});
+ htmlColorToRgb.put("darkred", new int[] {139, 0, 0});
+ htmlColorToRgb.put("darksalmon", new int[] {233, 150, 122});
+ htmlColorToRgb.put("darkviolet", new int[] {148, 0, 211});
+ htmlColorToRgb.put("fuchsia", new int[] {255, 0, 255});
+ htmlColorToRgb.put("gold", new int[] {255, 215, 0});
+ htmlColorToRgb.put("green", new int[] {0, 128, 0});
+ htmlColorToRgb.put("indigo", new int[] {75, 0, 130});
+ htmlColorToRgb.put("khaki", new int[] {240, 230, 140});
+ htmlColorToRgb.put("lightblue", new int[] {173, 216, 230});
+ htmlColorToRgb.put("lightcyan", new int[] {224, 255, 255});
+ htmlColorToRgb.put("lightgreen", new int[] {144, 238, 144});
+ htmlColorToRgb.put("lightgrey", new int[] {211, 211, 211});
+ htmlColorToRgb.put("lightpink", new int[] {255, 182, 193});
+ htmlColorToRgb.put("lightyellow", new int[] {255, 255, 224});
+ htmlColorToRgb.put("lime", new int[] {0, 255, 0});
+ htmlColorToRgb.put("magenta", new int[] {255, 0, 255});
+ htmlColorToRgb.put("maroon", new int[] {128, 0, 0});
+ htmlColorToRgb.put("navy", new int[] {0, 0, 128});
+ htmlColorToRgb.put("olive", new int[] {128, 128, 0});
+ htmlColorToRgb.put("orange", new int[] {255, 165, 0});
+ htmlColorToRgb.put("pink", new int[] {255, 192, 203});
+ htmlColorToRgb.put("purple", new int[] {128, 0, 128});
+ htmlColorToRgb.put("violet", new int[] {128, 0, 128});
+ htmlColorToRgb.put("red", new int[] {255, 0, 0});
+ htmlColorToRgb.put("silver", new int[] {192, 192, 192});
+ htmlColorToRgb.put("white", new int[] {255, 255, 255});
+ htmlColorToRgb.put("yellow", new int[] {255, 255, 0});
}
protected int[] endColor;
double ret = (start + ((end - start) * progress));
String val = ("px".equals(unit) ? ((int) ret) : ret) + unit;
if ("scrollTop".equals(cssprop)) {
- g.scrollTop((int)ret);
+ g.scrollTop((int) ret);
} else if ("scrollLeft".equals(cssprop)) {
- g.scrollLeft((int)ret);
+ g.scrollLeft((int) ret);
} else if (attribute != null) {
g.attr(attribute, val);
} else {
*/
public interface Easing {
double interpolate(double progress);
+
/**
* @deprecated use EasingCurve.linear instead
*/
*
*/
public static enum EasingCurve implements Easing {
- linear (0, 0, 1, 1) {
- public double interpolate(double p){return p;}
- public String toString() {return "linear";}
- },
- ease (0.25, 0.1, 0.25, 1) {
- public String toString() {return "ease";}
- },
- easeIn (0.42, 0, 1, 1) {
- public String toString() {return "ease-in";}
- },
- easeOut (0, 0, 0.58, 1) {
- public String toString() {return "ease-out";}
- },
- easeInOut (0.42, 0, 0.58, 1) {
- public String toString() {return "ease-in-out";}
- },
- snap (0,1,.5,1),
- swing (.02,.01,.47,1),
- easeInCubic (.550,.055,.675,.190),
- easeOutCubic (.215,.61,.355,1),
- easeInOutCubic (.645,.045,.355,1),
- easeInCirc (.6,.04,.98,.335),
- easeOutCirc (.075,.82,.165,1),
- easeInOutCirc (.785,.135,.15,.86),
- easeInExpo (.95,.05,.795,.035),
- easeOutExpo (.19,1,.22,1),
- easeInOutExpo (1,0,0,1),
- easeInQuad (.55,.085,.68,.53),
- easeOutQuad (.25,.46,.45,.94),
- easeInOutQuad (.455,.03,.515,.955),
- easeInQuart (.895,.03,.685,.22),
- easeOutQuart (.165,.84,.44,1),
- easeInOutQuart (.77,0,.175,1),
- easeInQuint (.755,.05,.855,.06),
- easeOutQuint (.23,1,.32,1),
- easeInOutQuint (.86,0,.07,1),
- easeInSine (.47,0,.745,.715),
- easeOutSine (.39,.575,.565,1),
- easeInOutSine (.445,.05,.55,.95),
- easeInBack (.6,-.28,.735,.045),
- easeOutBack (.175, .885,.32,1.275),
- easeInOutBack (.68,-.55,.265,1.55),
- custom(0, 0, 1, 1);
-
- private Bezier c = new Bezier(0, 0, 1, 1);
- EasingCurve(double x1, double y1, double x2, double y2) {
- with(x1, y1, x2, y2);
- }
- public Easing with(double x1, double y1, double x2, double y2) {
- c = new Bezier(x1, y1, x2, y2);
- return this;
- }
- public double interpolate(double progress) {
- return c.f(progress);
- }
- public String toString() {
+ linear(0, 0, 1, 1) {
+ public double interpolate(double p) {
+ return p;
+ }
+
+ public String toString() {
+ return "linear";
+ }
+ },
+ ease(0.25, 0.1, 0.25, 1) {
+ public String toString() {
+ return "ease";
+ }
+ },
+ easeIn(0.42, 0, 1, 1) {
+ public String toString() {
+ return "ease-in";
+ }
+ },
+ easeOut(0, 0, 0.58, 1) {
+ public String toString() {
+ return "ease-out";
+ }
+ },
+ easeInOut(0.42, 0, 0.58, 1) {
+ public String toString() {
+ return "ease-in-out";
+ }
+ },
+ snap(0, 1, .5, 1),
+ swing(.02, .01, .47, 1),
+ easeInCubic(.550, .055, .675, .190),
+ easeOutCubic(.215, .61, .355, 1),
+ easeInOutCubic(.645, .045, .355, 1),
+ easeInCirc(.6, .04, .98, .335),
+ easeOutCirc(.075, .82, .165, 1),
+ easeInOutCirc(.785, .135, .15, .86),
+ easeInExpo(.95, .05, .795, .035),
+ easeOutExpo(.19, 1, .22, 1),
+ easeInOutExpo(1, 0, 0, 1),
+ easeInQuad(.55, .085, .68, .53),
+ easeOutQuad(.25, .46, .45, .94),
+ easeInOutQuad(.455, .03, .515, .955),
+ easeInQuart(.895, .03, .685, .22),
+ easeOutQuart(.165, .84, .44, 1),
+ easeInOutQuart(.77, 0, .175, 1),
+ easeInQuint(.755, .05, .855, .06),
+ easeOutQuint(.23, 1, .32, 1),
+ easeInOutQuint(.86, 0, .07, 1),
+ easeInSine(.47, 0, .745, .715),
+ easeOutSine(.39, .575, .565, 1),
+ easeInOutSine(.445, .05, .55, .95),
+ easeInBack(.6, -.28, .735, .045),
+ easeOutBack(.175, .885, .32, 1.275),
+ easeInOutBack(.68, -.55, .265, 1.55),
+ custom(0, 0, 1, 1);
+
+ private Bezier c = new Bezier(0, 0, 1, 1);
+
+ EasingCurve(double x1, double y1, double x2, double y2) {
+ with(x1, y1, x2, y2);
+ }
+
+ public Easing with(double x1, double y1, double x2, double y2) {
+ c = new Bezier(x1, y1, x2, y2);
+ return this;
+ }
+
+ public double interpolate(double progress) {
+ return c.f(progress);
+ }
+
+ public String toString() {
return "cubic-bezier(" + c + ")";
- }
- }
+ }
+ }
- protected static final String[] ATTRS_TO_SAVE = new String[]{"overflow"};
+ protected static final String[] ATTRS_TO_SAVE = new String[] {"overflow"};
private static final RegExp REGEX_NUMBER_UNIT = RegExp.compile("^([0-9+-.]+)(.*)?$");
- protected static final RegExp REGEX_SYMBOL_NUMBER_UNIT = RegExp.compile("^([+-]=)?([0-9+-.]+)(.*)?$");
+ protected static final RegExp REGEX_SYMBOL_NUMBER_UNIT = RegExp
+ .compile("^([+-]=)?([0-9+-.]+)(.*)?$");
protected static final RegExp REGEX_NON_PIXEL_ATTRS =
RegExp.compile("z-?index|font-?weight|opacity|zoom|line-?height|scale|rotation|^\\$", "i");
private static final RegExp REGEX_BORDERCOLOR = RegExp.compile("^bordercolor$", "i");
- private static final RegExp REGEX_BACKGROUNDCOLOR =RegExp.compile("^backgroundcolor$", "i");
+ private static final RegExp REGEX_BACKGROUNDCOLOR = RegExp.compile("^backgroundcolor$", "i");
public static Fx computeFxProp(Element e, String key, String val,
boolean hidden) {
// transparent)
Element current = e;
- while ((initialColor == null || initialColor.length() == 0 || initialColor.equals("transparent"))
+ while ((initialColor == null || initialColor.length() == 0 || initialColor
+ .equals("transparent"))
&& current != null) {
initialColor = GQuery.$(current).css(key, false);
current = !"body".equalsIgnoreCase(current.getTagName())
if (rkey == null) {
unit = REGEX_NON_PIXEL_ATTRS.test(key) ? "" : //
- p3 == null || p3.isEmpty() ? "px" : p3;
+ p3 == null || p3.isEmpty() ? "px" : p3;
if (!"px".equals(unit)) {
double to = end == 0 ? 1 : end;
g.css(key, to + unit);
@Override
public void onCancel() {
Boolean jumpToEnd = Effects.$(e).data(Effects.JUMP_TO_END, Boolean.class);
- if (jumpToEnd != null && jumpToEnd){
+ if (jumpToEnd != null && jumpToEnd) {
onComplete();
} else {
g.dequeue();
Button button = new Button();
button.getElement().setInnerText(e.getInnerText());
- if ("button".equalsIgnoreCase(e.getTagName())){
- copyAttributes((ButtonElement)e.cast(), (ButtonElement)button.getElement().cast());
+ if ("button".equalsIgnoreCase(e.getTagName())) {
+ copyAttributes((ButtonElement) e.cast(), (ButtonElement) button.getElement().cast());
}
WidgetsUtils.replaceOrAppend(e, button);
return button;
}
- protected void copyAttributes(ButtonElement source,ButtonElement destination) {
+ protected void copyAttributes(ButtonElement source, ButtonElement destination) {
destination.setAccessKey(source.getAccessKey());
destination.setDisabled(source.isDisabled());
destination.setName(source.getName());
@Override
protected void copyAttributes(Element src, Element dest) {
- TextAreaElement source= src.cast();
+ TextAreaElement source = src.cast();
TextAreaElement destination = dest.cast();
destination.setAccessKey(source.getAccessKey());
public class WidgetsUtils {
static final String[] appendingTags = {
- "td", "th", "li"};
+ "td", "th", "li"};
/**
* Append a widget to a dom element, and hide it.
* Element classes will be copied to the new widget.
*/
- public static void hideAndAfter(Element e, Widget widget) {
- assert e != null && widget != null;
- if ($(e).widget() != null && $(e).widget().isAttached()) {
- replaceWidget($(e).widget(), widget, false);
- } else {
- detachWidget(widget);
- hideAndAfter(e, widget.getElement());
- attachWidget(widget, getFirstParentWidget(widget));
- }
- }
+ public static void hideAndAfter(Element e, Widget widget) {
+ assert e != null && widget != null;
+ if ($(e).widget() != null && $(e).widget().isAttached()) {
+ replaceWidget($(e).widget(), widget, false);
+ } else {
+ detachWidget(widget);
+ hideAndAfter(e, widget.getElement());
+ attachWidget(widget, getFirstParentWidget(widget));
+ }
+ }
/**
* Test if the tag name of the element is one of tag names given in parameter.
return e.getTagName().toUpperCase().matches(regExp.toString());
}
- /**
- * Replace a dom element by a widget.
- * Old element classes will be copied to the new widget.
- */
- public static void replaceOrAppend(Element e, Widget widget) {
- assert e != null && widget != null;
- if ($(e).widget() != null && $(e).widget().isAttached()) {
- replaceWidget($(e).widget(), widget, true);
- } else {
- detachWidget(widget);
- replaceOrAppend(e, widget.getElement());
- attachWidget(widget, getFirstParentWidget(widget));
- }
- }
+ /**
+ * Replace a dom element by a widget.
+ * Old element classes will be copied to the new widget.
+ */
+ public static void replaceOrAppend(Element e, Widget widget) {
+ assert e != null && widget != null;
+ if ($(e).widget() != null && $(e).widget().isAttached()) {
+ replaceWidget($(e).widget(), widget, true);
+ } else {
+ detachWidget(widget);
+ replaceOrAppend(e, widget.getElement());
+ attachWidget(widget, getFirstParentWidget(widget));
+ }
+ }
- private static Widget getFirstParentWidget(Widget w) {
- Element e = w.getElement().getParentElement();
- BodyElement body = Document.get().getBody();
- while ((e != null) && (body != e)) {
- if (Event.getEventListener(e) != null) {
- Widget p = $(e).widget();
- if (p != null){
- return p;
- }
- }
- e = e.getParentElement();
- }
- return null;
- }
+ private static Widget getFirstParentWidget(Widget w) {
+ Element e = w.getElement().getParentElement();
+ BodyElement body = Document.get().getBody();
+ while ((e != null) && (body != e)) {
+ if (Event.getEventListener(e) != null) {
+ Widget p = $(e).widget();
+ if (p != null) {
+ return p;
+ }
+ }
+ e = e.getParentElement();
+ }
+ return null;
+ }
- private static void hideAndAfter(Element oldElement, Element newElement) {
- assert oldElement != null && newElement != null;
- GQuery.$(oldElement).hide().after(newElement);
- String c = oldElement.getClassName();
- if (!c.isEmpty()) {
- newElement.addClassName(c);
- }
- }
+ private static void hideAndAfter(Element oldElement, Element newElement) {
+ assert oldElement != null && newElement != null;
+ GQuery.$(oldElement).hide().after(newElement);
+ String c = oldElement.getClassName();
+ if (!c.isEmpty()) {
+ newElement.addClassName(c);
+ }
+ }
/**
* If the <code>oldElement</code> is a td, th, li tags, the new element will replaced its content.
* In other cases, the <code>oldElement</code> will be replaced by the <code>newElement</code>
* and the old element classes will be copied to the new element.
*/
- private static void replaceOrAppend(Element oldElement, Element newElement) {
+ private static void replaceOrAppend(Element oldElement, Element newElement) {
assert oldElement != null && newElement != null;
- if(matchesTags(oldElement, appendingTags)){
+ if (matchesTags(oldElement, appendingTags)) {
GQuery.$(oldElement).html("").append(newElement);
- }else{
+ } else {
GQuery.$(oldElement).replaceWith(newElement);
// copy class
// ensure no duplicate id
oldElement.setId("");
}
- }
+ }
- private static void replaceWidget(Widget oldWidget, Widget newWidget, boolean remove) {
- Widget parent = oldWidget.getParent();
- boolean removed = false;
- // TODO: handle tables
- if (parent instanceof HTMLPanel) {
- ((HTMLPanel) parent).addAndReplaceElement(newWidget,
- (com.google.gwt.dom.client.Element)oldWidget.getElement());
- if (!remove) {
- $(newWidget).before($(oldWidget));
- }
- removed = true;
- } else if (parent instanceof ComplexPanel) {
- ((ComplexPanel) parent).add(newWidget);
- } else if (parent instanceof SimplePanel) {
- ((SimplePanel) parent).setWidget(newWidget);
- } else if (parent instanceof Panel) {
- ((Panel) parent).add(newWidget);
- } else {
- assert false : "Can not replace an attached widget whose parent is a " + parent.getClass().getName();
- }
- if (remove && !removed && oldWidget.isAttached()) {
- oldWidget.removeFromParent();
- } else {
- oldWidget.setVisible(false);
- }
- }
+ private static void replaceWidget(Widget oldWidget, Widget newWidget, boolean remove) {
+ Widget parent = oldWidget.getParent();
+ boolean removed = false;
+ // TODO: handle tables
+ if (parent instanceof HTMLPanel) {
+ ((HTMLPanel) parent).addAndReplaceElement(newWidget,
+ (com.google.gwt.dom.client.Element) oldWidget.getElement());
+ if (!remove) {
+ $(newWidget).before($(oldWidget));
+ }
+ removed = true;
+ } else if (parent instanceof ComplexPanel) {
+ ((ComplexPanel) parent).add(newWidget);
+ } else if (parent instanceof SimplePanel) {
+ ((SimplePanel) parent).setWidget(newWidget);
+ } else if (parent instanceof Panel) {
+ ((Panel) parent).add(newWidget);
+ } else {
+ assert false : "Can not replace an attached widget whose parent is a "
+ + parent.getClass().getName();
+ }
+ if (remove && !removed && oldWidget.isAttached()) {
+ oldWidget.removeFromParent();
+ } else {
+ oldWidget.setVisible(false);
+ }
+ }
- /**
- * Attach a widget to the GWT widget list. Normally used when GQuery
- * creates widgets wrapping existing dom elements.
- * It does nothing if the widget is already attached to another widget.
- *
- * @param widget to attach
- * @param firstParentWidget the parent widget,
- * If it is null and it is not inside any other widget, we just add
- * the widget to the gwt detach list
- */
- public static void attachWidget(Widget widget, Widget firstParentWidget) {
- if (widget != null && widget.getParent() == null) {
- if (firstParentWidget == null) {
- firstParentWidget = getFirstParentWidget(widget);
- if (firstParentWidget == null) {
- RootPanel.detachOnWindowClose(widget);
- widgetOnAttach(widget);
- } else {
- attachWidget(widget, firstParentWidget);
- }
- } else if (firstParentWidget instanceof HTMLPanel) {
- HTMLPanel h = (HTMLPanel) firstParentWidget;
- Element p = widget.getElement().getParentElement();
- if (p != null) {
- h.add(widget, p);
- } else {
- h.add(widget);
- }
- } else if (firstParentWidget instanceof HasOneWidget) {
- ((HasOneWidget)firstParentWidget).setWidget(widget);
- } else if (firstParentWidget instanceof HasWidgets) {
- try {
- ((HasWidgets)firstParentWidget).add(widget);
- } catch (UnsupportedOperationException e) {
- // Some widgets like 'table' has no implementation of 'add(widget)'
- widgetSetParent(widget, firstParentWidget);
- }
- } else {
- widgetSetParent(widget, firstParentWidget);
- }
- }
- }
+ /**
+ * Attach a widget to the GWT widget list. Normally used when GQuery
+ * creates widgets wrapping existing dom elements.
+ * It does nothing if the widget is already attached to another widget.
+ *
+ * @param widget to attach
+ * @param firstParentWidget the parent widget,
+ * If it is null and it is not inside any other widget, we just add
+ * the widget to the gwt detach list
+ */
+ public static void attachWidget(Widget widget, Widget firstParentWidget) {
+ if (widget != null && widget.getParent() == null) {
+ if (firstParentWidget == null) {
+ firstParentWidget = getFirstParentWidget(widget);
+ if (firstParentWidget == null) {
+ RootPanel.detachOnWindowClose(widget);
+ widgetOnAttach(widget);
+ } else {
+ attachWidget(widget, firstParentWidget);
+ }
+ } else if (firstParentWidget instanceof HTMLPanel) {
+ HTMLPanel h = (HTMLPanel) firstParentWidget;
+ Element p = widget.getElement().getParentElement();
+ if (p != null) {
+ h.add(widget, p);
+ } else {
+ h.add(widget);
+ }
+ } else if (firstParentWidget instanceof HasOneWidget) {
+ ((HasOneWidget) firstParentWidget).setWidget(widget);
+ } else if (firstParentWidget instanceof HasWidgets) {
+ try {
+ ((HasWidgets) firstParentWidget).add(widget);
+ } catch (UnsupportedOperationException e) {
+ // Some widgets like 'table' has no implementation of 'add(widget)'
+ widgetSetParent(widget, firstParentWidget);
+ }
+ } else {
+ widgetSetParent(widget, firstParentWidget);
+ }
+ }
+ }
- /**
- * Remove a widget from the detach list.
- */
- public static void detachWidget(final Widget widget) {
- if (widget != null) {
- widget.removeFromParent();
- }
- }
+ /**
+ * Remove a widget from the detach list.
+ */
+ public static void detachWidget(final Widget widget) {
+ if (widget != null) {
+ widget.removeFromParent();
+ }
+ }
- /**
- * This method detach a widget of its parent without doing a physical
- * detach (DOM manipulation).
- */
- public static void doLogicalDetachFromHtmlPanel(Widget w) {
- Widget parent = w.getParent();
+ /**
+ * This method detach a widget of its parent without doing a physical
+ * detach (DOM manipulation).
+ */
+ public static void doLogicalDetachFromHtmlPanel(Widget w) {
+ Widget parent = w.getParent();
- if (parent instanceof HTMLPanel) {
- complexPanelGetChildren((HTMLPanel) parent).remove(w);
- widgetSetParent(w, null);
- } else{
- throw new IllegalStateException(
- "You can only use this method to detach a child from an HTMLPanel");
- }
- }
+ if (parent instanceof HTMLPanel) {
+ complexPanelGetChildren((HTMLPanel) parent).remove(w);
+ widgetSetParent(w, null);
+ } else {
+ throw new IllegalStateException(
+ "You can only use this method to detach a child from an HTMLPanel");
+ }
+ }
- /**
- * Return children of the first widget's panel.
- */
- public static Iterator<Widget> getChildren(Widget w){
- if(w instanceof Panel){
- return ((Panel)w).iterator();
- }
- if(w instanceof Composite){
- return getChildren(compositeGetWidget((Composite)w));
- }
- return null;
- }
+ /**
+ * Return children of the first widget's panel.
+ */
+ public static Iterator<Widget> getChildren(Widget w) {
+ if (w instanceof Panel) {
+ return ((Panel) w).iterator();
+ }
+ if (w instanceof Composite) {
+ return getChildren(compositeGetWidget((Composite) w));
+ }
+ return null;
+ }
- /**
- * Return the first widget parent of the element, or null if it is not
- * attached to any widget yet.
- */
- private static Widget getFirstParentWidgetElement(Element element) {
- return $(element).parents().widget();
- }
+ /**
+ * Return the first widget parent of the element, or null if it is not
+ * attached to any widget yet.
+ */
+ private static Widget getFirstParentWidgetElement(Element element) {
+ return $(element).parents().widget();
+ }
- private static native void widgetOnAttach(Widget w) /*-{
- w.@com.google.gwt.user.client.ui.Widget::onAttach()();
- }-*/;
+ private static native void widgetOnAttach(Widget w) /*-{
+ w.@com.google.gwt.user.client.ui.Widget::onAttach()();
+ }-*/;
- private static native void widgetSetParent(Widget w, Widget p) /*-{
- w.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(p);
- }-*/;
+ private static native void widgetSetParent(Widget w, Widget p) /*-{
+ w.@com.google.gwt.user.client.ui.Widget::setParent(Lcom/google/gwt/user/client/ui/Widget;)(p);
+ }-*/;
- private static native Widget compositeGetWidget(Composite w) /*-{
- return w.@com.google.gwt.user.client.ui.Composite::getWidget()();
- }-*/;
+ private static native Widget compositeGetWidget(Composite w) /*-{
+ return w.@com.google.gwt.user.client.ui.Composite::getWidget()();
+ }-*/;
- private static native WidgetCollection complexPanelGetChildren(ComplexPanel w) /*-{
- return w.@com.google.gwt.user.client.ui.ComplexPanel::getChildren()();
- }-*/;
+ private static native WidgetCollection complexPanelGetChildren(ComplexPanel w) /*-{
+ return w.@com.google.gwt.user.client.ui.ComplexPanel::getChildren()();
+ }-*/;
}
@Deprecated
protected String getModulePrefix(TreeLogger logger, LinkerContext context,
String strongName) throws UnableToCompleteException {
- logger.log(Type.WARN,
- "GQuery IFrameWithDocTypeLinker is deprecated, remove <add-linker name=\"stddoctype\"/> from your module file");
+ logger
+ .log(
+ Type.WARN,
+ "GQuery IFrameWithDocTypeLinker is deprecated, remove <add-linker name=\"stddoctype\"/> from your module file");
return DOCTYPE + super.getModulePrefix(logger, context, strongName);
}
@Deprecated
protected String getModulePrefix(TreeLogger logger, LinkerContext context,
String strongName, int numFragments) throws UnableToCompleteException {
- logger.log(Type.WARN,
- "GQuery IFrameWithDocTypeLinker is deprecated, remove <add-linker name=\"stddoctype\"/> from your module file");
+ logger
+ .log(
+ Type.WARN,
+ "GQuery IFrameWithDocTypeLinker is deprecated, remove <add-linker name=\"stddoctype\"/> from your module file");
return DOCTYPE
+ super.getModulePrefix(logger, context, strongName, numFragments);
}
}
-
*/
public class BrowserGenerator extends Generator {
@Override
- public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
+ public String generate(TreeLogger logger, GeneratorContext context, String typeName)
+ throws UnableToCompleteException {
TypeOracle oracle = context.getTypeOracle();
PropertyOracle propOracle = context.getPropertyOracle();
PrintWriter pw = context.tryCreate(logger, packageName, className);
if (pw != null) {
- ClassSourceFileComposerFactory fact = new ClassSourceFileComposerFactory(packageName, className);
+ ClassSourceFileComposerFactory fact =
+ new ClassSourceFileComposerFactory(packageName, className);
if (clazz.isInterface() != null) {
fact.addImplementedInterface(requestedClass);
} else {
}
try {
// Read the javascript content
- String content = getContent(logger, packageName.replace(".", "/") , value);
+ String content = getContent(logger, packageName.replace(".", "/"), value);
// Adjust javascript so as we can introduce it in a JSNI comment block without
// breaking java syntax.
String jsni = parseJavascriptSource(content);
for (int i = 0; i < replace.length - 1; i += 2) {
- jsni = jsni.replaceAll(replace[i], replace[i+1]);
+ jsni = jsni.replaceAll(replace[i], replace[i + 1]);
}
pw.println(method.toString().replace("abstract", "native") + "/*-{");
pw.println(postpend);
pw.println("}-*/;");
} catch (Exception e) {
- logger.log(TreeLogger.ERROR, "Error parsing javascript source: " + value + " "+ e.getMessage());
+ logger.log(TreeLogger.ERROR, "Error parsing javascript source: " + value + " "
+ + e.getMessage());
throw new UnableToCompleteException();
}
}
/**
* Get the content of a javascript source. It supports remote sources hosted in CDN's.
*/
- private String getContent(TreeLogger logger, String path, String src) throws UnableToCompleteException {
+ private String getContent(TreeLogger logger, String path, String src)
+ throws UnableToCompleteException {
HttpURLConnection connection = null;
InputStream in = null;
try {
if (!src.matches("(?i)https?://.*")) {
String file = path + "/" + src;
- logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - importing external javascript: " + file);
+ logger.log(TreeLogger.INFO, getClass().getSimpleName()
+ + " - importing external javascript: " + file);
in = this.getClass().getClassLoader().getResourceAsStream(file);
if (in == null) {
logger.log(TreeLogger.ERROR, "Unable to read javascript file: " + file);
}
} else {
- logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - downloading external javascript: " + src);
+ logger.log(TreeLogger.INFO, getClass().getSimpleName()
+ + " - downloading external javascript: " + src);
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
- logger.log(TreeLogger.ERROR, "Server Error: " + status + " " + connection.getResponseMessage());
+ logger.log(TreeLogger.ERROR, "Server Error: " + status + " "
+ + connection.getResponseMessage());
throw new UnableToCompleteException();
}
boolean isSingQuot = false;
boolean isDblQuot = false;
boolean isSlash = false;
- boolean isCComment=false;
- boolean isCPPComment=false;
+ boolean isCComment = false;
+ boolean isCPPComment = false;
boolean isRegex = false;
boolean isOper = false;
Character last = 0;
Character prev = 0;
- for (int i = 0, l = js.length(); i < l ; i++) {
+ for (int i = 0, l = js.length(); i < l; i++) {
Character c = js.charAt(i);
String out = c.toString();
if (isJS) {
isDblQuot = c == '"';
- isSingQuot = c == '\'';
- isSlash = c == '/';
- isJS = !isDblQuot && !isSingQuot && !isSlash;
+ isSingQuot = c == '\'';
+ isSlash = c == '/';
+ isJS = !isDblQuot && !isSingQuot && !isSlash;
if (!isJS) {
out = tmp = "";
isCPPComment = isCComment = isRegex = false;
}
} else if (isSingQuot) {
isJS = !(isSingQuot = last == '\\' || c != '\'');
- if (isJS) out = escapeQuotedString(tmp, c);
- else tmp += c;
+ if (isJS)
+ out = escapeQuotedString(tmp, c);
+ else
+ tmp += c;
} else if (isDblQuot) {
isJS = !(isDblQuot = last == '\\' || c != '"');
- if (isJS) out = escapeQuotedString(tmp, c);
- else tmp += c;
+ if (isJS)
+ out = escapeQuotedString(tmp, c);
+ else
+ tmp += c;
} else if (isSlash) {
if (!isCPPComment && !isCComment && !isRegex && !isOper) {
isCPPComment = c == '/';
- isCComment = c == '*';
- isOper = !isCPPComment && !isCComment && !"=(&|?:;},".contains(""+prev);
+ isCComment = c == '*';
+ isOper = !isCPPComment && !isCComment && !"=(&|?:;},".contains("" + prev);
isRegex = !isCPPComment && !isCComment && !isOper;
}
if (isOper) {
out = "" + last + c;
} else if (isCPPComment) {
isJS = !(isSlash = isCPPComment = c != '\n');
- if (isJS) out = "\n";
+ if (isJS)
+ out = "\n";
} else if (isCComment) {
isSlash = isCComment = !(isJS = (last == '*' && c == '/'));
- if (isJS) out = "";
+ if (isJS)
+ out = "";
} else if (isRegex) {
isJS = !(isSlash = isRegex = (last == '\\' || c != '/'));
if (isJS) {
String mod = "";
while (++i < l) {
c = js.charAt(i);
- if ("igm".contains(""+c)) mod += c;
- else break;
+ if ("igm".contains("" + c))
+ mod += c;
+ else
+ break;
}
out = escapeInlineRegex(tmp, mod) + c;
} else {
private String escapeInlineRegex(String s, String mod) {
if (s.endsWith("*")) {
- return "new RegExp('" + s.replace("\\", "\\\\") + "','" + mod + "')";
+ return "new RegExp('" + s.replace("\\", "\\\\") + "','" + mod + "')";
} else {
return '/' + s + '/' + mod;
}
public static String deCapitalize(String s) {
return s == null || s.isEmpty() ? s :
- (s.substring(0, 1).toLowerCase() + (s.length() > 1 ? s.substring(1) : ""));
+ (s.substring(0, 1).toLowerCase() + (s.length() > 1 ? s.substring(1) : ""));
}
TypeOracle oracle;
throws UnableToCompleteException {
oracle = generatorContext.getTypeOracle();
- JClassType clazz = oracle.findType(requestedClass);
+ JClassType clazz = oracle.findType(requestedClass);
jsonBuilderType = oracle.findType(JsonBuilder.class.getName());
settingsType = oracle.findType(IsProperties.class.getName());
boolean isFactory = clazz.isAssignableTo(jsonFactoryType);
- SourceWriter sw = getSourceWriter(treeLogger, generatorContext, t[0], t[1], isFactory, requestedClass);
+ SourceWriter sw =
+ getSourceWriter(treeLogger, generatorContext, t[0], t[1], isFactory, requestedClass);
if (sw != null) {
if (isFactory) {
generateCreateMethod(sw, treeLogger);
for (JMethod method : clazz.getInheritableMethods()) {
String methName = method.getName();
// skip method from JsonBuilder
- if(jsonBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null ||
- settingsType.findMethod(method.getName(), method.getParameterTypes()) != null ) {
+ if (jsonBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null ||
+ settingsType.findMethod(method.getName(), method.getParameterTypes()) != null) {
continue;
}
Name nameAnnotation = method.getAnnotation(Name.class);
String name = nameAnnotation != null
- ? nameAnnotation.value()
- : methName.replaceFirst("^(get|set)", "");
+ ? nameAnnotation.value()
+ : methName.replaceFirst("^(get|set)", "");
if (nameAnnotation == null) {
name = name.substring(0, 1).toLowerCase() + name.substring(1);
}
} else {
sw.println("return Arrays.asList(" + ret + ");");
}
- } else if (method.getReturnType().isEnum() != null){
- sw.println("return "+ method.getReturnType().getQualifiedSourceName() + ".valueOf(p.getStr(\"" + name + "\"));");
+ } else if (method.getReturnType().isEnum() != null) {
+ sw.println("return " + method.getReturnType().getQualifiedSourceName()
+ + ".valueOf(p.getStr(\"" + name + "\"));");
} else {
sw.println("System.err.println(\"JsonBuilderGenerator WARN: unknown return type "
+ retType + " " + ifaceName + "." + name + "()\"); ");
sw.println("setArrayBase(\"" + name + "\", " + a + ");");
} else if (type.getParameterizedQualifiedSourceName().matches("java.util.Date")) {
sw.println("p.setNumber(\"" + name + "\", a.getTime());");
- } else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) {
+ } else if (type
+ .getParameterizedQualifiedSourceName()
+ .matches(
+ "(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) {
sw.println("p.setNumber(\"" + name + "\", a);");
} else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.Boolean|boolean)")) {
sw.println("p.setBoolean(\"" + name + "\", a);");
- } else if (type.getParameterizedQualifiedSourceName().matches("com.google.gwt.query.client.Function")) {
+ } else if (type.getParameterizedQualifiedSourceName().matches(
+ "com.google.gwt.query.client.Function")) {
sw.println("p.setFunction(\"" + name + "\", a);");
- } else if (type.isEnum() != null){
+ } else if (type.isEnum() != null) {
sw.println("p.set(\"" + name + "\", a.name());");
- }else {
+ } else {
sw.println("set(\"" + name + "\", a);");
}
if (!"void".equals(retType)) {
sw.indent();
ArrayList<JClassType> types = new ArrayList<JClassType>();
for (JClassType t : oracle.getTypes()) {
- if (t.isInterface() != null && t.isAssignableTo(jsonBuilderType) ) {
+ if (t.isInterface() != null && t.isAssignableTo(jsonBuilderType)) {
if (t.isPublic()) {
- sw.println("if (clz == " + t.getQualifiedSourceName() + ".class) return GWT.<T>create(" + t.getQualifiedSourceName() + ".class);");
+ sw.println("if (clz == " + t.getQualifiedSourceName() + ".class) return GWT.<T>create("
+ + t.getQualifiedSourceName() + ".class);");
} else {
logger.log(Type.WARN, t.getQualifiedSourceName() + " is not public");
}
sw.println("}");
sw.println("public " + IsProperties.class.getName() + " create(String s) {");
sw.indent();
- sw.println("return (" + IsProperties.class.getName() + ")" + JsUtils.class.getName() + ".parseJSON(s);");
+ sw.println("return (" + IsProperties.class.getName() + ")" + JsUtils.class.getName()
+ + ".parseJSON(s);");
sw.outdent();
sw.println("}");
sw.println("public " + IsProperties.class.getName() + " create() {");
}
}
- if (targetType == null) return null;
+ if (targetType == null)
+ return null;
assert targetType != null : "Parameter of Lazy<T> not found";
String genClass = targetType.getPackage().getName() + "."
if (printWriter == null) {
return null;
}
- ClassSourceFileComposerFactory composerFactory
- = new ClassSourceFileComposerFactory(packageName, className);
+ ClassSourceFileComposerFactory composerFactory =
+ new ClassSourceFileComposerFactory(packageName, className);
composerFactory.addImport("com.google.gwt.core.client.*");
composerFactory.addImport("com.google.gwt.query.client.*");
composerFactory.addImport("com.google.gwt.dom.client.Element");
sw.println(
"ctx = GQuery.$(getElement()).as(" + nonLazyType.getQualifiedSourceName() + "."
- + classID + ");");
+ + classID + ");");
sw.println("for (int i = 0; i < closures.length(); i++) {");
sw.indent();
sw.println("closures.get(i).invoke();");
+ "\"; }");
sw
.println("public NodeList<Element> runSelector(Node ctx) { return " +
- (m.getName() + (m.getParameters().length == 0 ? "()" : "(ctx)")) +
- ("NodeList".equals(m.getReturnType().getSimpleSourceName()) ? "" : ".get()") + ";}"
- ) ;
+ (m.getName() + (m.getParameters().length == 0 ? "()" : "(ctx)")) +
+ ("NodeList".equals(m.getReturnType().getSimpleSourceName()) ? "" : ".get()") + ";}"
+ );
sw.outdent();
sw.println("},");
}
} catch (XPathExpressionException e1) {
System.err.println("Invalid XPath generated selector, please revise it: " + xselector);
if (!selector.equals(xselector)) {
- System.err.println("If your css2 selector syntax is correct, open an issue in the gwtquery project. cssselector:"
- + selector + " xpath: " + xselector);
+ System.err
+ .println("If your css2 selector syntax is correct, open an issue in the gwtquery project. cssselector:"
+ + selector + " xpath: " + xselector);
}
throw new UnableToCompleteException();
}
protected static Pattern nthRe2 = Pattern.compile("\\D");
- protected static RuleMatcher[] matchers = new RuleMatcher[]{
+ protected static RuleMatcher[] matchers = new RuleMatcher[] {
new RuleMatcher("^\\.([a-zA-Z_0-9-]+)",
"n = byClassName(n, null, \"{0}\");"),
new RuleMatcher("^\\:([a-zA-Z_0-9-]+)(?:\\(((?:[^ >]*|.*?))\\))?",
sw.println("return " + wrap(method,
"impl.select(\"" + selector + "\", root)") + ";");
-// sw.println("JSArray n = JSArray.create();");
-// if(!hasContext) {
-// sw.println("Node root = Document.get();");
-// }
-//
-// // add root node as context.
-// // TODO: support any context
-// sw.println("n.addNode(root);");
-// String q = selector, lq = null;
-// Matcher lmode = modeRe.matcher(q);
-// Matcher mm = null;
-// String mode = "";
-// if (lmode.lookingAt() && notNull(lmode.group(1))) {
-// mode = lmode.group(1).replaceAll(trimReStr, "").trim();
-// q = q.replaceFirst("\\Q" + lmode.group(1) + "\\E", "");
-// }
-//
-// while (notNull(q) && !q.equals(lq)) {
-// debug("Doing q=" + q);
-//
-// lq = q;
-// Matcher tm = tagTokenRe.matcher(q);
-// if (tm.lookingAt()) {
-// if ("#".equals(tm.group(1))) {
-// sw.println("n = quickId(n, \"" + mode + "\", root, \"" + tm.group(2)
-// + "\");");
-// } else {
-// String tagName = tm.group(2);
-// tagName = "".equals(tagName) ? "*" : tagName;
-// // sw.println("if (n.size() == 0) { n=JSArray.create(); }");
-// String func = "";
-// if ("".equals(mode)) {
-// func = "getDescendentNodes";
-// } else if (">".equals(mode)) {
-// func = "getChildNodes";
-// } else if ("+".equals(mode)) {
-// func = "getSiblingNodes";
-// } else if ("~".equals(mode)) {
-// func = "getGeneralSiblingNodes";
-// } else {
-// treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
-// + mode + " not recognized in " + selector, null);
-// throw new UnableToCompleteException();
-// }
-// sw.println("n = " + func + "(n, \"" + tagName + "\");");
-// }
-// debug("replacing in q, the value " + tm.group(0));
-// q = q.replaceFirst("\\Q" + tm.group(0) + "\\E", "");
-// } else {
-// String func = "";
-// String tagName = "*";
-// if ("".equals(mode)) {
-// func = "getDescendentNodes";
-// } else if (">".equals(mode)) {
-// func = "getChildNodes";
-// } else if ("+".equals(mode)) {
-// func = "getSiblingNodes";
-// } else if ("~".equals(mode)) {
-// func = "getGeneralSiblingNodes";
-// } else {
-// treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
-// + mode + " not recognized in " + selector, null);
-// throw new UnableToCompleteException();
-// }
-// sw.println("n = " + func + "(n, \"" + tagName + "\");");
-// }
-//
-// while (!(mm = modeRe.matcher(q)).lookingAt()) {
-// debug("Looking at " + q);
-// boolean matched = false;
-// for (RuleMatcher rm : matchers) {
-// Matcher rmm = rm.re.matcher(q);
-// if (rmm.lookingAt()) {
-// String res[] = new String[rmm.groupCount()];
-// for (int i = 1; i <= rmm.groupCount(); i++) {
-// res[i - 1] = rmm.group(i);
-// debug("added param " + res[i - 1]);
-// }
-// Object[] r = res;
-// // inline enum, perhaps type-tightening will allow inlined eval()
-// // call
-// if (rm.fnTemplate.indexOf("byPseudo") != -1) {
-// sw.println("n = Pseudo."+res[0].toUpperCase().replace("-", "_") +
-// ".eval(n, \""+res[1]+"\");");
-// } else {
-// sw.println(MessageFormat.format(rm.fnTemplate, r));
-// }
-// q = q.replaceFirst("\\Q" + rmm.group(0) + "\\E", "");
-// matched = true;
-// break;
-// }
-// }
-// if (!matched) {
-// treeLogger
-// .log(TreeLogger.ERROR, "Error parsing selector at " + q, null);
-// throw new UnableToCompleteException();
-// }
-// }
-//
-// if (notNull(mm.group(1))) {
-// mode = mm.group(1).replaceAll(trimReStr, "");
-// debug("replacing q=" + q + " this part: " + mm.group(1));
-// q = q.replaceFirst("\\Q" + mm.group(1) + "\\E", "");
-// }
-// }
-// sw.println("return "+wrap(method, "nodup(n)")+";");
+ // sw.println("JSArray n = JSArray.create();");
+ // if(!hasContext) {
+ // sw.println("Node root = Document.get();");
+ // }
+ //
+ // // add root node as context.
+ // // TODO: support any context
+ // sw.println("n.addNode(root);");
+ // String q = selector, lq = null;
+ // Matcher lmode = modeRe.matcher(q);
+ // Matcher mm = null;
+ // String mode = "";
+ // if (lmode.lookingAt() && notNull(lmode.group(1))) {
+ // mode = lmode.group(1).replaceAll(trimReStr, "").trim();
+ // q = q.replaceFirst("\\Q" + lmode.group(1) + "\\E", "");
+ // }
+ //
+ // while (notNull(q) && !q.equals(lq)) {
+ // debug("Doing q=" + q);
+ //
+ // lq = q;
+ // Matcher tm = tagTokenRe.matcher(q);
+ // if (tm.lookingAt()) {
+ // if ("#".equals(tm.group(1))) {
+ // sw.println("n = quickId(n, \"" + mode + "\", root, \"" + tm.group(2)
+ // + "\");");
+ // } else {
+ // String tagName = tm.group(2);
+ // tagName = "".equals(tagName) ? "*" : tagName;
+ // // sw.println("if (n.size() == 0) { n=JSArray.create(); }");
+ // String func = "";
+ // if ("".equals(mode)) {
+ // func = "getDescendentNodes";
+ // } else if (">".equals(mode)) {
+ // func = "getChildNodes";
+ // } else if ("+".equals(mode)) {
+ // func = "getSiblingNodes";
+ // } else if ("~".equals(mode)) {
+ // func = "getGeneralSiblingNodes";
+ // } else {
+ // treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
+ // + mode + " not recognized in " + selector, null);
+ // throw new UnableToCompleteException();
+ // }
+ // sw.println("n = " + func + "(n, \"" + tagName + "\");");
+ // }
+ // debug("replacing in q, the value " + tm.group(0));
+ // q = q.replaceFirst("\\Q" + tm.group(0) + "\\E", "");
+ // } else {
+ // String func = "";
+ // String tagName = "*";
+ // if ("".equals(mode)) {
+ // func = "getDescendentNodes";
+ // } else if (">".equals(mode)) {
+ // func = "getChildNodes";
+ // } else if ("+".equals(mode)) {
+ // func = "getSiblingNodes";
+ // } else if ("~".equals(mode)) {
+ // func = "getGeneralSiblingNodes";
+ // } else {
+ // treeLogger.log(TreeLogger.ERROR, "Error parsing selector, combiner "
+ // + mode + " not recognized in " + selector, null);
+ // throw new UnableToCompleteException();
+ // }
+ // sw.println("n = " + func + "(n, \"" + tagName + "\");");
+ // }
+ //
+ // while (!(mm = modeRe.matcher(q)).lookingAt()) {
+ // debug("Looking at " + q);
+ // boolean matched = false;
+ // for (RuleMatcher rm : matchers) {
+ // Matcher rmm = rm.re.matcher(q);
+ // if (rmm.lookingAt()) {
+ // String res[] = new String[rmm.groupCount()];
+ // for (int i = 1; i <= rmm.groupCount(); i++) {
+ // res[i - 1] = rmm.group(i);
+ // debug("added param " + res[i - 1]);
+ // }
+ // Object[] r = res;
+ // // inline enum, perhaps type-tightening will allow inlined eval()
+ // // call
+ // if (rm.fnTemplate.indexOf("byPseudo") != -1) {
+ // sw.println("n = Pseudo."+res[0].toUpperCase().replace("-", "_") +
+ // ".eval(n, \""+res[1]+"\");");
+ // } else {
+ // sw.println(MessageFormat.format(rm.fnTemplate, r));
+ // }
+ // q = q.replaceFirst("\\Q" + rmm.group(0) + "\\E", "");
+ // matched = true;
+ // break;
+ // }
+ // }
+ // if (!matched) {
+ // treeLogger
+ // .log(TreeLogger.ERROR, "Error parsing selector at " + q, null);
+ // throw new UnableToCompleteException();
+ // }
+ // }
+ //
+ // if (notNull(mm.group(1))) {
+ // mode = mm.group(1).replaceAll(trimReStr, "");
+ // debug("replacing q=" + q + " this part: " + mm.group(1));
+ // q = q.replaceFirst("\\Q" + mm.group(1) + "\\E", "");
+ // }
+ // }
+ // sw.println("return "+wrap(method, "nodup(n)")+";");
}
protected String getImplSuffix() {
} else if (selector.contains("!=")) {
sw.println("return "
+ wrap(method, "querySelectorAll(\""
- + selector.replaceAll("(\\[\\w+)!(=[^\\]]+\\])", ":not($1$2)")
- + "\", root)") + ";");
+ + selector.replaceAll("(\\[\\w+)!(=[^\\]]+\\])", ":not($1$2)")
+ + "\", root)") + ";");
} else if (selector.matches(SelectorEngineNative.NATIVE_EXCEPTIONS_REGEXP)) {
super.generateMethodBody(sw, method, treeLogger, hasContext);
} else {
public String tagRelation;
}
- private static Pattern cssSelectorRegExp = Pattern.compile(
- "^(\\w+)?(#[a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+|(\\*))?((\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[a-zA-Z_0-9\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+|((\\w*\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[a-zA-Z_0-9\\-]*))\\))?)*)?(>|\\+|~)?");
+ private static Pattern cssSelectorRegExp =
+ Pattern
+ .compile(
+ "^(\\w+)?(#[a-zA-Z_0-9\u00C0-\uFFFF\\-\\_]+|(\\*))?((\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?((\\[\\w+(\\^|\\$|\\*|\\||~)?(=[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+)?\\]+)*)?(((:\\w+[a-zA-Z_0-9\\-]*)(\\((odd|even|\\-?\\d*n?((\\+|\\-)\\d+)?|[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+|((\\w*\\.[a-zA-Z_0-9\u00C0-\uFFFF\\-_]+)*)?|(\\[#?\\w+(\\^|\\$|\\*|\\||~)?=?[a-zA-Z_0-9\u00C0-\uFFFF\\s\\-\\_\\.]+\\]+)|(:\\w+[a-zA-Z_0-9\\-]*))\\))?)*)?(>|\\+|~)?");
private static Pattern selectorSplitRegExp = Pattern
.compile("(?:\\[[^\\[]*\\]|\\(.*\\)|[^\\s\\+>~\\[\\(])+|[\\+>~]");
private Sequence getSequence(String expression) {
int start = 0, add = 2, max = -1, modVal = -1;
- Pattern expressionRegExp = Pattern.compile(
- "^((odd|even)|([1-9]\\d*)|((([1-9]\\d*)?)n([\\+\\-]\\d+)?)|(\\-(([1-9]\\d*)?)n\\+(\\d+)))$");
+ Pattern expressionRegExp =
+ Pattern
+ .compile(
+ "^((odd|even)|([1-9]\\d*)|((([1-9]\\d*)?)n([\\+\\-]\\d+)?)|(\\-(([1-9]\\d*)?)n\\+(\\d+)))$");
Matcher pseudoValue = expressionRegExp.matcher(expression);
if (!pseudoValue.matches()) {
return null;
} else {
- if (notNull(pseudoValue.group(2))) { // odd or even
+ if (notNull(pseudoValue.group(2))) { // odd or even
start = ("odd".equals(pseudoValue.group(2))) ? 1 : 2;
modVal = (start == 1) ? 1 : 0;
- } else if (notNull(pseudoValue.group(3))) { // single digit
+ } else if (notNull(pseudoValue.group(3))) { // single digit
start = Integer.parseInt(pseudoValue.group(3), 10);
add = 0;
max = start;
- } else if (notNull(pseudoValue.group(4))) { // an+b
+ } else if (notNull(pseudoValue.group(4))) { // an+b
add = notNull(pseudoValue.group(6)) ? getInt(pseudoValue.group(6), 1)
: 1;
start = notNull(pseudoValue.group(7)) ? getInt(pseudoValue.group(7), 0)
}
modVal = (start > add) ? (start - add) % add
: ((start == add) ? 0 : start);
- } else if (notNull(pseudoValue.group(8))) { // -an+b
+ } else if (notNull(pseudoValue.group(8))) { // -an+b
add = notNull(pseudoValue.group(10)) ? Integer
.parseInt(pseudoValue.group(10), 10) : 1;
start = max = Integer.parseInt(pseudoValue.group(10), 10);
} else {
xpath = position + " mod " + sequence.add + " = " + sequence.modVal
+ ((sequence.start > 1) ? " and " + position + " >= "
- + sequence.start : "") + ((sequence.max > 0) ? " and "
- + position + " <= " + sequence.max : "");
+ + sequence.start : "") + ((sequence.max > 0) ? " and "
+ + position + " <= " + sequence.max : "");
}
}
}
if (sw != null) {
for (JMethod method : clazz.getInheritableMethods()) {
// skip method from JsonBuilder
- if(xmlBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null){
- continue;
+ if (xmlBuilderType.findMethod(method.getName(), method.getParameterTypes()) != null) {
+ continue;
}
generateMethod(sw, method, treeLogger);
}
} else if (isTypeAssignableTo(method.getReturnType(), xmlBuilderType)) {
String q = method.getReturnType().getQualifiedSourceName();
sw.println("Element e = getElementBase(\"" + name + "\");");
- sw.println("return e == null ? null : (" + q + ")((" + q + ")GWT.create(" + q + ".class)).load(e);");
- } else if (retType.equals(Properties.class.getName())){
+ sw.println("return e == null ? null : (" + q + ")((" + q + ")GWT.create(" + q
+ + ".class)).load(e);");
+ } else if (retType.equals(Properties.class.getName())) {
sw.println("return getPropertiesBase(\"" + name + "\");");
} else if (arr != null) {
String q = arr.getComponentType().getQualifiedSourceName();
- sw.println("ArrayList<" + q + "> l = new ArrayList<" + q+ ">();");
+ sw.println("ArrayList<" + q + "> l = new ArrayList<" + q + ">();");
sw.println("for (Element e: getElementsBase(\"" + name + "\")) {");
sw.println(" " + q + " c = GWT.create(" + q + ".class);");
sw.println(" c.load(e);");
} else {
sw.println("setBase(\"" + name + "\", a);");
}
- if (!"void".equals(retType)){
+ if (!"void".equals(retType)) {
if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) {
sw.println("return this;");
} else {
followRedirections = b;
}
- private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0";
+ private static final String USER_AGENT =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:26.0) Gecko/20100101 Firefox/26.0";
private final String jsonpCbRexp = "(?ms)^.*jre_callback\\((.*)\\).*$";
public Promise getJsonP(final Settings settings) {
}
return getXhr(settings, false)
- .then(new Function() {
- public Object f(Object... args) {
- Response response = arguments(0);
- if (response.getText().matches(jsonpCbRexp)) {
- return GQ.create(response.getText().replaceFirst(jsonpCbRexp, "$1"));
- } else {
- return GQuery.Deferred().reject().promise();
+ .then(new Function() {
+ public Object f(Object... args) {
+ Response response = arguments(0);
+ if (response.getText().matches(jsonpCbRexp)) {
+ return GQ.create(response.getText().replaceFirst(jsonpCbRexp, "$1"));
+ } else {
+ return GQuery.Deferred().reject().promise();
+ }
}
- }
- });
+ });
}
public Promise getLoadScript(Settings settings) {
int status = response.getStatusCode();
if (status <= 0 || status >= 400) {
String statusText = status <= 0 ? "Bad CORS" : response.getStatusText();
- dfd.reject(new RequestException("HTTP ERROR: " + status + " " + statusText + "\n" + response.getText()), null);
+ dfd.reject(new RequestException("HTTP ERROR: " + status + " " + statusText + "\n"
+ + response.getText()), null);
} else {
dfd.resolve(response, null);
}
c.setRequestMethod(s.getType());
c.setRequestProperty("User-Agent", USER_AGENT);
if (s.getUsername() != null && s.getPassword() != null) {
- c.setRequestProperty ("Authorization", "Basic " + Base64Utils.toBase64((s.getUsername() + ":" + s.getPassword()).getBytes()));
+ c.setRequestProperty("Authorization", "Basic "
+ + Base64Utils.toBase64((s.getUsername() + ":" + s.getPassword()).getBytes()));
}
if (cookieManager != null) {
cookieManager.setCookies(c);
*/
public class CookieManager {
- private Map<String,Map<String,Map<String, String>>> store = new HashMap<String, Map<String,Map<String, String>>>();
+ private Map<String, Map<String, Map<String, String>>> store =
+ new HashMap<String, Map<String, Map<String, String>>>();
private static final String SET_COOKIE = "Set-Cookie";
private static final String COOKIE_VALUE_DELIMITER = ";";
}
public void removeDomainCookie(String domain, String... cookies) {
- Map<String, Map<String, String>> domainStore = store.get(domain);
+ Map<String, Map<String, String>> domainStore = store.get(domain);
if (domainStore != null) {
- for (String cookie: cookies) {
+ for (String cookie : cookies) {
domainStore.remove(cookie);
}
}
public void setDomcainCookieProperty(String host, String name, String prop, String value) {
String domain = getDomainFromHost(host);
- Map<String, Map<String, String>> domainStore = store.get(domain);
+ Map<String, Map<String, String>> domainStore = store.get(domain);
if (domainStore == null) {
- domainStore = new HashMap<String, Map<String,String>>();
+ domainStore = new HashMap<String, Map<String, String>>();
store.put(domain, domainStore);
}
Map<String, String> cookie = domainStore.get(name);
// let's determine the domain from where these cookies are being sent
String domain = getDomainFromHost(conn.getURL().getHost());
- Map<String,Map<String, String>> domainStore; // this is where we will store cookies for this domain
+ Map<String, Map<String, String>> domainStore; // this is where we will store cookies for this domain
// now let's check the store to see if we have an entry for this domain
if (store.containsKey(domain)) {
domainStore = store.get(domain);
} else {
// we don't, so let's create it and put it in the store
- domainStore = new HashMap<String, Map<String,String>>();
+ domainStore = new HashMap<String, Map<String, String>>();
store.put(domain, domainStore);
}
while (st.hasMoreTokens()) {
String token = st.nextToken().toLowerCase();
int idx = token.indexOf(NAME_VALUE_SEPARATOR);
- if (idx > 0 && idx < token.length() -1) {
- cookie.put(token.substring(0, idx).toLowerCase(), token.substring(idx + 1, token.length()));
+ if (idx > 0 && idx < token.length() - 1) {
+ cookie.put(token.substring(0, idx).toLowerCase(), token.substring(idx + 1, token
+ .length()));
}
}
}
}
String path = url.getPath();
- Map<String, Map<String, String>> domainStore = store.get(domain);
+ Map<String, Map<String, String>> domainStore = store.get(domain);
if (domainStore == null)
return;
StringBuffer cookieStringBuffer = new StringBuffer();
* It uses java.util.reflect.Proxy to implement JsonBuilders
* and elemental light weight json to handle json data.
*/
-public class JsonFactoryJre implements JsonFactory {
+public class JsonFactoryJre implements JsonFactory {
static JsonFactoryJre jsonFactory = new JsonFactoryJre();
*/
static class JreJsonFunction extends JreJsonNull {
private final Function function;
+
public JreJsonFunction(Function f) {
function = f;
}
+
@Override
public String toJson() {
return function.toString();
}
+
public Function getFunction() {
return function;
}
}
public JsonBuilderHandler(JsonObject j) {
- jsonObject = j;
+ jsonObject = j;
}
public JsonBuilderHandler(String payload) throws Throwable {
@SuppressWarnings("unchecked")
private <T> Object jsonArrayToList(JsonArray j, Class<T> ctype, boolean isArray) {
List<T> l = new ArrayList<T>();
- for (int i = 0; j != null && i < j.length() ; i++) {
- l.add((T)getValue(j, i, null, null, ctype, null));
+ for (int i = 0; j != null && i < j.length(); i++) {
+ l.add((T) getValue(j, i, null, null, ctype, null));
}
- return l.isEmpty() ? null : isArray ? l.toArray((T[])Array.newInstance(ctype, l.size())) : l;
+ return l.isEmpty() ? null : isArray ? l.toArray((T[]) Array.newInstance(ctype, l.size())) : l;
}
private Double toDouble(String attr, JsonArray arr, int idx, JsonObject obj) {
}
}
- private Object getValue(JsonArray arr, int idx, JsonObject obj, String attr, Class<?> clz, Method method) {
- if (clz.equals(Boolean.class) || clz == Boolean.TYPE) {
+ private Object getValue(JsonArray arr, int idx, JsonObject obj, String attr, Class<?> clz,
+ Method method) {
+ if (clz.equals(Boolean.class) || clz == Boolean.TYPE) {
try {
- return obj != null ? obj.getBoolean(attr): arr.getBoolean(idx);
+ return obj != null ? obj.getBoolean(attr) : arr.getBoolean(idx);
} catch (Exception e) {
return Boolean.FALSE;
}
} else if (clz.equals(Date.class)) {
- return new Date((long)(obj != null ? obj.getNumber(attr): arr.getNumber(idx)));
+ return new Date((long) (obj != null ? obj.getNumber(attr) : arr.getNumber(idx)));
} else if (clz.equals(Byte.class) || clz == Byte.TYPE) {
return toDouble(attr, arr, idx, obj).byteValue();
} else if (clz.equals(Short.class) || clz == Short.TYPE) {
return toDouble(attr, arr, idx, obj).longValue();
}
- Object ret = obj != null ? obj.get(attr): arr.get(idx);
+ Object ret = obj != null ? obj.get(attr) : arr.get(idx);
if (ret instanceof JreJsonFunction || clz.equals(Function.class)) {
- return ret != null && ret instanceof JreJsonFunction ? ((JreJsonFunction)ret).getFunction() : null;
+ return ret != null && ret instanceof JreJsonFunction ? ((JreJsonFunction) ret)
+ .getFunction() : null;
} else if (ret instanceof JsonNull) {
return null;
} else if (ret instanceof JsonString) {
- return ((JsonString)ret).asString();
+ return ((JsonString) ret).asString();
} else if (ret instanceof JsonBoolean) {
- return ((JsonBoolean)ret).asBoolean();
+ return ((JsonBoolean) ret).asBoolean();
} else if (ret instanceof JsonNumber) {
return toDouble(attr, arr, idx, obj);
} else if (ret instanceof JsonArray || clz.isArray() || clz.equals(List.class)) {
} else {
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
- ctype = (Class<?>)((ParameterizedType) returnType).getActualTypeArguments()[0];
+ ctype = (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[0];
}
}
return jsonArrayToList(obj.getArray(attr), ctype, clz.isArray());
} else if (ret instanceof JsonObject) {
if (clz == Object.class) {
- return jsonFactory.createBinder((JsonObject)ret);
- } else if (IsProperties.class.isAssignableFrom(clz) && !clz.isAssignableFrom(ret.getClass())) {
- return jsonFactory.create(clz, (JsonObject)ret);
+ return jsonFactory.createBinder((JsonObject) ret);
+ } else if (IsProperties.class.isAssignableFrom(clz)
+ && !clz.isAssignableFrom(ret.getClass())) {
+ return jsonFactory.create(clz, (JsonObject) ret);
}
}
return ret;
}
- private <T> JsonArray listToJsonArray(Object...l) throws Throwable {
+ private <T> JsonArray listToJsonArray(Object... l) throws Throwable {
JsonArray ret = Json.createArray();
- for (Object o: l) {
+ for (Object o : l) {
setValue(ret, null, null, o);
}
return ret;
try {
Class<?> valClaz = JsonValue.class;
if (val instanceof Number) {
- val = ((Number)val).doubleValue();
+ val = ((Number) val).doubleValue();
valClaz = Double.TYPE;
} else if (val instanceof Boolean) {
valClaz = Boolean.TYPE;
} else if (val instanceof Date) {
- val = ((Date)val).getTime();
+ val = ((Date) val).getTime();
valClaz = Double.TYPE;
} else if (val instanceof String) {
valClaz = String.class;
} else if (val instanceof IsProperties) {
- val = ((IsProperties)val).getDataImpl();
+ val = ((IsProperties) val).getDataImpl();
} else if (val.getClass().isArray() || val instanceof List) {
- val = listToJsonArray(val.getClass().isArray() ? (Object[])val : ((List<?>)val).toArray());
+ val =
+ listToJsonArray(val.getClass().isArray() ? (Object[]) val : ((List<?>) val).toArray());
} else if (val instanceof Function) {
- val = new JreJsonFunction((Function)val);
+ val = new JreJsonFunction((Function) val);
}
if (jsObj != null) {
Method mth = jsObj.getClass().getMethod("put", String.class, valClaz);
- mth.invoke(jsObj, new Object[]{attr, val});
+ mth.invoke(jsObj, new Object[] {attr, val});
return jsObj;
} else {
Method mth = jsArr.getClass().getMethod("set", Integer.TYPE, valClaz);
- mth.invoke(jsArr, new Object[]{new Integer(jsArr.length()), val});
+ mth.invoke(jsArr, new Object[] {new Integer(jsArr.length()), val});
return jsArr;
}
} catch (Throwable e) {
return jsonObject.keys();
} else if ("as".equals(mname)) {
@SuppressWarnings("unchecked")
- Class<? extends JsonBuilder> clz = (Class<? extends JsonBuilder>)args[0];
+ Class<? extends JsonBuilder> clz = (Class<? extends JsonBuilder>) args[0];
return jsonFactory.create(clz, jsonObject);
} else if ("getJsonName".equals(mname)) {
return JsonBuilderGenerator.classNameToJsonName(getDataBindingClassName(proxy.getClass()));
} else if (mname.matches("toString")) {
return jsonObject.toString();
} else if (mname.matches("toJsonWithName")) {
- String jsonName = JsonBuilderGenerator.classNameToJsonName(getDataBindingClassName(proxy.getClass()));
- return "{\"" + jsonName + "\":"+ jsonObject.toString() + "}";
+ String jsonName =
+ JsonBuilderGenerator.classNameToJsonName(getDataBindingClassName(proxy.getClass()));
+ return "{\"" + jsonName + "\":" + jsonObject.toString() + "}";
} else if (mname.matches("toJson")) {
- return jsonObject.toString() ;
+ return jsonObject.toString();
} else if ("toQueryString".equals(mname)) {
return param(jsonObject);
} else if (largs == 1 && mname.equals("get")) {
ret += ret.isEmpty() ? "" : "&";
JsonValue v = o.get(k);
if (v instanceof JsonArray) {
- for (int i = 0, l = ((JsonArray)v).length(); i < l ; i++) {
+ for (int i = 0, l = ((JsonArray) v).length(); i < l; i++) {
ret += i > 0 ? "&" : "";
- JsonValue e = ((JsonArray)v).get(i);
+ JsonValue e = ((JsonArray) v).get(i);
ret += k + "[]=" + e.toJson();
}
} else {
public IsProperties createBinder() {
InvocationHandler handler = new JsonBuilderHandler();
- return (IsProperties)Proxy.newProxyInstance(IsProperties.class.getClassLoader(), new Class[] {IsProperties.class}, handler);
+ return (IsProperties) Proxy.newProxyInstance(IsProperties.class.getClassLoader(),
+ new Class[] {IsProperties.class}, handler);
}
public IsProperties createBinder(JsonObject jso) {
InvocationHandler handler = new JsonBuilderHandler(jso);
- return (IsProperties)Proxy.newProxyInstance(IsProperties.class.getClassLoader(), new Class[] {IsProperties.class}, handler);
+ return (IsProperties) Proxy.newProxyInstance(IsProperties.class.getClassLoader(),
+ new Class[] {IsProperties.class}, handler);
}
@Override
*/
public class ResponseJre extends Response {
private int status;
- private Map<String,List<String>> headers;
+ private Map<String, List<String>> headers;
private String responseText;
private String statusText;
- public ResponseJre(int status, String statusText, String text, Map<String,List<String>> headers) {
+ public ResponseJre(int status, String statusText, String text, Map<String, List<String>> headers) {
this.status = status;
this.headers = headers;
this.responseText = text;
public String getValue() {
return v;
}
+
public String getName() {
return s;
}
}
return ret;
}
+
public String getHeadersAsString() {
String ret = "";
for (Header h : getHeaders()) {
- ret += h.getName() + ":" + h.getValue() + "\n";
+ ret += h.getName() + ":" + h.getValue() + "\n";
}
return ret;
}
+
public int getStatusCode() {
return status;
}
+
public String getStatusText() {
return statusText;
}
+
public String getText() {
return responseText;
}
public void onConstraintViolation(Set<ConstraintViolation<?>> violations) {
dfd.reject(new ServerFailure("ConstraintViolation"), violations);
}
+
public void onFailure(ServerFailure error) {
dfd.reject(error);
}
+
public void onSuccess(Object response) {
responses.add(response);
// Resolve only when all requests have been received