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