2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.Annotation;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.FormatAdapter;
30 import jalview.util.MessageManager;
32 import java.awt.Color;
33 import java.awt.Dimension;
35 import java.awt.FontMetrics;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.Image;
39 import java.awt.MediaTracker;
40 import java.awt.RenderingHints;
41 import java.awt.Toolkit;
42 import java.awt.datatransfer.StringSelection;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.MouseEvent;
46 import java.awt.event.MouseListener;
47 import java.awt.event.MouseMotionListener;
48 import java.awt.geom.AffineTransform;
49 import java.awt.image.BufferedImage;
50 import java.util.Vector;
51 import java.util.regex.Pattern;
53 import javax.swing.JCheckBoxMenuItem;
54 import javax.swing.JMenuItem;
55 import javax.swing.JPanel;
56 import javax.swing.JPopupMenu;
57 import javax.swing.SwingUtilities;
58 import javax.swing.ToolTipManager;
66 public class AnnotationLabels extends JPanel implements MouseListener,
67 MouseMotionListener, ActionListener
69 String TOGGLE_LABELSCALE = MessageManager.getString("label.scale_label_to_column");
71 String ADDNEW = MessageManager.getString("label.add_new_row");
73 String EDITNAME = MessageManager.getString("label.edit_label_description");
75 String HIDE = MessageManager.getString("label.hide_row");
77 String DELETE = MessageManager.getString("label.delete_row");
79 String SHOWALL = MessageManager.getString("label.show_all_hidden_rows");
81 String OUTPUT_TEXT = MessageManager.getString("label.export_annotation");
83 String COPYCONS_SEQ = MessageManager.getString("label.copy_consensus_sequence");
85 boolean resizePanel = false;
93 boolean resizing = false;
101 int scrollOffset = 0;
103 Font font = new Font("Arial", Font.PLAIN, 11);
105 private boolean hasHiddenRows;
108 * Creates a new AnnotationLabels object.
113 public AnnotationLabels(AlignmentPanel ap)
117 ToolTipManager.sharedInstance().registerComponent(this);
119 java.net.URL url = getClass().getResource("/images/idwidth.gif");
124 temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
129 MediaTracker mt = new MediaTracker(this);
130 mt.addImage(temp, 0);
132 } catch (Exception ex)
136 BufferedImage bi = new BufferedImage(temp.getHeight(this),
137 temp.getWidth(this), BufferedImage.TYPE_INT_RGB);
138 Graphics2D g = (Graphics2D) bi.getGraphics();
139 g.rotate(Math.toRadians(90));
140 g.drawImage(temp, 0, -bi.getWidth(this), this);
143 addMouseListener(this);
144 addMouseMotionListener(this);
145 addMouseWheelListener(ap.annotationPanel);
148 public AnnotationLabels(AlignViewport av)
159 public void setScrollOffset(int y)
166 * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
170 * coordinate position to search for a row
172 void getSelectedRow(int y)
175 AlignmentAnnotation[] aa = ap.av.getAlignment()
176 .getAlignmentAnnotation();
180 for (int i = 0; i < aa.length; i++)
188 height += aa[i].height;
206 public void actionPerformed(ActionEvent evt)
208 AlignmentAnnotation[] aa = ap.av.getAlignment()
209 .getAlignmentAnnotation();
211 if (evt.getActionCommand().equals(ADDNEW))
213 AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
214 null, new Annotation[ap.av.getAlignment().getWidth()]);
216 if (!editLabelDescription(newAnnotation))
221 ap.av.getAlignment().addAnnotation(newAnnotation);
222 ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
224 else if (evt.getActionCommand().equals(EDITNAME))
226 editLabelDescription(aa[selectedRow]);
229 else if (evt.getActionCommand().equals(HIDE))
231 aa[selectedRow].visible = false;
233 else if (evt.getActionCommand().equals(DELETE))
235 ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
237 else if (evt.getActionCommand().equals(SHOWALL))
239 for (int i = 0; i < aa.length; i++)
241 if (!aa[i].visible && aa[i].annotations != null)
243 aa[i].visible = true;
247 else if (evt.getActionCommand().equals(OUTPUT_TEXT))
249 new AnnotationExporter().exportAnnotations(ap,
250 new AlignmentAnnotation[]
251 { aa[selectedRow] }, null, null);
253 else if (evt.getActionCommand().equals(COPYCONS_SEQ))
255 SequenceI cons = null;
256 if (aa[selectedRow].groupRef != null)
258 cons = aa[selectedRow].groupRef.getConsensusSeq();
262 cons = av.getConsensusSeq();
266 copy_annotseqtoclipboard(cons);
270 else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
272 aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
282 protected void refresh()
284 ap.validateAnnotationDimensions(false);
295 boolean editLabelDescription(AlignmentAnnotation annotation)
297 EditNameDialog dialog = new EditNameDialog(annotation.label,
298 annotation.description, " Annotation Name ",
299 "Annotation Description ", "Edit Annotation Name/Description",
307 annotation.label = dialog.getName();
309 String text = dialog.getDescription();
310 if (text != null && text.length() == 0)
314 annotation.description = text;
325 public void mousePressed(MouseEvent evt)
327 getSelectedRow(evt.getY() - scrollOffset);
337 public void mouseReleased(MouseEvent evt)
339 int start = selectedRow;
340 getSelectedRow(evt.getY() - scrollOffset);
341 int end = selectedRow;
345 // Swap these annotations
346 AlignmentAnnotation startAA = ap.av.getAlignment()
347 .getAlignmentAnnotation()[start];
350 end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
352 AlignmentAnnotation endAA = ap.av.getAlignment()
353 .getAlignmentAnnotation()[end];
355 ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
356 ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
362 ap.annotationPanel.repaint();
371 public void mouseEntered(MouseEvent evt)
386 public void mouseExited(MouseEvent evt)
388 if (dragEvent == null)
401 public void mouseDragged(MouseEvent evt)
407 Dimension d = ap.annotationScroller.getPreferredSize();
408 int dif = evt.getY() - oldY;
410 dif /= ap.av.charHeight;
411 dif *= ap.av.charHeight;
413 if ((d.height - dif) > 20)
415 ap.annotationScroller.setPreferredSize(new Dimension(d.width,
417 d = ap.annotationSpaceFillerHolder.getPreferredSize();
418 ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
419 d.width, d.height - dif));
420 ap.paintAlignment(true);
437 public void mouseMoved(MouseEvent evt)
439 resizePanel = evt.getY() < 10;
441 getSelectedRow(evt.getY() - scrollOffset);
444 && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
446 AlignmentAnnotation aa = ap.av.getAlignment()
447 .getAlignmentAnnotation()[selectedRow];
449 StringBuffer desc = new StringBuffer();
450 if (aa.description != null
451 && !aa.description.equals("New description"))
453 // TODO: we could refactor and merge this code with the code in
454 // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
456 desc.append(aa.getDescription(true).trim());
457 // check to see if the description is an html fragment.
458 if (desc.length() < 6
459 || (desc.substring(0, 6).toLowerCase().indexOf("<html>") < 0))
461 // clean the description ready for embedding in html
462 desc = new StringBuffer(Pattern.compile("<").matcher(desc)
463 .replaceAll("<"));
464 desc.insert(0, "<html>");
468 // remove terminating html if any
469 int i = desc.substring(desc.length() - 7).toLowerCase()
470 .lastIndexOf("</html>");
473 desc.setLength(desc.length() - 7 + i);
478 desc.append("<br/>");
484 // begin the tooltip's html fragment
485 desc.append("<html>");
489 // TODO: limit precision of score to avoid noise from imprecise doubles
490 // (64.7 becomes 64.7+/some tiny value).
491 desc.append(" Score: " + aa.score);
494 if (desc.length() > 6)
496 desc.append("</html>");
497 this.setToolTipText(desc.toString());
500 this.setToolTipText(null);
511 public void mouseClicked(MouseEvent evt)
513 final AlignmentAnnotation[] aa = ap.av.getAlignment()
514 .getAlignmentAnnotation();
515 if (SwingUtilities.isLeftMouseButton(evt))
517 if (selectedRow > -1 && selectedRow < aa.length)
519 if (aa[selectedRow].groupRef != null)
521 if (evt.getClickCount() >= 2)
523 // todo: make the ap scroll to the selection - not necessary, first
524 // click highlights/scrolls, second selects
525 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
526 ap.av.setSelectionGroup(// new SequenceGroup(
527 aa[selectedRow].groupRef); // );
528 ap.paintAlignment(false);
529 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
530 ap.av.sendSelection();
534 ap.seqPanel.ap.idPanel
535 .highlightSearchResults(aa[selectedRow].groupRef
536 .getSequences(null));
540 else if (aa[selectedRow].sequenceRef != null)
542 Vector sr = new Vector();
543 sr.addElement(aa[selectedRow].sequenceRef);
544 if (evt.getClickCount() == 1)
546 ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
548 else if (evt.getClickCount() >= 2)
550 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
551 SequenceGroup sg = new SequenceGroup();
552 sg.addSequence(aa[selectedRow].sequenceRef, false);
553 ap.av.setSelectionGroup(sg);
554 ap.av.sendSelection();
555 ap.paintAlignment(false);
556 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
562 if (!SwingUtilities.isRightMouseButton(evt))
567 JPopupMenu pop = new JPopupMenu(
568 MessageManager.getString("label.annotations"));
569 JMenuItem item = new JMenuItem(ADDNEW);
570 item.addActionListener(this);
575 { // let the user make everything visible again
576 item = new JMenuItem(SHOWALL);
577 item.addActionListener(this);
580 pop.show(this, evt.getX(), evt.getY());
583 item = new JMenuItem(EDITNAME);
584 item.addActionListener(this);
586 item = new JMenuItem(HIDE);
587 item.addActionListener(this);
589 // JAL-1264 hide all sequence-specific annotations of this type
590 final String label = aa[selectedRow].label;
591 if (selectedRow < aa.length)
593 if (aa[selectedRow].sequenceRef != null)
595 JMenuItem hideType = new JMenuItem();
596 String text = MessageManager.getString("label.hide_all") + " " + label;
597 hideType.setText(text);
598 hideType.addActionListener(new ActionListener()
601 public void actionPerformed(ActionEvent e)
603 for (AlignmentAnnotation ann : ap.av.getAlignment()
604 .getAlignmentAnnotation())
606 if (ann.sequenceRef != null && ann.label != null
607 && ann.label.equals(label))
618 item = new JMenuItem(DELETE);
619 item.addActionListener(this);
623 item = new JMenuItem(SHOWALL);
624 item.addActionListener(this);
627 item = new JMenuItem(OUTPUT_TEXT);
628 item.addActionListener(this);
630 // TODO: annotation object should be typed for autocalculated/derived
632 if (selectedRow < aa.length)
634 if (!aa[selectedRow].autoCalculated)
636 if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
638 // display formatting settings for this row.
640 // av and sequencegroup need to implement same interface for
641 item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
642 aa[selectedRow].scaleColLabel);
643 item.addActionListener(this);
647 else if (label.indexOf("Consensus") > -1)
650 // av and sequencegroup need to implement same interface for
651 final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
652 "Ignore Gaps In Consensus",
653 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
654 .getIgnoreGapsConsensus() : ap.av
655 .getIgnoreGapsConsensus());
656 final AlignmentAnnotation aaa = aa[selectedRow];
657 cbmi.addActionListener(new ActionListener()
659 public void actionPerformed(ActionEvent e)
661 if (aaa.groupRef != null)
663 // TODO: pass on reference to ap so the view can be updated.
664 aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
665 ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
669 ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
674 // av and sequencegroup need to implement same interface for
675 if (aaa.groupRef != null)
677 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
678 "Show Group Histogram",
679 aa[selectedRow].groupRef.isShowConsensusHistogram());
680 chist.addActionListener(new ActionListener()
682 public void actionPerformed(ActionEvent e)
684 // TODO: pass on reference
690 aaa.groupRef.setShowConsensusHistogram(chist.getState());
692 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
696 final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
698 aa[selectedRow].groupRef.isShowSequenceLogo());
699 cprofl.addActionListener(new ActionListener()
701 public void actionPerformed(ActionEvent e)
703 // TODO: pass on reference
709 aaa.groupRef.setshowSequenceLogo(cprofl.getState());
711 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
715 final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
716 "Normalise Group Logo",
717 aa[selectedRow].groupRef.isNormaliseSequenceLogo());
718 cproflnorm.addActionListener(new ActionListener()
720 public void actionPerformed(ActionEvent e)
723 // TODO: pass on reference
729 aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
730 // automatically enable logo display if we're clicked
731 aaa.groupRef.setshowSequenceLogo(true);
733 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
740 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
741 "Show Histogram", av.isShowConsensusHistogram());
742 chist.addActionListener(new ActionListener()
744 public void actionPerformed(ActionEvent e)
746 // TODO: pass on reference
752 av.setShowConsensusHistogram(chist.getState());
753 ap.alignFrame.setMenusForViewport();
755 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
759 final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
760 "Show Logo", av.isShowSequenceLogo());
761 cprof.addActionListener(new ActionListener()
763 public void actionPerformed(ActionEvent e)
765 // TODO: pass on reference
771 av.setShowSequenceLogo(cprof.getState());
772 ap.alignFrame.setMenusForViewport();
774 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
778 final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
779 "Normalise Logo", av.isNormaliseSequenceLogo());
780 cprofnorm.addActionListener(new ActionListener()
782 public void actionPerformed(ActionEvent e)
784 // TODO: pass on reference
790 av.setShowSequenceLogo(true);
791 av.setNormaliseSequenceLogo(cprofnorm.getState());
792 ap.alignFrame.setMenusForViewport();
794 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
799 final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
800 consclipbrd.addActionListener(this);
801 pop.add(consclipbrd);
804 pop.show(this, evt.getX(), evt.getY());
808 * do a single sequence copy to jalview and the system clipboard
811 * sequence to be copied to clipboard
813 protected void copy_annotseqtoclipboard(SequenceI sq)
815 SequenceI[] seqs = new SequenceI[]
817 String[] omitHidden = null;
818 SequenceI[] dseqs = new SequenceI[]
819 { sq.getDatasetSequence() };
820 if (dseqs[0] == null)
822 dseqs[0] = new Sequence(sq);
823 dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
824 jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
826 sq.setDatasetSequence(dseqs[0]);
828 Alignment ds = new Alignment(dseqs);
829 if (av.hasHiddenColumns())
831 omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
832 sq.getLength(), seqs);
835 String output = new FormatAdapter().formatSequences("Fasta", seqs,
838 Toolkit.getDefaultToolkit().getSystemClipboard()
839 .setContents(new StringSelection(output), Desktop.instance);
841 Vector hiddenColumns = null;
842 if (av.hasHiddenColumns())
844 hiddenColumns = new Vector();
845 for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
847 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
850 hiddenColumns.addElement(new int[]
851 { region[0], region[1] });
855 Desktop.jalviewClipboard = new Object[]
856 { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
857 // sequence as special.
867 public void paintComponent(Graphics g)
870 int width = getWidth();
873 width = ap.calculateIdWidth().width + 4;
876 Graphics2D g2 = (Graphics2D) g;
879 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
880 RenderingHints.VALUE_ANTIALIAS_ON);
883 drawComponent(g2, true, width);
888 * Draw the full set of annotation Labels for the alignment at the given
892 * Graphics2D instance (needed for font scaling)
894 * Width for scaling labels
897 public void drawComponent(Graphics g, int width)
899 drawComponent(g, false, width);
902 private final boolean debugRedraw = false;
905 * Draw the full set of annotation Labels for the alignment at the given
909 * Graphics2D instance (needed for font scaling)
911 * - true indicates that only current visible area needs to be
914 * Width for scaling labels
916 public void drawComponent(Graphics g, boolean clip, int width)
918 if (av.getFont().getSize() < 10)
924 g.setFont(av.getFont());
927 FontMetrics fm = g.getFontMetrics(g.getFont());
928 g.setColor(Color.white);
929 g.fillRect(0, 0, getWidth(), getHeight());
931 g.translate(0, scrollOffset);
932 g.setColor(Color.black);
934 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
935 int fontHeight = g.getFont().getSize();
940 Font baseFont = g.getFont();
941 FontMetrics baseMetrics = fm;
942 int ofontH = fontHeight;
945 int[] visr = (ap != null && ap.annotationPanel != null) ? ap.annotationPanel
946 .getVisibleVRange() : null;
947 if (clip && visr != null)
952 boolean visible = true, before = false, after = false;
955 hasHiddenRows = false;
957 for (int i = 0; i < aa.length; i++)
962 hasHiddenRows = true;
975 System.out.println("before vis: " + i);
979 // don't draw what isn't visible
989 System.out.println("Scroll offset: " + sOffset
990 + " after vis: " + i);
994 // don't draw what isn't visible
998 g.setColor(Color.black);
1000 offset = -aa[i].height / 2;
1004 offset += fm.getHeight() / 2;
1005 offset -= fm.getDescent();
1008 offset += fm.getDescent();
1010 x = width - fm.stringWidth(aa[i].label) - 3;
1012 if (aa[i].graphGroup > -1)
1015 // TODO: JAL-1291 revise rendering model so the graphGroup map is
1016 // computed efficiently for all visible labels
1017 for (int gg = 0; gg < aa.length; gg++)
1019 if (aa[gg].graphGroup == aa[i].graphGroup)
1024 if (groupSize * (fontHeight + 8) < aa[i].height)
1026 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1030 // scale font to fit
1031 float h = aa[i].height / (float) groupSize, s;
1038 fontHeight = -8 + (int) h;
1039 s = ((float) fontHeight) / (float) ofontH;
1040 Font f = baseFont.deriveFont(AffineTransform
1041 .getScaleInstance(s, s));
1043 fm = g.getFontMetrics();
1044 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1049 for (int gg = 0; gg < aa.length; gg++)
1051 if (aa[gg].graphGroup == aa[i].graphGroup)
1053 x = width - fm.stringWidth(aa[gg].label) - 3;
1054 g.drawString(aa[gg].label, x, y - graphExtras);
1056 if (aa[gg]._linecolour != null)
1059 g.setColor(aa[gg]._linecolour);
1060 g.drawLine(x, y - graphExtras + 3,
1061 x + fm.stringWidth(aa[gg].label), y - graphExtras
1065 g.setColor(Color.black);
1066 graphExtras += fontHeight + 8;
1070 g.setFont(baseFont);
1072 fontHeight = ofontH;
1076 g.drawString(aa[i].label, x, y + offset);
1083 g.drawImage(image, 2, 0 - scrollOffset, this);
1085 else if (dragEvent != null && aa != null)
1087 g.setColor(Color.lightGray);
1088 g.drawString(aa[selectedRow].label, dragEvent.getX(),
1089 dragEvent.getY() - scrollOffset);
1092 if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1094 g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1095 g.drawString(MessageManager.getString("label.to_add_annotation"), 2,