Skip to content
This repository has been archived by the owner on Mar 30, 2020. It is now read-only.

Add inheritance support #5

Merged
merged 6 commits into from
Mar 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 28 additions & 32 deletions api/src/main/java/io/sweers/barber/Barber.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import android.util.Log;
import android.view.View;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

Expand All @@ -21,9 +19,9 @@ public class Barber {
public static final String ANDROID_PREFIX = "android.";
public static final String JAVA_PREFIX = "java.";
private static final String TAG = "Barber";
private static final Method NO_OP = null;
private static final IBarbershop<View> NO_OP = null;
private static boolean debug = false;
private static final Map<Class<?>, Method> BARBERSHOPS = new LinkedHashMap<>();
private static final Map<Class<?>, IBarbershop<View>> BARBERSHOPS = new LinkedHashMap<>();

public static void style(View target, AttributeSet set, int[] attrs) {
style(target, set, attrs, 0);
Expand All @@ -35,35 +33,26 @@ public static void style(View target, AttributeSet set, int[] attrs, int defStyl

public static void style(View target, AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
Class<?> targetClass = target.getClass();
try {
if (debug) {
Log.d(TAG, "Looking up barbershop for " + targetClass.getName());
}
Method style = findStyleMethodForClass(targetClass);
if (style != NO_OP) {
style.invoke(null, target, set, attrs, defStyleAttr, defStyleRes);
}
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
Throwable t = e;
if (t instanceof InvocationTargetException) {
t = t.getCause();
}
throw new RuntimeException("Unable to inject styleable value for " + target, t);
if (debug) {
Log.d(TAG, "Looking up barbershop for " + targetClass.getName());
}
IBarbershop<View> barbershop = findBarbershopForClass(targetClass);
if (barbershop != NO_OP) {
barbershop.style(target, set, attrs, defStyleAttr, defStyleRes);
}
}

/**
* Searches for the style() method given an instance of a generated class. Caches for efficiency.
* Searches for $$Barbershop class for the given instance, cached for efficiency.
*
* @param cls Instance of a *$$Barbershop instance
* @return style Method for the instance
* @throws NoSuchMethodException
* @param cls Source class to find a matching $$Barbershop class for
* @return $$Barbershop class instance
*/
private static Method findStyleMethodForClass(Class<?> cls) throws NoSuchMethodException {
Method style = BARBERSHOPS.get(cls);
if (style != null) {
if (debug) Log.d(TAG, "HIT: Cached in shop map.");
return style;
private static IBarbershop<View> findBarbershopForClass(Class<?> cls) {
IBarbershop<View> barbershop = BARBERSHOPS.get(cls);
if (barbershop != null) {
if (debug) Log.d(TAG, "HIT: Cached in barbershop map.");
return barbershop;
}
String clsName = cls.getName();
if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) {
Expand All @@ -73,19 +62,26 @@ private static Method findStyleMethodForClass(Class<?> cls) throws NoSuchMethodE
return NO_OP;
}
try {
Class<?> barbershop = Class.forName(clsName + SUFFIX);
style = barbershop.getMethod("style", cls, AttributeSet.class, int[].class, int.class, int.class);
Class<?> barbershopClass = Class.forName(clsName + SUFFIX);
//noinspection unchecked
barbershop = (IBarbershop<View>) barbershopClass.newInstance();
if (debug) {
Log.d(TAG, "HIT: Class loaded barbershop class.");
}
} catch (ClassNotFoundException e) {
if (debug) {
Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
}
style = findStyleMethodForClass(cls.getSuperclass());
barbershop = findBarbershopForClass(cls.getSuperclass());
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
BARBERSHOPS.put(cls, style);
return style;
BARBERSHOPS.put(cls, barbershop);
return barbershop;
}

/** DO NOT USE. Exposed for generated classes' use. */
public interface IBarbershop<T> {
public void style(final T target, final AttributeSet set, final int[] attrs, final int defStyleAttr, final int defStyleRes);
}
}
193 changes: 193 additions & 0 deletions api/src/main/java/io/sweers/barber/WeakHashSet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package io.sweers.barber;

/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* glassfish/bootstrap/legal/CDDLv1.0.txt or
* https://glassfish.dev.java.net/public/CDDLv1.0.html.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/

/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Iterator;

/**
* A weak HashSet. An element stored in the WeakHashSet might be
* garbage collected, if there is no strong reference to this element.
*/

public class WeakHashSet extends HashSet {
/**
* Helps to detect garbage collected values.
*/
ReferenceQueue queue = new ReferenceQueue();

/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set.
*/
public Iterator iterator() {
// remove garbage collected elements
processQueue();

// get an iterator of the superclass WeakHashSet
final Iterator i = super.iterator();

return new Iterator() {
public boolean hasNext() {
return i.hasNext();
}

public Object next() {
// unwrap the element
return getReferenceObject((WeakReference) i.next());
}

public void remove() {
// remove the element from the HashSet
i.remove();
}
};
}

/**
* Returns <code>true</code> if this set contains the specified element.
*
* @param o element whose presence in this set is to be tested.
* @return <code>true</code> if this set contains the specified element.
*/
public boolean contains(Object o) {
return super.contains(WeakElement.create(o));
}

/**
* Adds the specified element to this set if it is not already
* present.
*
* @param o element to be added to this set.
* @return <code>true</code> if the set did not already contain the specified
* element.
*/
public boolean add(Object o) {
processQueue();
return super.add(WeakElement.create(o, this.queue));
}

/**
* Removes the given element from this set if it is present.
*
* @param o object to be removed from this set, if present.
* @return <code>true</code> if the set contained the specified element.
*/
public boolean remove(Object o) {
boolean ret = super.remove(WeakElement.create(o));
processQueue();
return ret;
}

/**
* A convenience method to return the object held by the
* weak reference or <code>null</code> if it does not exist.
*/
private Object getReferenceObject(WeakReference ref) {
return (ref == null) ? null : ref.get();
}

/**
* Removes all garbage collected values with their keys from the map.
* Since we don't know how much the ReferenceQueue.poll() operation
* costs, we should call it only in the add() method.
*/
private void processQueue() {
WeakElement wv = null;

while ((wv = (WeakElement) this.queue.poll()) != null) {
super.remove(wv);
}
}

/**
* A WeakHashSet stores objects of class WeakElement.
* A WeakElement wraps the element that should be stored in the WeakHashSet.
* WeakElement inherits from java.lang.ref.WeakReference.
* It redefines equals and hashCode which delegate to the corresponding methods
* of the wrapped element.
*/
static private class WeakElement extends WeakReference {
private int hash; /* Hashcode of key, stored here since the key
may be tossed by the GC */

private WeakElement(Object o) {
super(o);
hash = o.hashCode();
}

private WeakElement(Object o, ReferenceQueue q) {
super(o, q);
hash = o.hashCode();
}

private static WeakElement create(Object o) {
return (o == null) ? null : new WeakElement(o);
}

private static WeakElement create(Object o, ReferenceQueue q) {
return (o == null) ? null : new WeakElement(o, q);
}

/* A WeakElement is equal to another WeakElement iff they both refer to objects
that are, in turn, equal according to their own equals methods */
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof WeakElement))
return false;
Object t = this.get();
Object u = ((WeakElement) o).get();
if (t == u)
return true;
if ((t == null) || (u == null))
return false;
return t.equals(u);
}

public int hashCode() {
return hash;
}
}

}
35 changes: 33 additions & 2 deletions compiler/src/main/java/io/sweers/barber/BarberProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

Expand All @@ -18,6 +19,9 @@
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
Expand Down Expand Up @@ -56,6 +60,7 @@ public synchronized void init(ProcessingEnvironment processingEnv) {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Map<TypeElement, Barbershop> targetClassMap = new LinkedHashMap<>();
Set<String> erasedTargetNames = new LinkedHashSet<>();

for (Element element : roundEnv.getElementsAnnotatedWith(StyledAttr.class)) {
try {
Expand All @@ -64,13 +69,20 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
return false;
}
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
Barbershop barbershop = getOrCreateBarber(targetClassMap, enclosingElement);
Barbershop barbershop = getOrCreateBarber(targetClassMap, enclosingElement, erasedTargetNames);
barbershop.createAndAddBinding(element);
} catch (Exception e) {
error(element, "%s", e.getMessage());
}
}

for (Map.Entry<TypeElement, Barbershop> entry : targetClassMap.entrySet()) {
String parentClassFqcn = findParentFqcn(entry.getKey(), erasedTargetNames);
if (parentClassFqcn != null) {
entry.getValue().setParentBarbershop(parentClassFqcn + Barber.SUFFIX);
}
}

for (Barbershop barbershop : targetClassMap.values()) {
try {
barbershop.writeToFiler(filer);
Expand All @@ -82,19 +94,38 @@ public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
return true;
}

private Barbershop getOrCreateBarber(Map<TypeElement, Barbershop> targetClassMap, TypeElement enclosingElement) {
private Barbershop getOrCreateBarber(Map<TypeElement, Barbershop> targetClassMap, TypeElement enclosingElement, Set<String> erasedTargetNames) {
Barbershop barbershop = targetClassMap.get(enclosingElement);
if (barbershop == null) {
String targetType = enclosingElement.getQualifiedName().toString();
String classPackage = getPackageName(enclosingElement);
String className = getClassName(enclosingElement, classPackage) + Barber.SUFFIX;
barbershop = new Barbershop(classPackage, className, targetType);
targetClassMap.put(enclosingElement, barbershop);
erasedTargetNames.add(enclosingElement.toString());
}

return barbershop;
}

/**
* Finds the parent barbershop type in the supplied set, if any.
*/
private String findParentFqcn(TypeElement typeElement, Set<String> parents) {
TypeMirror type;
while (true) {
type = typeElement.getSuperclass();
if (type.getKind() == TypeKind.NONE) {
return null;
}
typeElement = (TypeElement) ((DeclaredType) type).asElement();
if (parents.contains(typeElement.toString())) {
String packageName = getPackageName(typeElement);
return packageName + "." + getClassName(typeElement, packageName);
}
}
}

private void error(Element e, String msg, Object... args) {
messager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e);
}
Expand Down
Loading