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 final String CONSTRUCTOR = "<init>";
36    private static final String CLASS_INIT = "<clinit>";
37
38    public static final 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 to the writer.
82            return super.visitMethod(access, name, desc, signature, exceptions);
83        }
84
85        if (CONSTRUCTOR.equals(name) || CLASS_INIT.equals(name)) {
86            // We don't currently support generating delegates for constructors.
87            throw new UnsupportedOperationException(
88                String.format(
89                    "Delegate doesn't support overriding constructor %1$s:%2$s(%3$s)",  //$NON-NLS-1$
90                    mClassName, name, desc));
91        }
92
93        if (isNative) {
94            // Remove native flag
95            access = access & ~Opcodes.ACC_NATIVE;
96            MethodVisitor mwDelegate = super.visitMethod(access, name, desc, signature, exceptions);
97
98            DelegateMethodAdapter a = new DelegateMethodAdapter(
99                    mLog, null, mwDelegate, mClassName, name, desc, isStatic);
100
101            // A native has no code to visit, so we need to generate it directly.
102            a.generateDelegateCode();
103
104            return mwDelegate;
105        }
106
107        // Given a non-native SomeClass.MethodName(), we want to generate 2 methods:
108        // - A copy of the original method named SomeClass.MethodName_Original().
109        //   The content is the original method as-is from the reader.
110        // - A brand new implementation of SomeClass.MethodName() which calls to a
111        //   non-existing method named SomeClass_Delegate.MethodName().
112        //   The implementation of this 'delegate' method is done in layoutlib_bridge.
113
114        int accessDelegate = access;
115        access = access & ~Opcodes.ACC_PRIVATE;  // If private, make it package protected.
116
117        MethodVisitor mwOriginal = super.visitMethod(access, name + ORIGINAL_SUFFIX,
118                                                     desc, signature, exceptions);
119        MethodVisitor mwDelegate = super.visitMethod(accessDelegate, name,
120                                                     desc, signature, exceptions);
121
122        return new DelegateMethodAdapter(
123                mLog, mwOriginal, mwDelegate, mClassName, name, desc, isStatic);
124    }
125}
126