2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportListenerI;
39 import jalview.viewmodel.ViewportRanges;
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.ComponentAdapter;
52 import java.awt.event.ComponentEvent;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.beans.PropertyChangeEvent;
57 import java.beans.PropertyChangeListener;
59 import java.io.FileWriter;
60 import java.io.PrintWriter;
61 import java.util.List;
63 import javax.swing.SwingUtilities;
69 * @version $Revision: 1.161 $
71 public class AlignmentPanel extends GAlignmentPanel implements
72 AdjustmentListener, Printable, AlignmentViewPanel,
75 public AlignViewport av;
77 ViewportRanges vpRanges;
79 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 // this value is set false when selection area being dragged
99 boolean fastPaint = true;
101 private int hextent = 0;
103 private int vextent = 0;
106 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107 * true, suppresses invoking the same method recursively.
109 private boolean dontScrollComplement;
111 private PropertyChangeListener propertyChangeListener;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
123 vpRanges = av.getRanges();
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 addComponentListener(new ComponentAdapter()
150 public void componentResized(ComponentEvent evt)
152 // reset the viewport ranges when the alignment panel is resized
153 // in particular, this initialises the end residue value when Jalview
157 if (av.getWrapAlignment())
159 int widthInRes = getSeqPanel().seqCanvas
160 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
161 vpRanges.setStartEndRes(vpRanges.getStartRes(), widthInRes);
165 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
166 .getCharWidth()) - 1;
167 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight()) - 1;
169 vpRanges.setStartEndRes(vpRanges.getStartRes(), widthInRes);
170 vpRanges.setStartEndSeq(vpRanges.getStartSeq(), heightInSeq);
178 final AlignmentPanel ap = this;
179 propertyChangeListener = new PropertyChangeListener()
182 public void propertyChange(PropertyChangeEvent evt)
184 if (evt.getPropertyName().equals("alignment"))
186 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
191 av.addPropertyChangeListener(propertyChangeListener);
193 av.getRanges().addPropertyChangeListener(this);
195 adjustAnnotationHeight();
200 public AlignViewportI getAlignViewport()
205 public void alignmentChanged()
207 av.alignmentChanged(this);
209 alignFrame.updateEditMenuBar();
211 paintAlignment(true);
218 public void fontChanged()
220 // set idCanvas bufferedImage to null
221 // to prevent drawing old image
222 FontMetrics fm = getFontMetrics(av.getFont());
224 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
226 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
227 .getCharHeight() + fm.getDescent()));
229 getIdPanel().getIdCanvas().gg = null;
230 getSeqPanel().seqCanvas.img = null;
231 getAnnotationPanel().adjustPanelHeight();
233 Dimension d = calculateIdWidth();
235 d.setSize(d.width + 4, d.height);
236 getIdPanel().getIdCanvas().setPreferredSize(d);
237 hscrollFillerPanel.setPreferredSize(d);
239 if (this.alignFrame.getSplitViewContainer() != null)
241 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
248 * Calculate the width of the alignment labels based on the displayed names
249 * and any bounds on label width set in preferences.
251 * @return Dimension giving the maximum width of the alignment label panel
252 * that should be used.
254 public Dimension calculateIdWidth()
256 // calculate sensible default width when no preference is available
258 if (av.getIdWidth() < 0)
260 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
261 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
262 r = calculateIdWidth(maxwidth);
263 av.setIdWidth(r.width);
268 r.width = av.getIdWidth();
275 * Calculate the width of the alignment labels based on the displayed names
276 * and any bounds on label width set in preferences.
279 * -1 or maximum width allowed for IdWidth
280 * @return Dimension giving the maximum width of the alignment label panel
281 * that should be used.
283 public Dimension calculateIdWidth(int maxwidth)
285 Container c = new Container();
287 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
288 Font.ITALIC, av.font.getSize()));
290 AlignmentI al = av.getAlignment();
295 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
297 SequenceI s = al.getSequenceAt(i);
299 id = s.getDisplayId(av.getShowJVSuffix());
301 if (fm.stringWidth(id) > idWidth)
303 idWidth = fm.stringWidth(id);
309 // Also check annotation label widths
312 if (al.getAlignmentAnnotation() != null)
314 fm = c.getFontMetrics(getAlabels().getFont());
316 while (i < al.getAlignmentAnnotation().length)
318 String label = al.getAlignmentAnnotation()[i].label;
320 if (fm.stringWidth(label) > idWidth)
322 idWidth = fm.stringWidth(label);
329 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
334 * Highlight the given results on the alignment.
337 public void highlightSearchResults(SearchResultsI results)
339 scrollToPosition(results);
340 getSeqPanel().seqCanvas.highlightSearchResults(results);
344 * Scroll the view to show the position of the highlighted region in results
345 * (if any) and redraw the overview
349 public boolean scrollToPosition(SearchResultsI results)
351 return scrollToPosition(results, 0, true, false);
355 * Scroll the view to show the position of the highlighted region in results
358 * @param searchResults
359 * @param redrawOverview
362 public boolean scrollToPosition(SearchResultsI searchResults,
363 boolean redrawOverview)
365 return scrollToPosition(searchResults, 0, redrawOverview, false);
369 * Scroll the view to show the position of the highlighted region in results
373 * @param verticalOffset
374 * if greater than zero, allows scrolling to a position below the
375 * first displayed sequence
376 * @param redrawOverview
377 * - when set, the overview will be recalculated (takes longer)
379 * if true, try to centre the search results horizontally in the view
380 * @return false if results were not found
382 public boolean scrollToPosition(SearchResultsI results,
383 int verticalOffset, boolean redrawOverview, boolean centre)
385 int startv, endv, starts, ends;
386 // TODO: properly locate search results in view when large numbers of hidden
387 // columns exist before highlighted region
388 // do we need to scroll the panel?
389 // TODO: tons of nullpointerexceptions raised here.
390 if (results != null && results.getSize() > 0 && av != null
391 && av.getAlignment() != null)
393 int seqIndex = av.getAlignment().findIndex(results);
398 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
400 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
408 // System.err.println(this.av.viewName + " Seq : " + seqIndex
409 // + " Scroll to " + start + "," + end);
412 * To centre results, scroll to positions half the visible width
413 * left/right of the start/end positions
417 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
418 start = Math.max(start - offset, 0);
419 end = end + offset - 1;
425 if (end == seq.getEnd())
429 if (av.hasHiddenColumns())
431 start = av.getColumnSelection().findColumnPosition(start);
432 end = av.getColumnSelection().findColumnPosition(end);
435 if (!av.getColumnSelection().isVisible(r[0]))
437 // don't scroll - position isn't visible
444 * allow for offset of target sequence (actually scroll to one above it)
446 seqIndex = Math.max(0, seqIndex - verticalOffset);
448 // System.out.println("start=" + start + ", end=" + end + ", startv="
449 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
450 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
451 if (!av.getWrapAlignment())
453 if ((startv = vpRanges.getStartRes()) >= start)
456 * Scroll left to make start of search results visible
458 // setScrollValues(start - 1, seqIndex); // plus one residue
459 setScrollValues(start, seqIndex);
461 else if ((endv = vpRanges.getEndRes()) <= end)
464 * Scroll right to make end of search results visible
466 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
467 setScrollValues(startv + end - endv, seqIndex);
469 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
472 * Scroll up to make start of search results visible
474 setScrollValues(vpRanges.getStartRes(), seqIndex);
476 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
479 * Scroll down to make end of search results visible
481 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
485 * Else results are already visible - no need to scroll
490 vpRanges.scrollToWrappedVisible(start);
491 // scrollToWrappedVisible(start);
495 paintAlignment(redrawOverview);
502 * @return DOCUMENT ME!
504 public OverviewPanel getOverviewPanel()
506 return overviewPanel;
515 public void setOverviewPanel(OverviewPanel op)
523 * Hide or show annotation panel
526 public void setAnnotationVisible(boolean b)
528 if (!av.getWrapAlignment())
530 annotationSpaceFillerHolder.setVisible(b);
531 annotationScroller.setVisible(b);
537 * automatically adjust annotation panel height for new annotation whilst
538 * ensuring the alignment is still visible.
541 public void adjustAnnotationHeight()
543 // TODO: display vertical annotation scrollbar if necessary
544 // this is called after loading new annotation onto alignment
545 if (alignFrame.getHeight() == 0)
547 System.out.println("NEEDS FIXING");
549 validateAnnotationDimensions(true);
551 paintAlignment(true);
555 * calculate the annotation dimensions and refresh slider values accordingly.
556 * need to do repaints/notifys afterwards.
558 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
560 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
562 if (adjustPanelHeight)
564 int rowHeight = av.getCharHeight();
565 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
568 * Estimate available height in the AlignFrame for alignment +
569 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
570 * hscroll, status bar (as these are not laid out we can't inspect their
571 * actual heights). Insets gives frame borders.
573 int stuff = Platform.isAMac() ? 80 : 100;
574 Insets insets = alignFrame.getInsets();
575 int availableHeight = alignFrame.getHeight() - stuff - insets.top
579 * If not enough vertical space, maximize annotation height while keeping
580 * at least two rows of alignment visible
582 if (annotationHeight + alignmentHeight > availableHeight)
584 annotationHeight = Math.min(annotationHeight, availableHeight - 2
590 // maintain same window layout whilst updating sliders
591 annotationHeight = annotationScroller.getSize().height;
595 annotationScroller.setPreferredSize(new Dimension(annotationScroller
596 .getWidth(), annotationHeight));
598 Dimension e = idPanel.getSize();
599 alabels.setSize(new Dimension(e.width, annotationHeight));
601 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
602 annotationSpaceFillerHolder.getWidth(), annotationHeight));
603 annotationScroller.validate();
604 annotationScroller.addNotify();
608 * update alignment layout for viewport settings
613 public void updateLayout()
616 setAnnotationVisible(av.isShowAnnotation());
617 boolean wrap = av.getWrapAlignment();
618 vpRanges.setStartSeq(0);
619 scalePanelHolder.setVisible(!wrap);
620 hscroll.setVisible(!wrap);
621 idwidthAdjuster.setVisible(!wrap);
625 annotationScroller.setVisible(false);
626 annotationSpaceFillerHolder.setVisible(false);
628 else if (av.isShowAnnotation())
630 annotationScroller.setVisible(true);
631 annotationSpaceFillerHolder.setVisible(true);
636 int widthInRes = getSeqPanel().seqCanvas
637 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
638 vpRanges.setStartEndRes(vpRanges.getStartRes(), widthInRes);
642 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
643 .getCharWidth()) - 1;
644 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
645 .getCharHeight()) - 1;
647 vpRanges.setStartEndRes(vpRanges.getStartRes(), widthInRes);
648 vpRanges.setStartEndSeq(vpRanges.getStartSeq(), heightInSeq);
651 idSpaceFillerPanel1.setVisible(!wrap);
658 * Adjust row/column scrollers to show a visible position in the alignment.
661 * visible column to scroll to
663 * visible row to scroll to
666 public void setScrollValues(int x, int y)
668 if (av == null || av.getAlignment() == null)
673 if (av.getWrapAlignment())
675 setScrollingForWrappedPanel(x);
680 int width = av.getAlignment().getWidth();
681 int height = av.getAlignment().getHeight();
683 if (av.hasHiddenColumns())
685 // reset the width to exclude hidden columns
686 width = av.getColumnSelection().findColumnPosition(width);
689 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
690 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
697 if (vextent > height)
702 if ((hextent + x) > width)
707 if ((vextent + y) > height)
709 y = height - vextent;
722 // update the scroll values
723 hscroll.setValues(x, hextent, 0, width);
724 vscroll.setValues(y, vextent, 0, height);
735 public void adjustmentValueChanged(AdjustmentEvent evt)
737 int oldX = vpRanges.getStartRes();
738 int oldwidth = vpRanges.getViewportWidth();
739 int oldY = vpRanges.getStartSeq();
740 int oldheight = vpRanges.getViewportHeight();
742 if (av.getWrapAlignment())
744 if (evt.getSource() == hscroll)
746 return; // no horizontal scroll when wrapped
748 else if (evt.getSource() == vscroll)
750 int offy = vscroll.getValue();
751 int rowSize = getSeqPanel().seqCanvas
752 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
754 // if we're scrolling to the position we're already at, stop
755 // this prevents infinite recursion of events when the scroll/viewport
756 // ranges values are the same
757 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
763 vpRanges.setStartEndRes(offy * rowSize, (offy + 1) * rowSize);
767 // This is only called if file loaded is a jar file that
768 // was wrapped when saved and user has wrap alignment true
769 // as preference setting
770 SwingUtilities.invokeLater(new Runnable()
775 setScrollValues(vpRanges.getStartRes(),
776 vpRanges.getStartSeq());
786 if (evt.getSource() == hscroll)
788 int x = hscroll.getValue();
789 int width = (getSeqPanel().seqCanvas.getWidth() / av.getCharWidth()) - 1;
791 // if we're scrolling to the position we're already at, stop
792 // this prevents infinite recursion of events when the scroll/viewport
793 // ranges values are the same
794 if ((x == oldX) && (width == oldwidth))
798 vpRanges.setStartEndRes(x, x + width);
800 else if (evt.getSource() == vscroll)
802 int y = vscroll.getValue();
803 int height = (getSeqPanel().seqCanvas.getHeight() / av
804 .getCharHeight()) - 1;
806 // if we're scrolling to the position we're already at, stop
807 // this prevents infinite recursion of events when the scroll/viewport
808 // ranges values are the same
809 if ((y == oldY) && (height == oldheight))
813 vpRanges.setStartEndSeq(y, y + height);
823 * Repaint the alignment including the annotations and overview panels (if
827 public void paintAlignment(boolean updateOverview)
829 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
830 av.isShowAutocalculatedAbove());
831 sorter.sort(getAlignment().getAlignmentAnnotation(),
832 av.getSortAnnotationsBy());
837 // TODO: determine if this paintAlignment changed structure colours
838 av.getStructureSelectionManager().sequenceColoursChanged(this);
840 if (overviewPanel != null)
842 overviewPanel.updateOverviewImage();
854 public void paintComponent(Graphics g)
858 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
859 idPanelHolder.setPreferredSize(d);
860 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
864 * set scroll bar positions
866 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
870 * Set vertical scroll bar parameters for wrapped panel
872 * the residue to scroll to
874 private void setScrollingForWrappedPanel(int res)
876 // get the width of the alignment in residues
877 int maxwidth = av.getAlignment().getWidth();
878 if (av.hasHiddenColumns())
880 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
883 // get the width of the canvas in residues
884 int canvasWidth = getSeqPanel().seqCanvas
885 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
888 // position we want to scroll to is number of canvasWidth's to get there
889 int current = res / canvasWidth;
891 // max scroll position: add one because extent is 1 and scrollbar value
892 // can only be set to at most max - extent
893 int max = maxwidth / canvasWidth + 1;
894 vscroll.setUnitIncrement(1);
895 vscroll.setValues(current, 1, 0, max);
909 * @return DOCUMENT ME!
911 * @throws PrinterException
915 public int print(Graphics pg, PageFormat pf, int pi)
916 throws PrinterException
918 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
920 int pwidth = (int) pf.getImageableWidth();
921 int pheight = (int) pf.getImageableHeight();
923 if (av.getWrapAlignment())
925 return printWrappedAlignment(pwidth, pheight, pi, pg);
929 return printUnwrapped(pwidth, pheight, pi, pg, pg);
945 * @return DOCUMENT ME!
947 * @throws PrinterException
951 * Draws the alignment image, including sequence ids, sequences, and
952 * annotation labels and annotations if shown, on either one or two Graphics
959 * the graphics context for sequence ids and annotation labels
960 * @param alignmentGraphics
961 * the graphics context for sequences and annotations (may or may not
962 * be the same context as idGraphics)
964 * @throws PrinterException
966 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
967 Graphics idGraphics, Graphics alignmentGraphics)
968 throws PrinterException
970 final int idWidth = getVisibleIdWidth(false);
973 * Get the horizontal offset to where we draw the sequences.
974 * This is idWidth if using a single Graphics context, else zero.
976 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
978 FontMetrics fm = getFontMetrics(av.getFont());
979 int charHeight = av.getCharHeight();
980 int scaleHeight = charHeight + fm.getDescent();
982 idGraphics.setColor(Color.white);
983 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
984 idGraphics.setFont(av.getFont());
987 * How many sequences and residues can we fit on a printable page?
989 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
991 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
993 int alignmentWidth = av.getAlignment().getWidth();
994 int pagesWide = (alignmentWidth / totalRes) + 1;
996 final int startRes = (pi % pagesWide) * totalRes;
997 int endRes = (startRes + totalRes) - 1;
999 if (endRes > (alignmentWidth - 1))
1001 endRes = alignmentWidth - 1;
1004 final int startSeq = (pi / pagesWide) * totalSeq;
1005 int endSeq = startSeq + totalSeq;
1007 int alignmentHeight = av.getAlignment().getHeight();
1008 if (endSeq > alignmentHeight)
1010 endSeq = alignmentHeight;
1013 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1016 if (av.isShowAnnotation())
1018 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1021 pagesHigh /= pageHeight;
1023 if (pi >= (pagesWide * pagesHigh))
1025 return Printable.NO_SUCH_PAGE;
1027 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1031 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1033 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1034 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1035 pageWidth - idWidth, scaleHeight);
1036 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1039 * Draw the sequence ids, offset for scale height,
1040 * then reset to top left (0, 0)
1042 idGraphics.translate(0, scaleHeight);
1043 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1044 Color currentColor = null;
1045 Color currentTextColor = null;
1048 for (int i = startSeq; i < endSeq; i++)
1050 seq = av.getAlignment().getSequenceAt(i);
1051 if ((av.getSelectionGroup() != null)
1052 && av.getSelectionGroup().getSequences(null).contains(seq))
1055 * gray out ids of sequences in selection group (if any)
1057 currentColor = Color.gray;
1058 currentTextColor = Color.black;
1062 currentColor = av.getSequenceColour(seq);
1063 currentTextColor = Color.black;
1066 idGraphics.setColor(currentColor);
1067 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1070 idGraphics.setColor(currentTextColor);
1073 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1074 if (av.isRightAlignIds())
1076 fm = idGraphics.getFontMetrics();
1078 - fm.stringWidth(displayId)
1082 idGraphics.drawString(displayId, xPos,
1083 (((i - startSeq) * charHeight) + charHeight)
1084 - (charHeight / 5));
1086 idGraphics.setFont(av.getFont());
1087 idGraphics.translate(0, -scaleHeight);
1090 * draw the sequences, offset for scale height, and id width (if using a
1091 * single graphics context), then reset to (0, scale height)
1093 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1094 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1095 startSeq, endSeq, 0);
1096 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1098 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1101 * draw annotation labels; drawComponent() translates by
1102 * getScrollOffset(), so compensate for that first;
1103 * then reset to (0, scale height)
1105 int offset = getAlabels().getScrollOffset();
1106 idGraphics.translate(0, -offset);
1107 idGraphics.translate(0, alignmentDrawnHeight);
1108 getAlabels().drawComponent(idGraphics, idWidth);
1109 idGraphics.translate(0, -alignmentDrawnHeight);
1112 * draw the annotations starting at
1113 * (idOffset, alignmentHeight) from (0, scaleHeight)
1115 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1116 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1117 alignmentGraphics, -1, startRes, endRes + 1);
1120 return Printable.PAGE_EXISTS;
1135 * @return DOCUMENT ME!
1137 * @throws PrinterException
1140 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1141 Graphics pg) throws PrinterException
1143 int annotationHeight = 0;
1144 AnnotationLabels labels = null;
1145 if (av.isShowAnnotation())
1147 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1148 labels = new AnnotationLabels(av);
1151 int hgap = av.getCharHeight();
1152 if (av.getScaleAboveWrapped())
1154 hgap += av.getCharHeight();
1157 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1160 int idWidth = getVisibleIdWidth(false);
1162 int maxwidth = av.getAlignment().getWidth();
1163 if (av.hasHiddenColumns())
1165 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1168 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1171 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1173 pg.setColor(Color.white);
1174 pg.fillRect(0, 0, pwidth, pheight);
1175 pg.setFont(av.getFont());
1179 pg.setColor(Color.black);
1181 pg.translate(0, -pi * pheight);
1183 pg.setClip(0, pi * pheight, pwidth, pheight);
1189 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1191 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1192 SequenceI s = av.getAlignment().getSequenceAt(i);
1193 String string = s.getDisplayId(av.getShowJVSuffix());
1195 if (av.isRightAlignIds())
1197 FontMetrics fm = pg.getFontMetrics();
1198 xPos = idWidth - fm.stringWidth(string) - 4;
1200 pg.drawString(string, xPos,
1201 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1202 - (av.getCharHeight() / 5));
1207 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1209 pg.setFont(av.getFont());
1210 labels.drawComponent(pg, idWidth);
1214 - (av.getAlignment().getHeight() * av
1219 } while (ypos < totalHeight);
1221 pg.translate(idWidth, 0);
1223 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1226 if ((pi * pheight) < totalHeight)
1228 return Printable.PAGE_EXISTS;
1233 return Printable.NO_SUCH_PAGE;
1238 * get current sequence ID panel width, or nominal value if panel were to be
1239 * displayed using default settings
1243 public int getVisibleIdWidth()
1245 return getVisibleIdWidth(true);
1249 * get current sequence ID panel width, or nominal value if panel were to be
1250 * displayed using default settings
1253 * indicate if the Id width for onscreen or offscreen display should
1257 public int getVisibleIdWidth(boolean onscreen)
1259 // see if rendering offscreen - check preferences and calc width accordingly
1260 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1262 return calculateIdWidth(-1).width + 4;
1264 Integer idwidth = null;
1266 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1268 int w = getIdPanel().getWidth();
1269 return (w > 0 ? w : calculateIdWidth().width + 4);
1271 return idwidth.intValue() + 4;
1274 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1276 int boarderBottomOffset = 5;
1277 long pSessionId = System.currentTimeMillis();
1278 headless = (System.getProperty("java.awt.headless") != null && System
1279 .getProperty("java.awt.headless").equals("true"));
1280 if (alignFrame != null && !headless)
1284 alignFrame.setProgressBar(MessageManager.formatMessage(
1285 "status.saving_file", new Object[] { type.getLabel() }),
1291 AlignmentDimension aDimension = getAlignmentDimension();
1294 jalview.util.ImageMaker im;
1295 final String imageAction, imageTitle;
1296 if (type == jalview.util.ImageMaker.TYPE.PNG)
1298 imageAction = "Create PNG image from alignment";
1301 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1303 imageAction = "Create EPS file from alignment";
1304 imageTitle = alignFrame.getTitle();
1308 imageAction = "Create SVG file from alignment";
1309 imageTitle = alignFrame.getTitle();
1312 im = new jalview.util.ImageMaker(this, type, imageAction,
1313 aDimension.getWidth(), aDimension.getHeight()
1314 + boarderBottomOffset, file, imageTitle,
1315 alignFrame, pSessionId, headless);
1316 Graphics graphics = im.getGraphics();
1317 if (av.getWrapAlignment())
1319 if (graphics != null)
1321 printWrappedAlignment(aDimension.getWidth(),
1322 aDimension.getHeight() + boarderBottomOffset, 0,
1329 if (graphics != null)
1331 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1332 0, graphics, graphics);
1337 } catch (OutOfMemoryError err)
1340 System.out.println("########################\n" + "OUT OF MEMORY "
1341 + file + "\n" + "########################");
1342 new OOMWarning("Creating Image for " + file, err);
1343 // System.out.println("Create IMAGE: " + err);
1344 } catch (Exception ex)
1346 ex.printStackTrace();
1354 public AlignmentDimension getAlignmentDimension()
1356 int maxwidth = av.getAlignment().getWidth();
1357 if (av.hasHiddenColumns())
1359 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1362 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1363 + getScalePanel().getHeight();
1364 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1366 if (av.getWrapAlignment())
1368 height = getWrappedHeight();
1371 // need to obtain default alignment width and then add in any
1372 // additional allowance for id margin
1373 // this duplicates the calculation in getWrappedHeight but adjusts for
1375 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1376 - alignFrame.getInsets().left
1377 - alignFrame.getInsets().right - getVisibleIdWidth()
1378 + getVisibleIdWidth(false);
1382 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1386 else if (av.isShowAnnotation())
1388 height += getAnnotationPanel().adjustPanelHeight() + 3;
1390 return new AlignmentDimension(width, height);
1397 public void makeEPS(File epsFile)
1399 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1405 public void makePNG(File pngFile)
1407 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1410 public void makeSVG(File svgFile)
1412 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1415 public void makePNGImageMap(File imgMapFile, String imageName)
1417 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1418 // ////////////////////////////////////////////
1419 int idWidth = getVisibleIdWidth(false);
1420 FontMetrics fm = getFontMetrics(av.getFont());
1421 int scaleHeight = av.getCharHeight() + fm.getDescent();
1424 // ////////////////////////////////
1425 if (imgMapFile != null)
1429 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1430 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1431 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1432 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1433 out.println("<img src=\"" + imageName
1434 + "\" border=\"0\" usemap=\"#Map\" >"
1435 + "<map name=\"Map\">");
1437 for (s = 0; s < sSize; s++)
1439 sy = s * av.getCharHeight() + scaleHeight;
1441 SequenceI seq = av.getAlignment().getSequenceAt(s);
1442 SequenceFeature[] features = seq.getSequenceFeatures();
1443 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1444 for (res = 0; res < alwidth; res++)
1446 StringBuilder text = new StringBuilder();
1447 String triplet = null;
1448 if (av.getAlignment().isNucleotide())
1450 triplet = ResidueProperties.nucleotideName.get(seq
1451 .getCharAt(res) + "");
1455 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1459 if (triplet == null)
1464 int alIndex = seq.findPosition(res);
1465 gSize = groups.length;
1466 for (g = 0; g < gSize; g++)
1468 if (text.length() < 1)
1470 text.append("<area shape=\"rect\" coords=\"")
1471 .append((idWidth + res * av.getCharWidth()))
1472 .append(",").append(sy).append(",")
1473 .append((idWidth + (res + 1) * av.getCharWidth()))
1474 .append(",").append((av.getCharHeight() + sy))
1475 .append("\"").append(" onMouseOver=\"toolTip('")
1476 .append(alIndex).append(" ").append(triplet);
1479 if (groups[g].getStartRes() < res
1480 && groups[g].getEndRes() > res)
1482 text.append("<br><em>").append(groups[g].getName())
1487 if (features != null)
1489 if (text.length() < 1)
1491 text.append("<area shape=\"rect\" coords=\"")
1492 .append((idWidth + res * av.getCharWidth()))
1493 .append(",").append(sy).append(",")
1494 .append((idWidth + (res + 1) * av.getCharWidth()))
1495 .append(",").append((av.getCharHeight() + sy))
1496 .append("\"").append(" onMouseOver=\"toolTip('")
1497 .append(alIndex).append(" ").append(triplet);
1499 fSize = features.length;
1500 for (f = 0; f < fSize; f++)
1503 if ((features[f].getBegin() <= seq.findPosition(res))
1504 && (features[f].getEnd() >= seq.findPosition(res)))
1506 if (features[f].isContactFeature())
1508 if (features[f].getBegin() == seq.findPosition(res)
1509 || features[f].getEnd() == seq
1512 text.append("<br>").append(features[f].getType())
1513 .append(" ").append(features[f].getBegin())
1514 .append(":").append(features[f].getEnd());
1519 text.append("<br>");
1520 text.append(features[f].getType());
1521 if (features[f].getDescription() != null
1522 && !features[f].getType().equals(
1523 features[f].getDescription()))
1525 text.append(" ").append(features[f].getDescription());
1528 if (features[f].getValue("status") != null)
1530 text.append(" (").append(features[f].getValue("status"))
1538 if (text.length() > 1)
1540 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1541 out.println(text.toString());
1545 out.println("</map></body></html>");
1548 } catch (Exception ex)
1550 ex.printStackTrace();
1552 } // /////////END OF IMAGE MAP
1556 int getWrappedHeight()
1558 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1560 if (System.getProperty("java.awt.headless") != null
1561 && System.getProperty("java.awt.headless").equals("true"))
1563 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1564 - vscroll.getPreferredSize().width
1565 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1568 int chunkWidth = getSeqPanel().seqCanvas
1569 .getWrappedCanvasWidth(seqPanelWidth);
1571 int hgap = av.getCharHeight();
1572 if (av.getScaleAboveWrapped())
1574 hgap += av.getCharHeight();
1577 int annotationHeight = 0;
1578 if (av.isShowAnnotation())
1580 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1583 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1586 int maxwidth = av.getAlignment().getWidth();
1587 if (av.hasHiddenColumns())
1589 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1592 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1598 * close the panel - deregisters all listeners and nulls any references to
1601 public void closePanel()
1603 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1604 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1605 PaintRefresher.RemoveComponent(this);
1608 * try to ensure references are nulled
1610 if (annotationPanel != null)
1612 annotationPanel.dispose();
1617 av.removePropertyChangeListener(propertyChangeListener);
1618 jalview.structure.StructureSelectionManager ssm = av
1619 .getStructureSelectionManager();
1620 ssm.removeStructureViewerListener(getSeqPanel(), null);
1621 ssm.removeSelectionListener(getSeqPanel());
1622 ssm.removeCommandListener(av);
1623 ssm.removeStructureViewerListener(getSeqPanel(), null);
1624 ssm.removeSelectionListener(getSeqPanel());
1630 if (Cache.log.isDebugEnabled())
1632 Cache.log.warn("Closing alignment panel which is already closed.");
1638 * hides or shows dynamic annotation rows based on groups and av state flags
1640 public void updateAnnotation()
1642 updateAnnotation(false, false);
1645 public void updateAnnotation(boolean applyGlobalSettings)
1647 updateAnnotation(applyGlobalSettings, false);
1650 public void updateAnnotation(boolean applyGlobalSettings,
1651 boolean preserveNewGroupSettings)
1653 av.updateGroupAnnotationSettings(applyGlobalSettings,
1654 preserveNewGroupSettings);
1655 adjustAnnotationHeight();
1659 public AlignmentI getAlignment()
1661 return av == null ? null : av.getAlignment();
1665 public String getViewName()
1671 * Make/Unmake this alignment panel the current input focus
1675 public void setSelected(boolean b)
1679 if (alignFrame.getSplitViewContainer() != null)
1682 * bring enclosing SplitFrame to front first if there is one
1684 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1686 alignFrame.setSelected(b);
1687 } catch (Exception ex)
1693 alignFrame.setDisplayedView(this);
1698 public StructureSelectionManager getStructureSelectionManager()
1700 return av.getStructureSelectionManager();
1704 public void raiseOOMWarning(String string, OutOfMemoryError error)
1706 new OOMWarning(string, error, this);
1710 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1713 return new FeatureRenderer(this);
1717 public jalview.api.FeatureRenderer getFeatureRenderer()
1719 return seqPanel.seqCanvas.getFeatureRenderer();
1722 public void updateFeatureRenderer(
1723 jalview.renderer.seqfeatures.FeatureRenderer fr)
1725 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1728 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1730 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1732 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1736 public ScalePanel getScalePanel()
1741 public void setScalePanel(ScalePanel scalePanel)
1743 this.scalePanel = scalePanel;
1746 public SeqPanel getSeqPanel()
1751 public void setSeqPanel(SeqPanel seqPanel)
1753 this.seqPanel = seqPanel;
1756 public AnnotationPanel getAnnotationPanel()
1758 return annotationPanel;
1761 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1763 this.annotationPanel = annotationPanel;
1766 public AnnotationLabels getAlabels()
1771 public void setAlabels(AnnotationLabels alabels)
1773 this.alabels = alabels;
1776 public IdPanel getIdPanel()
1781 public void setIdPanel(IdPanel idPanel)
1783 this.idPanel = idPanel;
1787 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1788 * The aim is to keep the two alignments 'lined up' on their centre columns.
1791 * holds mapped region(s) of this alignment that we are scrolling
1792 * 'to'; may be modified for sequence offset by this method
1793 * @param verticalOffset
1794 * the number of visible sequences to show above the mapped region
1796 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1799 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1800 * mapped), we can make the scroll-to location a sequence above the one
1803 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1804 List<SequenceI> seqs = av.getAlignment().getSequences();
1807 * This is like AlignmentI.findIndex(seq) but here we are matching the
1808 * dataset sequence not the aligned sequence
1810 boolean matched = false;
1811 for (SequenceI seq : seqs)
1813 if (mappedTo == seq.getDatasetSequence())
1821 return; // failsafe, shouldn't happen
1825 * Scroll to position but centring the target residue.
1827 scrollToPosition(sr, verticalOffset, true, true);
1831 * Set a flag to say do not scroll any (cDNA/protein) complement.
1835 protected void setDontScrollComplement(boolean b)
1837 this.dontScrollComplement = b;
1840 protected boolean isDontScrollComplement()
1842 return this.dontScrollComplement;
1848 * @adjustHeight if true, try to recalculate panel height for visible
1851 protected void refresh(boolean adjustHeight)
1853 validateAnnotationDimensions(adjustHeight);
1857 // sort, repaint, update overview
1858 paintAlignment(true);
1862 // lightweight repaint
1869 * Property change event fired when a change is made to the viewport ranges
1870 * object associated with this alignment panel's viewport
1872 public void propertyChange(PropertyChangeEvent evt)
1874 // update this panel's scroll values based on the new viewport ranges values
1875 int x = vpRanges.getStartRes();
1876 int y = vpRanges.getStartSeq();
1877 setScrollValues(x, y);
1879 // now update any complementary alignment (its viewport ranges object
1880 // is different so does not get automatically updated)
1881 if (!isDontScrollComplement())
1883 setDontScrollComplement(true);
1884 av.scrollComplementaryAlignment();
1885 setDontScrollComplement(false);