das source browser uses local source method from jalview.bin.Cache and methods refact...
[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    * blocking call to initialise the das source browser
854    */
855   public void initDasSources()
856   {
857     dassourceBrowser.initDasSources();
858   }
859   /**
860    * examine the current list of das sources and return any matching the given nicknames in sources 
861    * @param sources Vector of Strings to resolve to DAS source nicknames.
862    * @return sources that are present in source list.
863    */
864   public Vector resolveSourceNicknames(Vector sources)
865   {
866     return dassourceBrowser.resolveSourceNicknames(sources);
867   }
868   /**
869    * get currently selected das sources. ensure you have called initDasSources before calling this.
870    * @return vector of selected das source nicknames
871    */
872   public Vector getSelectedSources()
873   {
874     return dassourceBrowser.getSelectedSources();
875   }
876   /**
877    * properly initialise DAS fetcher and then initiate a new thread to fetch
878    * features from the named sources (rather than any turned on by default)
879    * 
880    * @param sources
881    */
882   public void fetchDasFeatures(Vector sources)
883   {
884     initDasSources();
885     Vector resolved = resolveSourceNicknames(sources);
886     if (resolved.size() == 0)
887     {
888       resolved = dassourceBrowser.getSelectedSources();
889     }
890     if (resolved.size() > 0)
891     {
892       final Vector dassources = resolved;
893       SwingUtilities.invokeLater(new Runnable()
894       {
895
896         public void run()
897         {
898           fetchDAS.setEnabled(false);
899           cancelDAS.setEnabled(true);
900           doDasFeatureFetch(dassources, true, false);
901
902         }
903       });
904     }
905   }
906
907   public void saveDAS_actionPerformed(ActionEvent e)
908   {
909     dassourceBrowser
910             .saveProperties(jalview.bin.Cache.applicationProperties);
911   }
912
913   public void complete()
914   {
915     fetchDAS.setEnabled(true);
916     cancelDAS.setEnabled(false);
917   }
918
919   public void cancelDAS_actionPerformed(ActionEvent e)
920   {
921     if (dasFeatureFetcher != null)
922     {
923       dasFeatureFetcher.cancel();
924     }
925     fetchDAS.setEnabled(true);
926     cancelDAS.setEnabled(false);
927   }
928
929   public void noDasSourceActive()
930   {
931     complete();
932     JOptionPane.showInternalConfirmDialog(Desktop.desktop,
933             "No das sources were selected.\n"
934                     + "Please select some sources and\n" + " try again.",
935             "No Sources Selected", JOptionPane.DEFAULT_OPTION,
936             JOptionPane.INFORMATION_MESSAGE);
937   }
938
939   // ///////////////////////////////////////////////////////////////////////
940   // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
941   // ///////////////////////////////////////////////////////////////////////
942   class FeatureTableModel extends AbstractTableModel
943   {
944     FeatureTableModel(Object[][] data)
945     {
946       this.data = data;
947     }
948
949     private String[] columnNames =
950     { "Feature Type", "Colour", "Display" };
951
952     private Object[][] data;
953
954     public Object[][] getData()
955     {
956       return data;
957     }
958
959     public void setData(Object[][] data)
960     {
961       this.data = data;
962     }
963
964     public int getColumnCount()
965     {
966       return columnNames.length;
967     }
968
969     public Object[] getRow(int row)
970     {
971       return data[row];
972     }
973
974     public int getRowCount()
975     {
976       return data.length;
977     }
978
979     public String getColumnName(int col)
980     {
981       return columnNames[col];
982     }
983
984     public Object getValueAt(int row, int col)
985     {
986       return data[row][col];
987     }
988
989     public Class getColumnClass(int c)
990     {
991       return getValueAt(0, c).getClass();
992     }
993
994     public boolean isCellEditable(int row, int col)
995     {
996       return col == 0 ? false : true;
997     }
998
999     public void setValueAt(Object value, int row, int col)
1000     {
1001       data[row][col] = value;
1002       fireTableCellUpdated(row, col);
1003       updateFeatureRenderer(data);
1004     }
1005
1006   }
1007
1008   class ColorRenderer extends JLabel implements TableCellRenderer
1009   {
1010     javax.swing.border.Border unselectedBorder = null;
1011
1012     javax.swing.border.Border selectedBorder = null;
1013
1014     public ColorRenderer()
1015     {
1016       setOpaque(true); // MUST do this for background to show up.
1017     }
1018
1019     public Component getTableCellRendererComponent(JTable table,
1020             Object color, boolean isSelected, boolean hasFocus, int row,
1021             int column)
1022     {
1023       Color newColor = (Color) color;
1024       setBackground(newColor);
1025       if (isSelected)
1026       {
1027         if (selectedBorder == null)
1028         {
1029           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1030                   table.getSelectionBackground());
1031         }
1032         setBorder(selectedBorder);
1033       }
1034       else
1035       {
1036         if (unselectedBorder == null)
1037         {
1038           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1039                   table.getBackground());
1040         }
1041         setBorder(unselectedBorder);
1042       }
1043
1044       setToolTipText("RGB value: " + newColor.getRed() + ", "
1045               + newColor.getGreen() + ", " + newColor.getBlue());
1046       return this;
1047     }
1048   }
1049 }
1050
1051 class ColorEditor extends AbstractCellEditor implements TableCellEditor,
1052         ActionListener
1053 {
1054   Color currentColor;
1055
1056   JButton button;
1057
1058   JColorChooser colorChooser;
1059
1060   JDialog dialog;
1061
1062   protected static final String EDIT = "edit";
1063
1064   public ColorEditor()
1065   {
1066     // Set up the editor (from the table's point of view),
1067     // which is a button.
1068     // This button brings up the color chooser dialog,
1069     // which is the editor from the user's point of view.
1070     button = new JButton();
1071     button.setActionCommand(EDIT);
1072     button.addActionListener(this);
1073     button.setBorderPainted(false);
1074     // Set up the dialog that the button brings up.
1075     colorChooser = new JColorChooser();
1076     dialog = JColorChooser.createDialog(button, "Select new Colour", true, // modal
1077             colorChooser, this, // OK button handler
1078             null); // no CANCEL button handler
1079   }
1080
1081   /**
1082    * Handles events from the editor button and from the dialog's OK button.
1083    */
1084   public void actionPerformed(ActionEvent e)
1085   {
1086
1087     if (EDIT.equals(e.getActionCommand()))
1088     {
1089       // The user has clicked the cell, so
1090       // bring up the dialog.
1091       button.setBackground(currentColor);
1092       colorChooser.setColor(currentColor);
1093       dialog.setVisible(true);
1094
1095       // Make the renderer reappear.
1096       fireEditingStopped();
1097
1098     }
1099     else
1100     { // User pressed dialog's "OK" button.
1101       currentColor = colorChooser.getColor();
1102     }
1103   }
1104
1105   // Implement the one CellEditor method that AbstractCellEditor doesn't.
1106   public Object getCellEditorValue()
1107   {
1108     return currentColor;
1109   }
1110
1111   // Implement the one method defined by TableCellEditor.
1112   public Component getTableCellEditorComponent(JTable table, Object value,
1113           boolean isSelected, int row, int column)
1114   {
1115     currentColor = (Color) value;
1116     return button;
1117   }
1118 }