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 @ 165

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 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
        public ScriptingManager getManager(){
89
                return this.manager;
90
        }
91
        
92
        public ScriptingFolder getRoot(){
93
                return this.root;
94
        }
95
        
96
        public void addDefaultActionListener(ActionListener actionlistener) {
97
                this.defaultActionlistener = actionlistener;  
98
        }
99
        
100
        public void addSelectionActionListener(ActionListener actionlistener) {
101
                this.selectionActionlistener = actionlistener;  
102
        }
103
        
104
        public void addDropDownActionListener(ActionListener actionlistener) {
105
                this.dropDownActionlistener = actionlistener;  
106
        }
107
                
108
        private void makeUI(){
109
                //Creamos el nodo raíz
110
                String[] iconNames = root.getIconNames();
111
                rootNode = new DefaultMutableTreeNode(new IconData(
112
                                this.uimanager.getIcon(iconNames[0]),this.uimanager.getIcon(iconNames[1]), root)
113
                );
114

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

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

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

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

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

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

    
155
                        public void mouseEntered(MouseEvent arg0) {
156
                        }
157

    
158
                        public void mouseExited(MouseEvent arg0) {
159
                        }
160

    
161
                        public void mousePressed(MouseEvent arg0) {
162
                        }
163

    
164
                        public void mouseReleased(MouseEvent arg0) {
165
                        }
166
                });
167

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

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

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

    
216
                        ScriptingUnit subunit = null;
217

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

    
240
        /** 
241
         * Función para la inicialización de los datos del árbol.
242
         **/
243
        private void initializeTree(){
244

    
245
                ScriptingUnit unit = null;
246

    
247
                List files = this.root.getUnits();
248

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

    
254
                        IconData data = new IconData(
255
                                        uimanager.getIcon(iconNames[0]),
256
                                        uimanager.getIcon(iconNames[1]),
257
                                        unit
258
                        );
259

    
260
                        // Insertamos en el nodo raíz del árbol
261
                        this.addObject(this.rootNode,data);
262
                        }
263
                }
264

    
265
        }
266

    
267

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

    
276
        private DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
277
                        Object child) {
278
                return addObject(parent, child, false);
279
        }
280

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

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

    
300
                return childNode;
301
        }
302

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

    
313
                public IconData(Icon icon, Object data)
314
                {
315
                        m_icon = icon;
316
                        m_expandedIcon = null;
317
                        m_data = data;
318
                }
319

    
320
                public IconData(Icon icon, Icon expandedIcon, Object data)
321
                {
322
                        m_icon = icon;
323
                        m_expandedIcon = expandedIcon;
324
                        m_data = data;
325
                }
326

    
327
                public Icon getIcon() 
328
                { 
329
                        return m_icon;
330
                }
331

    
332
                public Icon getExpandedIcon() 
333
                { 
334
                        return m_expandedIcon!=null ? m_expandedIcon : m_icon;
335
                }
336

    
337
                public Object getObject() 
338
                { 
339
                        return m_data;
340
                }
341

    
342
                public String toString() 
343
                { 
344
                        return m_data.toString();
345
                }
346
        }
347

    
348
        private class IconCellRenderer extends JLabel implements TreeCellRenderer {
349

    
350
                /**
351
                 * 
352
                 */
353
                private static final long serialVersionUID = 1L;
354
                protected Color m_textSelectionColor;
355
                protected Color m_textNonSelectionColor;
356
                protected Color m_bkSelectionColor;
357
                protected Color m_bkNonSelectionColor;
358
                protected Color m_borderSelectionColor;
359

    
360
                protected boolean m_selected;
361

    
362
                public IconCellRenderer()
363
                {
364
                        super();
365
                        m_textSelectionColor = UIManager.getColor(
366
                        "Tree.selectionForeground");
367
                        m_textNonSelectionColor = UIManager.getColor(
368
                        "Tree.textForeground");
369
                        m_bkSelectionColor = UIManager.getColor(
370
                        "Tree.selectionBackground");
371
                        m_bkNonSelectionColor = UIManager.getColor(
372
                        "Tree.textBackground");
373
                        m_borderSelectionColor = UIManager.getColor(
374
                        "Tree.selectionBorderColor");
375
                        setOpaque(false);
376
                }
377

    
378
                public Component getTreeCellRendererComponent(JTree tree, 
379
                                Object value, boolean sel, boolean expanded, boolean leaf, 
380
                                int row, boolean hasFocus) 
381

    
382
                {
383
                        DefaultMutableTreeNode node = 
384
                                (DefaultMutableTreeNode)value;
385
                        Object obj = node.getUserObject();
386
                        setText(obj.toString());
387

    
388
                        if (obj instanceof Boolean)
389
                                setText("Retrieving data...");
390

    
391
                        if (obj instanceof IconData)
392
                        {
393
                                IconData idata = (IconData)obj;
394
                                if (expanded)
395
                                        setIcon(idata.getExpandedIcon());
396
                                else
397
                                        setIcon(idata.getIcon());
398
                        }
399
                        else
400
                                setIcon(null);
401

    
402
                        setFont(tree.getFont());
403
                        setForeground(sel ? m_textSelectionColor : 
404
                                m_textNonSelectionColor);
405
                        setBackground(sel ? m_bkSelectionColor : 
406
                                m_bkNonSelectionColor);
407
                        m_selected = sel;
408
                        return this;
409
                }
410

    
411
                public void paintComponent(Graphics g) 
412
                {
413
                        Color bColor = getBackground();
414
                        Icon icon = getIcon();
415

    
416
                        g.setColor(bColor);
417
                        int offset = 0;
418
                        if(icon != null && getText() != null) 
419
                                offset = (icon.getIconWidth() + getIconTextGap());
420
                        g.fillRect(offset, 0, getWidth() - 1 - offset,
421
                                        getHeight() - 1);
422

    
423
                        if (m_selected) 
424
                        {
425
                                g.setColor(m_borderSelectionColor);
426
                                g.drawRect(offset, 0, getWidth()-1-offset, getHeight()-1);
427
                        }
428
                        super.paintComponent(g);
429
                }
430
        }
431

    
432
}