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