summaryrefslogtreecommitdiff
path: root/smartdashboard/src/edu/wpi/first/smartdashboard/livewindow/elements/LWSubsystem.java
blob: d1d8ea06250f1013601f14ea72cbfc3401d54739 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package edu.wpi.first.smartdashboard.livewindow.elements;

import edu.wpi.first.smartdashboard.gui.MainPanel;
import edu.wpi.first.smartdashboard.gui.Widget;
import edu.wpi.first.smartdashboard.gui.elements.bindings.AbstractTableWidget;
import edu.wpi.first.smartdashboard.properties.Property;
import edu.wpi.first.smartdashboard.types.DataType;
import edu.wpi.first.smartdashboard.types.named.LWSubsystemType;
import edu.wpi.first.smartdashboard.xml.SmartDashboardXMLReader;
import edu.wpi.first.wpilibj.tables.ITable;
import edu.wpi.first.wpilibj.tables.ITableListener;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.SwingUtilities;

/**
 * The main player in the Live Window. Subsystems hold every component that
 * corresponds to that physical subsystem on the robot (e.g. a drive train would
 * contain speed controllers and encoders).
 *
 * @author Sam Carlberg
 */
public class LWSubsystem extends AbstractTableWidget {

    public static final DataType[] TYPES = {LWSubsystemType.get()};
    private BoxLayout layout;
    private Dimension preferredSize = new Dimension(100, 100);
    /**
     * An implementation of {@link MouseAdapter} that's responsible for dragging
     * widgets.
     */
    private Mouse mouse;
    /**
     * Whether or not it is possible to move widgets within a subsystem.
     */
    private static boolean editable = false;
    /**
     * A widget being dragged.
     */
    private Widget selected = null;
    /**
     * A list of components within this subsystem.
     */
    private final ArrayList<Widget> widgets = new ArrayList<Widget>(20);
    /**
     * Responsible for reading data from a save file.
     */
    private static SmartDashboardXMLReader reader;

    public LWSubsystem() {
        super(true);//listen for sub tables
        MainPanel.getPanel("LiveWindow").addSubsystem(this);
    }

    /**
     * Initializes this subsystem.
     */
    public void init() {
        layout = new BoxLayout(this, BoxLayout.Y_AXIS);
        setLayout(layout);
        setObstruction(true);
        setOpaque(true);
        setVisible(true);
        setBorder(BorderFactory.createTitledBorder(getFieldName()));
        mouse = new Mouse(this);
        addMouseListener(mouse);
        addMouseMotionListener(mouse);
    }

    private void addSubsystemElement(String key, ITable value) {
        // don't add duplicate widgets
        for (Widget widget : widgets) {
            if (widget != null && widget.getFieldName().equals(key))
                return;
        }
        try {
            System.out.println("\nSubsystem \"" + getFieldName() + "\" does not contain widget \"" + key + "\"");
            System.out.println("Table: " + value);
            System.out.println("Type: " + value.getString("~TYPE~"));
            System.out.println("Trying to add a widget of type \"" + DataType.getType(value) + "\" and key " + key);
            Class<? extends Widget> widgetClass = DataType.getType(value).getDefault();
            Widget widget = widgetClass.newInstance();
            widget.setFieldName(key);
            widget.setType(DataType.getType(value));
            widget.init();
            widget.setValue(value);
            widgets.add(widget);
            add(widget);
            preferredSize = layout.preferredLayoutSize(this);
            setPreferredSize(preferredSize);
            setMinimumSize(preferredSize);
            setSavedSize(preferredSize);
            setSize(preferredSize);
            System.out.println("New size [" + preferredSize.width + ", " + preferredSize.height + "]");
            revalidate();
            repaint();
            System.out.println();
        } catch (InstantiationException ex) {
            Logger.getLogger(LWSubsystem.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(LWSubsystem.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param source Required by ITableListener. Not used.
     * @param key The name of the changed table.
     * @param value The table that has been changed.
     * @param isNew Required by ITableListener. Not used.
     */
    @Override
    public void tableChanged(ITable source, final String key, final ITable table, boolean isNew) {
        boolean alreadyHasWidget = false;
        if (reader != null) {
            alreadyHasWidget = reader.containsWidgetOfName(this, key);
        }

        if (!alreadyHasWidget) {
            table.addTableListenerEx("~TYPE~", new ITableListener() {
                public void valueChanged(final ITable typeSource, final String typeKey, final Object typeValue, final boolean typeIsNew) {
                    table.removeTableListener(this);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            addSubsystemElement(key, table);
                        }
                    });
                }
            }, ITable.NOTIFY_IMMEDIATE | ITable.NOTIFY_LOCAL | ITable.NOTIFY_NEW | ITable.NOTIFY_UPDATE);
        }
    }

    /**
     * Sets the reader responsible for loading a save file.
     *
     * @param XMLreader
     */
    public static void setLoaded(SmartDashboardXMLReader XMLreader) {
        reader = XMLreader;
    }

    @Override
    public void propertyChanged(Property property) {
    }

    /**
     * Gets a widget at a specific point. Used for dragging.
     */
    public Widget getWidgetAt(Point p) {
        if (getComponentAt(p) instanceof Widget) {
            Widget w = (Widget) getComponentAt(p);
            return w;
        } else {
            return null;
        }
    }

    /**
     * Gets all the widgets contained within this subsystem.
     */
    public ArrayList<Widget> getWidgets() {
        return widgets;
    }

    /**
     * Adds the specified widget to this subsystem.
     *
     * @param widget The widget to add.
     */
    public void addWidget(Widget widget) {
        widgets.add(widget);
    }

    /**
     * Sets whether or not it is possible to edit subsystems.
     */
    public static void setEditable(boolean editable) {
        LWSubsystem.editable = editable;
    }

    /**
     * @return whether or not it is possible to edit subsystems.
     */
    public static boolean isEditable() {
        return editable;
    }

    /**
     * Used for DnD for widgets within a subsystem.
     */
    private class Mouse extends MouseAdapter {

        int yclick = 0;
        private final LWSubsystem subsystem;

        public Mouse(LWSubsystem subsystem) {
            this.subsystem = subsystem;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (editable) {
                if (selected == null) {
                    selected = getWidgetAt(e.getPoint());
                }
                if (selected != null) {

                    final int mouseY = e.getY(); // Mouse's y-coordinate. We don't care about its x-coord
                    int index = subsystem.getComponentZOrder(selected); // The index of the dragged widget
                    int newIndex = index + (mouseY < yclick ? -1 : 1); // The index to insert the dragged widget

                    boolean goingUp = false, // Flags for which direction the widget is being dragged
                            goingDown = false;

                    // Check to see if the new index is within acceptable bounds
                    if (newIndex >= 0 && newIndex < (subsystem.getComponentCount())) {
                        goingUp = newIndex < index;
                        goingDown = newIndex > index;
                    }

                    if (goingUp || goingDown) {
                        Component next = subsystem.getComponent(newIndex);

                        // If the stars align... move the widget
                        if ((goingDown && mouseY > next.getY() + next.getHeight())
                                || (goingUp && mouseY < next.getY())) {
                            subsystem.remove(selected);
                            subsystem.add(selected, newIndex);
                        }

                        subsystem.revalidate();
                        subsystem.repaint();
                    }
                }
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            yclick = e.getY();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            selected = null;
            yclick = 0;
        }
    }
}