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