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.hierarchyviewer.util;
18
19import com.android.hierarchyviewerlib.actions.ImageAction;
20
21import org.eclipse.jface.action.Action;
22import org.eclipse.jface.util.IPropertyChangeListener;
23import org.eclipse.jface.util.PropertyChangeEvent;
24import org.eclipse.swt.SWT;
25import org.eclipse.swt.events.SelectionEvent;
26import org.eclipse.swt.events.SelectionListener;
27import org.eclipse.swt.widgets.Button;
28import org.eclipse.swt.widgets.Composite;
29
30public class ActionButton implements IPropertyChangeListener, SelectionListener {
31    private Button mButton;
32
33    private Action mAction;
34
35    public ActionButton(Composite parent, ImageAction action) {
36        this.mAction = (Action) action;
37        if (this.mAction.getStyle() == Action.AS_CHECK_BOX) {
38            mButton = new Button(parent, SWT.CHECK);
39        } else {
40            mButton = new Button(parent, SWT.PUSH);
41        }
42        mButton.setText(action.getText());
43        mButton.setImage(action.getImage());
44        this.mAction.addPropertyChangeListener(this);
45        mButton.addSelectionListener(this);
46        mButton.setToolTipText(action.getToolTipText());
47        mButton.setEnabled(this.mAction.isEnabled());
48    }
49
50    @Override
51    public void propertyChange(PropertyChangeEvent e) {
52        if (e.getProperty().toUpperCase().equals("ENABLED")) { //$NON-NLS-1$
53            mButton.setEnabled((Boolean) e.getNewValue());
54        } else if (e.getProperty().toUpperCase().equals("CHECKED")) { //$NON-NLS-1$
55            mButton.setSelection(mAction.isChecked());
56        }
57    }
58
59    public void setLayoutData(Object data) {
60        mButton.setLayoutData(data);
61    }
62
63    @Override
64    public void widgetDefaultSelected(SelectionEvent e) {
65        // pass
66    }
67
68    @Override
69    public void widgetSelected(SelectionEvent e) {
70        if (mAction.getStyle() == Action.AS_CHECK_BOX) {
71            mAction.setChecked(mButton.getSelection());
72        }
73        mAction.run();
74    }
75
76    public void addSelectionListener(SelectionListener listener) {
77        mButton.addSelectionListener(listener);
78    }
79
80    public void setVisible(boolean visible) {
81        mButton.setVisible(visible);
82    }
83}
84