apply gpl development license
[jalview.git] / src / jalview / appletgui / FeatureSettings.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3  * Copyright (C) 2009 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.appletgui;
20
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25
26 import jalview.analysis.AlignmentSorter;
27 import jalview.commands.OrderCommand;
28 import jalview.datamodel.*;
29
30 public class FeatureSettings extends Panel implements ItemListener,
31         MouseListener, MouseMotionListener, ActionListener,
32         AdjustmentListener
33 {
34   FeatureRenderer fr;
35
36   AlignmentPanel ap;
37
38   AlignViewport av;
39
40   Frame frame;
41
42   Panel groupPanel;
43
44   Panel featurePanel = new Panel();
45
46   ScrollPane scrollPane;
47
48   boolean alignmentHasFeatures = false;
49
50   Image linkImage;
51
52   Scrollbar transparency;
53
54   public FeatureSettings(final AlignmentPanel ap)
55   {
56     this.ap = ap;
57     this.av = ap.av;
58     ap.av.featureSettings = this;
59     fr = ap.seqPanel.seqCanvas.getFeatureRenderer();
60
61     transparency = new Scrollbar(Scrollbar.HORIZONTAL,
62             100 - (int) (fr.transparency * 100), 1, 1, 100);
63
64     if (fr.transparencySetter != null)
65     {
66       transparency.addAdjustmentListener(this);
67     }
68     else
69     {
70       transparency.setEnabled(false);
71     }
72
73     java.net.URL url = getClass().getResource("/images/link.gif");
74     if (url != null)
75     {
76       linkImage = java.awt.Toolkit.getDefaultToolkit().getImage(url);
77     }
78
79     if (av.featuresDisplayed == null)
80     {
81       fr.findAllFeatures();
82     }
83
84     setTableData();
85
86     this.setLayout(new BorderLayout());
87     scrollPane = new ScrollPane();
88     scrollPane.add(featurePanel);
89     if (alignmentHasFeatures)
90     {
91       add(scrollPane, BorderLayout.CENTER);
92     }
93
94     Button invert = new Button("Invert Selection");
95     invert.addActionListener(this);
96
97     Panel lowerPanel = new Panel(new GridLayout(2, 1, 5, 10));
98     lowerPanel.add(invert);
99
100     Panel tPanel = new Panel(new BorderLayout());
101
102     if (fr.transparencySetter != null)
103     {
104       tPanel.add(transparency, BorderLayout.CENTER);
105       tPanel.add(new Label("Transparency"), BorderLayout.EAST);
106     }
107     else
108     {
109       tPanel.add(
110               new Label("Transparency not available in this web browser"),
111               BorderLayout.CENTER);
112     }
113
114     lowerPanel.add(tPanel, BorderLayout.SOUTH);
115
116     add(lowerPanel, BorderLayout.SOUTH);
117
118     if (groupPanel != null)
119     {
120       groupPanel.setLayout(new GridLayout(fr.featureGroups.size() / 4 + 1,
121               4));
122       groupPanel.validate();
123
124       add(groupPanel, BorderLayout.NORTH);
125     }
126     frame = new Frame();
127     frame.add(this);
128     final FeatureSettings me = this;
129     frame.addWindowListener(new WindowAdapter()
130     {
131       public void windowClosing(WindowEvent e)
132       {
133         if (me.av.featureSettings == me)
134         {
135           me.av.featureSettings = null;
136           me.ap = null;
137           me.av = null;
138         }
139       }
140     });
141     int height = featurePanel.getComponentCount() * 50 + 60;
142
143     height = Math.max(200, height);
144     height = Math.min(400, height);
145     int width = 300;
146     jalview.bin.JalviewLite.addFrame(frame, "Feature Settings", width,
147             height);
148   }
149
150   public void paint(Graphics g)
151   {
152     g.setColor(Color.black);
153     g.drawString("No Features added to this alignment!!", 10, 20);
154     g.drawString("(Features can be added from searches or", 10, 40);
155     g.drawString("from Jalview / GFF features files)", 10, 60);
156   }
157   protected void popupSort(final String type, final Hashtable minmax,
158           int x, int y)
159   {
160     java.awt.PopupMenu men = new PopupMenu("Settings for " + type);
161     java.awt.MenuItem scr = new MenuItem("Sort by Score");
162     men.add(scr);
163     final FeatureSettings me = this;
164     scr.addActionListener(new ActionListener()
165     {
166
167       public void actionPerformed(ActionEvent e)
168       {
169         me.sortByScore(new String[]
170         { type });
171       }
172
173     });
174     MenuItem dens = new MenuItem("Sort by Density");
175     dens.addActionListener(new ActionListener()
176     {
177
178       public void actionPerformed(ActionEvent e)
179       {
180         me.sortByDens(new String[]
181         { type });
182       }
183
184     });
185     men.add(dens);
186     if (minmax != null)
187     {
188       final Object typeMinMax = minmax.get(type);
189       final java.awt.CheckboxMenuItem chb = new java.awt.CheckboxMenuItem("Vary Height");
190       // this is broken at the moment
191       chb.setState(minmax.get(type) != null);
192       chb.addActionListener(new ActionListener()
193       {
194
195         public void actionPerformed(ActionEvent e)
196         {
197           chb.setState(chb.getState());
198           if (chb.getState())
199           {
200             minmax.put(type, null);
201           }
202           else
203           {
204             minmax.put(type, typeMinMax);
205           }
206         }
207
208       });
209       men.add(chb);
210       if (typeMinMax != null && ((float[][]) typeMinMax)[0] != null)
211       {
212         // graduated colourschemes for those where minmax exists for the positional features
213         MenuItem mxcol = new MenuItem("Min Max Colour");
214         men.add(mxcol);
215         mxcol.addActionListener(new ActionListener()
216         {
217
218           public void actionPerformed(ActionEvent e)
219           {
220             new FeatureColourChooser(me, type);
221           }
222
223         });
224       }
225     }
226     this.featurePanel.add(men);
227     men.show(this.featurePanel, x, y);
228   }
229
230   public void setTableData()
231   {
232     alignmentHasFeatures = fr.buildGroupHash();
233     if (alignmentHasFeatures)
234     {
235       rebuildGroups();
236
237     }
238     resetTable(false);
239   }
240
241   /**
242    * rebuilds the group panel
243    */
244   public void rebuildGroups()
245   {
246     boolean rdrw = false;
247     if (groupPanel == null)
248     {
249       groupPanel = new Panel();
250     }
251     else
252     {
253       rdrw = true;
254       groupPanel.removeAll();
255     }
256
257     Enumeration gps = fr.featureGroups.keys();
258     while (gps.hasMoreElements())
259     {
260       String group = (String) gps.nextElement();
261       Boolean vis = (Boolean) fr.featureGroups.get(group);
262       Checkbox check = new MyCheckbox(group, vis.booleanValue(),
263               (fr.featureLinks != null && fr.featureLinks
264                       .containsKey(group)));
265       check.addMouseListener(this);
266       check.setFont(new Font("Serif", Font.BOLD, 12));
267       check.addItemListener(this);
268       groupPanel.add(check);
269     }
270     if (rdrw)
271     {
272       groupPanel.validate();
273     }
274   }
275
276   // This routine adds and removes checkboxes depending on
277   // Group selection states
278   void resetTable(boolean groupsChanged)
279   {
280     SequenceFeature[] tmpfeatures;
281     String group = null, type;
282     Vector visibleChecks = new Vector();
283
284     for (int i = 0; i < av.alignment.getHeight(); i++)
285     {
286       if (av.alignment.getSequenceAt(i).getSequenceFeatures() == null)
287       {
288         continue;
289       }
290
291       tmpfeatures = av.alignment.getSequenceAt(i).getSequenceFeatures();
292       int index = 0;
293       while (index < tmpfeatures.length)
294       {
295         group = tmpfeatures[index].featureGroup;
296
297         if (group == null || fr.featureGroups.get(group) == null
298                 || ((Boolean) fr.featureGroups.get(group)).booleanValue())
299         {
300           type = tmpfeatures[index].getType();
301           if (!visibleChecks.contains(type))
302           {
303             visibleChecks.addElement(type);
304           }
305         }
306         index++;
307       }
308     }
309
310     Component[] comps;
311     int cSize = featurePanel.getComponentCount();
312     Checkbox check;
313     // This will remove any checkboxes which shouldn't be
314     // visible
315     for (int i = 0; i < cSize; i++)
316     {
317       comps = featurePanel.getComponents();
318       check = (Checkbox) comps[i];
319       if (!visibleChecks.contains(check.getLabel()))
320       {
321         featurePanel.remove(i);
322         cSize--;
323         i--;
324       }
325     }
326
327     if (fr.renderOrder != null)
328     {
329       // First add the checks in the previous render order,
330       // in case the window has been closed and reopened
331       for (int ro = fr.renderOrder.length - 1; ro > -1; ro--)
332       {
333         String item = fr.renderOrder[ro];
334
335         if (!visibleChecks.contains(item))
336         {
337           continue;
338         }
339
340         visibleChecks.removeElement(item);
341
342         addCheck(false, item);
343       }
344     }
345
346     // now add checkboxes which should be visible,
347     // if they have not already been added
348     Enumeration en = visibleChecks.elements();
349
350     while (en.hasMoreElements())
351     {
352       addCheck(groupsChanged, en.nextElement().toString());
353     }
354
355     featurePanel.setLayout(new GridLayout(featurePanel.getComponentCount(),
356             1, 10, 5));
357     featurePanel.validate();
358
359     if (scrollPane != null)
360     {
361       scrollPane.validate();
362     }
363
364     itemStateChanged(null);
365   }
366
367   /**
368    * update the checklist of feature types with the given type
369    * 
370    * @param groupsChanged
371    *                true means if the type is not in the display list then it
372    *                will be added and displayed
373    * @param type
374    *                feature type to be checked for in the list.
375    */
376   void addCheck(boolean groupsChanged, String type)
377   {
378     boolean addCheck;
379     Component[] comps = featurePanel.getComponents();
380     Checkbox check;
381     addCheck = true;
382     for (int i = 0; i < featurePanel.getComponentCount(); i++)
383     {
384       check = (Checkbox) comps[i];
385       if (check.getLabel().equals(type))
386       {
387         addCheck = false;
388         break;
389       }
390     }
391
392     if (addCheck)
393     {
394       boolean selected = false;
395       if (groupsChanged || av.featuresDisplayed.containsKey(type))
396       {
397         selected = true;
398       }
399
400       check = new MyCheckbox(
401               type,
402               selected,
403               (fr.featureLinks != null && fr.featureLinks.containsKey(type)));
404
405       check.addMouseListener(this);
406       check.addMouseMotionListener(this);
407       check.setBackground(fr.getColour(type));
408       check.addItemListener(this);
409       if (groupsChanged)
410       {
411         // add at beginning of stack.
412         featurePanel.add(check, 0);
413       }
414       else
415       {
416         // add at end of stack.
417         featurePanel.add(check);
418       }
419     }
420   }
421
422   public void actionPerformed(ActionEvent evt)
423   {
424     for (int i = 0; i < featurePanel.getComponentCount(); i++)
425     {
426       Checkbox check = (Checkbox) featurePanel.getComponent(i);
427       check.setState(!check.getState());
428     }
429     selectionChanged();
430   }
431
432   public void itemStateChanged(ItemEvent evt)
433   {
434     if (evt != null)
435     {
436       // Is the source a top level featureGroup?
437       Checkbox source = (Checkbox) evt.getSource();
438       if (fr.featureGroups.containsKey(source.getLabel()))
439       {
440         fr.featureGroups.put(source.getLabel(), new Boolean(source
441                 .getState()));
442         ap.seqPanel.seqCanvas.repaint();
443         if (ap.overviewPanel != null)
444         {
445           ap.overviewPanel.updateOverviewImage();
446         }
447
448         resetTable(true);
449         return;
450       }
451     }
452     selectionChanged();
453   }
454
455   void selectionChanged()
456   {
457     Component[] comps = featurePanel.getComponents();
458     int cSize = comps.length;
459
460     Object[][] tmp = new Object[cSize][3];
461     int tmpSize = 0;
462     for (int i = 0; i < cSize; i++)
463     {
464       Checkbox check = (Checkbox) comps[i];
465       tmp[tmpSize][0] = check.getLabel();
466       tmp[tmpSize][1] = fr.getColour(check.getLabel());
467       tmp[tmpSize][2] = new Boolean(check.getState());
468       tmpSize++;
469     }
470
471     Object[][] data = new Object[tmpSize][3];
472     System.arraycopy(tmp, 0, data, 0, tmpSize);
473
474     fr.setFeaturePriority(data);
475
476     ap.paintAlignment(true);
477   }
478
479   MyCheckbox selectedCheck;
480
481   boolean dragging = false;
482
483   public void mousePressed(MouseEvent evt)
484   {
485
486     selectedCheck = (MyCheckbox) evt.getSource();
487
488     if (fr.featureLinks != null
489             && fr.featureLinks.containsKey(selectedCheck.getLabel()))
490     {
491       if (evt.getX() > selectedCheck.stringWidth + 20)
492       {
493         evt.consume();
494       }
495     }
496
497   }
498
499   public void mouseDragged(MouseEvent evt)
500   {
501     if (((Component) evt.getSource()).getParent() != featurePanel)
502     {
503       return;
504     }
505     dragging = true;
506   }
507
508   public void mouseReleased(MouseEvent evt)
509   {
510     if (((Component) evt.getSource()).getParent() != featurePanel)
511     {
512       return;
513     }
514
515     Component comp = null;
516     Checkbox target = null;
517
518     int height = evt.getY() + evt.getComponent().getLocation().y;
519
520     if (height > featurePanel.getSize().height)
521     {
522
523       comp = featurePanel
524               .getComponent(featurePanel.getComponentCount() - 1);
525     }
526     else if (height < 0)
527     {
528       comp = featurePanel.getComponent(0);
529     }
530     else
531     {
532       comp = featurePanel.getComponentAt(evt.getX(), evt.getY()
533               + evt.getComponent().getLocation().y);
534     }
535
536     if (comp != null && comp instanceof Checkbox)
537     {
538       target = (Checkbox) comp;
539     }
540
541     if (selectedCheck != null && target != null && selectedCheck != target)
542     {
543       int targetIndex = -1;
544       for (int i = 0; i < featurePanel.getComponentCount(); i++)
545       {
546         if (target == featurePanel.getComponent(i))
547         {
548           targetIndex = i;
549           break;
550         }
551       }
552
553       featurePanel.remove(selectedCheck);
554       featurePanel.add(selectedCheck, targetIndex);
555       featurePanel.validate();
556       itemStateChanged(null);
557     }
558   }
559
560   public void setUserColour(String feature, Color col)
561   {
562     fr.setColour(feature, col);
563     featurePanel.removeAll();
564     resetTable(false);
565     ap.paintAlignment(true);
566   }
567
568   public void mouseEntered(MouseEvent evt)
569   {
570   }
571
572   public void mouseExited(MouseEvent evt)
573   {
574   }
575
576   public void mouseClicked(MouseEvent evt)
577   {
578     MyCheckbox check = (MyCheckbox) evt.getSource();
579     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK)!=0)
580     {
581       this.popupSort(check.getLabel(), fr.minmax, evt.getX(), evt.getY());
582     }
583     if (fr.featureLinks != null
584             && fr.featureLinks.containsKey(check.getLabel()))
585     {
586       if (evt.getX() > check.stringWidth + 20)
587       {
588         evt.consume();
589         String link = fr.featureLinks.get(check.getLabel()).toString();
590         ap.alignFrame.showURL(link.substring(link.indexOf("|") + 1), link
591                 .substring(0, link.indexOf("|")));
592       }
593     }
594
595     if (check.getParent() != featurePanel)
596     {
597       return;
598     }
599
600     if (evt.getClickCount() > 1)
601     {
602       new UserDefinedColours(this, check.getLabel(), fr.getColour(check
603               .getLabel()));
604     }
605   }
606
607   public void mouseMoved(MouseEvent evt)
608   {
609   }
610
611   public void adjustmentValueChanged(AdjustmentEvent evt)
612   {
613     fr.transparency = ((float) (100 - transparency.getValue()) / 100f);
614     ap.seqPanel.seqCanvas.repaint();
615
616   }
617
618   class MyCheckbox extends Checkbox
619   {
620     public int stringWidth;
621
622     boolean hasLink;
623
624     public MyCheckbox(String label, boolean checked, boolean haslink)
625     {
626       super(label, checked);
627
628       FontMetrics fm = av.nullFrame.getFontMetrics(av.nullFrame.getFont());
629       stringWidth = fm.stringWidth(label);
630       this.hasLink = haslink;
631     }
632
633     public void paint(Graphics g)
634     {
635       if (hasLink)
636       {
637         g.drawImage(linkImage, stringWidth + 25,
638                 (getSize().height - linkImage.getHeight(this)) / 2, this);
639       }
640     }
641   }
642   protected void sortByDens(String[] typ)
643   {
644     sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY);
645   }
646   private String[] getDisplayedFeatureTypes()
647   {
648     String[] typ = null;
649     if (fr != null)
650     {
651       synchronized (fr.renderOrder)
652       {
653         typ = new String[fr.renderOrder.length];
654         System.arraycopy(fr.renderOrder, 0, typ, 0, typ.length);
655         for (int i = 0; i < typ.length; i++)
656         {
657           if (av.featuresDisplayed.get(typ[i]) == null)
658           {
659             typ[i] = null;
660           }
661         }
662       }
663     }
664     return typ;
665   }
666
667
668   protected void sortBy(String[] typ, String methodText, final String method)
669   {
670     if (typ == null)
671     {
672       typ = getDisplayedFeatureTypes();
673     }
674     String gps[] = null;
675     gps = fr.getGroups(true);
676     if (typ != null)
677     {
678       for (int i = 0; i < typ.length; i++)
679       {
680         System.err.println("Sorting on Types:" + typ[i]);
681       }
682     }
683     if (gps != null)
684     {
685
686       for (int i = 0; i < gps.length; i++)
687       {
688         System.err.println("Sorting on groups:" + gps[i]);
689       }
690     }
691     AlignmentPanel alignPanel = ap;
692     AlignmentI al = alignPanel.av.getAlignment();
693
694     int start, stop;
695     SequenceGroup sg = alignPanel.av.getSelectionGroup();
696     if (sg != null)
697     {
698       start = sg.getStartRes();
699       stop = sg.getEndRes();
700     }
701     else
702     {
703       start = 0;
704       stop = al.getWidth();
705     }
706     SequenceI[] oldOrder = al.getSequencesArray();
707     AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method);
708     this.ap.alignFrame.addHistoryItem(new OrderCommand(methodText, oldOrder, alignPanel.av
709             .getAlignment()));
710     alignPanel.paintAlignment(true);
711
712   }
713
714   protected void sortByScore(String[] typ)
715   {
716     sortBy(typ, "Sort by Feature Score", AlignmentSorter.FEATURE_SCORE);
717   }
718
719 }