9e0925b73bfb30e68275758c9a6c674b468fd975
[jalview.git] / src / jalview / gui / FeatureSettings.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package jalview.gui;
20
21 import java.io.*;
22 import java.util.*;
23 import java.util.List;
24 import java.awt.*;
25 import java.awt.event.*;
26 import java.beans.PropertyChangeEvent;
27 import java.beans.PropertyChangeListener;
28
29 import javax.swing.*;
30 import javax.swing.event.*;
31 import javax.swing.table.*;
32
33 import jalview.analysis.AlignmentSorter;
34 import jalview.bin.Cache;
35 import jalview.commands.OrderCommand;
36 import jalview.datamodel.*;
37 import jalview.io.*;
38 import jalview.schemes.AnnotationColourGradient;
39 import jalview.schemes.GraduatedColor;
40 import jalview.util.MessageManager;
41 import jalview.ws.dbsources.das.api.jalviewSourceI;
42
43 public class FeatureSettings extends JPanel
44 {
45   DasSourceBrowser dassourceBrowser;
46
47   jalview.ws.DasSequenceFeatureFetcher dasFeatureFetcher;
48
49   JPanel settingsPane = new JPanel();
50
51   JPanel dasSettingsPane = new JPanel();
52
53   final FeatureRenderer fr;
54
55   public final AlignFrame af;
56
57   Object[][] originalData;
58
59   final JInternalFrame frame;
60
61   JScrollPane scrollPane = new JScrollPane();
62
63   JTable table;
64
65   JPanel groupPanel;
66
67   JSlider transparency = new JSlider();
68
69   JPanel transPanel = new JPanel(new GridLayout(1, 2));
70
71   public FeatureSettings(AlignFrame af)
72   {
73     this.af = af;
74     fr = af.getFeatureRenderer();
75
76     transparency.setMaximum(100 - (int) (fr.transparency * 100));
77
78     try
79     {
80       jbInit();
81     } catch (Exception ex)
82     {
83       ex.printStackTrace();
84     }
85
86     table = new JTable();
87     table.getTableHeader().setFont(new Font("Verdana", Font.PLAIN, 12));
88     table.setFont(new Font("Verdana", Font.PLAIN, 12));
89     table.setDefaultRenderer(Color.class, new ColorRenderer());
90
91     table.setDefaultEditor(Color.class, new ColorEditor(this));
92
93     table.setDefaultEditor(GraduatedColor.class, new ColorEditor(this));
94     table.setDefaultRenderer(GraduatedColor.class, new ColorRenderer());
95     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
96
97     table.addMouseListener(new MouseAdapter()
98     {
99       public void mousePressed(MouseEvent evt)
100       {
101         selectedRow = table.rowAtPoint(evt.getPoint());
102         if (evt.isPopupTrigger())
103         {
104           popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0),
105                   table.getValueAt(selectedRow, 1), fr.minmax, evt.getX(),
106                   evt.getY());
107         }
108         else if (evt.getClickCount() == 2)
109         {
110           fr.ap.alignFrame.avc.markColumnsContainingFeatures(
111                   evt.isShiftDown(),
112                   (String) table.getValueAt(selectedRow, 0));
113         }
114       }
115     });
116
117     table.addMouseMotionListener(new MouseMotionAdapter()
118     {
119       public void mouseDragged(MouseEvent evt)
120       {
121         int newRow = table.rowAtPoint(evt.getPoint());
122         if (newRow != selectedRow && selectedRow != -1 && newRow != -1)
123         {
124           Object[] temp = new Object[3];
125           temp[0] = table.getValueAt(selectedRow, 0);
126           temp[1] = table.getValueAt(selectedRow, 1);
127           temp[2] = table.getValueAt(selectedRow, 2);
128
129           table.setValueAt(table.getValueAt(newRow, 0), selectedRow, 0);
130           table.setValueAt(table.getValueAt(newRow, 1), selectedRow, 1);
131           table.setValueAt(table.getValueAt(newRow, 2), selectedRow, 2);
132
133           table.setValueAt(temp[0], newRow, 0);
134           table.setValueAt(temp[1], newRow, 1);
135           table.setValueAt(temp[2], newRow, 2);
136
137           selectedRow = newRow;
138         }
139       }
140     });
141
142     scrollPane.setViewportView(table);
143
144     dassourceBrowser = new DasSourceBrowser(this);
145     dasSettingsPane.add(dassourceBrowser, BorderLayout.CENTER);
146
147     if (af.getViewport().featuresDisplayed == null
148             || fr.renderOrder == null)
149     {
150       fr.findAllFeatures(true); // display everything!
151     }
152
153     setTableData();
154     final PropertyChangeListener change;
155     final FeatureSettings fs = this;
156     fr.addPropertyChangeListener(change = new PropertyChangeListener()
157     {
158       public void propertyChange(PropertyChangeEvent evt)
159       {
160         if (!fs.resettingTable && !fs.handlingUpdate)
161         {
162           fs.handlingUpdate = true;
163           fs.resetTable(null); // new groups may be added with new seuqence
164           // feature types only
165           fs.handlingUpdate = false;
166         }
167       }
168
169     });
170
171     frame = new JInternalFrame();
172     frame.setContentPane(this);
173     if (new jalview.util.Platform().isAMac())
174     {
175       Desktop.addInternalFrame(frame, MessageManager.getString("label.sequence_feature_settings"), 475, 480);
176     }
177     else
178     {
179       Desktop.addInternalFrame(frame, MessageManager.getString("label.sequence_feature_settings"), 400, 450);
180     }
181
182     frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
183     {
184       public void internalFrameClosed(
185               javax.swing.event.InternalFrameEvent evt)
186       {
187         fr.removePropertyChangeListener(change);
188         dassourceBrowser.fs = null;
189       };
190     });
191     frame.setLayer(JLayeredPane.PALETTE_LAYER);
192   }
193
194   protected void popupSort(final int selectedRow, final String type,
195           final Object typeCol, final Hashtable minmax, int x, int y)
196   {
197     JPopupMenu men = new JPopupMenu(MessageManager.formatMessage("label.settings_for_param", new String[]{type}));
198     JMenuItem scr = new JMenuItem(MessageManager.getString("label.sort_by_score"));
199     men.add(scr);
200     final FeatureSettings me = this;
201     scr.addActionListener(new ActionListener()
202     {
203
204       public void actionPerformed(ActionEvent e)
205       {
206         me.sortByScore(new String[]
207         { type });
208       }
209
210     });
211     JMenuItem dens = new JMenuItem(MessageManager.getString("label.sort_by_density"));
212     dens.addActionListener(new ActionListener()
213     {
214
215       public void actionPerformed(ActionEvent e)
216       {
217         me.sortByDens(new String[]
218         { type });
219       }
220
221     });
222     men.add(dens);
223     if (minmax != null)
224     {
225       final Object typeMinMax = minmax.get(type);
226       /*
227        * final JCheckBoxMenuItem chb = new JCheckBoxMenuItem("Vary Height"); //
228        * this is broken at the moment and isn't that useful anyway!
229        * chb.setSelected(minmax.get(type) != null); chb.addActionListener(new
230        * ActionListener() {
231        * 
232        * public void actionPerformed(ActionEvent e) {
233        * chb.setState(chb.getState()); if (chb.getState()) { minmax.put(type,
234        * null); } else { minmax.put(type, typeMinMax); } }
235        * 
236        * });
237        * 
238        * men.add(chb);
239        */
240       if (typeMinMax != null && ((float[][]) typeMinMax)[0] != null)
241       {
242         // if (table.getValueAt(row, column));
243         // graduated colourschemes for those where minmax exists for the
244         // positional features
245         final JCheckBoxMenuItem mxcol = new JCheckBoxMenuItem(
246                 "Graduated Colour");
247         mxcol.setSelected(!(typeCol instanceof Color));
248         men.add(mxcol);
249         mxcol.addActionListener(new ActionListener()
250         {
251           JColorChooser colorChooser;
252
253           public void actionPerformed(ActionEvent e)
254           {
255             if (e.getSource() == mxcol)
256             {
257               if (typeCol instanceof Color)
258               {
259                 FeatureColourChooser fc = new FeatureColourChooser(me.fr,
260                         type);
261                 fc.addActionListener(this);
262               }
263               else
264               {
265                 // bring up simple color chooser
266                 colorChooser = new JColorChooser();
267                 JDialog dialog = JColorChooser.createDialog(me,
268                         "Select new Colour", true, // modal
269                         colorChooser, this, // OK button handler
270                         null); // no CANCEL button handler
271                 colorChooser.setColor(((GraduatedColor) typeCol)
272                         .getMaxColor());
273                 dialog.setVisible(true);
274               }
275             }
276             else
277             {
278               if (e.getSource() instanceof FeatureColourChooser)
279               {
280                 FeatureColourChooser fc = (FeatureColourChooser) e
281                         .getSource();
282                 table.setValueAt(fc.getLastColour(), selectedRow, 1);
283                 table.validate();
284               }
285               else
286               {
287                 // probably the color chooser!
288                 table.setValueAt(colorChooser.getColor(), selectedRow, 1);
289                 table.validate();
290                 me.updateFeatureRenderer(
291                         ((FeatureTableModel) table.getModel()).getData(),
292                         false);
293               }
294             }
295           }
296
297         });
298       }
299     }
300     JMenuItem selCols = new JMenuItem(MessageManager.getString("label.select_columns_containing"));
301     selCols.addActionListener(new ActionListener()
302     {
303       
304       @Override
305       public void actionPerformed(ActionEvent arg0)
306       {
307         fr.ap.alignFrame.avc.markColumnsContainingFeatures(false, type);
308       }
309     });
310     JMenuItem clearCols = new JMenuItem(MessageManager.getString("label.select_columns_not_containing"));
311     clearCols.addActionListener(new ActionListener()
312     {
313       
314       @Override
315       public void actionPerformed(ActionEvent arg0)
316       {
317         fr.ap.alignFrame.avc.markColumnsContainingFeatures(true, type);
318       }
319     });
320     men.add(selCols);
321     men.add(clearCols);
322     men.show(table, x, y);
323   }
324
325   /**
326    * true when Feature Settings are updating from feature renderer
327    */
328   private boolean handlingUpdate = false;
329
330   /**
331    * contains a float[3] for each feature type string. created by setTableData
332    */
333   Hashtable typeWidth = null;
334
335   synchronized public void setTableData()
336   {
337     if (fr.featureGroups == null)
338     {
339       fr.featureGroups = new Hashtable();
340     }
341     Vector allFeatures = new Vector();
342     Vector allGroups = new Vector();
343     SequenceFeature[] tmpfeatures;
344     String group;
345     for (int i = 0; i < af.getViewport().getAlignment().getHeight(); i++)
346     {
347       if (af.getViewport().getAlignment().getSequenceAt(i)
348               .getDatasetSequence().getSequenceFeatures() == null)
349       {
350         continue;
351       }
352
353       tmpfeatures = af.getViewport().getAlignment().getSequenceAt(i)
354               .getDatasetSequence().getSequenceFeatures();
355
356       int index = 0;
357       while (index < tmpfeatures.length)
358       {
359         if (tmpfeatures[index].begin == 0 && tmpfeatures[index].end == 0)
360         {
361           index++;
362           continue;
363         }
364
365         if (tmpfeatures[index].getFeatureGroup() != null)
366         {
367           group = tmpfeatures[index].featureGroup;
368           if (!allGroups.contains(group))
369           {
370             allGroups.addElement(group);
371             if (group != null)
372             {
373               checkGroupState(group);
374             }
375           }
376         }
377
378         if (!allFeatures.contains(tmpfeatures[index].getType()))
379         {
380           allFeatures.addElement(tmpfeatures[index].getType());
381         }
382         index++;
383       }
384     }
385
386     resetTable(null);
387
388     validate();
389   }
390
391   /**
392    * 
393    * @param group
394    * @return true if group has been seen before and is already added to set.
395    */
396   private boolean checkGroupState(String group)
397   {
398     boolean visible;
399     if (fr.featureGroups.containsKey(group))
400     {
401       visible = ((Boolean) fr.featureGroups.get(group)).booleanValue();
402     }
403     else
404     {
405       visible = true; // new group is always made visible
406     }
407
408     if (groupPanel == null)
409     {
410       groupPanel = new JPanel();
411     }
412
413     boolean alreadyAdded = false;
414     for (int g = 0; g < groupPanel.getComponentCount(); g++)
415     {
416       if (((JCheckBox) groupPanel.getComponent(g)).getText().equals(group))
417       {
418         alreadyAdded = true;
419         ((JCheckBox) groupPanel.getComponent(g)).setSelected(visible);
420         break;
421       }
422     }
423
424     if (alreadyAdded)
425     {
426
427       return true;
428     }
429
430     fr.featureGroups.put(group, new Boolean(visible));
431     final String grp = group;
432     final JCheckBox check = new JCheckBox(group, visible);
433     check.setFont(new Font("Serif", Font.BOLD, 12));
434     check.addItemListener(new ItemListener()
435     {
436       public void itemStateChanged(ItemEvent evt)
437       {
438         fr.featureGroups.put(check.getText(),
439                 new Boolean(check.isSelected()));
440         af.alignPanel.seqPanel.seqCanvas.repaint();
441         if (af.alignPanel.overviewPanel != null)
442         {
443           af.alignPanel.overviewPanel.updateOverviewImage();
444         }
445
446         resetTable(new String[]
447         { grp });
448       }
449     });
450     groupPanel.add(check);
451     return false;
452   }
453
454   boolean resettingTable = false;
455
456   synchronized void resetTable(String[] groupChanged)
457   {
458     if (resettingTable == true)
459     {
460       return;
461     }
462     resettingTable = true;
463     typeWidth = new Hashtable();
464     // TODO: change avWidth calculation to 'per-sequence' average and use long
465     // rather than float
466     float[] avWidth = null;
467     SequenceFeature[] tmpfeatures;
468     String group = null, type;
469     Vector visibleChecks = new Vector();
470
471     // Find out which features should be visible depending on which groups
472     // are selected / deselected
473     // and recompute average width ordering
474     for (int i = 0; i < af.getViewport().getAlignment().getHeight(); i++)
475     {
476
477       tmpfeatures = af.getViewport().getAlignment().getSequenceAt(i)
478               .getDatasetSequence().getSequenceFeatures();
479       if (tmpfeatures == null)
480       {
481         continue;
482       }
483
484       int index = 0;
485       while (index < tmpfeatures.length)
486       {
487         group = tmpfeatures[index].featureGroup;
488
489         if (tmpfeatures[index].begin == 0 && tmpfeatures[index].end == 0)
490         {
491           index++;
492           continue;
493         }
494
495         if (group == null || fr.featureGroups.get(group) == null
496                 || ((Boolean) fr.featureGroups.get(group)).booleanValue())
497         {
498           if (group != null)
499             checkGroupState(group);
500           type = tmpfeatures[index].getType();
501           if (!visibleChecks.contains(type))
502           {
503             visibleChecks.addElement(type);
504           }
505         }
506         if (!typeWidth.containsKey(tmpfeatures[index].getType()))
507         {
508           typeWidth.put(tmpfeatures[index].getType(),
509                   avWidth = new float[3]);
510         }
511         else
512         {
513           avWidth = (float[]) typeWidth.get(tmpfeatures[index].getType());
514         }
515         avWidth[0]++;
516         if (tmpfeatures[index].getBegin() > tmpfeatures[index].getEnd())
517         {
518           avWidth[1] += 1 + tmpfeatures[index].getBegin()
519                   - tmpfeatures[index].getEnd();
520         }
521         else
522         {
523           avWidth[1] += 1 + tmpfeatures[index].getEnd()
524                   - tmpfeatures[index].getBegin();
525         }
526         index++;
527       }
528     }
529
530     int fSize = visibleChecks.size();
531     Object[][] data = new Object[fSize][3];
532     int dataIndex = 0;
533
534     if (fr.renderOrder != null)
535     {
536       if (!handlingUpdate)
537         fr.findAllFeatures(groupChanged != null); // prod to update
538       // colourschemes. but don't
539       // affect display
540       // First add the checks in the previous render order,
541       // in case the window has been closed and reopened
542       for (int ro = fr.renderOrder.length - 1; ro > -1; ro--)
543       {
544         type = fr.renderOrder[ro];
545
546         if (!visibleChecks.contains(type))
547         {
548           continue;
549         }
550
551         data[dataIndex][0] = type;
552         data[dataIndex][1] = fr.getFeatureStyle(type);
553         data[dataIndex][2] = new Boolean(
554                 af.getViewport().featuresDisplayed.containsKey(type));
555         dataIndex++;
556         visibleChecks.removeElement(type);
557       }
558     }
559
560     fSize = visibleChecks.size();
561     for (int i = 0; i < fSize; i++)
562     {
563       // These must be extra features belonging to the group
564       // which was just selected
565       type = visibleChecks.elementAt(i).toString();
566       data[dataIndex][0] = type;
567
568       data[dataIndex][1] = fr.getFeatureStyle(type);
569       if (data[dataIndex][1] == null)
570       {
571         // "Colour has been updated in another view!!"
572         fr.renderOrder = null;
573         return;
574       }
575
576       data[dataIndex][2] = new Boolean(true);
577       dataIndex++;
578     }
579
580     if (originalData == null)
581     {
582       originalData = new Object[data.length][3];
583       for (int i = 0; i < data.length; i++)
584       {
585         System.arraycopy(data[i], 0, originalData[i], 0, 3);
586       }
587     }
588
589     table.setModel(new FeatureTableModel(data));
590     table.getColumnModel().getColumn(0).setPreferredWidth(200);
591
592     if (groupPanel != null)
593     {
594       groupPanel.setLayout(new GridLayout(fr.featureGroups.size() / 4 + 1,
595               4));
596
597       groupPanel.validate();
598       bigPanel.add(groupPanel, BorderLayout.NORTH);
599     }
600
601     updateFeatureRenderer(data, groupChanged != null);
602     resettingTable = false;
603   }
604
605   /**
606    * reorder data based on the featureRenderers global priority list.
607    * 
608    * @param data
609    */
610   private void ensureOrder(Object[][] data)
611   {
612     boolean sort = false;
613     float[] order = new float[data.length];
614     for (int i = 0; i < order.length; i++)
615     {
616       order[i] = fr.getOrder(data[i][0].toString());
617       if (order[i] < 0)
618         order[i] = fr.setOrder(data[i][0].toString(), i / order.length);
619       if (i > 1)
620         sort = sort || order[i - 1] > order[i];
621     }
622     if (sort)
623       jalview.util.QuickSort.sort(order, data);
624   }
625
626   void load()
627   {
628     JalviewFileChooser chooser = new JalviewFileChooser(
629             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
630             { "fc" }, new String[]
631             { "Sequence Feature Colours" }, "Sequence Feature Colours");
632     chooser.setFileView(new jalview.io.JalviewFileView());
633     chooser.setDialogTitle("Load Feature Colours");
634     chooser.setToolTipText(MessageManager.getString("action.load"));
635
636     int value = chooser.showOpenDialog(this);
637
638     if (value == JalviewFileChooser.APPROVE_OPTION)
639     {
640       File file = chooser.getSelectedFile();
641
642       try
643       {
644         InputStreamReader in = new InputStreamReader(new FileInputStream(
645                 file), "UTF-8");
646
647         jalview.schemabinding.version2.JalviewUserColours jucs = new jalview.schemabinding.version2.JalviewUserColours();
648         jucs = (jalview.schemabinding.version2.JalviewUserColours) jucs
649                 .unmarshal(in);
650
651         for (int i = jucs.getColourCount() - 1; i >= 0; i--)
652         {
653           String name;
654           jalview.schemabinding.version2.Colour newcol = jucs.getColour(i);
655           if (newcol.hasMax())
656           {
657             Color mincol = null, maxcol = null;
658             try
659             {
660               mincol = new Color(Integer.parseInt(newcol.getMinRGB(), 16));
661               maxcol = new Color(Integer.parseInt(newcol.getRGB(), 16));
662
663             } catch (Exception e)
664             {
665               Cache.log.warn("Couldn't parse out graduated feature color.",
666                       e);
667             }
668             GraduatedColor gcol = new GraduatedColor(mincol, maxcol,
669                     newcol.getMin(), newcol.getMax());
670             if (newcol.hasAutoScale())
671             {
672               gcol.setAutoScaled(newcol.getAutoScale());
673             }
674             if (newcol.hasColourByLabel())
675             {
676               gcol.setColourByLabel(newcol.getColourByLabel());
677             }
678             if (newcol.hasThreshold())
679             {
680               gcol.setThresh(newcol.getThreshold());
681               gcol.setThreshType(AnnotationColourGradient.NO_THRESHOLD); // default
682             }
683             if (newcol.getThreshType().length() > 0)
684             {
685               String ttyp = newcol.getThreshType();
686               if (ttyp.equalsIgnoreCase("NONE"))
687               {
688                 gcol.setThreshType(AnnotationColourGradient.NO_THRESHOLD);
689               }
690               if (ttyp.equalsIgnoreCase("ABOVE"))
691               {
692                 gcol.setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
693               }
694               if (ttyp.equalsIgnoreCase("BELOW"))
695               {
696                 gcol.setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
697               }
698             }
699             fr.setColour(name = newcol.getName(), gcol);
700           }
701           else
702           {
703             fr.setColour(name = jucs.getColour(i).getName(), new Color(
704                     Integer.parseInt(jucs.getColour(i).getRGB(), 16)));
705           }
706           fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount());
707         }
708         if (table != null)
709         {
710           resetTable(null);
711           Object[][] data = ((FeatureTableModel) table.getModel())
712                   .getData();
713           ensureOrder(data);
714           updateFeatureRenderer(data, false);
715           table.repaint();
716         }
717       } catch (Exception ex)
718       {
719         System.out.println("Error loading User Colour File\n" + ex);
720       }
721     }
722   }
723
724   void save()
725   {
726     JalviewFileChooser chooser = new JalviewFileChooser(
727             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
728             { "fc" }, new String[]
729             { "Sequence Feature Colours" }, "Sequence Feature Colours");
730     chooser.setFileView(new jalview.io.JalviewFileView());
731     chooser.setDialogTitle("Save Feature Colour Scheme");
732     chooser.setToolTipText(MessageManager.getString("action.save"));
733
734     int value = chooser.showSaveDialog(this);
735
736     if (value == JalviewFileChooser.APPROVE_OPTION)
737     {
738       String choice = chooser.getSelectedFile().getPath();
739       jalview.schemabinding.version2.JalviewUserColours ucs = new jalview.schemabinding.version2.JalviewUserColours();
740       ucs.setSchemeName("Sequence Features");
741       try
742       {
743         PrintWriter out = new PrintWriter(new OutputStreamWriter(
744                 new FileOutputStream(choice), "UTF-8"));
745
746         Iterator e = fr.featureColours.keySet().iterator();
747         float[] sortOrder = new float[fr.featureColours.size()];
748         String[] sortTypes = new String[fr.featureColours.size()];
749         int i = 0;
750         while (e.hasNext())
751         {
752           sortTypes[i] = e.next().toString();
753           sortOrder[i] = fr.getOrder(sortTypes[i]);
754           i++;
755         }
756         jalview.util.QuickSort.sort(sortOrder, sortTypes);
757         sortOrder = null;
758         Object fcol;
759         GraduatedColor gcol;
760         for (i = 0; i < sortTypes.length; i++)
761         {
762           jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
763           col.setName(sortTypes[i]);
764           col.setRGB(jalview.util.Format.getHexString(fr.getColour(col
765                   .getName())));
766           fcol = fr.getFeatureStyle(sortTypes[i]);
767           if (fcol instanceof GraduatedColor)
768           {
769             gcol = (GraduatedColor) fcol;
770             col.setMin(gcol.getMin());
771             col.setMax(gcol.getMax());
772             col.setMinRGB(jalview.util.Format.getHexString(gcol
773                     .getMinColor()));
774             col.setAutoScale(gcol.isAutoScale());
775             col.setThreshold(gcol.getThresh());
776             col.setColourByLabel(gcol.isColourByLabel());
777             switch (gcol.getThreshType())
778             {
779             case AnnotationColourGradient.NO_THRESHOLD:
780               col.setThreshType("NONE");
781               break;
782             case AnnotationColourGradient.ABOVE_THRESHOLD:
783               col.setThreshType("ABOVE");
784               break;
785             case AnnotationColourGradient.BELOW_THRESHOLD:
786               col.setThreshType("BELOW");
787               break;
788             }
789           }
790           ucs.addColour(col);
791         }
792         ucs.marshal(out);
793         out.close();
794       } catch (Exception ex)
795       {
796         ex.printStackTrace();
797       }
798     }
799   }
800
801   public void invertSelection()
802   {
803     for (int i = 0; i < table.getRowCount(); i++)
804     {
805       Boolean value = (Boolean) table.getValueAt(i, 2);
806
807       table.setValueAt(new Boolean(!value.booleanValue()), i, 2);
808     }
809   }
810
811   public void orderByAvWidth()
812   {
813     if (table == null || table.getModel() == null)
814       return;
815     Object[][] data = ((FeatureTableModel) table.getModel()).getData();
816     float[] width = new float[data.length];
817     float[] awidth;
818     float max = 0;
819     int num = 0;
820     for (int i = 0; i < data.length; i++)
821     {
822       awidth = (float[]) typeWidth.get(data[i][0]);
823       if (awidth[0] > 0)
824       {
825         width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better
826         // weight - but have to make per
827         // sequence, too (awidth[2])
828         // if (width[i]==1) // hack to distinguish single width sequences.
829         num++;
830       }
831       else
832       {
833         width[i] = 0;
834       }
835       if (max < width[i])
836         max = width[i];
837     }
838     boolean sort = false;
839     for (int i = 0; i < width.length; i++)
840     {
841       // awidth = (float[]) typeWidth.get(data[i][0]);
842       if (width[i] == 0)
843       {
844         width[i] = fr.getOrder(data[i][0].toString());
845         if (width[i] < 0)
846         {
847           width[i] = fr.setOrder(data[i][0].toString(), i / data.length);
848         }
849       }
850       else
851       {
852         width[i] /= max; // normalize
853         fr.setOrder(data[i][0].toString(), width[i]); // store for later
854       }
855       if (i > 0)
856         sort = sort || width[i - 1] > width[i];
857     }
858     if (sort)
859       jalview.util.QuickSort.sort(width, data);
860     // update global priority order
861
862     updateFeatureRenderer(data, false);
863     table.repaint();
864   }
865
866   public void close()
867   {
868     try
869     {
870       frame.setClosed(true);
871     } catch (Exception exe)
872     {
873     }
874
875   }
876
877   public void updateFeatureRenderer(Object[][] data)
878   {
879     updateFeatureRenderer(data, true);
880   }
881
882   private void updateFeatureRenderer(Object[][] data, boolean visibleNew)
883   {
884     fr.setFeaturePriority(data, visibleNew);
885     af.alignPanel.paintAlignment(true);
886   }
887
888   int selectedRow = -1;
889
890   JTabbedPane tabbedPane = new JTabbedPane();
891
892   BorderLayout borderLayout1 = new BorderLayout();
893
894   BorderLayout borderLayout2 = new BorderLayout();
895
896   BorderLayout borderLayout3 = new BorderLayout();
897
898   JPanel bigPanel = new JPanel();
899
900   BorderLayout borderLayout4 = new BorderLayout();
901
902   JButton invert = new JButton();
903
904   JPanel buttonPanel = new JPanel();
905
906   JButton cancel = new JButton();
907
908   JButton ok = new JButton();
909
910   JButton loadColours = new JButton();
911
912   JButton saveColours = new JButton();
913
914   JPanel dasButtonPanel = new JPanel();
915
916   JButton fetchDAS = new JButton();
917
918   JButton saveDAS = new JButton();
919
920   JButton cancelDAS = new JButton();
921
922   JButton optimizeOrder = new JButton();
923
924   JButton sortByScore = new JButton();
925
926   JButton sortByDens = new JButton();
927
928   JPanel transbuttons = new JPanel(new GridLayout(4, 1));
929
930   private void jbInit() throws Exception
931   {
932     this.setLayout(borderLayout1);
933     settingsPane.setLayout(borderLayout2);
934     dasSettingsPane.setLayout(borderLayout3);
935     bigPanel.setLayout(borderLayout4);
936     invert.setFont(JvSwingUtils.getLabelFont());
937     invert.setText(MessageManager.getString("label.invert_selection"));
938     invert.addActionListener(new ActionListener()
939     {
940       public void actionPerformed(ActionEvent e)
941       {
942         invertSelection();
943       }
944     });
945     optimizeOrder.setFont(JvSwingUtils.getLabelFont());
946     optimizeOrder.setText(MessageManager.getString("label.optimise_order"));
947     optimizeOrder.addActionListener(new ActionListener()
948     {
949       public void actionPerformed(ActionEvent e)
950       {
951         orderByAvWidth();
952       }
953     });
954     sortByScore.setFont(JvSwingUtils.getLabelFont());
955     sortByScore.setText(MessageManager.getString("label.seq_sort_by_score"));
956     sortByScore.addActionListener(new ActionListener()
957     {
958       public void actionPerformed(ActionEvent e)
959       {
960         sortByScore(null);
961       }
962     });
963     sortByDens.setFont(JvSwingUtils.getLabelFont());
964     sortByDens.setText(MessageManager.getString("label.sequence_sort_by_density"));
965     sortByDens.addActionListener(new ActionListener()
966     {
967       public void actionPerformed(ActionEvent e)
968       {
969         sortByDens(null);
970       }
971     });
972     cancel.setFont(JvSwingUtils.getLabelFont());
973     cancel.setText(MessageManager.getString("action.cancel"));
974     cancel.addActionListener(new ActionListener()
975     {
976       public void actionPerformed(ActionEvent e)
977       {
978         updateFeatureRenderer(originalData);
979         close();
980       }
981     });
982     ok.setFont(JvSwingUtils.getLabelFont());
983     ok.setText(MessageManager.getString("action.ok"));
984     ok.addActionListener(new ActionListener()
985     {
986       public void actionPerformed(ActionEvent e)
987       {
988         close();
989       }
990     });
991     loadColours.setFont(JvSwingUtils.getLabelFont());
992     loadColours.setText(MessageManager.getString("label.load_colours"));
993     loadColours.addActionListener(new ActionListener()
994     {
995       public void actionPerformed(ActionEvent e)
996       {
997         load();
998       }
999     });
1000     saveColours.setFont(JvSwingUtils.getLabelFont());
1001     saveColours.setText(MessageManager.getString("label.save_colours"));
1002     saveColours.addActionListener(new ActionListener()
1003     {
1004       public void actionPerformed(ActionEvent e)
1005       {
1006         save();
1007       }
1008     });
1009     transparency.addChangeListener(new ChangeListener()
1010     {
1011       public void stateChanged(ChangeEvent evt)
1012       {
1013         fr.setTransparency((float) (100 - transparency.getValue()) / 100f);
1014         af.alignPanel.paintAlignment(true);
1015       }
1016     });
1017
1018     transparency.setMaximum(70);
1019     fetchDAS.setText(MessageManager.getString("label.fetch_das_features"));
1020     fetchDAS.addActionListener(new ActionListener()
1021     {
1022       public void actionPerformed(ActionEvent e)
1023       {
1024         fetchDAS_actionPerformed(e);
1025       }
1026     });
1027     saveDAS.setText(MessageManager.getString("action.save_as_default"));
1028     saveDAS.addActionListener(new ActionListener()
1029     {
1030       public void actionPerformed(ActionEvent e)
1031       {
1032         saveDAS_actionPerformed(e);
1033       }
1034     });
1035     dasButtonPanel.setBorder(BorderFactory.createEtchedBorder());
1036     dasSettingsPane.setBorder(null);
1037     cancelDAS.setEnabled(false);
1038     cancelDAS.setText(MessageManager.getString("action.cancel_fetch"));
1039     cancelDAS.addActionListener(new ActionListener()
1040     {
1041       public void actionPerformed(ActionEvent e)
1042       {
1043         cancelDAS_actionPerformed(e);
1044       }
1045     });
1046     this.add(tabbedPane, java.awt.BorderLayout.CENTER);
1047     tabbedPane.addTab("Feature Settings", settingsPane);
1048     tabbedPane.addTab("DAS Settings", dasSettingsPane);
1049     bigPanel.add(transPanel, java.awt.BorderLayout.SOUTH);
1050     transbuttons.add(optimizeOrder);
1051     transbuttons.add(invert);
1052     transbuttons.add(sortByScore);
1053     transbuttons.add(sortByDens);
1054     transPanel.add(transparency);
1055     transPanel.add(transbuttons);
1056     buttonPanel.add(ok);
1057     buttonPanel.add(cancel);
1058     buttonPanel.add(loadColours);
1059     buttonPanel.add(saveColours);
1060     bigPanel.add(scrollPane, java.awt.BorderLayout.CENTER);
1061     dasSettingsPane.add(dasButtonPanel, java.awt.BorderLayout.SOUTH);
1062     dasButtonPanel.add(fetchDAS);
1063     dasButtonPanel.add(cancelDAS);
1064     dasButtonPanel.add(saveDAS);
1065     settingsPane.add(bigPanel, java.awt.BorderLayout.CENTER);
1066     settingsPane.add(buttonPanel, java.awt.BorderLayout.SOUTH);
1067   }
1068
1069   protected void sortByDens(String[] typ)
1070   {
1071     sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY);
1072   }
1073
1074   protected void sortBy(String[] typ, String methodText, final String method)
1075   {
1076     if (typ == null)
1077     {
1078       typ = getDisplayedFeatureTypes();
1079     }
1080     String gps[] = null;
1081     gps = getDisplayedFeatureGroups();
1082     if (typ != null)
1083     {
1084       ArrayList types = new ArrayList();
1085       for (int i = 0; i < typ.length; i++)
1086       {
1087         if (typ[i] != null)
1088         {
1089           types.add(typ[i]);
1090         }
1091         typ = new String[types.size()];
1092         types.toArray(typ);
1093       }
1094     }
1095     if (gps != null)
1096     {
1097       ArrayList grps = new ArrayList();
1098
1099       for (int i = 0; i < gps.length; i++)
1100       {
1101         if (gps[i] != null)
1102         {
1103           grps.add(gps[i]);
1104         }
1105       }
1106       gps = new String[grps.size()];
1107       grps.toArray(gps);
1108     }
1109     AlignmentPanel alignPanel = af.alignPanel;
1110     AlignmentI al = alignPanel.av.getAlignment();
1111
1112     int start, stop;
1113     SequenceGroup sg = alignPanel.av.getSelectionGroup();
1114     if (sg != null)
1115     {
1116       start = sg.getStartRes();
1117       stop = sg.getEndRes();
1118     }
1119     else
1120     {
1121       start = 0;
1122       stop = al.getWidth();
1123     }
1124     SequenceI[] oldOrder = al.getSequencesArray();
1125     AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method);
1126     af.addHistoryItem(new OrderCommand(methodText, oldOrder, alignPanel.av
1127             .getAlignment()));
1128     alignPanel.paintAlignment(true);
1129
1130   }
1131
1132   protected void sortByScore(String[] typ)
1133   {
1134     sortBy(typ, "Sort by Feature Score", AlignmentSorter.FEATURE_SCORE);
1135   }
1136
1137   private String[] getDisplayedFeatureTypes()
1138   {
1139     String[] typ = null;
1140     if (fr != null)
1141     {
1142       synchronized (fr.renderOrder)
1143       {
1144         typ = new String[fr.renderOrder.length];
1145         System.arraycopy(fr.renderOrder, 0, typ, 0, typ.length);
1146         for (int i = 0; i < typ.length; i++)
1147         {
1148           if (af.viewport.featuresDisplayed.get(typ[i]) == null)
1149           {
1150             typ[i] = null;
1151           }
1152         }
1153       }
1154     }
1155     return typ;
1156   }
1157
1158   private String[] getDisplayedFeatureGroups()
1159   {
1160     String[] gps = null;
1161     ArrayList<String> _gps = new ArrayList<String>();
1162     if (fr != null)
1163     {
1164
1165       if (fr.featureGroups != null)
1166       {
1167         Iterator en = fr.featureGroups.keySet().iterator();
1168         int g = 0;
1169         boolean valid = false;
1170         while (en.hasNext())
1171         {
1172           String gp = (String) en.next();
1173           Boolean on = (Boolean) fr.featureGroups.get(gp);
1174           if (on != null && on.booleanValue())
1175           {
1176             valid = true;
1177             _gps.add(gp);
1178           }
1179         }
1180         if (!valid)
1181         {
1182           return null;
1183         } else {
1184           gps = new String[_gps.size()];
1185           _gps.toArray(gps);
1186         }
1187       }
1188     }
1189     return gps;
1190   }
1191
1192   public void fetchDAS_actionPerformed(ActionEvent e)
1193   {
1194     fetchDAS.setEnabled(false);
1195     cancelDAS.setEnabled(true);
1196     dassourceBrowser.setGuiEnabled(false);
1197     Vector selectedSources = dassourceBrowser.getSelectedSources();
1198     doDasFeatureFetch(selectedSources, true, true);
1199   }
1200
1201   /**
1202    * get the features from selectedSources for all or the current selection
1203    * 
1204    * @param selectedSources
1205    * @param checkDbRefs
1206    * @param promptFetchDbRefs
1207    */
1208   private void doDasFeatureFetch(List<jalviewSourceI> selectedSources,
1209           boolean checkDbRefs, boolean promptFetchDbRefs)
1210   {
1211     SequenceI[] dataset, seqs;
1212     int iSize;
1213     AlignViewport vp = af.getViewport();
1214     if (vp.getSelectionGroup() != null
1215             && vp.getSelectionGroup().getSize() > 0)
1216     {
1217       iSize = vp.getSelectionGroup().getSize();
1218       dataset = new SequenceI[iSize];
1219       seqs = vp.getSelectionGroup().getSequencesInOrder(vp.getAlignment());
1220     }
1221     else
1222     {
1223       iSize = vp.getAlignment().getHeight();
1224       seqs = vp.getAlignment().getSequencesArray();
1225     }
1226
1227     dataset = new SequenceI[iSize];
1228     for (int i = 0; i < iSize; i++)
1229     {
1230       dataset[i] = seqs[i].getDatasetSequence();
1231     }
1232
1233     cancelDAS.setEnabled(true);
1234     dasFeatureFetcher = new jalview.ws.DasSequenceFeatureFetcher(dataset,
1235             this, selectedSources, checkDbRefs, promptFetchDbRefs);
1236     af.getViewport().setShowSequenceFeatures(true);
1237     af.showSeqFeatures.setSelected(true);
1238   }
1239
1240   /**
1241    * blocking call to initialise the das source browser
1242    */
1243   public void initDasSources()
1244   {
1245     dassourceBrowser.initDasSources();
1246   }
1247
1248   /**
1249    * examine the current list of das sources and return any matching the given
1250    * nicknames in sources
1251    * 
1252    * @param sources
1253    *          Vector of Strings to resolve to DAS source nicknames.
1254    * @return sources that are present in source list.
1255    */
1256   public List<jalviewSourceI> resolveSourceNicknames(Vector sources)
1257   {
1258     return dassourceBrowser.sourceRegistry.resolveSourceNicknames(sources);
1259   }
1260
1261   /**
1262    * get currently selected das sources. ensure you have called initDasSources
1263    * before calling this.
1264    * 
1265    * @return vector of selected das source nicknames
1266    */
1267   public Vector getSelectedSources()
1268   {
1269     return dassourceBrowser.getSelectedSources();
1270   }
1271
1272   /**
1273    * properly initialise DAS fetcher and then initiate a new thread to fetch
1274    * features from the named sources (rather than any turned on by default)
1275    * 
1276    * @param sources
1277    * @param block
1278    *          if true then runs in same thread, otherwise passes to the Swing
1279    *          executor
1280    */
1281   public void fetchDasFeatures(Vector sources, boolean block)
1282   {
1283     initDasSources();
1284     List<jalviewSourceI> resolved = dassourceBrowser.sourceRegistry
1285             .resolveSourceNicknames(sources);
1286     if (resolved.size() == 0)
1287     {
1288       resolved = dassourceBrowser.getSelectedSources();
1289     }
1290     if (resolved.size() > 0)
1291     {
1292       final List<jalviewSourceI> dassources = resolved;
1293       fetchDAS.setEnabled(false);
1294       // cancelDAS.setEnabled(true); doDasFetch does this.
1295       Runnable fetcher = new Runnable()
1296       {
1297
1298         public void run()
1299         {
1300           doDasFeatureFetch(dassources, true, false);
1301
1302         }
1303       };
1304       if (block)
1305       {
1306         fetcher.run();
1307       }
1308       else
1309       {
1310         SwingUtilities.invokeLater(fetcher);
1311       }
1312     }
1313   }
1314
1315   public void saveDAS_actionPerformed(ActionEvent e)
1316   {
1317     dassourceBrowser
1318             .saveProperties(jalview.bin.Cache.applicationProperties);
1319   }
1320
1321   public void complete()
1322   {
1323     fetchDAS.setEnabled(true);
1324     cancelDAS.setEnabled(false);
1325     dassourceBrowser.setGuiEnabled(true);
1326
1327   }
1328
1329   public void cancelDAS_actionPerformed(ActionEvent e)
1330   {
1331     if (dasFeatureFetcher != null)
1332     {
1333       dasFeatureFetcher.cancel();
1334     }
1335     complete();
1336   }
1337
1338   public void noDasSourceActive()
1339   {
1340     complete();
1341     JOptionPane.showInternalConfirmDialog(Desktop.desktop,
1342             MessageManager.getString("label.no_das_sources_selected_warn"),
1343             MessageManager.getString("label.no_das_sources_selected_title"), JOptionPane.DEFAULT_OPTION,
1344             JOptionPane.INFORMATION_MESSAGE);
1345   }
1346
1347   // ///////////////////////////////////////////////////////////////////////
1348   // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
1349   // ///////////////////////////////////////////////////////////////////////
1350   class FeatureTableModel extends AbstractTableModel
1351   {
1352     FeatureTableModel(Object[][] data)
1353     {
1354       this.data = data;
1355     }
1356
1357     private String[] columnNames =
1358     { "Feature Type", "Colour", "Display" };
1359
1360     private Object[][] data;
1361
1362     public Object[][] getData()
1363     {
1364       return data;
1365     }
1366
1367     public void setData(Object[][] data)
1368     {
1369       this.data = data;
1370     }
1371
1372     public int getColumnCount()
1373     {
1374       return columnNames.length;
1375     }
1376
1377     public Object[] getRow(int row)
1378     {
1379       return data[row];
1380     }
1381
1382     public int getRowCount()
1383     {
1384       return data.length;
1385     }
1386
1387     public String getColumnName(int col)
1388     {
1389       return columnNames[col];
1390     }
1391
1392     public Object getValueAt(int row, int col)
1393     {
1394       return data[row][col];
1395     }
1396
1397     public Class getColumnClass(int c)
1398     {
1399       return getValueAt(0, c).getClass();
1400     }
1401
1402     public boolean isCellEditable(int row, int col)
1403     {
1404       return col == 0 ? false : true;
1405     }
1406
1407     public void setValueAt(Object value, int row, int col)
1408     {
1409       data[row][col] = value;
1410       fireTableCellUpdated(row, col);
1411       updateFeatureRenderer(data);
1412     }
1413
1414   }
1415
1416   class ColorRenderer extends JLabel implements TableCellRenderer
1417   {
1418     javax.swing.border.Border unselectedBorder = null;
1419
1420     javax.swing.border.Border selectedBorder = null;
1421
1422     final String baseTT = "Click to edit, right/apple click for menu.";
1423
1424     public ColorRenderer()
1425     {
1426       setOpaque(true); // MUST do this for background to show up.
1427       setHorizontalTextPosition(SwingConstants.CENTER);
1428       setVerticalTextPosition(SwingConstants.CENTER);
1429     }
1430
1431     public Component getTableCellRendererComponent(JTable table,
1432             Object color, boolean isSelected, boolean hasFocus, int row,
1433             int column)
1434     {
1435       // JLabel comp = new JLabel();
1436       // comp.
1437       setOpaque(true);
1438       // comp.
1439       // setBounds(getBounds());
1440       Color newColor;
1441       setToolTipText(baseTT);
1442       setBackground(table.getBackground());
1443       if (color instanceof GraduatedColor)
1444       {
1445         Rectangle cr = table.getCellRect(row, column, false);
1446         FeatureSettings.renderGraduatedColor(this, (GraduatedColor) color,
1447                 (int) cr.getWidth(), (int) cr.getHeight());
1448
1449       }
1450       else
1451       {
1452         this.setText("");
1453         this.setIcon(null);
1454         newColor = (Color) color;
1455         // comp.
1456         setBackground(newColor);
1457         // comp.setToolTipText("RGB value: " + newColor.getRed() + ", "
1458         // + newColor.getGreen() + ", " + newColor.getBlue());
1459       }
1460       if (isSelected)
1461       {
1462         if (selectedBorder == null)
1463         {
1464           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1465                   table.getSelectionBackground());
1466         }
1467         // comp.
1468         setBorder(selectedBorder);
1469       }
1470       else
1471       {
1472         if (unselectedBorder == null)
1473         {
1474           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1475                   table.getBackground());
1476         }
1477         // comp.
1478         setBorder(unselectedBorder);
1479       }
1480
1481       return this;
1482     }
1483   }
1484
1485   /**
1486    * update comp using rendering settings from gcol
1487    * 
1488    * @param comp
1489    * @param gcol
1490    */
1491   public static void renderGraduatedColor(JLabel comp, GraduatedColor gcol)
1492   {
1493     int w = comp.getWidth(), h = comp.getHeight();
1494     if (w < 20)
1495     {
1496       w = (int) comp.getPreferredSize().getWidth();
1497       h = (int) comp.getPreferredSize().getHeight();
1498       if (w < 20)
1499       {
1500         w = 80;
1501         h = 12;
1502       }
1503     }
1504     renderGraduatedColor(comp, gcol, w, h);
1505   }
1506
1507   public static void renderGraduatedColor(JLabel comp, GraduatedColor gcol,
1508           int w, int h)
1509   {
1510     boolean thr = false;
1511     String tt = "";
1512     String tx = "";
1513     if (gcol.getThreshType() == AnnotationColourGradient.ABOVE_THRESHOLD)
1514     {
1515       thr = true;
1516       tx += ">";
1517       tt += "Thresholded (Above " + gcol.getThresh() + ") ";
1518     }
1519     if (gcol.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
1520     {
1521       thr = true;
1522       tx += "<";
1523       tt += "Thresholded (Below " + gcol.getThresh() + ") ";
1524     }
1525     if (gcol.isColourByLabel())
1526     {
1527       tt = "Coloured by label text. " + tt;
1528       if (thr)
1529       {
1530         tx += " ";
1531       }
1532       tx += "Label";
1533       comp.setIcon(null);
1534     }
1535     else
1536     {
1537       Color newColor = gcol.getMaxColor();
1538       comp.setBackground(newColor);
1539       // System.err.println("Width is " + w / 2);
1540       Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr);
1541       comp.setIcon(ficon);
1542       // tt+="RGB value: Max (" + newColor.getRed() + ", "
1543       // + newColor.getGreen() + ", " + newColor.getBlue()
1544       // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen()
1545       // + ", " + minCol.getBlue() + ")");
1546     }
1547     comp.setHorizontalAlignment(SwingConstants.CENTER);
1548     comp.setText(tx);
1549     if (tt.length() > 0)
1550     {
1551       if (comp.getToolTipText() == null)
1552       {
1553         comp.setToolTipText(tt);
1554       }
1555       else
1556       {
1557         comp.setToolTipText(tt + " " + comp.getToolTipText());
1558       }
1559     }
1560   }
1561 }
1562
1563 class FeatureIcon implements Icon
1564 {
1565   GraduatedColor gcol;
1566
1567   Color backg;
1568
1569   boolean midspace = false;
1570
1571   int width = 50, height = 20;
1572
1573   int s1, e1; // start and end of midpoint band for thresholded symbol
1574
1575   Color mpcolour = Color.white;
1576
1577   FeatureIcon(GraduatedColor gfc, Color bg, int w, int h, boolean mspace)
1578   {
1579     gcol = gfc;
1580     backg = bg;
1581     width = w;
1582     height = h;
1583     midspace = mspace;
1584     if (midspace)
1585     {
1586       s1 = width / 3;
1587       e1 = s1 * 2;
1588     }
1589     else
1590     {
1591       s1 = width / 2;
1592       e1 = s1;
1593     }
1594   }
1595
1596   public int getIconWidth()
1597   {
1598     return width;
1599   }
1600
1601   public int getIconHeight()
1602   {
1603     return height;
1604   }
1605
1606   public void paintIcon(Component c, Graphics g, int x, int y)
1607   {
1608
1609     if (gcol.isColourByLabel())
1610     {
1611       g.setColor(backg);
1612       g.fillRect(0, 0, width, height);
1613       // need an icon here.
1614       g.setColor(gcol.getMaxColor());
1615
1616       g.setFont(new Font("Verdana", Font.PLAIN, 9));
1617
1618       // g.setFont(g.getFont().deriveFont(
1619       // AffineTransform.getScaleInstance(
1620       // width/g.getFontMetrics().stringWidth("Label"),
1621       // height/g.getFontMetrics().getHeight())));
1622
1623       g.drawString(MessageManager.getString("label.label"), 0, 0);
1624
1625     }
1626     else
1627     {
1628       Color minCol = gcol.getMinColor();
1629       g.setColor(minCol);
1630       g.fillRect(0, 0, s1, height);
1631       if (midspace)
1632       {
1633         g.setColor(Color.white);
1634         g.fillRect(s1, 0, e1 - s1, height);
1635       }
1636       g.setColor(gcol.getMaxColor());
1637       g.fillRect(0, e1, width - e1, height);
1638     }
1639   }
1640 }
1641
1642 class ColorEditor extends AbstractCellEditor implements TableCellEditor,
1643         ActionListener
1644 {
1645   FeatureSettings me;
1646
1647   GraduatedColor currentGColor;
1648
1649   FeatureColourChooser chooser;
1650
1651   String type;
1652
1653   Color currentColor;
1654
1655   JButton button;
1656
1657   JColorChooser colorChooser;
1658
1659   JDialog dialog;
1660
1661   protected static final String EDIT = "edit";
1662
1663   int selectedRow = 0;
1664
1665   public ColorEditor(FeatureSettings me)
1666   {
1667     this.me = me;
1668     // Set up the editor (from the table's point of view),
1669     // which is a button.
1670     // This button brings up the color chooser dialog,
1671     // which is the editor from the user's point of view.
1672     button = new JButton();
1673     button.setActionCommand(EDIT);
1674     button.addActionListener(this);
1675     button.setBorderPainted(false);
1676     // Set up the dialog that the button brings up.
1677     colorChooser = new JColorChooser();
1678     dialog = JColorChooser.createDialog(button, "Select new Colour", true, // modal
1679             colorChooser, this, // OK button handler
1680             null); // no CANCEL button handler
1681   }
1682
1683   /**
1684    * Handles events from the editor button and from the dialog's OK button.
1685    */
1686   public void actionPerformed(ActionEvent e)
1687   {
1688
1689     if (EDIT.equals(e.getActionCommand()))
1690     {
1691       // The user has clicked the cell, so
1692       // bring up the dialog.
1693       if (currentColor != null)
1694       {
1695         // bring up simple color chooser
1696         button.setBackground(currentColor);
1697         colorChooser.setColor(currentColor);
1698         dialog.setVisible(true);
1699       }
1700       else
1701       {
1702         // bring up graduated chooser.
1703         chooser = new FeatureColourChooser(me.fr, type);
1704         chooser.setRequestFocusEnabled(true);
1705         chooser.requestFocus();
1706         chooser.addActionListener(this);
1707       }
1708       // Make the renderer reappear.
1709       fireEditingStopped();
1710
1711     }
1712     else
1713     { // User pressed dialog's "OK" button.
1714       if (currentColor != null)
1715       {
1716         currentColor = colorChooser.getColor();
1717       }
1718       else
1719       {
1720         // class cast exceptions may be raised if the chooser created on a
1721         // non-graduated color
1722         currentGColor = (GraduatedColor) chooser.getLastColour();
1723       }
1724       me.table.setValueAt(getCellEditorValue(), selectedRow, 1);
1725       fireEditingStopped();
1726       me.table.validate();
1727     }
1728   }
1729
1730   // Implement the one CellEditor method that AbstractCellEditor doesn't.
1731   public Object getCellEditorValue()
1732   {
1733     if (currentColor == null)
1734     {
1735       return currentGColor;
1736     }
1737     return currentColor;
1738   }
1739
1740   // Implement the one method defined by TableCellEditor.
1741   public Component getTableCellEditorComponent(JTable table, Object value,
1742           boolean isSelected, int row, int column)
1743   {
1744     currentGColor = null;
1745     currentColor = null;
1746     this.selectedRow = row;
1747     type = me.table.getValueAt(row, 0).toString();
1748     button.setOpaque(true);
1749     button.setBackground(me.getBackground());
1750     if (value instanceof GraduatedColor)
1751     {
1752       currentGColor = (GraduatedColor) value;
1753       JLabel btn = new JLabel();
1754       btn.setSize(button.getSize());
1755       FeatureSettings.renderGraduatedColor(btn, currentGColor);
1756       button.setBackground(btn.getBackground());
1757       button.setIcon(btn.getIcon());
1758       button.setText(btn.getText());
1759     }
1760     else
1761     {
1762       button.setText("");
1763       button.setIcon(null);
1764       currentColor = (Color) value;
1765       button.setBackground(currentColor);
1766     }
1767     return button;
1768   }
1769 }