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