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