2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
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 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/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
22 import java.util.regex.Pattern;
25 import java.awt.datatransfer.*;
26 import java.awt.event.*;
27 import java.awt.geom.AffineTransform;
28 import java.awt.image.*;
31 import jalview.datamodel.*;
33 import jalview.util.MessageManager;
41 public class AnnotationLabels extends JPanel implements MouseListener,
42 MouseMotionListener, ActionListener
44 static String TOGGLE_LABELSCALE = "Scale Label to Column";
46 static String ADDNEW = "Add New Row";
48 static String EDITNAME = "Edit Label/Description";
50 static String HIDE = "Hide This Row";
52 static String DELETE = "Delete This Row";
54 static String SHOWALL = "Show All Hidden Rows";
56 static String OUTPUT_TEXT = "Export Annotation";
58 static String COPYCONS_SEQ = "Copy Consensus Sequence";
60 boolean resizePanel = false;
68 boolean resizing = false;
78 Font font = new Font("Arial", Font.PLAIN, 11);
80 private boolean hasHiddenRows;
83 * Creates a new AnnotationLabels object.
88 public AnnotationLabels(AlignmentPanel ap)
92 ToolTipManager.sharedInstance().registerComponent(this);
94 java.net.URL url = getClass().getResource("/images/idwidth.gif");
99 temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
104 MediaTracker mt = new MediaTracker(this);
105 mt.addImage(temp, 0);
107 } catch (Exception ex)
111 BufferedImage bi = new BufferedImage(temp.getHeight(this),
112 temp.getWidth(this), BufferedImage.TYPE_INT_RGB);
113 Graphics2D g = (Graphics2D) bi.getGraphics();
114 g.rotate(Math.toRadians(90));
115 g.drawImage(temp, 0, -bi.getWidth(this), this);
118 addMouseListener(this);
119 addMouseMotionListener(this);
120 addMouseWheelListener(ap.annotationPanel);
123 public AnnotationLabels(AlignViewport av)
134 public void setScrollOffset(int y)
141 * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
145 * coordinate position to search for a row
147 void getSelectedRow(int y)
150 AlignmentAnnotation[] aa = ap.av.getAlignment()
151 .getAlignmentAnnotation();
155 for (int i = 0; i < aa.length; i++)
163 height += aa[i].height;
181 public void actionPerformed(ActionEvent evt)
183 AlignmentAnnotation[] aa = ap.av.getAlignment()
184 .getAlignmentAnnotation();
186 if (evt.getActionCommand().equals(ADDNEW))
188 AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
189 null, new Annotation[ap.av.getAlignment().getWidth()]);
191 if (!editLabelDescription(newAnnotation))
196 ap.av.getAlignment().addAnnotation(newAnnotation);
197 ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
199 else if (evt.getActionCommand().equals(EDITNAME))
201 editLabelDescription(aa[selectedRow]);
204 else if (evt.getActionCommand().equals(HIDE))
206 aa[selectedRow].visible = false;
208 else if (evt.getActionCommand().equals(DELETE))
210 ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
212 else if (evt.getActionCommand().equals(SHOWALL))
214 for (int i = 0; i < aa.length; i++)
216 if (!aa[i].visible && aa[i].annotations != null)
218 aa[i].visible = true;
222 else if (evt.getActionCommand().equals(OUTPUT_TEXT))
224 new AnnotationExporter().exportAnnotations(ap,
225 new AlignmentAnnotation[]
226 { aa[selectedRow] }, null, null);
228 else if (evt.getActionCommand().equals(COPYCONS_SEQ))
230 SequenceI cons = null;
231 if (aa[selectedRow].groupRef != null)
233 cons = aa[selectedRow].groupRef.getConsensusSeq();
237 cons = av.getConsensusSeq();
241 copy_annotseqtoclipboard(cons);
245 else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
247 aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
250 ap.validateAnnotationDimensions(false);
254 // ap.paintAlignment(true);
263 boolean editLabelDescription(AlignmentAnnotation annotation)
265 EditNameDialog dialog = new EditNameDialog(annotation.label,
266 annotation.description, " Annotation Name ",
267 "Annotation Description ", "Edit Annotation Name/Description",
275 annotation.label = dialog.getName();
277 String text = dialog.getDescription();
278 if (text != null && text.length() == 0)
282 annotation.description = text;
293 public void mousePressed(MouseEvent evt)
295 getSelectedRow(evt.getY() - scrollOffset);
305 public void mouseReleased(MouseEvent evt)
307 int start = selectedRow;
308 getSelectedRow(evt.getY() - scrollOffset);
309 int end = selectedRow;
313 // Swap these annotations
314 AlignmentAnnotation startAA = ap.av.getAlignment()
315 .getAlignmentAnnotation()[start];
318 end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
320 AlignmentAnnotation endAA = ap.av.getAlignment()
321 .getAlignmentAnnotation()[end];
323 ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
324 ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
330 ap.annotationPanel.repaint();
339 public void mouseEntered(MouseEvent evt)
354 public void mouseExited(MouseEvent evt)
356 if (dragEvent == null)
369 public void mouseDragged(MouseEvent evt)
375 Dimension d = ap.annotationScroller.getPreferredSize();
376 int dif = evt.getY() - oldY;
378 dif /= ap.av.charHeight;
379 dif *= ap.av.charHeight;
381 if ((d.height - dif) > 20)
383 ap.annotationScroller.setPreferredSize(new Dimension(d.width,
385 d = ap.annotationSpaceFillerHolder.getPreferredSize();
386 ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
387 d.width, d.height - dif));
388 ap.paintAlignment(true);
405 public void mouseMoved(MouseEvent evt)
407 resizePanel = evt.getY() < 10;
409 getSelectedRow(evt.getY() - scrollOffset);
412 && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
414 AlignmentAnnotation aa = ap.av.getAlignment()
415 .getAlignmentAnnotation()[selectedRow];
417 StringBuffer desc = new StringBuffer();
418 if (aa.description != null
419 && !aa.description.equals("New description"))
421 // TODO: we could refactor and merge this code with the code in
422 // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
424 desc.append(aa.getDescription(true).trim());
425 // check to see if the description is an html fragment.
426 if (desc.length() < 6
427 || (desc.substring(0, 6).toLowerCase().indexOf("<html>") < 0))
429 // clean the description ready for embedding in html
430 desc = new StringBuffer(Pattern.compile("<").matcher(desc)
431 .replaceAll("<"));
432 desc.insert(0, "<html>");
436 // remove terminating html if any
437 int i = desc.substring(desc.length() - 7).toLowerCase()
438 .lastIndexOf("</html>");
441 desc.setLength(desc.length() - 7 + i);
446 desc.append("<br/>");
452 // begin the tooltip's html fragment
453 desc.append("<html>");
457 // TODO: limit precision of score to avoid noise from imprecise doubles
458 // (64.7 becomes 64.7+/some tiny value).
459 desc.append(" Score: " + aa.score);
462 if (desc.length() > 6)
464 desc.append("</html>");
465 this.setToolTipText(desc.toString());
468 this.setToolTipText(null);
479 public void mouseClicked(MouseEvent evt)
481 AlignmentAnnotation[] aa = ap.av.getAlignment()
482 .getAlignmentAnnotation();
483 if (SwingUtilities.isLeftMouseButton(evt))
485 if (selectedRow > -1 && selectedRow < aa.length)
487 if (aa[selectedRow].groupRef != null)
489 if (evt.getClickCount() >= 2)
491 // todo: make the ap scroll to the selection - not necessary, first
492 // click highlights/scrolls, second selects
493 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
494 ap.av.setSelectionGroup(// new SequenceGroup(
495 aa[selectedRow].groupRef); // );
496 ap.paintAlignment(false);
497 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
498 ap.av.sendSelection();
502 ap.seqPanel.ap.idPanel
503 .highlightSearchResults(aa[selectedRow].groupRef
504 .getSequences(null));
508 else if (aa[selectedRow].sequenceRef != null)
510 Vector sr = new Vector();
511 sr.addElement(aa[selectedRow].sequenceRef);
512 if (evt.getClickCount() == 1)
514 ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
516 else if (evt.getClickCount() >= 2)
518 ap.seqPanel.ap.idPanel.highlightSearchResults(null);
519 SequenceGroup sg = new SequenceGroup();
520 sg.addSequence(aa[selectedRow].sequenceRef, false);
521 ap.av.setSelectionGroup(sg);
522 ap.av.sendSelection();
523 ap.paintAlignment(false);
524 PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
530 if (!SwingUtilities.isRightMouseButton(evt))
535 JPopupMenu pop = new JPopupMenu(MessageManager.getString("label.annotations"));
536 JMenuItem item = new JMenuItem(ADDNEW);
537 item.addActionListener(this);
542 { // let the user make everything visible again
543 item = new JMenuItem(SHOWALL);
544 item.addActionListener(this);
547 pop.show(this, evt.getX(), evt.getY());
550 item = new JMenuItem(EDITNAME);
551 item.addActionListener(this);
553 item = new JMenuItem(HIDE);
554 item.addActionListener(this);
556 item = new JMenuItem(DELETE);
557 item.addActionListener(this);
561 item = new JMenuItem(SHOWALL);
562 item.addActionListener(this);
565 item = new JMenuItem(OUTPUT_TEXT);
566 item.addActionListener(this);
568 // TODO: annotation object should be typed for autocalculated/derived
570 if (selectedRow < aa.length)
572 if (!aa[selectedRow].autoCalculated)
574 if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
576 // display formatting settings for this row.
578 // av and sequencegroup need to implement same interface for
579 item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
580 aa[selectedRow].scaleColLabel);
581 item.addActionListener(this);
585 else if (aa[selectedRow].label.indexOf("Consensus") > -1)
588 // av and sequencegroup need to implement same interface for
589 final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
590 "Ignore Gaps In Consensus",
591 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
592 .getIgnoreGapsConsensus() : ap.av
593 .getIgnoreGapsConsensus());
594 final AlignmentAnnotation aaa = aa[selectedRow];
595 cbmi.addActionListener(new ActionListener()
597 public void actionPerformed(ActionEvent e)
599 if (aaa.groupRef != null)
601 // TODO: pass on reference to ap so the view can be updated.
602 aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
603 ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
607 ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
612 // av and sequencegroup need to implement same interface for
613 if (aaa.groupRef != null)
615 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
616 "Show Group Histogram",
617 aa[selectedRow].groupRef.isShowConsensusHistogram());
618 chist.addActionListener(new ActionListener()
620 public void actionPerformed(ActionEvent e)
622 // TODO: pass on reference
628 aaa.groupRef.setShowConsensusHistogram(chist.getState());
630 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
634 final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
636 aa[selectedRow].groupRef.isShowSequenceLogo());
637 cprofl.addActionListener(new ActionListener()
639 public void actionPerformed(ActionEvent e)
641 // TODO: pass on reference
647 aaa.groupRef.setshowSequenceLogo(cprofl.getState());
649 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
653 final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
654 "Normalise Group Logo",
655 aa[selectedRow].groupRef.isNormaliseSequenceLogo());
656 cproflnorm.addActionListener(new ActionListener()
658 public void actionPerformed(ActionEvent e)
661 // TODO: pass on reference
667 aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
668 // automatically enable logo display if we're clicked
669 aaa.groupRef.setshowSequenceLogo(true);
671 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
678 final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
679 "Show Histogram", av.isShowConsensusHistogram());
680 chist.addActionListener(new ActionListener()
682 public void actionPerformed(ActionEvent e)
684 // TODO: pass on reference
690 av.setShowConsensusHistogram(chist.getState());
691 ap.alignFrame.setMenusForViewport();
693 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
697 final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
698 "Show Logo", av.isShowSequenceLogo());
699 cprof.addActionListener(new ActionListener()
701 public void actionPerformed(ActionEvent e)
703 // TODO: pass on reference
709 av.setShowSequenceLogo(cprof.getState());
710 ap.alignFrame.setMenusForViewport();
712 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
716 final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
717 "Normalise Logo", av.isNormaliseSequenceLogo());
718 cprofnorm.addActionListener(new ActionListener()
720 public void actionPerformed(ActionEvent e)
722 // TODO: pass on reference
728 av.setShowSequenceLogo(true);
729 av.setNormaliseSequenceLogo(cprofnorm.getState());
730 ap.alignFrame.setMenusForViewport();
732 // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
737 final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
738 consclipbrd.addActionListener(this);
739 pop.add(consclipbrd);
742 pop.show(this, evt.getX(), evt.getY());
746 * do a single sequence copy to jalview and the system clipboard
749 * sequence to be copied to clipboard
751 protected void copy_annotseqtoclipboard(SequenceI sq)
753 SequenceI[] seqs = new SequenceI[]
755 String[] omitHidden = null;
756 SequenceI[] dseqs = new SequenceI[]
757 { sq.getDatasetSequence() };
758 if (dseqs[0] == null)
760 dseqs[0] = new Sequence(sq);
761 dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
762 jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
764 sq.setDatasetSequence(dseqs[0]);
766 Alignment ds = new Alignment(dseqs);
767 if (av.hasHiddenColumns())
769 omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
770 sq.getLength(), seqs);
773 String output = new FormatAdapter().formatSequences("Fasta", seqs,
776 Toolkit.getDefaultToolkit().getSystemClipboard()
777 .setContents(new StringSelection(output), Desktop.instance);
779 Vector hiddenColumns = null;
780 if (av.hasHiddenColumns())
782 hiddenColumns = new Vector();
783 for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
785 int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
788 hiddenColumns.addElement(new int[]
789 { region[0], region[1] });
793 Desktop.jalviewClipboard = new Object[]
794 { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
795 // sequence as special.
805 public void paintComponent(Graphics g)
808 int width = getWidth();
811 width = ap.calculateIdWidth().width + 4;
814 Graphics2D g2 = (Graphics2D) g;
817 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
818 RenderingHints.VALUE_ANTIALIAS_ON);
821 drawComponent(g2, true, width);
826 * Draw the full set of annotation Labels for the alignment at the given cursor
828 * @param g Graphics2D instance (needed for font scaling)
829 * @param width Width for scaling labels
832 public void drawComponent(Graphics g, int width)
834 drawComponent(g, false, width);
837 private final boolean debugRedraw = false;
839 * Draw the full set of annotation Labels for the alignment at the given cursor
841 * @param g Graphics2D instance (needed for font scaling)
842 * @param clip - true indicates that only current visible area needs to be rendered
843 * @param width Width for scaling labels
845 public void drawComponent(Graphics g, boolean clip, int width)
847 if (av.getFont().getSize() < 10)
853 g.setFont(av.getFont());
856 FontMetrics fm = g.getFontMetrics(g.getFont());
857 g.setColor(Color.white);
858 g.fillRect(0, 0, getWidth(), getHeight());
860 g.translate(0, scrollOffset);
861 g.setColor(Color.black);
863 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
864 int fontHeight = g.getFont().getSize();
869 Font baseFont = g.getFont();
870 FontMetrics baseMetrics = fm;
871 int ofontH = fontHeight;
874 int[] visr = (ap!=null && ap.annotationPanel!=null) ? ap.annotationPanel.getVisibleVRange() : null;
875 if (clip && visr!=null){
879 boolean visible = true,before=false,after=false;
882 hasHiddenRows = false;
884 for (int i = 0; i < aa.length; i++)
889 hasHiddenRows = true;
894 if (clip) {if (y<sOffset)
899 System.out.println("before vis: "+i);
903 // don't draw what isn't visible
912 System.out.println("Scroll offset: "+sOffset+" after vis: "+i);
916 // don't draw what isn't visible
919 g.setColor(Color.black);
921 offset = -aa[i].height / 2;
925 offset += fm.getHeight() / 2;
926 offset -= fm.getDescent();
929 offset += fm.getDescent();
931 x = width - fm.stringWidth(aa[i].label) - 3;
933 if (aa[i].graphGroup > -1)
936 // TODO: JAL-1291 revise rendering model so the graphGroup map is computed efficiently for all visible labels
937 for (int gg = 0; gg < aa.length; gg++)
939 if (aa[gg].graphGroup == aa[i].graphGroup)
944 if (groupSize * (fontHeight + 8) < aa[i].height)
946 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
951 float h = aa[i].height / (float) groupSize, s;
958 fontHeight = -8 + (int) h;
959 s = ((float) fontHeight) / (float) ofontH;
960 Font f = baseFont.deriveFont(AffineTransform
961 .getScaleInstance(s, s));
963 fm = g.getFontMetrics();
964 graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
969 for (int gg = 0; gg < aa.length; gg++)
971 if (aa[gg].graphGroup == aa[i].graphGroup)
973 x = width - fm.stringWidth(aa[gg].label) - 3;
974 g.drawString(aa[gg].label, x, y - graphExtras);
976 if (aa[gg]._linecolour != null)
979 g.setColor(aa[gg]._linecolour);
980 g.drawLine(x, y - graphExtras + 3,
981 x + fm.stringWidth(aa[gg].label), y - graphExtras
985 g.setColor(Color.black);
986 graphExtras += fontHeight + 8;
996 g.drawString(aa[i].label, x, y + offset);
1003 g.drawImage(image, 2, 0 - scrollOffset, this);
1005 else if (dragEvent != null && aa != null)
1007 g.setColor(Color.lightGray);
1008 g.drawString(aa[selectedRow].label, dragEvent.getX(),
1009 dragEvent.getY() - scrollOffset);
1012 if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1014 g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1015 g.drawString(MessageManager.getString("label.to_add_annotation"), 2, 18);