2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
21 import java.util.regex.Pattern;
24 import java.awt.datatransfer.*;
25 import java.awt.event.*;
26 import java.awt.geom.AffineTransform;
27 import java.awt.image.*;
30 import jalview.datamodel.*;
39 public class AnnotationLabels extends JPanel implements MouseListener,
40 MouseMotionListener, ActionListener
42 static String TOGGLE_LABELSCALE = "Scale Label to Column";
44 static String ADDNEW = "Add New Row";
46 static String EDITNAME = "Edit Label/Description";
48 static String HIDE = "Hide This Row";
50 static String DELETE = "Delete This Row";
52 static String SHOWALL = "Show All Hidden Rows";
54 static String OUTPUT_TEXT = "Export Annotation";
56 static String COPYCONS_SEQ = "Copy Consensus Sequence";
58 boolean resizePanel = false;
66 boolean resizing = false;
76 Font font = new Font("Arial", Font.PLAIN, 11);
78 private boolean hasHiddenRows;
81 * Creates a new AnnotationLabels object.
86 public AnnotationLabels(AlignmentPanel ap)
90 ToolTipManager.sharedInstance().registerComponent(this);
92 java.net.URL url = getClass().getResource("/images/idwidth.gif");
97 temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
102 MediaTracker mt = new MediaTracker(this);
103 mt.addImage(temp, 0);
105 } catch (Exception ex)
109 BufferedImage bi = new BufferedImage(temp.getHeight(this),
110 temp.getWidth(this), BufferedImage.TYPE_INT_RGB);
111 Graphics2D g = (Graphics2D) bi.getGraphics();
112 g.rotate(Math.toRadians(90));
113 g.drawImage(temp, 0, -bi.getWidth(this), this);
116 addMouseListener(this);
117 addMouseMotionListener(this);
118 addMouseWheelListener(ap.annotationPanel);
121 public AnnotationLabels(AlignViewport av)
132 public void setScrollOffset(int y)
139 * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
143 * coordinate position to search for a row
145 void getSelectedRow(int y)
148 AlignmentAnnotation[] aa = ap.av.getAlignment()
149 .getAlignmentAnnotation();
153 for (int i = 0; i < aa.length; i++)
161 height += aa[i].height;
179 public void actionPerformed(ActionEvent evt)
181 AlignmentAnnotation[] aa = ap.av.getAlignment()
182 .getAlignmentAnnotation();
184 if (evt.getActionCommand().equals(ADDNEW))
186 AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
187 null, new Annotation[ap.av.getAlignment().getWidth()]);
189 if (!editLabelDescription(newAnnotation))
194 ap.av.getAlignment().addAnnotation(newAnnotation);
195 ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
197 else if (evt.getActionCommand().equals(EDITNAME))
199 editLabelDescription(aa[selectedRow]);
202 else if (evt.getActionCommand().equals(HIDE))
204 aa[selectedRow].visible = false;
206 else if (evt.getActionCommand().equals(DELETE))
208 ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
210 else if (evt.getActionCommand().equals(SHOWALL))
212 for (int i = 0; i < aa.length; i++)
214 if (!aa[i].visible && aa[i].annotations != null)
216 aa[i].visible = true;
220 else if (evt.getActionCommand().equals(OUTPUT_TEXT))
222 new AnnotationExporter().exportAnnotations(ap,
223 new AlignmentAnnotation[]
224 { aa[selectedRow] }, null, null);
226 else if (evt.getActionCommand().equals(COPYCONS_SEQ))
228 SequenceI cons = null;
229 if (aa[selectedRow].groupRef != null)
231 cons = aa[selectedRow].groupRef.getConsensusSeq();
235 cons = av.getConsensusSeq();
239 copy_annotseqtoclipboard(cons);
243 else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
245 aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
248 ap.validateAnnotationDimensions(false);
252 // ap.paintAlignment(true);
261 boolean editLabelDescription(AlignmentAnnotation annotation)
263 EditNameDialog dialog = new EditNameDialog(annotation.label,
264 annotation.description, " Annotation Name ",
265 "Annotation Description ", "Edit Annotation Name/Description",
273 annotation.label = dialog.getName();
275 String text = dialog.getDescription();
276 if (text != null && text.length() == 0)
280 annotation.description = text;
291 public void mousePressed(MouseEvent evt)
293 getSelectedRow(evt.getY() - scrollOffset);
303 public void mouseReleased(MouseEvent evt)
305 int start = selectedRow;
306 getSelectedRow(evt.getY() - scrollOffset);
307 int end = selectedRow;
311 // Swap these annotations
312 AlignmentAnnotation startAA = ap.av.getAlignment()
313 .getAlignmentAnnotation()[start];
316 end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
318 AlignmentAnnotation endAA = ap.av.getAlignment()
319 .getAlignmentAnnotation()[end];
321 ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
322 ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
328 ap.annotationPanel.repaint();
337 public void mouseEntered(MouseEvent evt)
352 public void mouseExited(MouseEvent evt)
354 if (dragEvent == null)
367 public void mouseDragged(MouseEvent evt)
373 Dimension d = ap.annotationScroller.getPreferredSize();
374 int dif = evt.getY() - oldY;
376 dif /= ap.av.charHeight;
377 dif *= ap.av.charHeight;
379 if ((d.height - dif) > 20)
381 ap.annotationScroller.setPreferredSize(new Dimension(d.width,
383 d = ap.annotationSpaceFillerHolder.getPreferredSize();
384 ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
385 d.width, d.height - dif));
386 ap.paintAlignment(true);
403 public void mouseMoved(MouseEvent evt)
405 resizePanel = evt.getY() < 10;
407 getSelectedRow(evt.getY() - scrollOffset);
410 && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
412 AlignmentAnnotation aa = ap.av.getAlignment()
413 .getAlignmentAnnotation()[selectedRow];
415 StringBuffer desc = new StringBuffer();
416 if (aa.description != null
417 && !aa.description.equals("New description"))
419 // TODO: we could refactor and merge this code with the code in
420 // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
422 desc.append(aa.getDescription(true).trim());
423 // check to see if the description is an html fragment.
424 if (desc.length() < 6
425 || (desc.substring(0, 6).toLowerCase().indexOf("<html>") < 0))
427 // clean the description ready for embedding in html
428 desc = new StringBuffer(Pattern.compile("<").matcher(desc)
429 .replaceAll("<"));
430 desc.insert(0, "<html>");
434 // remove terminating html if any
435 int i = desc.substring(desc.length() - 7).toLowerCase()
436 .lastIndexOf("</html>");
439 desc.setLength(desc.length() - 7 + i);
444 desc.append("<br/>");
450 // begin the tooltip's html fragment
451 desc.append("<html>");
455 // TODO: limit precision of score to avoid noise from imprecise doubles
456 // (64.7 becomes 64.7+/some tiny value).
457 desc.append(" Score: " + aa.score);
460 if (desc.length() > 6)
462 desc.append("</html>");
463 this.setToolTipText(desc.toString());
466 this.setToolTipText(null);
477 public void mouseClicked(MouseEvent evt)
479 AlignmentAnnotation[] aa = ap.av.getAlignment()
480 .getAlignmentAnnotation();
481 if (SwingUtilities.isLeftMouseButton(evt))
483 if (selectedRow > -1 && selectedRow < aa.length)
485 if (aa[selectedRow].groupRef != null)
487 if (evt.getClickCount() >= 2)
489 // todo: make the ap scroll to the selection - not necessary, first
490 // click highlights/scrolls, second selects
491 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
492 ap.av.setSelectionGroup(// new SequenceGroup(
493 aa[selectedRow].groupRef); // );
494 ap.paintAlignment(false);
495 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
496 ap.av.sendSelection();
500 ap.seqPanel.ap.idPanel
501 .highlightSearchResults(aa[selectedRow].groupRef
502 .getSequences(null));
506 else if (aa[selectedRow].sequenceRef != null)
508 Vector sr = new Vector();
509 sr.addElement(aa[selectedRow].sequenceRef);
510 if (evt.getClickCount() == 1)
512 ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
514 else if (evt.getClickCount() >= 2)
516 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
517 SequenceGroup sg = new SequenceGroup();
518 sg.addSequence(aa[selectedRow].sequenceRef, false);
519 ap.av.setSelectionGroup(sg);
520 ap.av.sendSelection();
521 ap.paintAlignment(false);
522 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
528 if (!SwingUtilities.isRightMouseButton(evt))
533 JPopupMenu pop = new JPopupMenu("Annotations");
534 JMenuItem item = new JMenuItem(ADDNEW);
535 item.addActionListener(this);
540 { // let the user make everything visible again
541 item = new JMenuItem(SHOWALL);
542 item.addActionListener(this);
545 pop.show(this, evt.getX(), evt.getY());
548 item = new JMenuItem(EDITNAME);
549 item.addActionListener(this);
551 item = new JMenuItem(HIDE);
552 item.addActionListener(this);
554 item = new JMenuItem(DELETE);
555 item.addActionListener(this);
559 item = new JMenuItem(SHOWALL);
560 item.addActionListener(this);
563 item = new JMenuItem(OUTPUT_TEXT);
564 item.addActionListener(this);
566 // TODO: annotation object should be typed for autocalculated/derived
568 if (selectedRow < aa.length)
570 if (!aa[selectedRow].autoCalculated)
572 if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
574 // display formatting settings for this row.
576 // av and sequencegroup need to implement same interface for
577 item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
578 aa[selectedRow].scaleColLabel);
579 item.addActionListener(this);
583 else if (aa[selectedRow].label.indexOf("Consensus") > -1)
586 // av and sequencegroup need to implement same interface for
587 final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
588 "Ignore Gaps In Consensus",
589 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
590 .getIgnoreGapsConsensus() : ap.av
591 .getIgnoreGapsConsensus());
592 final AlignmentAnnotation aaa = aa[selectedRow];
593 cbmi.addActionListener(new ActionListener()
595 public void actionPerformed(ActionEvent e)
597 if (aaa.groupRef != null)
599 // TODO: pass on reference to ap so the view can be updated.
600 aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
601 ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
605 ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
610 // av and sequencegroup need to implement same interface for
611 if (aaa.groupRef != null)
613 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
614 "Show Group Histogram",
615 aa[selectedRow].groupRef.isShowConsensusHistogram());
616 chist.addActionListener(new ActionListener()
618 public void actionPerformed(ActionEvent e)
620 // TODO: pass on reference
626 aaa.groupRef.setShowConsensusHistogram(chist.getState());
628 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
632 final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
634 aa[selectedRow].groupRef.isShowSequenceLogo());
635 cprofl.addActionListener(new ActionListener()
637 public void actionPerformed(ActionEvent e)
639 // TODO: pass on reference
645 aaa.groupRef.setshowSequenceLogo(cprofl.getState());
647 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
651 final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
652 "Normalise Group Logo",
653 aa[selectedRow].groupRef.isNormaliseSequenceLogo());
654 cproflnorm.addActionListener(new ActionListener()
656 public void actionPerformed(ActionEvent e)
659 // TODO: pass on reference
665 aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
666 // automatically enable logo display if we're clicked
667 aaa.groupRef.setshowSequenceLogo(true);
669 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
676 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
677 "Show Histogram", av.isShowConsensusHistogram());
678 chist.addActionListener(new ActionListener()
680 public void actionPerformed(ActionEvent e)
682 // TODO: pass on reference
688 av.setShowConsensusHistogram(chist.getState());
689 ap.alignFrame.setMenusForViewport();
691 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
695 final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
696 "Show Logo", av.isShowSequenceLogo());
697 cprof.addActionListener(new ActionListener()
699 public void actionPerformed(ActionEvent e)
701 // TODO: pass on reference
707 av.setShowSequenceLogo(cprof.getState());
708 ap.alignFrame.setMenusForViewport();
710 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
714 final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
715 "Normalise Logo", av.isNormaliseSequenceLogo());
716 cprofnorm.addActionListener(new ActionListener()
718 public void actionPerformed(ActionEvent e)
720 // TODO: pass on reference
726 av.setShowSequenceLogo(true);
727 av.setNormaliseSequenceLogo(cprofnorm.getState());
728 ap.alignFrame.setMenusForViewport();
730 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
735 final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
736 consclipbrd.addActionListener(this);
737 pop.add(consclipbrd);
740 pop.show(this, evt.getX(), evt.getY());
744 * do a single sequence copy to jalview and the system clipboard
747 * sequence to be copied to clipboard
749 protected void copy_annotseqtoclipboard(SequenceI sq)
751 SequenceI[] seqs = new SequenceI[]
753 String[] omitHidden = null;
754 SequenceI[] dseqs = new SequenceI[]
755 { sq.getDatasetSequence() };
756 if (dseqs[0] == null)
758 dseqs[0] = new Sequence(sq);
759 dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
760 jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
762 sq.setDatasetSequence(dseqs[0]);
764 Alignment ds = new Alignment(dseqs);
765 if (av.hasHiddenColumns())
767 omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
768 sq.getLength(), seqs);
771 String output = new FormatAdapter().formatSequences("Fasta", seqs,
774 Toolkit.getDefaultToolkit().getSystemClipboard()
775 .setContents(new StringSelection(output), Desktop.instance);
777 Vector hiddenColumns = null;
778 if (av.hasHiddenColumns())
780 hiddenColumns = new Vector();
781 for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
783 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
786 hiddenColumns.addElement(new int[]
787 { region[0], region[1] });
791 Desktop.jalviewClipboard = new Object[]
792 { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
793 // sequence as special.
803 public void paintComponent(Graphics g)
806 int width = getWidth();
809 width = ap.calculateIdWidth().width + 4;
812 Graphics2D g2 = (Graphics2D) g;
815 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
816 RenderingHints.VALUE_ANTIALIAS_ON);
819 drawComponent(g2, true, width);
824 * Draw the full set of annotation Labels for the alignment at the given cursor
826 * @param g Graphics2D instance (needed for font scaling)
827 * @param width Width for scaling labels
830 public void drawComponent(Graphics g, int width)
832 drawComponent(g, false, width);
835 private final boolean debugRedraw = false;
837 * Draw the full set of annotation Labels for the alignment at the given cursor
839 * @param g Graphics2D instance (needed for font scaling)
840 * @param clip - true indicates that only current visible area needs to be rendered
841 * @param width Width for scaling labels
843 public void drawComponent(Graphics g, boolean clip, int width)
845 if (av.getFont().getSize() < 10)
851 g.setFont(av.getFont());
854 FontMetrics fm = g.getFontMetrics(g.getFont());
855 g.setColor(Color.white);
856 g.fillRect(0, 0, getWidth(), getHeight());
858 g.translate(0, scrollOffset);
859 g.setColor(Color.black);
861 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
862 int fontHeight = g.getFont().getSize();
867 Font baseFont = g.getFont();
868 FontMetrics baseMetrics = fm;
869 int ofontH = fontHeight;
872 int[] visr = (ap!=null && ap.annotationPanel!=null) ? ap.annotationPanel.getVisibleVRange() : null;
873 if (clip && visr!=null){
877 boolean visible = true,before=false,after=false;
880 hasHiddenRows = false;
882 for (int i = 0; i < aa.length; i++)
887 hasHiddenRows = true;
892 if (clip) {if (y<sOffset)
897 System.out.println("before vis: "+i);
901 // don't draw what isn't visible
910 System.out.println("Scroll offset: "+sOffset+" after vis: "+i);
914 // don't draw what isn't visible
917 g.setColor(Color.black);
919 offset = -aa[i].height / 2;
923 offset += fm.getHeight() / 2;
924 offset -= fm.getDescent();
927 offset += fm.getDescent();
929 x = width - fm.stringWidth(aa[i].label) - 3;
931 if (aa[i].graphGroup > -1)
934 // TODO: JAL-1291 revise rendering model so the graphGroup map is computed efficiently for all visible labels
935 for (int gg = 0; gg < aa.length; gg++)
937 if (aa[gg].graphGroup == aa[i].graphGroup)
942 if (groupSize * (fontHeight + 8) < aa[i].height)
944 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
949 float h = aa[i].height / (float) groupSize, s;
956 fontHeight = -8 + (int) h;
957 s = ((float) fontHeight) / (float) ofontH;
958 Font f = baseFont.deriveFont(AffineTransform
959 .getScaleInstance(s, s));
961 fm = g.getFontMetrics();
962 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
967 for (int gg = 0; gg < aa.length; gg++)
969 if (aa[gg].graphGroup == aa[i].graphGroup)
971 x = width - fm.stringWidth(aa[gg].label) - 3;
972 g.drawString(aa[gg].label, x, y - graphExtras);
974 if (aa[gg]._linecolour != null)
977 g.setColor(aa[gg]._linecolour);
978 g.drawLine(x, y - graphExtras + 3,
979 x + fm.stringWidth(aa[gg].label), y - graphExtras
983 g.setColor(Color.black);
984 graphExtras += fontHeight + 8;
994 g.drawString(aa[i].label, x, y + offset);
1001 g.drawImage(image, 2, 0 - scrollOffset, this);
1003 else if (dragEvent != null && aa != null)
1005 g.setColor(Color.lightGray);
1006 g.drawString(aa[selectedRow].label, dragEvent.getX(),
1007 dragEvent.getY() - scrollOffset);
1010 if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1012 g.drawString("Right click", 2, 8);
1013 g.drawString("to add annotation", 2, 18);