JAL-1517 source formatting
[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,
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(
596               "Implementation error: Unsupported feature colour object.");
597     }
598     refreshTable();
599   }
600
601   public void refreshTable()
602   {
603     featurePanel.removeAll();
604     resetTable(false);
605     ap.paintAlignment(true);
606   }
607
608   public void mouseEntered(MouseEvent evt)
609   {
610   }
611
612   public void mouseExited(MouseEvent evt)
613   {
614   }
615
616   public void mouseClicked(MouseEvent evt)
617   {
618     MyCheckbox check = (MyCheckbox) evt.getSource();
619     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0)
620     {
621       this.popupSort(check, fr.minmax, evt.getX(), evt.getY());
622     }
623     if (fr.featureLinks != null && fr.featureLinks.containsKey(check.type))
624     {
625       if (evt.getX() > check.stringWidth + 20)
626       {
627         evt.consume();
628         String link = fr.featureLinks.get(check.type).toString();
629         ap.alignFrame.showURL(link.substring(link.indexOf("|") + 1),
630                 link.substring(0, link.indexOf("|")));
631       }
632     }
633
634     if (check.getParent() != featurePanel)
635     {
636       return;
637     }
638
639     if (evt.getClickCount() > 1)
640     {
641       Object fcol = fr.getFeatureStyle(check.type);
642       if (fcol instanceof Color)
643       {
644         new UserDefinedColours(this, check.type, (Color) fcol);
645       }
646       else
647       {
648         new FeatureColourChooser(this, check.type);
649         // write back the current colour object to update the table
650         check.updateColor(fr.getFeatureStyle(check.type));
651       }
652     }
653   }
654
655   public void mouseMoved(MouseEvent evt)
656   {
657   }
658
659   public void adjustmentValueChanged(AdjustmentEvent evt)
660   {
661     fr.transparency = ((float) (100 - transparency.getValue()) / 100f);
662     ap.seqPanel.seqCanvas.repaint();
663
664   }
665
666   class MyCheckbox extends Checkbox
667   {
668     public String type;
669
670     public int stringWidth;
671
672     boolean hasLink;
673
674     GraduatedColor gcol;
675
676     Color col;
677
678     public void updateColor(Object newcol)
679     {
680       if (newcol instanceof Color)
681       {
682         col = (Color) newcol;
683         gcol = null;
684       }
685       else if (newcol instanceof GraduatedColor)
686       {
687         gcol = (GraduatedColor) newcol;
688         col = null;
689       }
690       else
691       {
692         throw new Error("Invalid color for MyCheckBox");
693       }
694       if (col != null)
695       {
696         setBackground(col);
697       }
698       else
699       {
700         String vlabel = type;
701         if (gcol.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
702         {
703           vlabel += " "
704                   + ((gcol.getThreshType() == AnnotationColourGradient.ABOVE_THRESHOLD) ? "(>)"
705                           : "(<)");
706         }
707         if (gcol.isColourByLabel())
708         {
709           setBackground(Color.white);
710           vlabel += " (by Label)";
711         }
712         else
713         {
714           setBackground(gcol.getMinColor());
715         }
716         this.setLabel(vlabel);
717       }
718       repaint();
719     }
720
721     public MyCheckbox(String label, boolean checked, boolean haslink)
722     {
723       super(label, checked);
724       type = label;
725       FontMetrics fm = av.nullFrame.getFontMetrics(av.nullFrame.getFont());
726       stringWidth = fm.stringWidth(label);
727       this.hasLink = haslink;
728     }
729
730     public MyCheckbox(String type, boolean selected, boolean b,
731             Object featureStyle)
732     {
733       this(type, selected, b);
734       updateColor(featureStyle);
735     }
736
737     public void paint(Graphics g)
738     {
739       Dimension d = getSize();
740       if (gcol != null)
741       {
742         if (gcol.isColourByLabel())
743         {
744           g.setColor(Color.white);
745           g.fillRect(d.width / 2, 0, d.width / 2, d.height);
746           /*
747            * g.setColor(Color.black); Font f=g.getFont().deriveFont(9);
748            * g.setFont(f);
749            * 
750            * // g.setFont(g.getFont().deriveFont( //
751            * AffineTransform.getScaleInstance( //
752            * width/g.getFontMetrics().stringWidth("Label"), //
753            * height/g.getFontMetrics().getHeight()))); g.drawString("Label",
754            * width/2, 0);
755            */
756
757         }
758         else
759         {
760           Color maxCol = gcol.getMaxColor();
761           g.setColor(maxCol);
762           g.fillRect(d.width / 2, 0, d.width / 2, d.height);
763
764         }
765       }
766
767       if (hasLink)
768       {
769         g.drawImage(linkImage, stringWidth + 25,
770                 (getSize().height - linkImage.getHeight(this)) / 2, this);
771       }
772     }
773   }
774
775   protected void sortByDens(String[] typ)
776   {
777     sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY);
778   }
779
780   private String[] getDisplayedFeatureTypes()
781   {
782     String[] typ = null;
783     if (fr != null)
784     {
785       synchronized (fr.renderOrder)
786       {
787         typ = new String[fr.renderOrder.length];
788         System.arraycopy(fr.renderOrder, 0, typ, 0, typ.length);
789         for (int i = 0; i < typ.length; i++)
790         {
791           if (av.featuresDisplayed.get(typ[i]) == null)
792           {
793             typ[i] = null;
794           }
795         }
796       }
797     }
798     return typ;
799   }
800
801   protected void sortBy(String[] typ, String methodText, final String method)
802   {
803     if (typ == null)
804     {
805       typ = getDisplayedFeatureTypes();
806     }
807     String gps[] = null;
808     gps = fr.getGroups(true);
809     if (typ != null)
810     {
811       for (int i = 0; i < typ.length; i++)
812       {
813         System.err.println("Sorting on Types:" + typ[i]);
814       }
815     }
816     if (gps != null)
817     {
818
819       for (int i = 0; i < gps.length; i++)
820       {
821         System.err.println("Sorting on groups:" + gps[i]);
822       }
823     }
824     AlignmentPanel alignPanel = ap;
825     AlignmentI al = alignPanel.av.getAlignment();
826
827     int start, stop;
828     SequenceGroup sg = alignPanel.av.getSelectionGroup();
829     if (sg != null)
830     {
831       start = sg.getStartRes();
832       stop = sg.getEndRes();
833     }
834     else
835     {
836       start = 0;
837       stop = al.getWidth();
838     }
839     SequenceI[] oldOrder = al.getSequencesArray();
840     AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method);
841     this.ap.alignFrame.addHistoryItem(new OrderCommand(methodText,
842             oldOrder, alignPanel.av.getAlignment()));
843     alignPanel.paintAlignment(true);
844
845   }
846
847   protected void sortByScore(String[] typ)
848   {
849     sortBy(typ, "Sort by Feature Score", AlignmentSorter.FEATURE_SCORE);
850   }
851
852 }