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