merge from 2_4_Release branch
[jalview.git] / src / jalview / gui / FeatureSettings.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.io.*;
22 import java.util.*;
23
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.datamodel.*;
34 import jalview.io.*;
35
36 public class FeatureSettings extends JPanel
37 {
38   DasSourceBrowser dassourceBrowser;
39
40   jalview.ws.DasSequenceFeatureFetcher dasFeatureFetcher;
41
42   JPanel settingsPane = new JPanel();
43
44   JPanel dasSettingsPane = new JPanel();
45
46   final FeatureRenderer fr;
47
48   public final AlignFrame af;
49
50   Object[][] originalData;
51
52   final JInternalFrame frame;
53
54   JScrollPane scrollPane = new JScrollPane();
55
56   JTable table;
57
58   JPanel groupPanel;
59
60   JSlider transparency = new JSlider();
61
62   JPanel transPanel = new JPanel(new FlowLayout());
63
64   public FeatureSettings(AlignFrame af)
65   {
66     this.af = af;
67     fr = af.getFeatureRenderer();
68
69     transparency.setMaximum(100 - (int) (fr.transparency * 100));
70
71     try
72     {
73       jbInit();
74     } catch (Exception ex)
75     {
76       ex.printStackTrace();
77     }
78
79     table = new JTable();
80     table.getTableHeader().setFont(new Font("Verdana", Font.PLAIN, 12));
81     table.setFont(new Font("Verdana", Font.PLAIN, 12));
82     table.setDefaultRenderer(Color.class, new ColorRenderer());
83
84     table.setDefaultEditor(Color.class, new ColorEditor());
85
86     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
87
88     table.addMouseListener(new MouseAdapter()
89     {
90       public void mousePressed(MouseEvent evt)
91       {
92         selectedRow = table.rowAtPoint(evt.getPoint());
93       }
94     });
95
96     table.addMouseMotionListener(new MouseMotionAdapter()
97     {
98       public void mouseDragged(MouseEvent evt)
99       {
100         int newRow = table.rowAtPoint(evt.getPoint());
101         if (newRow != selectedRow && selectedRow != -1 && newRow != -1)
102         {
103           Object[] temp = new Object[3];
104           temp[0] = table.getValueAt(selectedRow, 0);
105           temp[1] = table.getValueAt(selectedRow, 1);
106           temp[2] = table.getValueAt(selectedRow, 2);
107
108           table.setValueAt(table.getValueAt(newRow, 0), selectedRow, 0);
109           table.setValueAt(table.getValueAt(newRow, 1), selectedRow, 1);
110           table.setValueAt(table.getValueAt(newRow, 2), selectedRow, 2);
111
112           table.setValueAt(temp[0], newRow, 0);
113           table.setValueAt(temp[1], newRow, 1);
114           table.setValueAt(temp[2], newRow, 2);
115
116           selectedRow = newRow;
117         }
118       }
119     });
120
121     scrollPane.setViewportView(table);
122
123     dassourceBrowser = new DasSourceBrowser();
124     dasSettingsPane.add(dassourceBrowser, BorderLayout.CENTER);
125
126     if (af.getViewport().featuresDisplayed == null
127             || fr.renderOrder == null)
128     {
129       fr.findAllFeatures(true); // display everything!
130     }
131
132     setTableData();
133     final PropertyChangeListener change;
134     final FeatureSettings fs = this;
135     fr.addPropertyChangeListener(change = new PropertyChangeListener()
136     {
137       public void propertyChange(PropertyChangeEvent evt)
138       {
139         if (!fs.resettingTable && !fs.handlingUpdate)
140         {
141           fs.handlingUpdate = true;
142           fs.resetTable(null); // new groups may be added with new seuqence
143                                 // feature types only
144           fs.handlingUpdate = false;
145         }
146       }
147
148     });
149
150     frame = new JInternalFrame();
151     frame.setContentPane(this);
152     Desktop.addInternalFrame(frame, "Sequence Feature Settings", 400, 450);
153     frame
154             .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
155             {
156               public void internalFrameClosed(
157                       javax.swing.event.InternalFrameEvent evt)
158               {
159                 fr.removePropertyChangeListener(change);
160               };
161             });
162     frame.setLayer(JLayeredPane.PALETTE_LAYER);
163   }
164
165   /**
166    * true when Feature Settings are updating from feature renderer
167    */
168   private boolean handlingUpdate = false;
169
170   /**
171    * contains a float[3] for each feature type string. created by setTableData
172    */
173   Hashtable typeWidth = null;
174
175   synchronized public void setTableData()
176   {
177     if (fr.featureGroups == null)
178     {
179       fr.featureGroups = new Hashtable();
180     }
181     Vector allFeatures = new Vector();
182     Vector allGroups = new Vector();
183     SequenceFeature[] tmpfeatures;
184     String group;
185     for (int i = 0; i < af.getViewport().alignment.getHeight(); i++)
186     {
187       if (af.getViewport().alignment.getSequenceAt(i).getDatasetSequence()
188               .getSequenceFeatures() == null)
189       {
190         continue;
191       }
192
193       tmpfeatures = af.getViewport().alignment.getSequenceAt(i)
194               .getDatasetSequence().getSequenceFeatures();
195
196       int index = 0;
197       while (index < tmpfeatures.length)
198       {
199         if (tmpfeatures[index].begin == 0 && tmpfeatures[index].end == 0)
200         {
201           index++;
202           continue;
203         }
204
205         if (tmpfeatures[index].getFeatureGroup() != null)
206         {
207           group = tmpfeatures[index].featureGroup;
208           if (!allGroups.contains(group))
209           {
210             allGroups.addElement(group);
211             if (group != null)
212             {
213               checkGroupState(group);
214             }
215           }
216         }
217
218         if (!allFeatures.contains(tmpfeatures[index].getType()))
219         {
220           allFeatures.addElement(tmpfeatures[index].getType());
221         }
222         index++;
223       }
224     }
225
226     resetTable(null);
227
228     validate();
229   }
230
231   /**
232    * 
233    * @param group
234    * @return true if group has been seen before and is already added to set.
235    */
236   private boolean checkGroupState(String group)
237   {
238     boolean visible;
239     if (fr.featureGroups.containsKey(group))
240     {
241       visible = ((Boolean) fr.featureGroups.get(group)).booleanValue();
242     }
243     else
244     {
245       visible = true; // new group is always made visible
246     }
247
248     if (groupPanel == null)
249     {
250       groupPanel = new JPanel();
251     }
252
253     boolean alreadyAdded = false;
254     for (int g = 0; g < groupPanel.getComponentCount(); g++)
255     {
256       if (((JCheckBox) groupPanel.getComponent(g)).getText().equals(group))
257       {
258         alreadyAdded = true;
259         ((JCheckBox) groupPanel.getComponent(g)).setSelected(visible);
260         break;
261       }
262     }
263
264     if (alreadyAdded)
265     {
266
267       return true;
268     }
269
270     fr.featureGroups.put(group, new Boolean(visible));
271     final String grp = group;
272     final JCheckBox check = new JCheckBox(group, visible);
273     check.setFont(new Font("Serif", Font.BOLD, 12));
274     check.addItemListener(new ItemListener()
275     {
276       public void itemStateChanged(ItemEvent evt)
277       {
278         fr.featureGroups.put(check.getText(), new Boolean(check
279                 .isSelected()));
280         af.alignPanel.seqPanel.seqCanvas.repaint();
281         if (af.alignPanel.overviewPanel != null)
282         {
283           af.alignPanel.overviewPanel.updateOverviewImage();
284         }
285
286         resetTable(new String[]
287         { grp });
288       }
289     });
290     groupPanel.add(check);
291     return false;
292   }
293
294   boolean resettingTable = false;
295
296   synchronized void resetTable(String[] groupChanged)
297   {
298     if (resettingTable == true)
299     {
300       return;
301     }
302     resettingTable = true;
303     typeWidth = new Hashtable();
304     // TODO: change avWidth calculation to 'per-sequence' average and use long
305     // rather than float
306     float[] avWidth = null;
307     SequenceFeature[] tmpfeatures;
308     String group = null, type;
309     Vector visibleChecks = new Vector();
310
311     // Find out which features should be visible depending on which groups
312     // are selected / deselected
313     // and recompute average width ordering
314     for (int i = 0; i < af.getViewport().alignment.getHeight(); i++)
315     {
316
317       tmpfeatures = af.getViewport().alignment.getSequenceAt(i)
318               .getDatasetSequence().getSequenceFeatures();
319       if (tmpfeatures == null)
320       {
321         continue;
322       }
323
324       int index = 0;
325       while (index < tmpfeatures.length)
326       {
327         group = tmpfeatures[index].featureGroup;
328
329         if (tmpfeatures[index].begin == 0 && tmpfeatures[index].end == 0)
330         {
331           index++;
332           continue;
333         }
334
335         if (group == null || fr.featureGroups.get(group) == null
336                 || ((Boolean) fr.featureGroups.get(group)).booleanValue())
337         {
338           if (group != null)
339             checkGroupState(group);
340           type = tmpfeatures[index].getType();
341           if (!visibleChecks.contains(type))
342           {
343             visibleChecks.addElement(type);
344           }
345         }
346         if (!typeWidth.containsKey(tmpfeatures[index].getType()))
347         {
348           typeWidth.put(tmpfeatures[index].getType(),
349                   avWidth = new float[3]);
350         }
351         else
352         {
353           avWidth = (float[]) typeWidth.get(tmpfeatures[index].getType());
354         }
355         avWidth[0]++;
356         if (tmpfeatures[index].getBegin() > tmpfeatures[index].getEnd())
357         {
358           avWidth[1] += 1 + tmpfeatures[index].getBegin()
359                   - tmpfeatures[index].getEnd();
360         }
361         else
362         {
363           avWidth[1] += 1 + tmpfeatures[index].getEnd()
364                   - tmpfeatures[index].getBegin();
365         }
366         index++;
367       }
368     }
369
370     int fSize = visibleChecks.size();
371     Object[][] data = new Object[fSize][3];
372     int dataIndex = 0;
373
374     if (fr.renderOrder != null)
375     {
376       if (!handlingUpdate)
377         fr.findAllFeatures(groupChanged != null); // prod to update
378                                                   // colourschemes. but don't
379                                                   // affect display
380       // First add the checks in the previous render order,
381       // in case the window has been closed and reopened
382       for (int ro = fr.renderOrder.length - 1; ro > -1; ro--)
383       {
384         type = fr.renderOrder[ro];
385
386         if (!visibleChecks.contains(type))
387         {
388           continue;
389         }
390
391         data[dataIndex][0] = type;
392         data[dataIndex][1] = fr.getColour(type);
393         data[dataIndex][2] = new Boolean(af.getViewport().featuresDisplayed
394                 .containsKey(type));
395         dataIndex++;
396         visibleChecks.removeElement(type);
397       }
398     }
399
400     fSize = visibleChecks.size();
401     for (int i = 0; i < fSize; i++)
402     {
403       // These must be extra features belonging to the group
404       // which was just selected
405       type = visibleChecks.elementAt(i).toString();
406       data[dataIndex][0] = type;
407
408       data[dataIndex][1] = fr.getColour(type);
409       if (data[dataIndex][1] == null)
410       {
411         // "Colour has been updated in another view!!"
412         fr.renderOrder = null;
413         return;
414       }
415
416       data[dataIndex][2] = new Boolean(true);
417       dataIndex++;
418     }
419
420     if (originalData == null)
421     {
422       originalData = new Object[data.length][3];
423       System.arraycopy(data, 0, originalData, 0, data.length);
424     }
425
426     table.setModel(new FeatureTableModel(data));
427     table.getColumnModel().getColumn(0).setPreferredWidth(200);
428
429     if (groupPanel != null)
430     {
431       groupPanel.setLayout(new GridLayout(fr.featureGroups.size() / 4 + 1,
432               4));
433
434       groupPanel.validate();
435       bigPanel.add(groupPanel, BorderLayout.NORTH);
436     }
437
438     updateFeatureRenderer(data, groupChanged != null);
439     resettingTable = false;
440   }
441
442   /**
443    * reorder data based on the featureRenderers global priority list.
444    * 
445    * @param data
446    */
447   private void ensureOrder(Object[][] data)
448   {
449     boolean sort = false;
450     float[] order = new float[data.length];
451     for (int i = 0; i < order.length; i++)
452     {
453       order[i] = fr.getOrder(data[i][0].toString());
454       if (order[i] < 0)
455         order[i] = fr.setOrder(data[i][0].toString(), i / order.length);
456       if (i > 1)
457         sort = sort || order[i - 1] > order[i];
458     }
459     if (sort)
460       jalview.util.QuickSort.sort(order, data);
461   }
462
463   void load()
464   {
465     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
466             .getProperty("LAST_DIRECTORY"), new String[]
467     { "fc" }, new String[]
468     { "Sequence Feature Colours" }, "Sequence Feature Colours");
469     chooser.setFileView(new jalview.io.JalviewFileView());
470     chooser.setDialogTitle("Load Feature Colours");
471     chooser.setToolTipText("Load");
472
473     int value = chooser.showOpenDialog(this);
474
475     if (value == JalviewFileChooser.APPROVE_OPTION)
476     {
477       File file = chooser.getSelectedFile();
478
479       try
480       {
481         InputStreamReader in = new InputStreamReader(new FileInputStream(
482                 file), "UTF-8");
483
484         jalview.binding.JalviewUserColours jucs = new jalview.binding.JalviewUserColours();
485         jucs = (jalview.binding.JalviewUserColours) jucs.unmarshal(in);
486
487         for (int i = jucs.getColourCount() - 1; i >= 0; i--)
488         {
489           String name;
490           fr.setColour(name = jucs.getColour(i).getName(), new Color(
491                   Integer.parseInt(jucs.getColour(i).getRGB(), 16)));
492           fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount());
493         }
494         if (table != null)
495         {
496           resetTable(null);
497           Object[][] data = ((FeatureTableModel) table.getModel())
498                   .getData();
499           ensureOrder(data);
500           updateFeatureRenderer(data, false);
501           table.repaint();
502         }
503       } catch (Exception ex)
504       {
505         System.out.println("Error loading User Colour File\n" + ex);
506       }
507     }
508   }
509
510   void save()
511   {
512     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
513             .getProperty("LAST_DIRECTORY"), new String[]
514     { "fc" }, new String[]
515     { "Sequence Feature Colours" }, "Sequence Feature Colours");
516     chooser.setFileView(new jalview.io.JalviewFileView());
517     chooser.setDialogTitle("Save Feature Colour Scheme");
518     chooser.setToolTipText("Save");
519
520     int value = chooser.showSaveDialog(this);
521
522     if (value == JalviewFileChooser.APPROVE_OPTION)
523     {
524       String choice = chooser.getSelectedFile().getPath();
525       jalview.binding.JalviewUserColours ucs = new jalview.binding.JalviewUserColours();
526       ucs.setSchemeName("Sequence Features");
527       try
528       {
529         PrintWriter out = new PrintWriter(new OutputStreamWriter(
530                 new FileOutputStream(choice), "UTF-8"));
531
532         Enumeration e = fr.featureColours.keys();
533         float[] sortOrder = new float[fr.featureColours.size()];
534         String[] sortTypes = new String[fr.featureColours.size()];
535         int i = 0;
536         while (e.hasMoreElements())
537         {
538           sortTypes[i] = e.nextElement().toString();
539           sortOrder[i] = fr.getOrder(sortTypes[i]);
540           i++;
541         }
542         jalview.util.QuickSort.sort(sortOrder, sortTypes);
543         sortOrder = null;
544         for (i = 0; i < sortTypes.length; i++)
545         {
546           jalview.binding.Colour col = new jalview.binding.Colour();
547           col.setName(sortTypes[i]);
548           col.setRGB(jalview.util.Format.getHexString(fr.getColour(col
549                   .getName())));
550           ucs.addColour(col);
551         }
552         ucs.marshal(out);
553         out.close();
554       } catch (Exception ex)
555       {
556         ex.printStackTrace();
557       }
558     }
559   }
560
561   public void invertSelection()
562   {
563     for (int i = 0; i < table.getRowCount(); i++)
564     {
565       Boolean value = (Boolean) table.getValueAt(i, 2);
566
567       table.setValueAt(new Boolean(!value.booleanValue()), i, 2);
568     }
569   }
570
571   public void orderByAvWidth()
572   {
573     if (table == null || table.getModel() == null)
574       return;
575     Object[][] data = ((FeatureTableModel) table.getModel()).getData();
576     float[] width = new float[data.length];
577     float[] awidth;
578     float max = 0;
579     int num = 0;
580     for (int i = 0; i < data.length; i++)
581     {
582       awidth = (float[]) typeWidth.get(data[i][0]);
583       if (awidth[0] > 0)
584       {
585         width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better
586                                           // weight - but have to make per
587                                           // sequence, too (awidth[2])
588         // if (width[i]==1) // hack to distinguish single width sequences.
589         num++;
590       }
591       else
592       {
593         width[i] = 0;
594       }
595       if (max < width[i])
596         max = width[i];
597     }
598     boolean sort = false;
599     for (int i = 0; i < width.length; i++)
600     {
601       // awidth = (float[]) typeWidth.get(data[i][0]);
602       if (width[i] == 0)
603       {
604         width[i] = fr.getOrder(data[i][0].toString());
605         if (width[i] < 0)
606         {
607           width[i] = fr.setOrder(data[i][0].toString(), i / data.length);
608         }
609       }
610       else
611       {
612         width[i] /= max; // normalize
613         fr.setOrder(data[i][0].toString(), width[i]); // store for later
614       }
615       if (i > 0)
616         sort = sort || width[i - 1] > width[i];
617     }
618     if (sort)
619       jalview.util.QuickSort.sort(width, data);
620     // update global priority order
621
622     updateFeatureRenderer(data, false);
623     table.repaint();
624   }
625
626   public void close()
627   {
628     try
629     {
630       frame.setClosed(true);
631     } catch (Exception exe)
632     {
633     }
634
635   }
636
637   public void updateFeatureRenderer(Object[][] data)
638   {
639     updateFeatureRenderer(data, true);
640   }
641
642   private void updateFeatureRenderer(Object[][] data, boolean visibleNew)
643   {
644     fr.setFeaturePriority(data, visibleNew);
645     af.alignPanel.paintAlignment(true);
646   }
647
648   int selectedRow = -1;
649
650   JTabbedPane tabbedPane = new JTabbedPane();
651
652   BorderLayout borderLayout1 = new BorderLayout();
653
654   BorderLayout borderLayout2 = new BorderLayout();
655
656   BorderLayout borderLayout3 = new BorderLayout();
657
658   JPanel bigPanel = new JPanel();
659
660   BorderLayout borderLayout4 = new BorderLayout();
661
662   JButton invert = new JButton();
663
664   JPanel buttonPanel = new JPanel();
665
666   JButton cancel = new JButton();
667
668   JButton ok = new JButton();
669
670   JButton loadColours = new JButton();
671
672   JButton saveColours = new JButton();
673
674   JPanel dasButtonPanel = new JPanel();
675
676   JButton fetchDAS = new JButton();
677
678   JButton saveDAS = new JButton();
679
680   JButton cancelDAS = new JButton();
681
682   JButton optimizeOrder = new JButton();
683
684   JPanel transbuttons = new JPanel(new BorderLayout());
685
686   private void jbInit() throws Exception
687   {
688     this.setLayout(borderLayout1);
689     settingsPane.setLayout(borderLayout2);
690     dasSettingsPane.setLayout(borderLayout3);
691     bigPanel.setLayout(borderLayout4);
692     invert.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
693     invert.setText("Invert Selection");
694     invert.addActionListener(new ActionListener()
695     {
696       public void actionPerformed(ActionEvent e)
697       {
698         invertSelection();
699       }
700     });
701     optimizeOrder.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
702     optimizeOrder.setText("Optimise Order");
703     optimizeOrder.addActionListener(new ActionListener()
704     {
705       public void actionPerformed(ActionEvent e)
706       {
707         orderByAvWidth();
708       }
709     });
710     cancel.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
711     cancel.setText("Cancel");
712     cancel.addActionListener(new ActionListener()
713     {
714       public void actionPerformed(ActionEvent e)
715       {
716         updateFeatureRenderer(originalData);
717         close();
718       }
719     });
720     ok.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
721     ok.setText("OK");
722     ok.addActionListener(new ActionListener()
723     {
724       public void actionPerformed(ActionEvent e)
725       {
726         close();
727       }
728     });
729     loadColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
730     loadColours.setText("Load Colours");
731     loadColours.addActionListener(new ActionListener()
732     {
733       public void actionPerformed(ActionEvent e)
734       {
735         load();
736       }
737     });
738     saveColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
739     saveColours.setText("Save Colours");
740     saveColours.addActionListener(new ActionListener()
741     {
742       public void actionPerformed(ActionEvent e)
743       {
744         save();
745       }
746     });
747     transparency.addChangeListener(new ChangeListener()
748     {
749       public void stateChanged(ChangeEvent evt)
750       {
751         fr.setTransparency((float) (100 - transparency.getValue()) / 100f);
752         af.alignPanel.paintAlignment(true);
753       }
754     });
755
756     transparency.setMaximum(70);
757     fetchDAS.setText("Fetch DAS Features");
758     fetchDAS.addActionListener(new ActionListener()
759     {
760       public void actionPerformed(ActionEvent e)
761       {
762         fetchDAS_actionPerformed(e);
763       }
764     });
765     saveDAS.setText("Save as default");
766     saveDAS.addActionListener(new ActionListener()
767     {
768       public void actionPerformed(ActionEvent e)
769       {
770         saveDAS_actionPerformed(e);
771       }
772     });
773     dasButtonPanel.setBorder(BorderFactory.createEtchedBorder());
774     dasSettingsPane.setBorder(null);
775     cancelDAS.setEnabled(false);
776     cancelDAS.setText("Cancel Fetch");
777     cancelDAS.addActionListener(new ActionListener()
778     {
779       public void actionPerformed(ActionEvent e)
780       {
781         cancelDAS_actionPerformed(e);
782       }
783     });
784     this.add(tabbedPane, java.awt.BorderLayout.CENTER);
785     tabbedPane.addTab("Feature Settings", settingsPane);
786     tabbedPane.addTab("DAS Settings", dasSettingsPane);
787     bigPanel.add(transPanel, java.awt.BorderLayout.SOUTH);
788     transPanel.add(transparency);
789     transbuttons.add(invert, java.awt.BorderLayout.NORTH);
790     transbuttons.add(optimizeOrder, java.awt.BorderLayout.SOUTH);
791     transPanel.add(transbuttons);
792     buttonPanel.add(ok);
793     buttonPanel.add(cancel);
794     buttonPanel.add(loadColours);
795     buttonPanel.add(saveColours);
796     bigPanel.add(scrollPane, java.awt.BorderLayout.CENTER);
797     dasSettingsPane.add(dasButtonPanel, java.awt.BorderLayout.SOUTH);
798     dasButtonPanel.add(fetchDAS);
799     dasButtonPanel.add(cancelDAS);
800     dasButtonPanel.add(saveDAS);
801     settingsPane.add(bigPanel, java.awt.BorderLayout.CENTER);
802     settingsPane.add(buttonPanel, java.awt.BorderLayout.SOUTH);
803   }
804
805   public void fetchDAS_actionPerformed(ActionEvent e)
806   {
807     fetchDAS.setEnabled(false);
808     cancelDAS.setEnabled(true);
809     Vector selectedSources = dassourceBrowser.getSelectedSources();
810     doDasFeatureFetch(selectedSources, true, true);
811   }
812
813   /**
814    * get the features from selectedSources for all or the current selection
815    * 
816    * @param selectedSources
817    * @param checkDbRefs
818    * @param promptFetchDbRefs
819    */
820   private void doDasFeatureFetch(Vector selectedSources,
821           boolean checkDbRefs, boolean promptFetchDbRefs)
822   {
823     SequenceI[] dataset, seqs;
824     int iSize;
825     AlignViewport vp = af.getViewport();
826     if (vp.getSelectionGroup() != null
827             && vp.getSelectionGroup().getSize() > 0)
828     {
829       iSize = vp.getSelectionGroup().getSize();
830       dataset = new SequenceI[iSize];
831       seqs = vp.getSelectionGroup().getSequencesInOrder(vp.getAlignment());
832     }
833     else
834     {
835       iSize = vp.getAlignment().getHeight();
836       seqs = vp.getAlignment().getSequencesArray();
837     }
838
839     dataset = new SequenceI[iSize];
840     for (int i = 0; i < iSize; i++)
841     {
842       dataset[i] = seqs[i].getDatasetSequence();
843     }
844
845     cancelDAS.setEnabled(true);
846     dasFeatureFetcher = new jalview.ws.DasSequenceFeatureFetcher(dataset,
847             this, selectedSources, checkDbRefs, promptFetchDbRefs);
848     af.getViewport().setShowSequenceFeatures(true);
849     af.showSeqFeatures.setSelected(true);
850   }
851
852   /**
853    * properly initialise DAS fetcher and then initiate a new thread to fetch
854    * features from the named sources (rather than any turned on by default)
855    * 
856    * @param sources
857    */
858   public void fetchDasFeatures(Vector sources)
859   {
860     Thread thr = new Thread(new Runnable()
861     {
862       public void run()
863       {
864         // this actually initialises the das source list
865         dassourceBrowser.paintComponent(null); // yuk
866       }
867     });
868     thr.start();
869     while (dassourceBrowser.loadingDasSources
870             || dassourceBrowser.dasSources == null)
871     {
872       try
873       {
874         Thread.sleep(10);
875       } catch (Exception e)
876       {
877       }
878       ;
879     }
880     Vector resolved = new Vector();
881     if (sources != null)
882     {
883       for (int i = 0; i < dassourceBrowser.dasSources.length; i++)
884       {
885         if (sources.contains(dassourceBrowser.dasSources[i].getNickname()))
886         {
887           if (!resolved.contains(dassourceBrowser.dasSources[i]))
888           {
889             resolved.addElement(dassourceBrowser.dasSources[i]);
890           }
891         }
892       }
893     }
894     if (resolved.size() == 0)
895     {
896       resolved = dassourceBrowser.getSelectedSources();
897     }
898     if (resolved.size() > 0)
899     {
900       final Vector dassources = resolved;
901       SwingUtilities.invokeLater(new Runnable()
902       {
903
904         public void run()
905         {
906           fetchDAS.setEnabled(false);
907           cancelDAS.setEnabled(true);
908           doDasFeatureFetch(dassources, true, false);
909
910         }
911       });
912     }
913   }
914
915   public void saveDAS_actionPerformed(ActionEvent e)
916   {
917     dassourceBrowser
918             .saveProperties(jalview.bin.Cache.applicationProperties);
919   }
920
921   public void complete()
922   {
923     fetchDAS.setEnabled(true);
924     cancelDAS.setEnabled(false);
925   }
926
927   public void cancelDAS_actionPerformed(ActionEvent e)
928   {
929     if (dasFeatureFetcher != null)
930     {
931       dasFeatureFetcher.cancel();
932     }
933     fetchDAS.setEnabled(true);
934     cancelDAS.setEnabled(false);
935   }
936
937   public void noDasSourceActive()
938   {
939     complete();
940     JOptionPane.showInternalConfirmDialog(Desktop.desktop,
941             "No das sources were selected.\n"
942                     + "Please select some sources and\n" + " try again.",
943             "No Sources Selected", JOptionPane.DEFAULT_OPTION,
944             JOptionPane.INFORMATION_MESSAGE);
945   }
946
947   // ///////////////////////////////////////////////////////////////////////
948   // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
949   // ///////////////////////////////////////////////////////////////////////
950   class FeatureTableModel extends AbstractTableModel
951   {
952     FeatureTableModel(Object[][] data)
953     {
954       this.data = data;
955     }
956
957     private String[] columnNames =
958     { "Feature Type", "Colour", "Display" };
959
960     private Object[][] data;
961
962     public Object[][] getData()
963     {
964       return data;
965     }
966
967     public void setData(Object[][] data)
968     {
969       this.data = data;
970     }
971
972     public int getColumnCount()
973     {
974       return columnNames.length;
975     }
976
977     public Object[] getRow(int row)
978     {
979       return data[row];
980     }
981
982     public int getRowCount()
983     {
984       return data.length;
985     }
986
987     public String getColumnName(int col)
988     {
989       return columnNames[col];
990     }
991
992     public Object getValueAt(int row, int col)
993     {
994       return data[row][col];
995     }
996
997     public Class getColumnClass(int c)
998     {
999       return getValueAt(0, c).getClass();
1000     }
1001
1002     public boolean isCellEditable(int row, int col)
1003     {
1004       return col == 0 ? false : true;
1005     }
1006
1007     public void setValueAt(Object value, int row, int col)
1008     {
1009       data[row][col] = value;
1010       fireTableCellUpdated(row, col);
1011       updateFeatureRenderer(data);
1012     }
1013
1014   }
1015
1016   class ColorRenderer extends JLabel implements TableCellRenderer
1017   {
1018     javax.swing.border.Border unselectedBorder = null;
1019
1020     javax.swing.border.Border selectedBorder = null;
1021
1022     public ColorRenderer()
1023     {
1024       setOpaque(true); // MUST do this for background to show up.
1025     }
1026
1027     public Component getTableCellRendererComponent(JTable table,
1028             Object color, boolean isSelected, boolean hasFocus, int row,
1029             int column)
1030     {
1031       Color newColor = (Color) color;
1032       setBackground(newColor);
1033       if (isSelected)
1034       {
1035         if (selectedBorder == null)
1036         {
1037           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1038                   table.getSelectionBackground());
1039         }
1040         setBorder(selectedBorder);
1041       }
1042       else
1043       {
1044         if (unselectedBorder == null)
1045         {
1046           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1047                   table.getBackground());
1048         }
1049         setBorder(unselectedBorder);
1050       }
1051
1052       setToolTipText("RGB value: " + newColor.getRed() + ", "
1053               + newColor.getGreen() + ", " + newColor.getBlue());
1054       return this;
1055     }
1056   }
1057 }
1058
1059 class ColorEditor extends AbstractCellEditor implements TableCellEditor,
1060         ActionListener
1061 {
1062   Color currentColor;
1063
1064   JButton button;
1065
1066   JColorChooser colorChooser;
1067
1068   JDialog dialog;
1069
1070   protected static final String EDIT = "edit";
1071
1072   public ColorEditor()
1073   {
1074     // Set up the editor (from the table's point of view),
1075     // which is a button.
1076     // This button brings up the color chooser dialog,
1077     // which is the editor from the user's point of view.
1078     button = new JButton();
1079     button.setActionCommand(EDIT);
1080     button.addActionListener(this);
1081     button.setBorderPainted(false);
1082     // Set up the dialog that the button brings up.
1083     colorChooser = new JColorChooser();
1084     dialog = JColorChooser.createDialog(button, "Select new Colour", true, // modal
1085             colorChooser, this, // OK button handler
1086             null); // no CANCEL button handler
1087   }
1088
1089   /**
1090    * Handles events from the editor button and from the dialog's OK button.
1091    */
1092   public void actionPerformed(ActionEvent e)
1093   {
1094
1095     if (EDIT.equals(e.getActionCommand()))
1096     {
1097       // The user has clicked the cell, so
1098       // bring up the dialog.
1099       button.setBackground(currentColor);
1100       colorChooser.setColor(currentColor);
1101       dialog.setVisible(true);
1102
1103       // Make the renderer reappear.
1104       fireEditingStopped();
1105
1106     }
1107     else
1108     { // User pressed dialog's "OK" button.
1109       currentColor = colorChooser.getColor();
1110     }
1111   }
1112
1113   // Implement the one CellEditor method that AbstractCellEditor doesn't.
1114   public Object getCellEditorValue()
1115   {
1116     return currentColor;
1117   }
1118
1119   // Implement the one method defined by TableCellEditor.
1120   public Component getTableCellEditorComponent(JTable table, Object value,
1121           boolean isSelected, int row, int column)
1122   {
1123     currentColor = (Color) value;
1124     return button;
1125   }
1126 }