1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.systemui.fragments;
16
17import android.app.Fragment;
18import android.content.Context;
19import android.util.Log;
20import android.view.View;
21
22import com.android.systemui.Dependency;
23import com.android.systemui.plugins.FragmentBase;
24import com.android.systemui.plugins.Plugin;
25import com.android.systemui.plugins.PluginListener;
26import com.android.systemui.plugins.PluginManager;
27
28public class PluginFragmentListener implements PluginListener<Plugin> {
29
30    private static final String TAG = "PluginFragmentListener";
31
32    private final FragmentHostManager mFragmentHostManager;
33    private final PluginManager mPluginManager;
34    private final Class<? extends Fragment> mDefaultClass;
35    private final Class<? extends FragmentBase> mExpectedInterface;
36    private final String mTag;
37
38    public PluginFragmentListener(View view, String tag, Class<? extends Fragment> defaultFragment,
39            Class<? extends FragmentBase> expectedInterface) {
40        mTag = tag;
41        mFragmentHostManager = FragmentHostManager.get(view);
42        mPluginManager = Dependency.get(PluginManager.class);
43        mExpectedInterface = expectedInterface;
44        mDefaultClass = defaultFragment;
45    }
46
47    public void startListening() {
48        mPluginManager.addPluginListener(this, mExpectedInterface,
49                false /* Only allow one */);
50    }
51
52    public void stopListening() {
53        mPluginManager.removePluginListener(this);
54    }
55
56    @Override
57    public void onPluginConnected(Plugin plugin, Context pluginContext) {
58        try {
59            mExpectedInterface.cast(plugin);
60            Fragment.class.cast(plugin);
61            mFragmentHostManager.getPluginManager().setCurrentPlugin(mTag,
62                    plugin.getClass().getName(), pluginContext);
63        } catch (ClassCastException e) {
64            Log.e(TAG, plugin.getClass().getName() + " must be a Fragment and implement "
65                    + mExpectedInterface.getName(), e);
66        }
67    }
68
69    @Override
70    public void onPluginDisconnected(Plugin plugin) {
71        mFragmentHostManager.getPluginManager().removePlugin(mTag,
72                plugin.getClass().getName(), mDefaultClass.getName());
73    }
74}
75