Statistics
| Revision:

gvsig-scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.swing / org.gvsig.scripting.swing.impl / src / main / java / org / gvsig / scripting / swing / impl / DefaultJScriptingBrowser.java @ 212

History | View | Annotate | Download (11.5 KB)

1
package org.gvsig.scripting.swing.impl;
2

    
3
import java.awt.Color;
4
import java.awt.Component;
5
import java.awt.Graphics;
6
import java.awt.GridLayout;
7
import java.awt.event.ActionEvent;
8
import java.awt.event.ActionListener;
9
import java.awt.event.MouseEvent;
10
import java.awt.event.MouseListener;
11
import java.util.List;
12

    
13
import javax.swing.Icon;
14
import javax.swing.JComponent;
15
import javax.swing.JLabel;
16
import javax.swing.JScrollPane;
17
import javax.swing.JTree;
18
import javax.swing.UIManager;
19
import javax.swing.event.TreeSelectionEvent;
20
import javax.swing.event.TreeSelectionListener;
21
import javax.swing.tree.DefaultMutableTreeNode;
22
import javax.swing.tree.DefaultTreeModel;
23
import javax.swing.tree.TreeCellRenderer;
24
import javax.swing.tree.TreePath;
25
import javax.swing.tree.TreeSelectionModel;
26

    
27
import org.gvsig.scripting.ScriptingBaseScript;
28
import org.gvsig.scripting.ScriptingFolder;
29
import org.gvsig.scripting.ScriptingManager;
30
import org.gvsig.scripting.ScriptingUnit;
31
import org.gvsig.scripting.swing.api.JScriptingBrowser;
32
import org.gvsig.scripting.swing.api.ScriptingUIManager;
33

    
34

    
35
public class DefaultJScriptingBrowser extends JScriptingBrowser{
36

    
37
        
38
        public static final int DEFAULT_ACTION = 1;
39
        public static final int SELECTION_ACTION = 2;
40
        public static final int DROPDOWN_ACTION = 3;
41
        /**
42
         * 
43
         */
44
        private static final long serialVersionUID = 1L;
45

    
46
        protected ScriptingUIManager uimanager;
47
        protected ScriptingManager manager;
48
        protected DefaultMutableTreeNode rootNode;
49
        protected DefaultTreeModel treeModel;
50
        protected JTree tree;
51
        protected ScriptingFolder root;
52
        protected ActionListener defaultActionlistener = null;
53
        protected ActionListener selectionActionlistener = null;
54
        protected ActionListener dropDownActionlistener = null;
55
        private final boolean foldersOnly;
56

    
57

    
58
        public static class BrowserActionEvent extends ActionEvent{
59
                /**
60
                 * 
61
                 */
62
                private static final long serialVersionUID = -1474410768278633364L;
63
                private ScriptingBaseScript script= null;
64
                
65
                public BrowserActionEvent(Object source, int id, String command, ScriptingBaseScript script) {
66
                        super(source,id,command);
67
                        this.script = script;
68
                }
69
                
70
                public ScriptingBaseScript getScript(){
71
                        return this.script;
72
                }
73
        }
74

    
75
        
76
        public DefaultJScriptingBrowser(ScriptingUIManager uimanager,ScriptingFolder root) {
77
                this(uimanager,root,false);
78
        }
79
        public DefaultJScriptingBrowser(ScriptingUIManager uimanager,ScriptingFolder root, boolean foldersOnly) {
80
                super(new GridLayout(1,2));
81
                this.foldersOnly = foldersOnly;
82
                this.uimanager = uimanager;
83
                this.manager = uimanager.getManager();
84
                this.root = root;
85
                this.makeUI();        
86
        }
87
        
88
        @Override
89
    public ScriptingManager getManager(){
90
                return this.manager;
91
        }
92
        
93
        @Override
94
    public ScriptingFolder getRoot(){
95
                return this.root;
96
        }
97
        
98
        public void addDefaultActionListener(ActionListener actionlistener) {
99
                this.defaultActionlistener = actionlistener;  
100
        }
101
        
102
        public void addSelectionActionListener(ActionListener actionlistener) {
103
                this.selectionActionlistener = actionlistener;  
104
        }
105
        
106
        public void addDropDownActionListener(ActionListener actionlistener) {
107
                this.dropDownActionlistener = actionlistener;  
108
        }
109
                
110
        private void makeUI(){
111
                //Creamos el nodo raíz
112
                String[] iconNames = root.getIconNames();
113
                rootNode = new DefaultMutableTreeNode(new IconData(
114
                                this.uimanager.getIcon(iconNames[0]),this.uimanager.getIcon(iconNames[1]), root)
115
                );
116

    
117
                // Lo asignamos al modelo del árbol e iniciamos el árbol con ese modelo
118
                treeModel = new DefaultTreeModel(rootNode);
119
                tree = new JTree(treeModel);
120

    
121
                // Cargamos la información inicial del árbol
122
                this.initializeTree();
123

    
124
                // Para asignar iconos especiales según el tipo de objeto
125
                TreeCellRenderer renderer = new IconCellRenderer();
126
                tree.setCellRenderer(renderer);
127

    
128
                //Para marcar que no son editables sus propiedades o nodos
129
                tree.setEditable(false);
130

    
131
                //Determina que sólo se puede seleccionar una linea
132
                tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
133

    
134
                // Añadimos un listener que se ejecutará cuando seleccionemos un elemento del árbol
135
                tree.addTreeSelectionListener(new TreeSelectionListener() {
136
                        public void valueChanged(TreeSelectionEvent e) {        
137
                                loadChildrenLazily(e.getPath());
138
                                if(selectionActionlistener!=null){
139
                                        JComponent tree = (JComponent) e.getSource();
140
                                        ActionEvent event = new BrowserActionEvent(tree.getParent(),SELECTION_ACTION,"select",null);
141
                                        selectionActionlistener.actionPerformed(event);
142
                                }
143
                        }
144
                });
145
                tree.addMouseListener(new MouseListener() {
146
                        public void mouseClicked(MouseEvent arg0) {
147
                                if (arg0.getClickCount() == 2) {
148
                                        JTree tree = (JTree) arg0.getSource();
149
                                        
150
                                                if(!tree.isSelectionEmpty()){
151
                                                        startingScript(tree.getSelectionPath());
152
                                                }
153
                                        
154
                                }
155
                        }
156

    
157
                        public void mouseEntered(MouseEvent arg0) {
158
                        }
159

    
160
                        public void mouseExited(MouseEvent arg0) {
161
                        }
162

    
163
                        public void mousePressed(MouseEvent arg0) {
164
                        }
165

    
166
                        public void mouseReleased(MouseEvent arg0) {
167
                        }
168
                });
169

    
170
                //Indica si el nodo raíz actúa como un nodo más o queda desplegado de manera fija
171
                tree.setShowsRootHandles(true);
172

    
173
                //Añadimos el Scroll
174
                JScrollPane scrollPane = new JScrollPane(tree);
175
                add(scrollPane);
176
                        
177
        }
178
        
179
        @Override
180
    public ScriptingUnit getSelectedNode(){
181
                DefaultMutableTreeNode node;
182
                if(tree.getSelectionPath()!=null){
183
                        node = (DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
184
                }else{
185
                        node = this.rootNode;
186
                }
187
                return ((ScriptingUnit)((IconData)(node.getUserObject())).m_data);
188
        }
189
        
190
        private void startingScript(TreePath path){
191
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
192
                ScriptingUnit unit = ((ScriptingUnit)((IconData)(node.getUserObject())).m_data);
193
                
194
                if (unit instanceof ScriptingBaseScript){
195
                        if(this.defaultActionlistener!=null){
196
                                ActionEvent event = new BrowserActionEvent(this,DEFAULT_ACTION,"default", (ScriptingBaseScript) unit);
197
                                this.defaultActionlistener.actionPerformed(event);
198
                        }
199
                }
200
        }
201
        
202

    
203
        /** 
204
         * Función para el despliegue de los hijos de un nodo bajo demanda. 
205
         **/ 
206
        private void loadChildrenLazily(TreePath path){
207
                // Mediante el path recuperamos el último nodo, del que
208
                // queremos obtener sus hijos dinámicamente
209
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
210
                ScriptingUnit unit = ((ScriptingUnit)((IconData)(node.getUserObject())).m_data);
211
                
212
        List<ScriptingUnit> files = null;
213
                
214
                // Si es un ScriptingFolder y no hemos obtenido previamente sus hijos
215
                if (unit instanceof ScriptingFolder && node.getChildCount() == 0){
216
                        // Obtenemos los hijos
217
                        files = ((ScriptingFolder)unit).getUnits();
218

    
219
                        ScriptingUnit subunit = null;
220

    
221
                        for (int i = 0; i < files.size(); i++){
222
                                subunit = files.get(i);
223
                                if((this.foldersOnly && subunit instanceof ScriptingFolder) || !this.foldersOnly){
224
                                        // Obtenemos los iconos específicos para ese tipo de objeto
225
                                        String[] iconNames = subunit.getIconNames();
226
                                        
227
                                        // Creamos el objeto IconData, con la información
228
                                        // del objeto y de hasta 2 iconos asociados
229
                                        IconData data = new IconData(
230
                                                        this.uimanager.getIcon(iconNames[0]),
231
                                                        this.uimanager.getIcon(iconNames[1]),
232
                                                        subunit
233
                                        );
234
        
235
                                        // Insertamos en el árbol el nuevo objeto creado
236
                                        addObject(node,data);
237
                                }
238
                        }
239
                }
240
                
241
        }
242

    
243
        /** 
244
         * Función para la inicialización de los datos del árbol.
245
         **/
246
        private void initializeTree(){
247

    
248
                ScriptingUnit unit = null;
249

    
250
        List<ScriptingUnit> files = this.root.getUnits();
251

    
252
                for (int i = 0; i < files.size(); i++){
253
                        unit = files.get(i);
254
                        if((this.foldersOnly && unit instanceof ScriptingFolder) || !this.foldersOnly){
255
                        String[] iconNames = unit.getIconNames();
256

    
257
                        IconData data = new IconData(
258
                                        uimanager.getIcon(iconNames[0]),
259
                                        uimanager.getIcon(iconNames[1]),
260
                                        unit
261
                        );
262

    
263
                        // Insertamos en el nodo raíz del árbol
264
                        this.addObject(this.rootNode,data);
265
                        }
266
                }
267

    
268
        }
269

    
270

    
271
        /** 
272
         * Función para añadir un hijo al nodo actual. 
273
         **/
274
//        private DefaultMutableTreeNode addObject(Object child) {
275
//                DefaultMutableTreeNode parentNode = rootNode;
276
//                return addObject(parentNode, child, true);
277
//        }
278

    
279
        private DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
280
                        Object child) {
281
                return addObject(parent, child, false);
282
        }
283

    
284
        private DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
285
                        Object child, 
286
                        boolean shouldBeVisible) {
287
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
288
                
289
                // Si no especificamos padre, lo colgará del raíz
290
                if (parent == null) {
291
                        parent = rootNode;
292
                }
293
                
294
                // Insertamos el nuevo nodo en el modelo del árbol
295
                treeModel.insertNodeInto(childNode, parent, 
296
                                parent.getChildCount());
297

    
298
                // Para que el usuario pueda ver el nuevo nodo
299
                if (shouldBeVisible) {
300
                        tree.scrollPathToVisible(new TreePath(childNode.getPath()));
301
                }
302

    
303
                return childNode;
304
        }
