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