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