305

    
306
        /**
307
         * Clase IconData permite asociar hasta dos iconos (para 
308
         * cuando está expandido y cuando no) a un objeto del árbol
309
         **/
310
        static private class IconData
311
        {
312
                protected Icon   m_icon;
313
                protected Icon   m_expandedIcon;
314
                protected Object m_data;
315

    
316
                public IconData(Icon icon, Icon expandedIcon, Object data)
317
                {
318
                        m_icon = icon;
319
                        m_expandedIcon = expandedIcon;
320
                        m_data = data;
321
                }
322

    
323
                public Icon getIcon() 
324
                { 
325
                        return m_icon;
326
                }
327

    
328
                public Icon getExpandedIcon() 
329
                { 
330
                        return m_expandedIcon!=null ? m_expandedIcon : m_icon;
331
                }
332

    
333
                @Override
334
        public String toString() 
335
                { 
336
                        return m_data.toString();
337
                }
338
        }
339

    
340
        private class IconCellRenderer extends JLabel implements TreeCellRenderer {
341

    
342
                /**
343
                 * 
344
                 */
345
                private static final long serialVersionUID = 1L;
346
                protected Color m_textSelectionColor;
347
                protected Color m_textNonSelectionColor;
348
                protected Color m_bkSelectionColor;
349
                protected Color m_bkNonSelectionColor;
350
                protected Color m_borderSelectionColor;
351

    
352
                protected boolean m_selected;
353

    
354
                public IconCellRenderer()
355
                {
356
                        super();
357
                        m_textSelectionColor = UIManager.getColor(
358
                        "Tree.selectionForeground");
359
                        m_textNonSelectionColor = UIManager.getColor(
360
                        "Tree.textForeground");
361
                        m_bkSelectionColor = UIManager.getColor(
362
                        "Tree.selectionBackground");
363
                        m_bkNonSelectionColor = UIManager.getColor(
364
                        "Tree.textBackground");
365
                        m_borderSelectionColor = UIManager.getColor(
366
                        "Tree.selectionBorderColor");
367
                        setOpaque(false);
368
                }
369

    
370
                public Component getTreeCellRendererComponent(JTree tree, 
371
                                Object value, boolean sel, boolean expanded, boolean leaf, 
372
                                int row, boolean hasFocus) 
373

    
374
                {
375
                        DefaultMutableTreeNode node = 
376
                                (DefaultMutableTreeNode)value;
377
                        Object obj = node.getUserObject();
378
                        setText(obj.toString());
379

    
380
                        if (obj instanceof Boolean)
381
                                setText("Retrieving data...");
382

    
383
                        if (obj instanceof IconData)
384
                        {
385
                                IconData idata = (IconData)obj;
386
                                if (expanded)
387
                                        setIcon(idata.getExpandedIcon());
388
                                else
389
                                        setIcon(idata.getIcon());
390
                        }
391
                        else
392
                                setIcon(null);
393

    
394
                        setFont(tree.getFont());
395
                        setForeground(sel ? m_textSelectionColor : 
396
                                m_textNonSelectionColor);
397
                        setBackground(sel ? m_bkSelectionColor : 
398
                                m_bkNonSelectionColor);
399
                        m_selected = sel;
400
                        return this;
401
                }
402

    
403
                @Override
404
        public void paintComponent(Graphics g) 
405
                {
406
                        Color bColor = getBackground();
407
                        Icon icon = getIcon();
408

    
409
                        g.setColor(bColor);
410
                        int offset = 0;
411
                        if(icon != null && getText() != null) 
412
                                offset = (icon.getIconWidth() + getIconTextGap());
413
                        g.fillRect(offset, 0, getWidth() - 1 - offset,
414
                                        getHeight() - 1);
415

    
416
                        if (m_selected) 
417
                        {
418
                                g.setColor(m_borderSelectionColor);
419
                                g.drawRect(offset, 0, getWidth()-1-offset, getHeight()-1);
420
                        }
421
                        super.paintComponent(g);
422
                }
423
        }
424

    
425
}