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