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