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 if (evt.getClickCount() == 1)
544 ap.seqPanel.ap.idPanel.highlightSearchResults(Arrays
545 .asList(new SequenceI[]
546 { aa[selectedRow].sequenceRef }));
548 else if (evt.getClickCount() >= 2)
550 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
551 SequenceGroup sg = ap.av.getSelectionGroup();
554 // we make a copy rather than edit the current selection if no modifiers pressed
555 // see Enhancement JAL-1557
556 if (!(evt.isControlDown() || evt.isShiftDown()))
558 sg = new SequenceGroup(sg);
560 sg.addSequence(aa[selectedRow].sequenceRef, false);
562 if (evt.isControlDown())
564 sg.addOrRemove(aa[selectedRow].sequenceRef, true);
566 // notionally, we should also add intermediate sequences from last added sequence ?
567 sg.addSequence(aa[selectedRow].sequenceRef, true);
571 sg = new SequenceGroup();
573 sg.setEndRes(ap.av.getAlignment().getWidth()-1);
574 sg.addSequence(aa[selectedRow].sequenceRef, false);
576 ap.av.setSelectionGroup(sg);
577 ap.av.sendSelection();
578 ap.paintAlignment(false);
579 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
585 if (!SwingUtilities.isRightMouseButton(evt))
590 JPopupMenu pop = new JPopupMenu(
591 MessageManager.getString("label.annotations"));
592 JMenuItem item = new JMenuItem(ADDNEW);
593 item.addActionListener(this);
598 { // let the user make everything visible again
599 item = new JMenuItem(SHOWALL);
600 item.addActionListener(this);
603 pop.show(this, evt.getX(), evt.getY());
606 item = new JMenuItem(EDITNAME);
607 item.addActionListener(this);
609 item = new JMenuItem(HIDE);
610 item.addActionListener(this);
612 // JAL-1264 hide all sequence-specific annotations of this type
613 final String label = aa[selectedRow].label;
614 if (selectedRow < aa.length)
616 if (aa[selectedRow].sequenceRef != null)
618 JMenuItem hideType = new JMenuItem();
619 String text = MessageManager.getString("label.hide_all") + " " + label;
620 hideType.setText(text);
621 hideType.addActionListener(new ActionListener()
624 public void actionPerformed(ActionEvent e)
626 for (AlignmentAnnotation ann : ap.av.getAlignment()
627 .getAlignmentAnnotation())
629 if (ann.sequenceRef != null && ann.label != null
630 && ann.label.equals(label))
641 item = new JMenuItem(DELETE);
642 item.addActionListener(this);
646 item = new JMenuItem(SHOWALL);
647 item.addActionListener(this);
650 item = new JMenuItem(OUTPUT_TEXT);
651 item.addActionListener(this);
653 // TODO: annotation object should be typed for autocalculated/derived
655 if (selectedRow < aa.length)
657 if (!aa[selectedRow].autoCalculated)
659 if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
661 // display formatting settings for this row.
663 // av and sequencegroup need to implement same interface for
664 item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
665 aa[selectedRow].scaleColLabel);
666 item.addActionListener(this);
670 else if (label.indexOf("Consensus") > -1)
673 // av and sequencegroup need to implement same interface for
674 final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
675 "Ignore Gaps In Consensus",
676 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
677 .getIgnoreGapsConsensus() : ap.av
678 .getIgnoreGapsConsensus());
679 final AlignmentAnnotation aaa = aa[selectedRow];
680 cbmi.addActionListener(new ActionListener()
682 public void actionPerformed(ActionEvent e)
684 if (aaa.groupRef != null)
686 // TODO: pass on reference to ap so the view can be updated.
687 aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
688 ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
692 ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
697 // av and sequencegroup need to implement same interface for
698 if (aaa.groupRef != null)
700 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
701 "Show Group Histogram",
702 aa[selectedRow].groupRef.isShowConsensusHistogram());
703 chist.addActionListener(new ActionListener()
705 public void actionPerformed(ActionEvent e)
707 // TODO: pass on reference
713 aaa.groupRef.setShowConsensusHistogram(chist.getState());
715 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
719 final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
721 aa[selectedRow].groupRef.isShowSequenceLogo());
722 cprofl.addActionListener(new ActionListener()
724 public void actionPerformed(ActionEvent e)
726 // TODO: pass on reference
732 aaa.groupRef.setshowSequenceLogo(cprofl.getState());
734 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
738 final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
739 "Normalise Group Logo",
740 aa[selectedRow].groupRef.isNormaliseSequenceLogo());
741 cproflnorm.addActionListener(new ActionListener()
743 public void actionPerformed(ActionEvent e)
746 // TODO: pass on reference
752 aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
753 // automatically enable logo display if we're clicked
754 aaa.groupRef.setshowSequenceLogo(true);
756 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
763 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
764 "Show Histogram", av.isShowConsensusHistogram());
765 chist.addActionListener(new ActionListener()
767 public void actionPerformed(ActionEvent e)
769 // TODO: pass on reference
775 av.setShowConsensusHistogram(chist.getState());
776 ap.alignFrame.setMenusForViewport();
778 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
782 final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
783 "Show Logo", av.isShowSequenceLogo());
784 cprof.addActionListener(new ActionListener()
786 public void actionPerformed(ActionEvent e)
788 // TODO: pass on reference
794 av.setShowSequenceLogo(cprof.getState());
795 ap.alignFrame.setMenusForViewport();
797 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
801 final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
802 "Normalise Logo", av.isNormaliseSequenceLogo());
803 cprofnorm.addActionListener(new ActionListener()
805 public void actionPerformed(ActionEvent e)
807 // TODO: pass on reference
813 av.setShowSequenceLogo(true);
814 av.setNormaliseSequenceLogo(cprofnorm.getState());
815 ap.alignFrame.setMenusForViewport();
817 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
822 final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
823 consclipbrd.addActionListener(this);
824 pop.add(consclipbrd);
827 pop.show(this, evt.getX(), evt.getY());
831 * do a single sequence copy to jalview and the system clipboard
834 * sequence to be copied to clipboard
836 protected void copy_annotseqtoclipboard(SequenceI sq)
838 SequenceI[] seqs = new SequenceI[]
840 String[] omitHidden = null;
841 SequenceI[] dseqs = new SequenceI[]
842 { sq.getDatasetSequence() };
843 if (dseqs[0] == null)
845 dseqs[0] = new Sequence(sq);
846 dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
847 jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
849 sq.setDatasetSequence(dseqs[0]);
851 Alignment ds = new Alignment(dseqs);
852 if (av.hasHiddenColumns())
854 omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
855 sq.getLength(), seqs);
858 String output = new FormatAdapter().formatSequences("Fasta", seqs,
861 Toolkit.getDefaultToolkit().getSystemClipboard()
862 .setContents(new StringSelection(output), Desktop.instance);
864 Vector hiddenColumns = null;
865 if (av.hasHiddenColumns())
867 hiddenColumns = new Vector();
868 for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
870 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
873 hiddenColumns.addElement(new int[]
874 { region[0], region[1] });
878 Desktop.jalviewClipboard = new Object[]
879 { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
880 // sequence as special.
890 public void paintComponent(Graphics g)
893 int width = getWidth();
896 width = ap.calculateIdWidth().width + 4;
899 Graphics2D g2 = (Graphics2D) g;
902 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
903 RenderingHints.VALUE_ANTIALIAS_ON);
906 drawComponent(g2, true, width);
911 * Draw the full set of annotation Labels for the alignment at the given
915 * Graphics2D instance (needed for font scaling)
917 * Width for scaling labels
920 public void drawComponent(Graphics g, int width)
922 drawComponent(g, false, width);
925 private final boolean debugRedraw = false;
928 * Draw the full set of annotation Labels for the alignment at the given
932 * Graphics2D instance (needed for font scaling)
934 * - true indicates that only current visible area needs to be
937 * Width for scaling labels
939 public void drawComponent(Graphics g, boolean clip, int width)
941 if (av.getFont().getSize() < 10)
947 g.setFont(av.getFont());
950 FontMetrics fm = g.getFontMetrics(g.getFont());
951 g.setColor(Color.white);
952 g.fillRect(0, 0, getWidth(), getHeight());
954 g.translate(0, scrollOffset);
955 g.setColor(Color.black);
957 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
958 int fontHeight = g.getFont().getSize();
963 Font baseFont = g.getFont();
964 FontMetrics baseMetrics = fm;
965 int ofontH = fontHeight;
968 int[] visr = (ap != null && ap.annotationPanel != null) ? ap.annotationPanel
969 .getVisibleVRange() : null;
970 if (clip && visr != null)
975 boolean visible = true, before = false, after = false;
978 hasHiddenRows = false;
980 for (int i = 0; i < aa.length; i++)
985 hasHiddenRows = true;
998 System.out.println("before vis: " + i);
1002 // don't draw what isn't visible
1005 if (olY > visHeight)
1012 System.out.println("Scroll offset: " + sOffset
1013 + " after vis: " + i);
1017 // don't draw what isn't visible
1021 g.setColor(Color.black);
1023 offset = -aa[i].height / 2;
1027 offset += fm.getHeight() / 2;
1028 offset -= fm.getDescent();
1031 offset += fm.getDescent();
1033 x = width - fm.stringWidth(aa[i].label) - 3;
1035 if (aa[i].graphGroup > -1)
1038 // TODO: JAL-1291 revise rendering model so the graphGroup map is
1039 // computed efficiently for all visible labels
1040 for (int gg = 0; gg < aa.length; gg++)
1042 if (aa[gg].graphGroup == aa[i].graphGroup)
1047 if (groupSize * (fontHeight + 8) < aa[i].height)
1049 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1053 // scale font to fit
1054 float h = aa[i].height / (float) groupSize, s;
1061 fontHeight = -8 + (int) h;
1062 s = ((float) fontHeight) / (float) ofontH;
1063 Font f = baseFont.deriveFont(AffineTransform
1064 .getScaleInstance(s, s));
1066 fm = g.getFontMetrics();
1067 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1072 for (int gg = 0; gg < aa.length; gg++)
1074 if (aa[gg].graphGroup == aa[i].graphGroup)
1076 x = width - fm.stringWidth(aa[gg].label) - 3;
1077 g.drawString(aa[gg].label, x, y - graphExtras);
1079 if (aa[gg]._linecolour != null)
1082 g.setColor(aa[gg]._linecolour);
1083 g.drawLine(x, y - graphExtras + 3,
1084 x + fm.stringWidth(aa[gg].label), y - graphExtras
1088 g.setColor(Color.black);
1089 graphExtras += fontHeight + 8;
1093 g.setFont(baseFont);
1095 fontHeight = ofontH;
1099 g.drawString(aa[i].label, x, y + offset);
1106 g.drawImage(image, 2, 0 - scrollOffset, this);
1108 else if (dragEvent != null && aa != null)
1110 g.setColor(Color.lightGray);
1111 g.drawString(aa[selectedRow].label, dragEvent.getX(),
1112 dragEvent.getY() - scrollOffset);
1115 if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1117 g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1118 g.drawString(MessageManager.getString("label.to_add_annotation"), 2,