1/*
2 * Copyright (C) 2015 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.layoutlib.bridge.bars;
18
19import com.android.ide.common.rendering.api.RenderResources;
20import com.android.ide.common.rendering.api.ResourceValue;
21import com.android.ide.common.rendering.api.SessionParams;
22import com.android.ide.common.rendering.api.StyleResourceValue;
23import com.android.layoutlib.bridge.android.BridgeContext;
24import com.android.layoutlib.bridge.impl.ResourceHelper;
25import com.android.resources.ResourceType;
26
27import android.annotation.NonNull;
28import android.annotation.Nullable;
29import android.content.Context;
30import android.graphics.drawable.Drawable;
31import android.view.ContextThemeWrapper;
32import android.view.LayoutInflater;
33import android.view.View;
34import android.widget.FrameLayout;
35
36import java.lang.reflect.InvocationTargetException;
37import java.lang.reflect.Method;
38
39
40/**
41 * Assumes that the AppCompat library is present in the project's classpath and creates an
42 * actionbar around it.
43 */
44public class AppCompatActionBar extends BridgeActionBar {
45
46    private Object mWindowDecorActionBar;
47    private static final String WINDOW_ACTION_BAR_CLASS = "android.support.v7.internal.app.WindowDecorActionBar";
48    private Class<?> mWindowActionBarClass;
49
50    /**
51     * Inflate the action bar and attach it to {@code parentView}
52     */
53    public AppCompatActionBar(@NonNull BridgeContext context, @NonNull SessionParams params) {
54        super(context, params);
55        int contentRootId = context.getProjectResourceValue(ResourceType.ID,
56                "action_bar_activity_content", 0);
57        View contentView = getDecorContent().findViewById(contentRootId);
58        if (contentView != null) {
59            assert contentView instanceof FrameLayout;
60            setContentRoot((FrameLayout) contentView);
61        } else {
62            // Something went wrong. Create a new FrameLayout in the enclosing layout.
63            FrameLayout contentRoot = new FrameLayout(context);
64            setMatchParent(contentRoot);
65            if (mEnclosingLayout != null) {
66                mEnclosingLayout.addView(contentRoot);
67            }
68            setContentRoot(contentRoot);
69        }
70        try {
71            Class[] constructorParams = {View.class};
72            Object[] constructorArgs = {getDecorContent()};
73            mWindowDecorActionBar = params.getLayoutlibCallback().loadView(WINDOW_ACTION_BAR_CLASS,
74                    constructorParams, constructorArgs);
75
76            mWindowActionBarClass = mWindowDecorActionBar == null ? null :
77                    mWindowDecorActionBar.getClass();
78            setupActionBar();
79        } catch (Exception e) {
80            e.printStackTrace();
81        }
82    }
83
84    @Override
85    protected ResourceValue getLayoutResource(BridgeContext context) {
86        // We always assume that the app has requested the action bar.
87        return context.getRenderResources().getProjectResource(ResourceType.LAYOUT,
88                "abc_screen_toolbar");
89    }
90
91    @Override
92    protected LayoutInflater getInflater(BridgeContext context) {
93        // Other than the resource resolution part, the code has been taken from the support
94        // library. see code from line 269 onwards in
95        // https://android.googlesource.com/platform/frameworks/support/+/android-5.1.0_r1/v7/appcompat/src/android/support/v7/app/ActionBarActivityDelegateBase.java
96        Context themedContext = context;
97        RenderResources resources = context.getRenderResources();
98        ResourceValue actionBarTheme = resources.findItemInTheme("actionBarTheme", false);
99        if (actionBarTheme != null) {
100            // resolve it, if needed.
101            actionBarTheme = resources.resolveResValue(actionBarTheme);
102        }
103        if (actionBarTheme instanceof StyleResourceValue) {
104            int styleId = context.getDynamicIdByStyle(((StyleResourceValue) actionBarTheme));
105            if (styleId != 0) {
106                themedContext = new ContextThemeWrapper(context, styleId);
107            }
108        }
109        return LayoutInflater.from(themedContext);
110    }
111
112    @Override
113    protected void setTitle(CharSequence title) {
114        if (title != null && mWindowDecorActionBar != null) {
115            Method setTitle = getMethod(mWindowActionBarClass, "setTitle", CharSequence.class);
116            invoke(setTitle, mWindowDecorActionBar, title);
117        }
118    }
119
120    @Override
121    protected void setSubtitle(CharSequence subtitle) {
122        if (subtitle != null && mWindowDecorActionBar != null) {
123            Method setSubtitle = getMethod(mWindowActionBarClass, "setSubtitle", CharSequence.class);
124            invoke(setSubtitle, mWindowDecorActionBar, subtitle);
125        }
126    }
127
128    @Override
129    protected void setIcon(String icon) {
130        // Do this only if the action bar doesn't already have an icon.
131        if (icon != null && !icon.isEmpty() && mWindowDecorActionBar != null) {
132            if (invoke(getMethod(mWindowActionBarClass, "hasIcon"), mWindowDecorActionBar)
133                    == Boolean.TRUE) {
134                Drawable iconDrawable = getDrawable(icon, false);
135                if (iconDrawable != null) {
136                    Method setIcon = getMethod(mWindowActionBarClass, "setIcon", Drawable.class);
137                    invoke(setIcon, mWindowDecorActionBar, iconDrawable);
138                }
139            }
140        }
141    }
142
143    @Override
144    protected void setHomeAsUp(boolean homeAsUp) {
145        if (mWindowDecorActionBar != null) {
146            Method setHomeAsUp = getMethod(mWindowActionBarClass,
147                    "setDefaultDisplayHomeAsUpEnabled", boolean.class);
148            invoke(setHomeAsUp, mWindowDecorActionBar, homeAsUp);
149        }
150    }
151
152    @Override
153    public void createMenuPopup() {
154        // it's hard to add menus to appcompat's actionbar, since it'll use a lot of reflection.
155        // so we skip it for now.
156    }
157
158    @Nullable
159    private static Method getMethod(Class<?> owner, String name, Class<?>... parameterTypes) {
160        try {
161            return owner == null ? null : owner.getMethod(name, parameterTypes);
162        } catch (NoSuchMethodException e) {
163            e.printStackTrace();
164        }
165        return null;
166    }
167
168    @Nullable
169    private static Object invoke(Method method, Object owner, Object... args) {
170        try {
171            return method == null ? null : method.invoke(owner, args);
172        } catch (InvocationTargetException e) {
173            e.printStackTrace();
174        } catch (IllegalAccessException e) {
175            e.printStackTrace();
176        }
177        return null;
178    }
179
180    // TODO: this is duplicated from FrameworkActionBarWrapper$WindowActionBarWrapper
181    @Nullable
182    private Drawable getDrawable(@NonNull String name, boolean isFramework) {
183        RenderResources res = mBridgeContext.getRenderResources();
184        ResourceValue value = res.findResValue(name, isFramework);
185        value = res.resolveResValue(value);
186        if (value != null) {
187            return ResourceHelper.getDrawable(value, mBridgeContext);
188        }
189        return null;
190    }
191}
192