Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.symbology / org.gvsig.symbology.swing / org.gvsig.symbology.swing.api / src / main / java / org / gvsig / app / gui / styling / StyleSelector.java @ 41238

History | View | Annotate | Download (15 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
/* CVS MESSAGES:
25
*
26
* $Id: StyleSelector.java 30289 2009-07-31 11:10:41Z jpiera $
27
* $Log$
28
* Revision 1.11  2007-08-21 09:32:53  jvidal
29
* javadoc
30
*
31
* Revision 1.10  2007/05/31 09:36:22  jaume
32
* *** empty log message ***
33
*
34
* Revision 1.9  2007/05/10 09:47:50  jaume
35
* *** empty log message ***
36
*
37
* Revision 1.8  2007/05/08 15:44:07  jaume
38
* *** empty log message ***
39
*
40
* Revision 1.7  2007/04/27 12:10:17  jaume
41
* *** empty log message ***
42
*
43
* Revision 1.6  2007/04/11 16:02:43  jaume
44
* file filter
45
*
46
* Revision 1.5  2007/04/05 16:08:34  jaume
47
* Styled labeling stuff
48
*
49
* Revision 1.4  2007/04/04 16:01:14  jaume
50
* *** empty log message ***
51
*
52
* Revision 1.2  2007/03/09 11:25:00  jaume
53
* Advanced symbology (start committing)
54
*
55
* Revision 1.1.2.4  2007/02/21 07:35:14  jaume
56
* *** empty log message ***
57
*
58
* Revision 1.1.2.3  2007/02/08 15:43:04  jaume
59
* some bug fixes in the editor and removed unnecessary imports
60
*
61
* Revision 1.1.2.2  2007/01/30 18:10:10  jaume
62
* start commiting labeling stuff
63
*
64
* Revision 1.1.2.1  2007/01/26 13:49:03  jaume
65
* *** empty log message ***
66
*
67
*
68
*/
69
package org.gvsig.app.gui.styling;
70

    
71
import java.awt.BorderLayout;
72
import java.awt.Color;
73
import java.awt.Component;
74
import java.awt.Dimension;
75
import java.awt.FlowLayout;
76
import java.awt.event.ActionEvent;
77
import java.awt.event.ActionListener;
78
import java.io.File;
79
import java.io.FileOutputStream;
80
import java.io.FileWriter;
81
import java.util.prefs.Preferences;
82

    
83
import javax.swing.BorderFactory;
84
import javax.swing.BoxLayout;
85
import javax.swing.JComponent;
86
import javax.swing.JFileChooser;
87
import javax.swing.JLabel;
88
import javax.swing.JList;
89
import javax.swing.JOptionPane;
90
import javax.swing.JPanel;
91
import javax.swing.JTextField;
92
import javax.swing.ListCellRenderer;
93
import javax.swing.ListModel;
94
import javax.swing.event.ListSelectionEvent;
95
import javax.swing.event.ListSelectionListener;
96

    
97
import org.exolab.castor.xml.Marshaller;
98
import org.slf4j.Logger;
99
import org.slf4j.LoggerFactory;
100

    
101
import org.gvsig.andami.PluginServices;
102
import org.gvsig.andami.messages.NotificationManager;
103
import org.gvsig.app.gui.JComboBoxUnits;
104
import org.gvsig.app.gui.panels.ImageSizePanel;
105
import org.gvsig.fmap.mapcontext.MapContextLocator;
106
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
107
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
108
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.ILabelStyle;
109
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
110
import org.gvsig.gui.beans.AcceptCancelPanel;
111
import org.gvsig.gui.beans.controls.dnd.JDnDList;
112
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
113
import org.gvsig.i18n.Messages;
114
import org.gvsig.tools.ToolsLocator;
115
import org.gvsig.tools.persistence.PersistenceManager;
116
import org.gvsig.tools.persistence.PersistentState;
117
import org.gvsig.utils.XMLEntity;
118

    
119

    
120
/**
121
 * Creates a panel where the user can select a style for an object that allows
122
 * to manage this property.This panel will be similar to the symbol selector panel
123
 * and, on it, the user will have a previsualization of the style of objects
124
 * stored and posibilities to modify an existing one, to create a new one
125
 * and so on.
126
 *
127
 * @author jaume dominguez faus - jaume.dominguez@iver.es
128
 *
129
 */
130
public class StyleSelector extends SymbolSelector {
131
    
132
    private static final Logger logger = LoggerFactory.getLogger(StyleSelector.class);
133
    
134
        private static final long serialVersionUID = -7476555713446755512L;
135
        private ImageSizePanel isp;
136

    
137
        public StyleSelector(IStyle style, int shapeType)
138
                        throws IllegalArgumentException {
139
                
140
                this(style, shapeType, new SelectorFilter() {
141
                        public boolean accepts(Object obj) {
142
                                return obj instanceof IStyle;
143
                        }
144
                });
145
        }
146
        /**
147
         * Constructor method
148
         *
149
         * @param style
150
         * @param shapeType
151
         * @param filter
152
         */
153
        public StyleSelector(IStyle style, int shapeType, SelectorFilter filter)
154
        throws IllegalArgumentException {
155
                
156
                super(null, shapeType, filter, false);
157

    
158
                rootDir = new File(
159
                                MapContextLocator.getSymbolManager().getSymbolPreferences()
160
                                .getSymbolLibraryPath());
161
                
162
            // Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
163
                // rootDir = new File(prefs.get("SymbolStylesFolder",
164
                // System.getProperty("user.home")+"/gvSIG/Styles"));
165
                
166
                if (!rootDir.exists())
167
                        rootDir.mkdir();
168

    
169
                initialize(style);
170
                
171
                lblTitle.setText(Messages.getText("label_styles"));
172
                treeRootName = Messages.getText("style_library");
173

    
174
        }
175

    
176
        @Override
177
        protected void initialize(Object currentElement) throws IllegalArgumentException {
178
            library = new StyleLibrary(rootDir);
179

    
180
            this.setLayout(new BorderLayout());
181
            this.setSize(400, 221);
182

    
183
            this.add(getJNorthPanel(), BorderLayout.NORTH);
184
            this.add(getJSplitPane(), BorderLayout.CENTER);
185
            this.add(getJEastPanel(), BorderLayout.EAST);
186
            ActionListener okAction = new ActionListener() {
187
                    public void actionPerformed(ActionEvent e) {
188
                            accepted = true;
189
                            PluginServices.getMDIManager().closeWindow(StyleSelector.this);
190
                    }
191
            }, cancelAction = new ActionListener() {
192
                    public void actionPerformed(ActionEvent e) {
193
                            setSymbol(null);
194
                            PluginServices.getMDIManager().closeWindow(StyleSelector.this);
195
                    }
196
            };
197

    
198
            okCancelPanel = new AcceptCancelPanel();
199
            okCancelPanel.setOkButtonActionListener(okAction);
200
            okCancelPanel.setCancelButtonActionListener(cancelAction);
201

    
202
            this.add(okCancelPanel, BorderLayout.SOUTH);
203
            libraryBrowser.setSelectionRow(0);
204

    
205
            SillyDragNDropAction dndAction = new SillyDragNDropAction();
206
            libraryBrowser.addMouseListener(dndAction);
207
            libraryBrowser.addMouseMotionListener(dndAction);
208
            getJListSymbols().addMouseListener(dndAction);
209
            getJListSymbols().addMouseMotionListener(dndAction);
210
            setSymbol(currentElement);
211
    }
212

    
213
        @Override
214
        public void setSymbol(Object style) {
215
                ((StylePreviewer) jPanelPreview).setStyle((IStyle) style);
216
                updateOptionsPanel();
217
        }
218

    
219
        @Override
220
        public Object getSelectedObject() {
221
                if (!accepted) return null;
222
                Object mySelectedElement = ((StylePreviewer) jPanelPreview).getStyle();
223

    
224
                if (mySelectedElement instanceof CartographicSupport) {
225
                        CartographicSupport csSym = (CartographicSupport) mySelectedElement;
226
                        csSym.setUnit(cmbUnits.getSelectedUnitIndex());
227
                        csSym.setReferenceSystem(cmbReferenceSystem.getSelectedIndex());
228
                }
229

    
230
                return mySelectedElement;
231
        }
232

    
233
        protected ListModel newListModel() {
234
                StyleSelectorListModel listModel = new StyleSelectorListModel(
235
                                dir,
236
                                sFilter,
237
                                StyleSelectorListModel.STYLE_FILE_EXTENSION);
238
                return listModel;
239

    
240
        }
241

    
242
        protected JPanel getJPanelOptions() {
243
                if (jPanelOptions == null) {
244
                        jPanelOptions = new GridBagLayoutPanel();
245
                        jPanelOptions.setBorder(BorderFactory.createTitledBorder(null, Messages.getText("options")));
246
                        jPanelOptions.addComponent(getImageSizePanel());
247
                        jPanelOptions.addComponent(Messages.getText("units"),
248
                                        cmbUnits = new JComboBoxUnits(true));
249
                        jPanelOptions.addComponent("",
250
                                        cmbReferenceSystem = new JComboBoxUnitsReferenceSystem());
251
                }
252
            return jPanelOptions;
253
    }
254

    
255
        /**
256
         *
257
     * This method initializes ImageSizePanel
258
     *
259
     * @return isp ImageSizePanel
260
     */
261
         private ImageSizePanel getImageSizePanel() {
262
                 if (isp == null) {
263
                        isp = new ImageSizePanel();
264
                        isp.addActionListener(new ActionListener() {
265
                                public void actionPerformed(ActionEvent e) {
266
                                        ILabelStyle st = (ILabelStyle) getSelectedObject();
267
                                        if (st != null) {
268
                                                double[] sz = isp.getImageDimension();
269
                                                st.setSize(sz[0], sz[1]);
270
                                        }
271
                                }
272
                        });
273
                }
274

    
275
                return isp;
276
        }
277

    
278
        protected void updateOptionsPanel() {
279
                IStyle s = ((StylePreviewer) jPanelPreview).getStyle();
280
            if (s instanceof ILabelStyle) {
281
                        ILabelStyle lab = (ILabelStyle) s;
282
                        Dimension sz = lab.getSize();
283
                        getImageSizePanel().setImageSize(sz);
284
                }
285
         }
286

    
287

    
288
    /**
289
     * This method initializes jList
290
     *
291
     * @return javax.swing.JList
292
     */
293
    protected JList getJListSymbols() {
294
            if (jListSymbols == null) {
295
                    jListSymbols = new JDnDList();
296
                    jListSymbols.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
297
            jListSymbols.setLayoutOrientation(JList.HORIZONTAL_WRAP);
298
            jListSymbols.setVisibleRowCount(-1);
299
            jListSymbols.addListSelectionListener(new ListSelectionListener() {
300
                    public void valueChanged(ListSelectionEvent e) {
301
                            setStyle(jListSymbols.getSelectedValue());
302
                            updateOptionsPanel();
303
                    }
304
            });
305
            ListCellRenderer renderer = new ListCellRenderer() {
306
                        private Color mySelectedBGColor = new Color(255,145,100,255);
307
                            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
308
                                    IStyle sty = (IStyle) value;
309
                                    JPanel pnl = new JPanel();
310
                                    BoxLayout layout = new BoxLayout(pnl, BoxLayout.Y_AXIS);
311
                                    pnl.setLayout(layout);
312
                                    Color bgColor = (isSelected) ? mySelectedBGColor
313
                                                             : getJListSymbols().getBackground();
314

    
315
                                    pnl.setBackground(bgColor);
316
                                    StylePreviewer sp = new StylePreviewer();
317
                                    sp.setShowOutline(false);
318
                                    sp.setAlignmentX(Component.CENTER_ALIGNMENT);
319
                                    sp.setPreferredSize(new Dimension(50, 50));
320
                                    sp.setStyle(sty);
321
                                    sp.setBackground(bgColor);
322
                                    pnl.add(sp);
323
                                    JLabel lbl = new JLabel(sty.getDescription());
324
                                    lbl.setBackground(bgColor);
325
                                    lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
326
                                    pnl.add(lbl);
327

    
328
                                    return pnl;
329
                            }
330

    
331
                };
332
                jListSymbols.setCellRenderer(renderer);
333
            }
334
            return jListSymbols;
335
    }
336
    /**
337
     * Modify the previsualization showed in the panel with the style of the
338
     * new object selected.
339
     *
340
     * @param selectedValue
341
     */
342
   protected void setStyle(Object selectedValue) {
343
                //selectedElement = selectedValue;
344
                ((StylePreviewer) jPanelPreview).setStyle((IStyle) selectedValue);
345
                doLayout();
346
                repaint();
347
        }
348

    
349
        protected void propertiesPressed() {
350
                StyleEditor se = new StyleEditor((IStyle) getSelectedObject());
351
                PluginServices.getMDIManager().addWindow(se);
352
                setStyle(se.getStyle());
353
        }
354

    
355
        protected void savePressed() {
356
                if (getSelectedObject() ==null)
357
                        return;
358

    
359
                JFileChooser jfc = new JFileChooser(rootDir);
360
                javax.swing.filechooser.FileFilter ff = new javax.swing.filechooser.FileFilter() {
361
                        public boolean accept(File f) {
362
                                return f.getAbsolutePath().
363
                                toLowerCase().
364
                                endsWith(StyleSelectorListModel.STYLE_FILE_EXTENSION);
365
                        }
366

    
367
                        public String getDescription() {
368
                                return Messages.getText("gvSIG_style_definition_file")+ " ("+StyleSelectorListModel.STYLE_FILE_EXTENSION+")";
369
                        }
370
                };
371
                jfc.setFileFilter(ff);
372
                JPanel accessory = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
373
                accessory.add(new JLabel(Messages.getText("enter_description")));
374
                JTextField txtDesc = new JTextField(25);
375
                txtDesc.setText(((IStyle) getSelectedObject()).getDescription());
376
                accessory.add(txtDesc);
377
                jfc.setAccessory(accessory);
378
                if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
379
                        File targetFile = jfc.getSelectedFile();
380

    
381
                        String fExtension = StyleSelectorListModel.STYLE_FILE_EXTENSION;
382

    
383
                        // apply description
384
                        String desc;
385
                        if (txtDesc.getText()==null || txtDesc.getText().trim().equals("")) {
386
                                // default to file name
387
                                String s = targetFile.getAbsolutePath();
388
                                desc = s.substring(s.lastIndexOf(File.separator)+1).replaceAll(fExtension, "");
389
                        } else {
390
                                desc = txtDesc.getText().trim();
391
                        }
392
                        IStyle s = (IStyle) getSelectedObject();
393
                        s.setDescription(desc);
394

    
395
                        // save it
396

    
397
                        if (!targetFile.
398
                                        getAbsolutePath().
399
                                        toLowerCase().
400
                                        endsWith(fExtension)) {
401
                            
402
                            targetFile = new File(targetFile.getAbsolutePath() + fExtension);
403
                        }
404

    
405
                        if(targetFile.exists()){
406
                                int resp = JOptionPane.showConfirmDialog(
407
                                                (Component) PluginServices.getMainFrame(),
408
                                                Messages.getText("fichero_ya_existe_seguro_desea_guardarlo"),
409
                                                Messages.getText("guardar"), JOptionPane.YES_NO_OPTION);
410
                                if (resp != JOptionPane.YES_OPTION) {
411
                                        return;
412
                                }
413
                        }
414
                        
415
                        // the object to persist is 's'
416
                        try {
417
                            
418
                            PersistenceManager pman = ToolsLocator.getPersistenceManager();
419
                            PersistentState psta = pman.getState(s, true);
420
                    if (psta.getContext().getErrors() != null) {
421
                        throw psta.getContext().getErrors();
422
                    }
423
                    FileOutputStream fos = new FileOutputStream(targetFile);
424
                    pman.saveState(psta, fos);
425
                    fos.close();
426

    
427
                        } catch (Exception ex) {
428
                                NotificationManager.addError(
429
                                                Messages.getText("save_error"), ex);
430
                        }
431
                        getJListSymbols().setModel(newListModel());
432
                }
433
        }
