diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f6dff7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +# built application files +*.apk +*.ap_ + +# files for the dex VM +*.dex + +# Java class files +*.class + +# generated files +bin/ +gen/ + + +# Local configuration file (sdk path, etc) +local.properties +/local.properties + +# Eclipse +.classpath +.project +.settings + +# Android Studio (InteliJ) +.idea/ +/.idea/workspace.xml +*.iml +*.iws +*.ipr +/*/out +/*/build +/*/*/production + +#Gradle +.gradletasknamecache +.gradle/ +build/ +bin/ + +#Crashlytics +com_crashlytics_export_strings.xml + +#OSx +.DS_Store + +#other +Notes \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7e2b03f --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +Decor +====== + +Decor is a library that enables to decor android layout with additional attributes +without the need to extend and create a cutom view for each functionnality that can't be +added through xml this avoid having classes like AutofitTextViewWithFont + +Decor plugs into Android layout inflation and applies custom attributes to views. +this library was inspired by and used as a starting point Pretty. + +A submodule decorators contains some examples of useful decorators that you can start using now +(take a look at the samples for how to use it) , more of them will be added soon. + + +THIS IS CURRENTLY A WORK IN PROGRESS. + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..03afd4c --- /dev/null +++ b/build.gradle @@ -0,0 +1,29 @@ +task wrapper(type: Wrapper) { + gradleVersion '2.3' +} + +buildscript { + repositories { + jcenter() + mavenCentral() + maven { + url 'https://oss.sonatype.org/content/repositories/snapshots' + } + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.0-beta2' + } +} + +allprojects { + repositories { + mavenCentral() + } + // Is Release Build? + ext.isReleaseVersion = has("release") + ext.versionCodeInt = getProperty('VERSION_CODE').toInteger() + version = VERSION_NAME +} + + + diff --git a/decor/.gitignore b/decor/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/decor/.gitignore @@ -0,0 +1 @@ +/build diff --git a/decor/build.gradle b/decor/build.gradle new file mode 100644 index 0000000..b647a84 --- /dev/null +++ b/decor/build.gradle @@ -0,0 +1,29 @@ +apply plugin: 'com.android.library' + +android { + + compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) + buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION + + defaultConfig { + minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) + targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) + versionName project.VERSION_NAME + versionCode Integer.parseInt(project.VERSION_CODE) + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile "com.android.support:appcompat-v7:${project.ANDROID_SUPPORT_VERSION}" + //compile "com.android.support:support-annotations:${project.ANDROID_SUPPORT_VERSION}" +} + +apply from: '../deploy.gradle' diff --git a/decor/gradle.properties b/decor/gradle.properties new file mode 100644 index 0000000..a2ccdf8 --- /dev/null +++ b/decor/gradle.properties @@ -0,0 +1,6 @@ +# SubProject Library Gradle Properties +# See parent properties for global properties + +POM_NAME=Decor +POM_ARTIFACT_ID=decor +POM_PACKAGING=aar \ No newline at end of file diff --git a/decor/proguard-rules.pro b/decor/proguard-rules.pro new file mode 100644 index 0000000..ffb7f18 --- /dev/null +++ b/decor/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/cheikhna/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/decor/src/androidTest/java/mona/android/decor/ApplicationTest.java b/decor/src/androidTest/java/mona/android/decor/ApplicationTest.java new file mode 100644 index 0000000..8cd861b --- /dev/null +++ b/decor/src/androidTest/java/mona/android/decor/ApplicationTest.java @@ -0,0 +1,13 @@ +package mona.android.decor; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/decor/src/main/AndroidManifest.xml b/decor/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3cc6f58 --- /dev/null +++ b/decor/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + + diff --git a/decor/src/main/java/mona/android/decor/AttrsDecorator.java b/decor/src/main/java/mona/android/decor/AttrsDecorator.java new file mode 100644 index 0000000..9e1642b --- /dev/null +++ b/decor/src/main/java/mona/android/decor/AttrsDecorator.java @@ -0,0 +1,99 @@ +package mona.android.decor; + +import android.content.Context; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.util.SparseArray; +import android.util.TypedValue; +import android.view.View; + +/** + * A base class for a decorator that transform certain View subtypes with certain attributes. Useful + * when you want to extend standard layout inflation to add your own attributes to system widgets. + * If a view with type {@code View<? extends T>} is inflated and it has one of the attributes + * returned by the {@link AttrsDecorator#attrs()} method then {@link AttrsDecorator#apply(View, SparseArray)} + * will be invoked for that view. + * @param The type or parent type of View that this decorator applies to. + */ +public abstract class AttrsDecorator implements Decorator { + + @Override + public final void apply(View view, View parent, String name, Context context, AttributeSet attrs) { + if (!clazz().isAssignableFrom(view.getClass())) { + return; + } + + TypedArray values = context.getResources().obtainAttributes(attrs, attrs()); + if (values == null) { + return; + } + + SparseArray typedValues = new SparseArray<>(); + try { + for (int i = 0; i < values.length(); i++) { + TypedValue buf = new TypedValue(); + if (values.hasValue(i) && values.getValue(i, buf)) { + typedValues.put(attrs()[i], new TypedValueInfo(buf, values, i)); + } + } + if(typedValues.size() > 0) { + // inspection disabled as we do know at this point that view can be cast to T + //noinspection unchecked + //TODO : find a better representation to be passed here than duplicating + // index and parent on each value per attribute + apply((T) view, typedValues); + } + } finally { + values.recycle(); + } + } + + /** + * Attributes supported by this decorator. + * + * @return a non-null array of android attr resource ids. + */ + + protected abstract int[] attrs(); + + /** + * The class for the given viewtype. Please be kind and just return the right class here :) + * + * @return The class/typetoken for T + */ + + protected abstract Class clazz(); + + /** + * This method will be called if a View of type T was inflated and it had one of the attributes + * specified by {@link AttrsDecorator#attrs()} set. + * @param view The view object that is being decorated. + * @param values An array of {@link TypedValueInfo} for each attribute. + * + */ + protected abstract void apply(T view, SparseArray values); + + public static class TypedValueInfo { + private TypedValue typedValue; + private TypedArray parentArray; + private int indexInValues; + + public TypedValueInfo(TypedValue typedValue, TypedArray parentArray, int indexInValues) { + this.typedValue = typedValue; + this.parentArray = parentArray; + this.indexInValues = indexInValues; + } + + public TypedValue getTypedValue() { + return typedValue; + } + + public TypedArray getParentArray() { + return parentArray; + } + + public int getIndexInValues() { + return indexInValues; + } + } +} \ No newline at end of file diff --git a/decor/src/main/java/mona/android/decor/DecorActivityFactory.java b/decor/src/main/java/mona/android/decor/DecorActivityFactory.java new file mode 100644 index 0000000..7a2ac8b --- /dev/null +++ b/decor/src/main/java/mona/android/decor/DecorActivityFactory.java @@ -0,0 +1,33 @@ +package mona.android.decor; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; + +/** + * Created by cheikhna on 07/04/2015. + */ +public interface DecorActivityFactory { + + /** + * Used to Wrap the Activity onCreateView method. + * + * You implement this method like so in you base activity. + *
+     * {@code
+     * public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
+     *   return CalligraphyContextWrapper.get(getBaseContext()).onActivityCreateView(super.onCreateView(parent, name, context, attrs), attrs);
+     * }
+     * }
+     * 
+ * + * @param parent parent view, can be null. + * @param view result of {@code super.onCreateView(parent, name, context, attrs)}, this might be null, which is fine. + * @param name Name of View we are trying to inflate + * @param context current context (normally the Activity's) + * @param attrs see {@link android.view.LayoutInflater.Factory2#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)} @return the result from the activities {@code onCreateView()} + * @return The view passed in, or null if nothing was passed in. + * @see android.view.LayoutInflater.Factory2 + */ + View onActivityCreateView(View parent, View view, String name, Context context, AttributeSet attrs); +} diff --git a/decor/src/main/java/mona/android/decor/DecorContextWrapper.java b/decor/src/main/java/mona/android/decor/DecorContextWrapper.java new file mode 100644 index 0000000..a4b87e5 --- /dev/null +++ b/decor/src/main/java/mona/android/decor/DecorContextWrapper.java @@ -0,0 +1,53 @@ +package mona.android.decor; + +import android.content.Context; +import android.content.ContextWrapper; +import android.view.LayoutInflater; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by cheikhna on 05/04/2015. + */ +public class DecorContextWrapper extends ContextWrapper { + + private DecorLayoutInflater mInflater; + private List mDecorators; + + /** + * @param base ContextBase to Wrap. + */ + public DecorContextWrapper(Context base) { + super(base); + mDecorators = new ArrayList<>(); + } + + /** + * wrap the context + * @param base ContextBase to Wrap. + * @return ContextWrapper to pass back to the activity. + */ + public static DecorContextWrapper wrap(Context base) { + return new DecorContextWrapper(base); + } + + public ContextWrapper with(Decorator... decorators) { + Collections.addAll(mDecorators, decorators); + return this; + } + + @Override + public Object getSystemService(String name) { + + if(LAYOUT_INFLATER_SERVICE.equals(name)) { + if(mInflater == null) { + mInflater = new DecorLayoutInflater(LayoutInflater.from(getBaseContext()), this, mDecorators); + } + return mInflater; + } + return super.getSystemService(name); + } + +} diff --git a/decor/src/main/java/mona/android/decor/DecorFactory.java b/decor/src/main/java/mona/android/decor/DecorFactory.java new file mode 100644 index 0000000..ab86f4d --- /dev/null +++ b/decor/src/main/java/mona/android/decor/DecorFactory.java @@ -0,0 +1,35 @@ +package mona.android.decor; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; + +import java.util.Collection; + +/** + * Created by cheikhna on 05/04/2015. + */ +public class DecorFactory { + + private final Collection decorators; + + public DecorFactory(Collection decorators) { + this.decorators = decorators; + } + + public View onViewCreated(View view, String name, View parent, Context context, AttributeSet attrs) { + if (view == null) { + return null; + } + for (Decorator d : decorators) { + d.apply(view, parent, name, context, attrs); + } + return view; + } + + public View onViewCreated(View view, Context context, AttributeSet attrs) { + //TODO: implement + return view; + } + +} diff --git a/decor/src/main/java/mona/android/decor/DecorLayoutInflater.java b/decor/src/main/java/mona/android/decor/DecorLayoutInflater.java new file mode 100644 index 0000000..2818493 --- /dev/null +++ b/decor/src/main/java/mona/android/decor/DecorLayoutInflater.java @@ -0,0 +1,296 @@ +package mona.android.decor; + +import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import java.lang.reflect.Method; +import java.util.Collection; + +/** + * Created by cheikhna on 05/04/2015. + */ +public class DecorLayoutInflater extends LayoutInflater implements DecorActivityFactory { + //TODO: If DecorActivityFactory is not realy needed delete it + + private static final String[] CLASS_PREFIX_LIST = { + "android.widget.", + "android.webkit." + }; + + private final DecorFactory mDecorFactory; + private Collection mDecorators; + private boolean mSetPrivateFactory = false; + + public DecorLayoutInflater(LayoutInflater original, Context newContext, Collection decorators) { + super(original, newContext); + mDecorators = decorators; + mDecorFactory = new DecorFactory(mDecorators); + initLayoutFactories(); + } + + @Override + public LayoutInflater cloneInContext(Context newContext) { + return new DecorLayoutInflater(this, newContext, mDecorators); + } + + + private void initLayoutFactories() { + // If we are HC+ we get and set Factory2 otherwise we just wrap Factory1 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + if (getFactory2() != null && !(getFactory2() instanceof WrapperFactory2)) { + // Sets both Factory/Factory2 + setFactory2(getFactory2()); + } + } + // We can do this as setFactory2 is used for both methods. + if (getFactory() != null && !(getFactory() instanceof WrapperFactory)) { + setFactory(getFactory()); + } + } + + @Override + public View inflate(int resource, ViewGroup root, boolean attachToRoot) { + setPrivateFactoryInternal(); + return super.inflate(resource, root, attachToRoot); + } + + private void setPrivateFactoryInternal() { + // Already tried to set the factory. + if (mSetPrivateFactory) return; + //if (!hasReflection()) return; + // Skip if not attached to an activity. + if (!(getContext() instanceof Factory2)) { + mSetPrivateFactory = true; + return; + } + + final Method setPrivateFactoryMethod = ReflectionUtils + .getMethod(LayoutInflater.class, "setPrivateFactory"); + + if (setPrivateFactoryMethod != null) { + ReflectionUtils.invokeMethod(this, + setPrivateFactoryMethod, + new PrivateWrapperFactory2((Factory2) getContext(), this, mDecorFactory)); + } + mSetPrivateFactory = true; + } + + //TODO: understand this + + @Override + public void setFactory(Factory factory) { + // Only set our factory and wrap calls to the Factory trying to be set! + if (!(factory instanceof WrapperFactory)) { + super.setFactory(new WrapperFactory(factory, this, mDecorFactory)); + } else { + super.setFactory(factory); + } + } + + //TODO: understand this + + @Override + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public void setFactory2(Factory2 factory2) { + // Only set our factory and wrap calls to the Factory2 trying to be set! + if (!(factory2 instanceof WrapperFactory2)) { + super.setFactory2(new WrapperFactory2(factory2, mDecorFactory)); + } else { + super.setFactory2(factory2); + } + } + + /** + * The LayoutInflater onCreateView is the fourth port of call for LayoutInflation. + * BUT only for none CustomViews. + */ + + @Override + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException { + return mDecorFactory.onViewCreated( + super.onCreateView(parent, name, attrs), name, parent, getContext(), attrs); + } + + /** + * The LayoutInflater onCreateView is the fourth port of call for LayoutInflation. + * BUT only for none CustomViews. + * Basically if this method doesn't inflate the View nothing probably will. + */ + + @Override + protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { + // This mimics the {@code PhoneLayoutInflater} in the way it tries to inflate the base + // classes, if this fails its pretty certain the app will fail at this point. + View view = null; + for (String prefix : CLASS_PREFIX_LIST) { + try { + view = createView(name, prefix, attrs); + } catch (ClassNotFoundException ignored) { + } + } + // In this case we want to let the base class take a crack + // at it. + if (view == null) view = super.onCreateView(name, attrs); + + return mDecorFactory.onViewCreated(view, name, null, view.getContext(), attrs); + } + + @Override + public View onActivityCreateView(View parent, View view, String name, Context context, AttributeSet attrs) { + return mDecorFactory.onViewCreated(createCustomViewInternal(parent, view, name, context, attrs), context, attrs); + } + + + /** + * Wrapped factories for Pre and Post HC + */ + + /** + * Factory 1 is the first port of call for LayoutInflation + */ + private static class WrapperFactory implements Factory { + + private final Factory mFactory; + private final DecorLayoutInflater mInflater; + private final DecorFactory mDecorFactory; + + public WrapperFactory(Factory factory, DecorLayoutInflater inflater, DecorFactory decorFactory) { + this.mFactory = factory; + this.mInflater = inflater; + this.mDecorFactory = decorFactory; + } + + @Override + public View onCreateView(String name, Context context, AttributeSet attrs) { + //TODO: handle this commented case (cf. calligraphy) + /*if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { + return mDecorFactory.onViewCreated( + mInflater.createCustomViewInternal( + null, mFactory.onCreateView(name, context, attrs), name, context, attrs + ), + context, attrs + ); + }*/ + return mDecorFactory.onViewCreated( + mFactory.onCreateView(name, context, attrs), + name, null, context, attrs + ); + } + } + + + /** + * Factory 2 is the second port of call for LayoutInflation + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private static class WrapperFactory2 implements Factory2 { + protected final Factory2 mFactory2; + protected final DecorFactory mDecorFactory; + + public WrapperFactory2(Factory2 mFactory2, DecorFactory mDecorFactory) { + this.mFactory2 = mFactory2; + this.mDecorFactory = mDecorFactory; + } + + + @Override + public View onCreateView(String name, Context context, AttributeSet attrs) { + return mDecorFactory.onViewCreated( + mFactory2.onCreateView(name, context, attrs), + name, null, context, attrs); + } + + + @Override + public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { + return mDecorFactory.onViewCreated( + mFactory2.onCreateView(parent, name, context, attrs), + name, parent, context, attrs); + } + } + + /** + * Private factory is step three for Activity Inflation, this is what is attached to the + * Activity on HC+ devices. + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private static class PrivateWrapperFactory2 extends WrapperFactory2 { + + private final DecorLayoutInflater mInflater; + + public PrivateWrapperFactory2(Factory2 factory2, DecorLayoutInflater inflater, DecorFactory calligraphyFactory) { + super(factory2, calligraphyFactory); + mInflater = inflater; + } + + @Override + public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { + return mDecorFactory.onViewCreated( + mInflater.createCustomViewInternal(parent, + mFactory2.onCreateView(parent, name, context, attrs), + name, context, attrs + ), + name, parent, context, attrs + ); + } + } + + + //TODO: understand this and why we need it + /** + * Nasty method to inflate custom layouts that haven't been handled else where. If this fails it + * will fall back through to the PhoneLayoutInflater method of inflating custom views where + * Calligraphy will NOT have a hook into. + * + * @param parent parent view + * @param view view if it has been inflated by this point, if this is not null this method + * just returns this value. + * @param name name of the thing to inflate. + * @param viewContext Context to inflate by if parent is null + * @param attrs Attr for this view which we can steal fontPath from too. + * @return view or the View we inflate in here. + */ + private View createCustomViewInternal(View parent, View view, String name, Context viewContext, AttributeSet attrs) { + // I by no means advise anyone to do this normally, but Google have locked down access to + // the createView() method, so we never get a callback with attributes at the end of the + // createViewFromTag chain (which would solve all this unnecessary rubbish). + // We at the very least try to optimise this as much as possible. + // We only call for customViews (As they are the ones that never go through onCreateView(...)). + // We also maintain the Field reference and make it accessible which will make a pretty + // significant difference to performance on Android 4.0+. + + // If CustomViewCreation is off skip this. + //TODO: have a DecorConfig that activate either all decors or only needed one + possibility deactivate customViewCreate + //if (!DecorConfig.get().isCustomViewCreation()) return view; + + //TODO: uncomment this implementation + /* if (view == null && name.indexOf('.') > -1) { + if (mConstructorArgs == null) + mConstructorArgs = ReflectionUtils.getField(LayoutInflater.class, "mConstructorArgs"); + + final Object[] mConstructorArgsArr = (Object[]) ReflectionUtils.getValue(mConstructorArgs, this); + final Object lastContext = mConstructorArgsArr[0]; + // The LayoutInflater actually finds out the correct context to use. We just need to set + // it on the mConstructor for the internal method. + // Set the constructor ars up for the createView, not sure why we can't pass these in. + mConstructorArgsArr[0] = viewContext; + ReflectionUtils.setValue(mConstructorArgs, this, mConstructorArgsArr); + try { + view = createView(name, null, attrs); + } catch (ClassNotFoundException ignored) { + } finally { + mConstructorArgsArr[0] = lastContext; + ReflectionUtils.setValue(mConstructorArgs, this, mConstructorArgsArr); + } + }*/ + return view; + } + + +} diff --git a/decor/src/main/java/mona/android/decor/Decorator.java b/decor/src/main/java/mona/android/decor/Decorator.java new file mode 100644 index 0000000..04cd56c --- /dev/null +++ b/decor/src/main/java/mona/android/decor/Decorator.java @@ -0,0 +1,23 @@ +package mona.android.decor; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; + + +/** + * A class that operates on already constructed views, i.e., decorates them. + */ +public interface Decorator { + /** + * Decorates the given view. + * This method will be called by Decor for every {@link View} created in the layout + * @param view The view to decorate. Never null. + * @param parent The parent view, if available. May be null. + * @param name The name of the tag in the layout file, e.g. {@code TextView}. + * @param context The context where the view was constructed in. + * @param attrs A read-only set of tag attributes. + */ + public void apply( View view, View parent, String name, Context context, AttributeSet attrs); + +} diff --git a/decor/src/main/java/mona/android/decor/ReflectionUtils.java b/decor/src/main/java/mona/android/decor/ReflectionUtils.java new file mode 100644 index 0000000..a6537c2 --- /dev/null +++ b/decor/src/main/java/mona/android/decor/ReflectionUtils.java @@ -0,0 +1,57 @@ +package mona.android.decor; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Created by chris on 17/12/14. + * For Calligraphy. + */ +class ReflectionUtils { + + static Field getField(Class clazz, String fieldName) { + try { + final Field f = clazz.getDeclaredField(fieldName); + f.setAccessible(true); + return f; + } catch (NoSuchFieldException ignored) { + } + return null; + } + + static Object getValue(Field field, Object obj) { + try { + return field.get(obj); + } catch (IllegalAccessException ignored) { + } + return null; + } + + static void setValue(Field field, Object obj, Object value) { + try { + field.set(obj, value); + } catch (IllegalAccessException ignored) { + } + } + + static Method getMethod(Class clazz, String methodName) { + final Method[] methods = clazz.getMethods(); + for (Method method : methods) { + if (method.getName().equals(methodName)) { + method.setAccessible(true); + return method; + } + } + return null; + } + + static void invokeMethod(Object object, Method method, Object... args) { + try { + if (method == null) return; + method.invoke(object, args); + } catch (IllegalAccessException | InvocationTargetException ignored) { + ignored.printStackTrace(); + } + } +} diff --git a/decor/src/main/res/values/strings.xml b/decor/src/main/res/values/strings.xml new file mode 100644 index 0000000..e51c2b2 --- /dev/null +++ b/decor/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + Decor + "M141,17 A9,9 0 1,1 142,16 L149,23" + diff --git a/decorators/.gitignore b/decorators/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/decorators/.gitignore @@ -0,0 +1 @@ +/build diff --git a/decorators/build.gradle b/decorators/build.gradle new file mode 100644 index 0000000..5dae2bb --- /dev/null +++ b/decorators/build.gradle @@ -0,0 +1,33 @@ +apply plugin: 'com.android.library' + +android { + + compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) + buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION + + defaultConfig { + minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) + targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) + versionName project.VERSION_NAME + versionCode Integer.parseInt(project.VERSION_CODE) + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + + +repositories { + mavenCentral() +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile(project(':decor')) + compile "com.android.support:appcompat-v7:${project.ANDROID_SUPPORT_VERSION}" + compile "com.android.support:palette-v7:${project.ANDROID_SUPPORT_VERSION}" + compile "com.android.support:support-v4:${project.ANDROID_SUPPORT_VERSION}@aar" +} diff --git a/decorators/proguard-rules.pro b/decorators/proguard-rules.pro new file mode 100644 index 0000000..ffb7f18 --- /dev/null +++ b/decorators/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/cheikhna/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/decorators/src/androidTest/java/mona/android/decorators/ApplicationTest.java b/decorators/src/androidTest/java/mona/android/decorators/ApplicationTest.java new file mode 100644 index 0000000..9e444cb --- /dev/null +++ b/decorators/src/androidTest/java/mona/android/decorators/ApplicationTest.java @@ -0,0 +1,13 @@ +package mona.android.decorators; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/decorators/src/main/AndroidManifest.xml b/decorators/src/main/AndroidManifest.xml new file mode 100644 index 0000000..56c8cec --- /dev/null +++ b/decorators/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + + diff --git a/decorators/src/main/java/mona/android/decorators/AutofitDecorator.java b/decorators/src/main/java/mona/android/decorators/AutofitDecorator.java new file mode 100644 index 0000000..ee0e1d7 --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/AutofitDecorator.java @@ -0,0 +1,268 @@ +package mona.android.decorators; + +/** + * Created by cheikhna on 09/04/2015. + */ + +import android.content.Context; +import android.content.res.Resources; +import android.support.annotation.NonNull; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextPaint; +import android.util.DisplayMetrics; +import android.util.Log; +import android.util.SparseArray; +import android.util.TypedValue; +import android.widget.TextView; + +import mona.android.decor.AttrsDecorator; + +/** + * A decorator for a TextView to resize it's text to be no larger than the width of the view. + * (An example of a complicated decorator ) + */ +public class AutofitDecorator extends AttrsDecorator { + + private static final String TAG = "AutofitDecorator"; + private static final boolean SPEW = false; + + private TextView mTextView; + + // Minimum size of the text in pixels + private static final int DEFAULT_MIN_TEXT_SIZE = 11; //sp + + // How precise we want to be when reaching the target textWidth size + private static final float PRECISION = 0.5f; + + // Attributes + private boolean mSizeToFit; + private int mMaxLines; + private float mMinTextSize; + private float mMaxTextSize; + + private float mPrecision; + + private TextPaint mPaint; + + + @Override + protected int[] attrs() { + return new int[]{ R.attr.decorAutofitText, R.attr.decorSizeToFit, R.attr.decorMinTextSize, R.attr.decorPrecision}; + } + + + @Override + protected Class clazz() { + return TextView.class; + } + + @Override + protected void apply(TextView view, SparseArray values) { + mTextView = view; + TypedValueInfo typedValueInfo = values.get(R.attr.decorAutofitText); + boolean isAutofit = typedValueInfo.getParentArray().getBoolean(typedValueInfo.getIndexInValues(), false); + if(!isAutofit) return; + + float scaledDensity = mTextView.getContext().getResources().getDisplayMetrics().scaledDensity; + boolean sizeToFit = true; + int minTextSize = (int) scaledDensity * DEFAULT_MIN_TEXT_SIZE; + float precision = PRECISION; + + //TODO: deal with case when one of these values is absent + + TypedValueInfo sizeToFitValueInfo = values.get(R.attr.decorSizeToFit); + sizeToFit = sizeToFitValueInfo.getParentArray().getBoolean(R.styleable.DecorAutofit_decorSizeToFit, sizeToFit); + + TypedValueInfo minSizeValueInfo = values.get(R.attr.decorMinTextSize); + minTextSize = minSizeValueInfo.getParentArray().getDimensionPixelSize(R.styleable.DecorAutofit_decorMinTextSize, minTextSize); + + TypedValueInfo precisionValueInfo = values.get(R.attr.decorPrecision); + precision = precisionValueInfo.getParentArray().getFloat(R.styleable.DecorAutofit_decorPrecision, precision); + + mPaint = new TextPaint(); + setSizeToFit(sizeToFit); + setRawTextSize(mTextView.getTextSize()); + setRawMinTextSize(minTextSize); + setPrecision(precision); + } + + /** + * If true, the text will automatically be resized to fit its constraints; if false, it will act + * like a normal TextView. + */ + public void setSizeToFit(boolean sizeToFit) { + mSizeToFit = sizeToFit; + refitText(); + } + + private void setRawTextSize(float size) { + if (size != mMaxTextSize) { + mMaxTextSize = size; + refitText(); + } + } + + private void setRawMinTextSize(float minSize) { + if (minSize != mMinTextSize) { + mMinTextSize = minSize; + refitText(); + } + } + + /** + * Set the amount of precision used to calculate the correct text size to fit within it's + * bounds. Lower precision is more precise and takes more time. + * + * @param precision The amount of precision. + */ + public void setPrecision(float precision) { + if (precision != mPrecision) { + mPrecision = precision; + refitText(); + } + } + + /** + * @return the amount of precision used to calculate the correct text size to fit within it's + * bounds. + */ + public float getPrecision() { + return mPrecision; + } + + + /** + * Re size the font so the specified text fits in the text box assuming the text box is the + * specified width. + */ + private void refitText() { + if (!mSizeToFit) { + return; + } + + if (mMaxLines <= 0) { + // Don't auto-size since there's no limit on lines. + return; + } + + String text = mTextView.getText().toString(); + int targetWidth = mTextView.getWidth() - mTextView.getPaddingLeft() - mTextView.getPaddingRight(); + if (targetWidth > 0) { + Context context = mTextView.getContext(); + Resources r = Resources.getSystem(); + DisplayMetrics displayMetrics; + + float size = mMaxTextSize; + float high = size; + float low = 0; + + if (context != null) { + r = context.getResources(); + } + displayMetrics = r.getDisplayMetrics(); + + mPaint.set(mTextView.getPaint()); + mPaint.setTextSize(size); + + if ((mMaxLines == 1 && mPaint.measureText(text) > targetWidth) + || getLineCount(text, mPaint, size, targetWidth, displayMetrics) > mMaxLines) { + size = getTextSize(text, mPaint, targetWidth, mMaxLines, low, high, mPrecision, + displayMetrics); + } + + if (size < mMinTextSize) { + size = mMinTextSize; + } + + mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size); + } + } + + /** + * Recursive binary search to find the best size for the text + */ + private static float getTextSize(String text, TextPaint paint, + float targetWidth, int maxLines, + float low, float high, float precision, + DisplayMetrics displayMetrics) { + float mid = (low + high) / 2.0f; + int lineCount = 1; + StaticLayout layout = null; + + paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, + displayMetrics)); + + if (maxLines != 1) { + layout = new StaticLayout(text, paint, (int) targetWidth, Layout.Alignment.ALIGN_NORMAL, + 1.0f, 0.0f, true); + lineCount = layout.getLineCount(); + } + + if (SPEW) { + Log.d(TAG, "low=" + low + " high=" + high + " mid=" + mid + + " target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount); + } + + if (lineCount > maxLines) { + return getTextSize(text, paint, targetWidth, maxLines, low, mid, precision, + displayMetrics); + } else if (lineCount < maxLines) { + return getTextSize(text, paint, targetWidth, maxLines, mid, high, precision, + displayMetrics); + } else { + float maxLineWidth = 0; + if (maxLines == 1) { + maxLineWidth = paint.measureText(text); + } else { + for (int i = 0; i < lineCount; i++) { + if (layout.getLineWidth(i) > maxLineWidth) { + maxLineWidth = layout.getLineWidth(i); + } + } + } + + if ((high - low) < precision) { + return low; + } else if (maxLineWidth > targetWidth) { + return getTextSize(text, paint, targetWidth, maxLines, low, mid, precision, + displayMetrics); + } else if (maxLineWidth < targetWidth) { + return getTextSize(text, paint, targetWidth, maxLines, mid, high, precision, + displayMetrics); + } else { + return mid; + } + } + } + + /** + * {@inheritDoc} + */ + //@Override //since we cant have override with it here -> issue when frmwrk calls setTextSize on this afterwards + //probably it wont work (is there a way to have a delegate for mTextView to pass to this when setTextSize is called on it) + public void setTextSize(int unit, float size) { + if (!mSizeToFit) { + mTextView.setTextSize(unit, size); + } + + Context context = mTextView.getContext(); + Resources r = Resources.getSystem(); + + if (context != null) { + r = context.getResources(); + } + + setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics())); + } + + private static int getLineCount(String text, TextPaint paint, float size, float width, + DisplayMetrics displayMetrics) { + paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size, + displayMetrics)); + StaticLayout layout = new StaticLayout(text, paint, (int) width, + Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true); + return layout.getLineCount(); + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/BlurDecorator.java b/decorators/src/main/java/mona/android/decorators/BlurDecorator.java new file mode 100644 index 0000000..080e330 --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/BlurDecorator.java @@ -0,0 +1,60 @@ +package mona.android.decorators; + +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.ImageView; + +import mona.android.decor.AttrsDecorator; +import mona.android.decorators.utils.BlurUtils; + +/** + * Created by cheikhna on 03/04/2015. + */ +public class BlurDecorator extends AttrsDecorator { + + + @Override + protected int[] attrs() { + return new int[]{R.attr.decorBlur}; + } + + + @Override + protected Class clazz() { + return View.class; + } + + @Override + protected void apply(View view, SparseArray values) { + TypedValueInfo typedValueInfo = values.get(R.attr.decorBlur); + boolean isBlur = typedValueInfo.getParentArray().getBoolean(typedValueInfo.getIndexInValues(), false); + if(!isBlur) return; + + //i'm guessing this part here doesnt work because i'm using the same blur as ngAndroid and they are + //doing their injection in a different point in the inflation + ViewGroup parent = (ViewGroup) view.getParent(); + FrameLayout layout = new FrameLayout(view.getContext()); + layout.setLayoutParams(view.getLayoutParams()); + int index = parent.indexOfChild(view); + parent.removeViewAt(index); + FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT); + view.setLayoutParams(layoutParams); + layout.addView(view); + parent.addView(layout, index); + + final ImageView imageView = new ImageView(view.getContext()); + imageView.setLayoutParams(layoutParams); + imageView.setVisibility(View.GONE); + layout.addView(imageView); + + view.setVisibility(View.GONE); + view.setDrawingCacheEnabled(true); + imageView.setImageBitmap(BlurUtils.blurBitmap(view.getDrawingCache(), view.getContext())); + imageView.setVisibility(View.VISIBLE); + } + +} \ No newline at end of file diff --git a/decorators/src/main/java/mona/android/decorators/ColorFilterDecorator.java b/decorators/src/main/java/mona/android/decorators/ColorFilterDecorator.java new file mode 100644 index 0000000..987536f --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/ColorFilterDecorator.java @@ -0,0 +1,35 @@ +package mona.android.decorators; + +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.widget.ImageView; + +import mona.android.decor.AttrsDecorator; + + +/** + * Created by cheikhna on 01/03/2015. + */ +public class ColorFilterDecorator extends AttrsDecorator { + + + @Override + protected int[] attrs() { + return new int[]{R.attr.decorColorFilter}; + } + + + @Override + protected Class clazz() { + return ImageView.class; + } + + @Override + protected void apply(ImageView view, SparseArray values) { + TypedValueInfo typedValueInfo = values.get(R.attr.decorColorFilter); + int color = typedValueInfo.getParentArray().getColor(typedValueInfo.getIndexInValues(), -1); + if(color == -1) return; + view.setColorFilter(color); + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/Decorators.java b/decorators/src/main/java/mona/android/decorators/Decorators.java new file mode 100644 index 0000000..e0f36ac --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/Decorators.java @@ -0,0 +1,32 @@ +package mona.android.decorators; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import mona.android.decor.Decorator; + +/** + * Created by cheikhna on 11/04/2015. + */ + +/** + * A utility class to obtain all decorators defined in this library + */ +public final class Decorators { + + /** + * Get all the decorators already defined + * @return available decorators + */ + public static Decorator[] getAll() { + return new Decorator[] { + new AutofitDecorator(), + new BlurDecorator(), + new ColorFilterDecorator(), + new ErrorDecorator(), + new FontDecorator() + }; + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/ErrorDecorator.java b/decorators/src/main/java/mona/android/decorators/ErrorDecorator.java new file mode 100644 index 0000000..73181a2 --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/ErrorDecorator.java @@ -0,0 +1,42 @@ +package mona.android.decorators; + +import android.graphics.drawable.Drawable; +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.widget.EditText; + +import mona.android.decor.AttrsDecorator; + +/** + * Created by cheikhna on 09/02/2015. + */ +public class ErrorDecorator extends AttrsDecorator { + + @Override + protected int[] attrs() { + return new int[] { R.attr.decorErrorIcon, R.attr.decorErrorText}; + } + + + @Override + protected Class clazz() { + return EditText.class; + } + + @Override + protected void apply(EditText view, SparseArray values) { + Drawable errorIcon = null; + CharSequence errorText = null; + TypedValueInfo errIconValueInfo = values.get(R.attr.decorErrorIcon); + if(errIconValueInfo != null) { + errorIcon = errIconValueInfo.getParentArray().getDrawable(errIconValueInfo.getIndexInValues()); + } + + TypedValueInfo errTextValueInfo = values.get(R.attr.decorErrorText); + if(errTextValueInfo != null) { + errorText = errTextValueInfo.getParentArray().getString(errTextValueInfo.getIndexInValues()); + } + view.setError(errorText, errorIcon); + } + +} \ No newline at end of file diff --git a/decorators/src/main/java/mona/android/decorators/FontDecorator.java b/decorators/src/main/java/mona/android/decorators/FontDecorator.java new file mode 100644 index 0000000..cca141c --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/FontDecorator.java @@ -0,0 +1,30 @@ +package mona.android.decorators; + +import android.graphics.Typeface; +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.widget.TextView; + +import mona.android.decor.AttrsDecorator; + + +public class FontDecorator extends AttrsDecorator { + + @Override + protected int[] attrs() { + return new int[] { R.attr.decorTypefaceAsset}; + } + + + @Override + protected Class clazz() { + return TextView.class; + } + + @Override + protected void apply(TextView view, SparseArray values) { + view.setTypeface(Typeface.createFromAsset(view.getResources().getAssets(), + values.get(R.attr.decorTypefaceAsset).getTypedValue().string.toString())); + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/OnActionBaseDecorator.java b/decorators/src/main/java/mona/android/decorators/OnActionBaseDecorator.java new file mode 100644 index 0000000..d912f4c --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/OnActionBaseDecorator.java @@ -0,0 +1,58 @@ +package mona.android.decorators; + +import android.app.Activity; +import android.support.annotation.NonNull; +import android.util.TypedValue; +import android.view.View; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import mona.android.decor.AttrsDecorator; + + +/** + * Created by cheikhna on 02/04/2015. + */ +public abstract class OnActionBaseDecorator extends AttrsDecorator { + + protected Activity mContainerActivity; + + public OnActionBaseDecorator(Activity activity) { + mContainerActivity = activity; + } + + + @Override + protected abstract int[] attrs(); + + + @Override + protected Class clazz() { + return View.class; + } + + protected boolean onAction(TypedValue value) { + Method mHandler = null; + try { + if(mContainerActivity != null) { + mHandler = mContainerActivity.getClass().getMethod(value.string.toString()); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + + if (mHandler == null) return false; + try { + mHandler.invoke(mContainerActivity); + return true; + } catch (IllegalAccessException e) { + e.printStackTrace(); + throw new IllegalStateException("Could not execute non public method of the activity", e); + } catch (InvocationTargetException e) { + e.printStackTrace(); + throw new IllegalStateException("Could not execute method of the activity", e); + } + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/OnLongClickDecorator.java b/decorators/src/main/java/mona/android/decorators/OnLongClickDecorator.java new file mode 100644 index 0000000..3789ebb --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/OnLongClickDecorator.java @@ -0,0 +1,35 @@ +package mona.android.decorators; + +import android.app.Activity; +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.view.View; +import android.view.View.OnLongClickListener; + +/** + * Created by cheikhna on 02/04/2015. + */ +public class OnLongClickDecorator extends OnActionBaseDecorator { + + public OnLongClickDecorator(Activity activity) { + super(activity); + } + + + @Override + protected int[] attrs() { + return new int[]{R.attr.decorOnLongClick}; + } + + @Override + protected void apply(View view, final SparseArray values) { + view.setOnLongClickListener(new OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + onAction(values.get(R.attr.decorOnLongClick).getTypedValue()); + return true; + } + }); + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/OnTouchDecorator.java b/decorators/src/main/java/mona/android/decorators/OnTouchDecorator.java new file mode 100644 index 0000000..ea85c22 --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/OnTouchDecorator.java @@ -0,0 +1,35 @@ +package mona.android.decorators; + +import android.app.Activity; +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnTouchListener; + +/** + * Created by cheikhna on 17/02/2015. + */ +public class OnTouchDecorator extends OnActionBaseDecorator { + + public OnTouchDecorator(Activity activity) { + super(activity); + } + + + @Override + protected int[] attrs() { + return new int[]{R.attr.decorOnTouch}; + } + + @Override + protected void apply(View view, final SparseArray values) { + view.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return OnTouchDecorator.this.onAction(values.get(R.attr.decorOnTouch).getTypedValue()); + } + }); + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/SearchAnimateDecorator.java b/decorators/src/main/java/mona/android/decorators/SearchAnimateDecorator.java new file mode 100644 index 0000000..578b4d8 --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/SearchAnimateDecorator.java @@ -0,0 +1,80 @@ +package mona.android.decorators; + +import android.annotation.TargetApi; +import android.graphics.drawable.AnimatedVectorDrawable; +import android.os.Build; +import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.view.View; +import android.view.animation.AnimationUtils; +import android.view.animation.Interpolator; +import android.widget.ImageView; + +import mona.android.decor.AttrsDecorator; + +/** + * Created by mounacheikhna on 01/04/2015. + */ +public class SearchAnimateDecorator extends AttrsDecorator { + + private boolean expanded = false; + private ImageView mIv; + private AnimatedVectorDrawable mSearchToBar; + private AnimatedVectorDrawable mBarToSearch; + private Interpolator mInterp; + private int mDuration; + private float mOffset; + + + @Override + protected int[] attrs() { + return new int[]{R.attr.decorAnimateSearch}; + } + + + @Override + protected Class clazz() { + return ImageView.class; + } + + @Override + protected void apply(ImageView view, SparseArray values) { + TypedValueInfo typedValueInfo = values.get(R.attr.decorAnimateSearch); + boolean shouldAnimate = typedValueInfo.getParentArray().getBoolean(typedValueInfo.getIndexInValues(), false); + if(!shouldAnimate) return; + + mIv = view; + mSearchToBar = (AnimatedVectorDrawable) view.getContext().getResources().getDrawable(R.drawable.anim_search_to_bar); + mBarToSearch = (AnimatedVectorDrawable) view.getContext().getResources().getDrawable(R.drawable.anim_bar_to_search); + mInterp = AnimationUtils.loadInterpolator(view.getContext(), android.R.interpolator.linear_out_slow_in); + mDuration = view.getContext().getResources().getInteger(R.integer.duration_bar); + // iv is sized to hold the search+bar so when only showing the search icon, translate the + // whole view left by half the difference to keep it centered + mOffset = -71f * (int) view.getContext().getResources().getDisplayMetrics().scaledDensity; + view.setTranslationX(mOffset); + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + animate(v); + } + }); + } + + //TODO: do a version of this for pre-lollipop or dont allow the use of it + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public void animate(View view) { + if (!expanded) { + mIv.setImageDrawable(mSearchToBar); + mSearchToBar.start(); + mIv.animate().translationX(0f).setDuration(mDuration).setInterpolator(mInterp); + //text.animate().alpha(1f).setStartDelay(duration - 100).setDuration(100).setInterpolator(interp); + } else { + mIv.setImageDrawable(mBarToSearch); + mBarToSearch.start(); + mIv.animate().translationX(mOffset).setDuration(mDuration).setInterpolator(mInterp); + //text.setAlpha(0f); + } + expanded = !expanded; + } + +} diff --git a/decorators/src/main/java/mona/android/decorators/utils/BlurUtils.java b/decorators/src/main/java/mona/android/decorators/utils/BlurUtils.java new file mode 100644 index 0000000..28ef89d --- /dev/null +++ b/decorators/src/main/java/mona/android/decorators/utils/BlurUtils.java @@ -0,0 +1,40 @@ +package mona.android.decorators.utils; + +import android.content.Context; +import android.graphics.Bitmap; +import android.renderscript.Allocation; +import android.renderscript.Element; +import android.renderscript.RenderScript; +import android.renderscript.ScriptIntrinsicBlur; + +/** + * Created by cheikhna on 04/04/2015. + */ +public class BlurUtils { + private static final float SCALE_RATIO = 5f; + private static final float DEFAULT_BLUR_RADIUS = 5.f; + + public static Bitmap blurBitmap(Bitmap bitmap, Context context){ + int width = bitmap.getWidth(), height = bitmap.getHeight(); + Bitmap b = Bitmap.createScaledBitmap(Bitmap.createScaledBitmap(bitmap,(int)(width/SCALE_RATIO), (int)(height/SCALE_RATIO), false), width, height, false); + return blurBitmap(b, DEFAULT_BLUR_RADIUS, context); + } + + + private static Bitmap blurBitmap(Bitmap src, float blurRadius, Context context) { + RenderScript rs = RenderScript.create(context); + Bitmap.Config conf = Bitmap.Config.ARGB_8888; + Bitmap blurredBitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), conf); + + final Allocation input = Allocation.createFromBitmap(rs, src, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); + final Allocation output = Allocation.createTyped(rs, input.getType()); + + final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); + script.setRadius(blurRadius); + script.setInput(input); + script.forEach(output); + output.copyTo(blurredBitmap); + return blurredBitmap; + } + +} diff --git a/decorators/src/main/res/anim/anim_bar_fill.xml b/decorators/src/main/res/anim/anim_bar_fill.xml new file mode 100644 index 0000000..0954679 --- /dev/null +++ b/decorators/src/main/res/anim/anim_bar_fill.xml @@ -0,0 +1,9 @@ + + \ No newline at end of file diff --git a/decorators/src/main/res/anim/anim_search_empty.xml b/decorators/src/main/res/anim/anim_search_empty.xml new file mode 100644 index 0000000..09a3f1b --- /dev/null +++ b/decorators/src/main/res/anim/anim_search_empty.xml @@ -0,0 +1,9 @@ + + \ No newline at end of file diff --git a/decorators/src/main/res/drawable/anim_bar_to_search.xml b/decorators/src/main/res/drawable/anim_bar_to_search.xml new file mode 100644 index 0000000..e439b6b --- /dev/null +++ b/decorators/src/main/res/drawable/anim_bar_to_search.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/decorators/src/main/res/drawable/anim_search_to_bar.xml b/decorators/src/main/res/drawable/anim_search_to_bar.xml new file mode 100644 index 0000000..97f171f --- /dev/null +++ b/decorators/src/main/res/drawable/anim_search_to_bar.xml @@ -0,0 +1,14 @@ + + + + + + + + diff --git a/decorators/src/main/res/drawable/search_vector_drawable.xml b/decorators/src/main/res/drawable/search_vector_drawable.xml new file mode 100644 index 0000000..49ecfde --- /dev/null +++ b/decorators/src/main/res/drawable/search_vector_drawable.xml @@ -0,0 +1,21 @@ + + + + + \ No newline at end of file diff --git a/decorators/src/main/res/values/attrs.xml b/decorators/src/main/res/values/attrs.xml new file mode 100644 index 0000000..c3a942d --- /dev/null +++ b/decorators/src/main/res/values/attrs.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/decorators/src/main/res/values/integers.xml b/decorators/src/main/res/values/integers.xml new file mode 100644 index 0000000..127d345 --- /dev/null +++ b/decorators/src/main/res/values/integers.xml @@ -0,0 +1,5 @@ + + + 800 + 800 + \ No newline at end of file diff --git a/decorators/src/main/res/values/strings.xml b/decorators/src/main/res/values/strings.xml new file mode 100644 index 0000000..b997c57 --- /dev/null +++ b/decorators/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Decor + diff --git a/deploy.gradle b/deploy.gradle new file mode 100644 index 0000000..725d2b9 --- /dev/null +++ b/deploy.gradle @@ -0,0 +1,109 @@ + +apply plugin: 'maven' +apply plugin: 'signing' + + +def isReleaseBuild() { + project.ext.isReleaseVersion +} + +def getReleaseRepositoryUrl() { + return "https://oss.sonatype.org/service/local/staging/deploy/maven2/" +} + +def getSnapshotRepositoryUrl() { + return "https://oss.sonatype.org/content/repositories/snapshots/" +} + +def getRepositoryUsername() { + return hasProperty('sonatypeUsername') ? sonatypeUsername : "" +} + +def getRepositoryPassword() { + return hasProperty('sonatypePassword') ? sonatypePassword : "" +} + + +// Debug Build or Release? +if (isReleaseBuild()) { + println "RELEASE BUILD $version" +} else { + version += "-SNAPSHOT" + println "DEBUG BUILD $version" +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + + pom.groupId = GROUP + pom.version = version + pom.artifactId = POM_ARTIFACT_ID + + repository(url: getReleaseRepositoryUrl()) { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + snapshotRepository(url: getSnapshotRepositoryUrl()) { + authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) + } + + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL + + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } + + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } + + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + email POM_DEVELOPER_EMAIL + } + } + } + } + } + } + + signing { + required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives + } + + task androidJavadocs(type: Javadoc) { + source = android.sourceSets.main.java.srcDirs + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) + } + + task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { + classifier = 'javadoc' + from androidJavadocs.destinationDir + } + + task androidSourcesJar(type: Jar) { + classifier = 'sources' + from android.sourceSets.main.java.srcDirs + } + + artifacts { + archives androidSourcesJar + archives androidJavadocsJar + } + +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..197e15e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,41 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Settings specified in this file will override any Gradle settings +# configured through the IDE. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +GROUP=mona.android +VERSION_NAME=0.1 +VERSION_CODE=1 + +POM_PACKAGING=aar +POM_URL=https://github.com/chemouna/Decor +POM_DESCRIPTION=Android layout decorator : Injecting custom attributes in layout files, Using decorators to get rid of explosition in inherietence for custom view +POM_SCM_URL=https://github.com/chemouna/Decor +POM_SCM_CONNECTION=scm:git@github.com:chemouna/Decor.git +POM_SCM_DEV_CONNECTION=scm:git@github.com:chemouna/Decor.git +POM_LICENCE_NAME=The Apache Software License, Version 2.0 +POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENCE_DIST=repo +POM_DEVELOPER_ID=chemouna +POM_DEVELOPER_NAME=Mouna Cheikhna +POM_DEVELOPER_EMAIL=cheikhnamouna@gmail.com + +ANDROID_BUILD_MIN_SDK_VERSION=8 +ANDROID_BUILD_TARGET_SDK_VERSION=21 +ANDROID_BUILD_SDK_VERSION=21 +ANDROID_BUILD_TOOLS_VERSION=22.0.1 +ANDROID_SUPPORT_VERSION=21.0.3 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d5c591c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6390a56 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Jan 26 23:14:25 CET 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/build.gradle b/samples/build.gradle new file mode 100644 index 0000000..bd426f9 --- /dev/null +++ b/samples/build.gradle @@ -0,0 +1,27 @@ +apply plugin: 'com.android.application' + +repositories { + mavenCentral() +} + + +android { + + compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) + buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION + + defaultConfig { + minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) + targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) + } + + lintOptions { + disable 'MissingPrefix' + } +} + +dependencies { + compile(project(':decor')) + compile(project(':decorators')) + compile "com.android.support:support-v4:${project.ANDROID_SUPPORT_VERSION}" +} diff --git a/samples/src/main/AndroidManifest.xml b/samples/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ac37103 --- /dev/null +++ b/samples/src/main/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + diff --git a/samples/src/main/assets/Ubuntu-M.ttf b/samples/src/main/assets/Ubuntu-M.ttf new file mode 100644 index 0000000..443ec8b Binary files /dev/null and b/samples/src/main/assets/Ubuntu-M.ttf differ diff --git a/samples/src/main/assets/ubuntu-font-license-1.0.txt b/samples/src/main/assets/ubuntu-font-license-1.0.txt new file mode 100644 index 0000000..7866fe1 --- /dev/null +++ b/samples/src/main/assets/ubuntu-font-license-1.0.txt @@ -0,0 +1,47 @@ +Version 1.0 + +Preamble + +This licence allows the licensed fonts to be used, studied, modified and redistributed freely. The fonts, including any derivative works, can be bundled, embedded, and redistributed provided the terms of this licence are met. The fonts and derivatives, however, cannot be released under any other licence. The requirement for fonts to remain under this licence does not require any document created using the fonts or their derivatives to be published under this licence, as long as the primary purpose of the document is not to be a vehicle for the distribution of the fonts. + +Definitions + +"Font Software" refers to the set of files released by the Copyright Holder(s) under this licence and clearly marked as such. This may include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily identified as dissimilar to the Font Software by users of the Font Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification and with or without charging a redistribution fee), making available to the public, and in some countries other activities as well. + +Permission & Conditions + +This licence does not grant any rights under trademark law and all such rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to propagate the Font Software, subject to the below conditions: + +Each copy of the Font Software must contain the above copyright notice and this licence. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. +The font name complies with the following: +The Original Version must retain its name, unmodified. +Modified Versions which are Substantially Changed must be renamed to avoid use of the name of the Original Version or similar names entirely. +Modified Versions which are not Substantially Changed must be renamed to both +retain the name of the Original Version and +add additional naming elements to distinguish the Modified Version from the Original Version. The name of such Modified Versions must be the name of the Original Version, with "derivative X" where X represents the name of the new work, appended to that name. +The name(s) of the Copyright Holder(s) and any contributor to the Font Software shall not be used to promote, endorse or advertise any Modified Version, except +as required by this licence, +to acknowledge the contribution(s) of the Copyright Holder(s) or +with their explicit written permission. +The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this licence, and must not be distributed under any other licence. The requirement for fonts to remain under this licence does not affect any document created using the Font Software, except any version of the Font Software extracted from a document created using the Font Software may only be distributed under this licence. +Termination + +This licence becomes null and void if any of the above conditions are not met. + +Disclaimer + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Ubuntu Font Licence Version 1.0 (plain text) diff --git a/samples/src/main/java/mona/android/decor/samples/CustomTextView.java b/samples/src/main/java/mona/android/decor/samples/CustomTextView.java new file mode 100644 index 0000000..515e3c4 --- /dev/null +++ b/samples/src/main/java/mona/android/decor/samples/CustomTextView.java @@ -0,0 +1,21 @@ +package mona.android.decor.samples; + +import android.content.Context; +import android.util.AttributeSet; +import android.widget.TextView; + +public class CustomTextView extends TextView { + + public CustomTextView(Context context) { + super(context); + } + + public CustomTextView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public CustomTextView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + +} diff --git a/samples/src/main/java/mona/android/decor/samples/SampleActivity.java b/samples/src/main/java/mona/android/decor/samples/SampleActivity.java new file mode 100644 index 0000000..04989b2 --- /dev/null +++ b/samples/src/main/java/mona/android/decor/samples/SampleActivity.java @@ -0,0 +1,34 @@ +package mona.android.decor.samples; + +import android.app.Activity; +import android.content.Context; +import android.os.Bundle; +import android.widget.Toast; + +import mona.android.decor.DecorContextWrapper; +import mona.android.decor.Decorator; +import mona.android.decorators.Decorators; + +public class SampleActivity extends /*ActionBarActivity*/ /*FragmentActivity*/ Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + } + + public void onIvTouch() { + Toast.makeText(this, " Touch detected ", Toast.LENGTH_SHORT).show(); + } + + public void onRobotLongClick() { + Toast.makeText(this, " Long click detected ", Toast.LENGTH_SHORT).show(); + } + + @Override + protected void attachBaseContext(Context newBase) { + super.attachBaseContext(DecorContextWrapper.wrap(newBase) + .with(Decorators.getAll())); + } + +} \ No newline at end of file diff --git a/samples/src/main/java/mona/android/decor/samples/SampleFragment.java b/samples/src/main/java/mona/android/decor/samples/SampleFragment.java new file mode 100644 index 0000000..c996d94 --- /dev/null +++ b/samples/src/main/java/mona/android/decor/samples/SampleFragment.java @@ -0,0 +1,16 @@ +package mona.android.decor.samples; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +public class SampleFragment extends /*Fragment*/ android.app.Fragment { + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return inflater.inflate(R.layout.main_frag, container, false); + } + +} + \ No newline at end of file diff --git a/samples/src/main/res/drawable-nodpi/photo1.jpg b/samples/src/main/res/drawable-nodpi/photo1.jpg new file mode 100644 index 0000000..3c4d150 Binary files /dev/null and b/samples/src/main/res/drawable-nodpi/photo1.jpg differ diff --git a/samples/src/main/res/drawable-xhdpi/ic_error_et.png b/samples/src/main/res/drawable-xhdpi/ic_error_et.png new file mode 100644 index 0000000..cd02f40 Binary files /dev/null and b/samples/src/main/res/drawable-xhdpi/ic_error_et.png differ diff --git a/samples/src/main/res/drawable-xhdpi/ic_launcher.png b/samples/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 0000000..71c6d76 Binary files /dev/null and b/samples/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/samples/src/main/res/drawable-xxhdpi/ic_error_et.png b/samples/src/main/res/drawable-xxhdpi/ic_error_et.png new file mode 100644 index 0000000..523164a Binary files /dev/null and b/samples/src/main/res/drawable-xxhdpi/ic_error_et.png differ diff --git a/samples/src/main/res/drawable-xxhdpi/tb3.png b/samples/src/main/res/drawable-xxhdpi/tb3.png new file mode 100644 index 0000000..876760d Binary files /dev/null and b/samples/src/main/res/drawable-xxhdpi/tb3.png differ diff --git a/samples/src/main/res/layout-v21/api_dependent_layout.xml b/samples/src/main/res/layout-v21/api_dependent_layout.xml new file mode 100644 index 0000000..8b55a94 --- /dev/null +++ b/samples/src/main/res/layout-v21/api_dependent_layout.xml @@ -0,0 +1,11 @@ + + \ No newline at end of file diff --git a/samples/src/main/res/layout/api_dependent_layout.xml b/samples/src/main/res/layout/api_dependent_layout.xml new file mode 100644 index 0000000..fbfa8f2 --- /dev/null +++ b/samples/src/main/res/layout/api_dependent_layout.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/samples/src/main/res/layout/main.xml b/samples/src/main/res/layout/main.xml new file mode 100644 index 0000000..0af05d6 --- /dev/null +++ b/samples/src/main/res/layout/main.xml @@ -0,0 +1,16 @@ + + + + + + + diff --git a/samples/src/main/res/layout/main_frag.xml b/samples/src/main/res/layout/main_frag.xml new file mode 100644 index 0000000..34193bc --- /dev/null +++ b/samples/src/main/res/layout/main_frag.xml @@ -0,0 +1,59 @@ + + + + + + + + + +