1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.tools.layoutlib.create;
18
19import org.objectweb.asm.ClassVisitor;
20import org.objectweb.asm.MethodVisitor;
21import org.objectweb.asm.Opcodes;
22
23import java.util.Set;
24
25/**
26 * A {@link DelegateClassAdapter} can transform some methods from a class into
27 * delegates that defer the call to an associated delegate class.
28 * <p/>
29 * This is used to override specific methods and or all native methods in classes.
30 */
31public class DelegateClassAdapter extends ClassVisitor {
32
33    /** Suffix added to original methods. */
34    private static final String ORIGINAL_SUFFIX = "_Original";
35    private static String CONSTRUCTOR = "<init>";
36    private static String CLASS_INIT = "<clinit>";
37
38    public final static String ALL_NATIVES = "<<all_natives>>";
39
40    private final String mClassName;
41    private final Set<String> mDelegateMethods;
42    private final Log mLog;
43
44    /**
45     * Creates a new {@link DelegateClassAdapter} that can transform some methods
46     * from a class into delegates that defer the call to an associated delegate class.
47     * <p/>
48     * This is used to override specific methods and or all native methods in classes.
49     *
50     * @param log The logger object. Must not be null.
51     * @param cv the class visitor to which this adapter must delegate calls.
52     * @param className The internal class name of the class to visit,
53     *          e.g. <code>com/android/SomeClass$InnerClass</code>.
54     * @param delegateMethods The set of method names to modify and/or the
55     *          special constant {@link #ALL_NATIVES} to convert all native methods.
56     */
57    public DelegateClassAdapter(Log log,
58            ClassVisitor cv,
59            String className,
60            Set<String> delegateMethods) {
61        super(Opcodes.ASM4, cv);
62        mLog = log;
63        mClassName = className;
64        mDelegateMethods = delegateMethods;
65    }
66
67    //----------------------------------
68    // Methods from the ClassAdapter
69
70    @Override
71    public MethodVisitor visitMethod(int access, String name, String desc,
72            String signature, String[] exceptions) {
73
74        boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
75        boolean isNative = (access & Opcodes.ACC_NATIVE) != 0;
76
77        boolean useDelegate = (isNative && mDelegateMethods.contains(ALL_NATIVES)) ||
78                              mDelegateMethods.contains(name);
79
80        if (!useDelegate) {
81            // Not creating a delegate for this method, pass it as-is from the reader
82            // to the writer.
83            return super.visitMethod(access, name, desc, signature, exceptions);
84        }
85
86        if (useDelegate) {
87            if (CONSTRUCTOR.equals(name) || CLASS_INIT.equals(name)) {
88                // We don't currently support generating delegates for constructors.
89                throw new UnsupportedOperationException(
90                    String.format(
91                        "Delegate doesn't support overriding constructor %1$s:%2$s(%3$s)",  //$NON-NLS-1$
92                        mClassName, name, desc));
93            }
94        }
95
96        if (isNative) {
97            // Remove native flag
98            access = access & ~Opcodes.ACC_NATIVE;
99            MethodVisitor mwDelegate = super.visitMethod(access, name, desc, signature, exceptions);
100
101            DelegateMethodAdapter2 a = new DelegateMethodAdapter2(
102                    mLog, null /*mwOriginal*/, mwDelegate, mClassName, name, desc, isStatic);
103
104            // A native has no code to visit, so we need to generate it directly.
105            a.generateDelegateCode();
106
107            return mwDelegate;
108        }
109
110        // Given a non-native SomeClass.MethodName(), we want to generate 2 methods:
111        // - A copy of the original method named SomeClass.MethodName_Original().
112        //   The content is the original method as-is from the reader.
113        // - A brand new implementation of SomeClass.MethodName() which calls to a
114        //   non-existing method named SomeClass_Delegate.MethodName().
115        //   The implementation of this 'delegate' method is done in layoutlib_brigde.
116
117        int accessDelegate = access;
118        // change access to public for the original one
119        if (Main.sOptions.generatePublicAccess) {
120            access &= ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE);
121            access |= Opcodes.ACC_PUBLIC;
122        }
123
124        MethodVisitor mwOriginal = super.visitMethod(access, name + ORIGINAL_SUFFIX,
125                                                     desc, signature, exceptions);
126        MethodVisitor mwDelegate = super.visitMethod(accessDelegate, name,
127                                                     desc, signature, exceptions);
128
129        DelegateMethodAdapter2 a = new DelegateMethodAdapter2(
130                mLog, mwOriginal, mwDelegate, mClassName, name, desc, isStatic);
131        return a;
132    }
133}
134