434
        
435
        protected void newPressed() {
436
        IStyle curr_sty = ((StylePreviewer) jPanelPreview).getStyle();
437
        
438
        try {
439
            curr_sty = (IStyle) curr_sty.clone();
440
        } catch (Exception cnse) {
441
            logger.info("Unable to clone style. "
442
                + "This can cause an empty style if user cancels dialog.",
443
                cnse);
444
        }
445

    
446
         StyleEditor se = new StyleEditor(curr_sty);
447
        PluginServices.getMDIManager().addWindow(se);
448
        this.setStyle(se.getStyle());
449
    }
450
        
451
    /**
452
     * This method initializes jPanelPreview
453
     *
454
     * @return javax.swing.JComponent
455
     */
456
    protected JComponent getJPanelPreview() {
457
            if (jPanelPreview == null) {
458
                    jPanelPreview = new StylePreviewer();
459
                    jPanelPreview.setPreferredSize(new java.awt.Dimension(100,100));
460
                    jPanelPreview.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
461
                    ((StylePreviewer) jPanelPreview).setShowOutline(true);
462
            }
463
            return jPanelPreview;
464
    }
465

    
466
    @Override
467
    public void actionPerformed(ActionEvent e) {
468
            if (!act) return;
469
                Object selectedElement = ((StylePreviewer) jPanelPreview).getStyle();//getSelectedObject();
470
                performActionOn(selectedElement, e);
471
                StyleSelector.this.repaint();
472
    }
473

    
474
    public int getUnit() {
475
            return cmbUnits.getSelectedUnitIndex();
476
    }
477

    
478
    public int getReferenceSystem() {
479
            return cmbReferenceSystem.getSelectedIndex();
480
    }
481

    
482
        public void setUnit(int unit) {
483
                cmbUnits.setSelectedUnitIndex(unit);
484
        }
485

    
486
        public void setReferenceSystem(int referenceSystem) {
487
                cmbReferenceSystem.setSelectedIndex(referenceSystem);
488
        }
489
}