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.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.jbgui.GAlignmentPanel;
34 import jalview.math.AlignmentDimension;
35 import jalview.schemes.ResidueProperties;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.Comparison;
38 import jalview.util.MessageManager;
39 import jalview.util.Platform;
40 import jalview.viewmodel.ViewportListenerI;
41 import jalview.viewmodel.ViewportRanges;
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Container;
46 import java.awt.Dimension;
48 import java.awt.FontMetrics;
49 import java.awt.Graphics;
50 import java.awt.Insets;
51 import java.awt.event.AdjustmentEvent;
52 import java.awt.event.AdjustmentListener;
53 import java.awt.event.ComponentAdapter;
54 import java.awt.event.ComponentEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.Printable;
57 import java.awt.print.PrinterException;
58 import java.beans.PropertyChangeEvent;
59 import java.beans.PropertyChangeListener;
61 import java.io.FileWriter;
62 import java.io.PrintWriter;
63 import java.util.List;
65 import javax.swing.SwingUtilities;
71 * @version $Revision: 1.161 $
73 public class AlignmentPanel extends GAlignmentPanel implements
74 AdjustmentListener, Printable, AlignmentViewPanel,
77 public AlignViewport av;
79 ViewportRanges vpRanges;
81 OverviewPanel overviewPanel;
83 private SeqPanel seqPanel;
85 private IdPanel idPanel;
87 private boolean headless;
89 IdwidthAdjuster idwidthAdjuster;
92 public AlignFrame alignFrame;
94 private ScalePanel scalePanel;
96 private AnnotationPanel annotationPanel;
98 private AnnotationLabels alabels;
100 // this value is set false when selection area being dragged
101 boolean fastPaint = true;
103 private int hextent = 0;
105 private int vextent = 0;
108 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
109 * false, suppresses invoking the same method recursively.
111 private boolean scrollComplementaryPanel = true;
113 private PropertyChangeListener propertyChangeListener;
115 private CalculationChooser calculationDialog;
118 * Creates a new AlignmentPanel object.
123 public AlignmentPanel(AlignFrame af, final AlignViewport av)
127 vpRanges = av.getRanges();
128 setSeqPanel(new SeqPanel(av, this));
129 setIdPanel(new IdPanel(av, this));
131 setScalePanel(new ScalePanel(av, this));
133 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
134 idwidthAdjuster = new IdwidthAdjuster(this);
135 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137 setAnnotationPanel(new AnnotationPanel(this));
138 setAlabels(new AnnotationLabels(this));
140 annotationScroller.setViewportView(getAnnotationPanel());
141 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
144 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146 setScrollValues(0, 0);
148 hscroll.addAdjustmentListener(this);
149 vscroll.addAdjustmentListener(this);
151 addComponentListener(new ComponentAdapter()
154 public void componentResized(ComponentEvent evt)
156 // reset the viewport ranges when the alignment panel is resized
157 // in particular, this initialises the end residue value when Jalview
159 if (av.getWrapAlignment())
161 int widthInRes = getSeqPanel().seqCanvas
162 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
163 vpRanges.setViewportWidth(widthInRes);
167 int widthInRes = getSeqPanel().seqCanvas.getWidth()
169 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
170 / av.getCharHeight();
172 vpRanges.setViewportWidth(widthInRes);
173 vpRanges.setViewportHeight(heightInSeq);
179 final AlignmentPanel ap = this;
180 propertyChangeListener = new PropertyChangeListener()
183 public void propertyChange(PropertyChangeEvent evt)
185 if (evt.getPropertyName().equals("alignment"))
187 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
192 av.addPropertyChangeListener(propertyChangeListener);
194 av.getRanges().addPropertyChangeListener(this);
196 adjustAnnotationHeight();
201 public AlignViewportI getAlignViewport()
206 public void alignmentChanged()
208 av.alignmentChanged(this);
210 if (getCalculationDialog() != null)
212 getCalculationDialog().validateCalcTypes();
215 alignFrame.updateEditMenuBar();
217 paintAlignment(true);
224 public void fontChanged()
226 // set idCanvas bufferedImage to null
227 // to prevent drawing old image
228 FontMetrics fm = getFontMetrics(av.getFont());
230 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
232 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
233 .getCharHeight() + fm.getDescent()));
235 getIdPanel().getIdCanvas().gg = null;
236 getSeqPanel().seqCanvas.img = null;
237 getAnnotationPanel().adjustPanelHeight();
239 Dimension d = calculateIdWidth();
241 d.setSize(d.width + 4, d.height);
242 getIdPanel().getIdCanvas().setPreferredSize(d);
243 hscrollFillerPanel.setPreferredSize(d);
245 if (this.alignFrame.getSplitViewContainer() != null)
247 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
254 * Calculate the width of the alignment labels based on the displayed names
255 * and any bounds on label width set in preferences.
257 * @return Dimension giving the maximum width of the alignment label panel
258 * that should be used.
260 public Dimension calculateIdWidth()
262 // calculate sensible default width when no preference is available
264 if (av.getIdWidth() < 0)
266 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
267 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
268 r = calculateIdWidth(maxwidth);
269 av.setIdWidth(r.width);
274 r.width = av.getIdWidth();
281 * Calculate the width of the alignment labels based on the displayed names
282 * and any bounds on label width set in preferences.
285 * -1 or maximum width allowed for IdWidth
286 * @return Dimension giving the maximum width of the alignment label panel
287 * that should be used.
289 public Dimension calculateIdWidth(int maxwidth)
291 Container c = new Container();
293 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
294 Font.ITALIC, av.font.getSize()));
296 AlignmentI al = av.getAlignment();
301 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
303 SequenceI s = al.getSequenceAt(i);
305 id = s.getDisplayId(av.getShowJVSuffix());
307 if (fm.stringWidth(id) > idWidth)
309 idWidth = fm.stringWidth(id);
315 // Also check annotation label widths
318 if (al.getAlignmentAnnotation() != null)
320 fm = c.getFontMetrics(getAlabels().getFont());
322 while (i < al.getAlignmentAnnotation().length)
324 String label = al.getAlignmentAnnotation()[i].label;
326 if (fm.stringWidth(label) > idWidth)
328 idWidth = fm.stringWidth(label);
335 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
340 * Highlight the given results on the alignment.
343 public void highlightSearchResults(SearchResultsI results)
345 scrollToPosition(results);
346 getSeqPanel().seqCanvas.highlightSearchResults(results);
350 * Scroll the view to show the position of the highlighted region in results
351 * (if any) and redraw the overview
355 public boolean scrollToPosition(SearchResultsI results)
357 return scrollToPosition(results, 0, true, false);
361 * Scroll the view to show the position of the highlighted region in results
364 * @param searchResults
365 * @param redrawOverview
368 public boolean scrollToPosition(SearchResultsI searchResults,
369 boolean redrawOverview)
371 return scrollToPosition(searchResults, 0, redrawOverview, false);
375 * Scroll the view to show the position of the highlighted region in results
379 * @param verticalOffset
380 * if greater than zero, allows scrolling to a position below the
381 * first displayed sequence
382 * @param redrawOverview
383 * - when set, the overview will be recalculated (takes longer)
385 * if true, try to centre the search results horizontally in the view
386 * @return false if results were not found
388 public boolean scrollToPosition(SearchResultsI results,
389 int verticalOffset, boolean redrawOverview, boolean centre)
391 int startv, endv, starts, ends;
392 // TODO: properly locate search results in view when large numbers of hidden
393 // columns exist before highlighted region
394 // do we need to scroll the panel?
395 // TODO: tons of nullpointerexceptions raised here.
396 if (results != null && results.getSize() > 0 && av != null
397 && av.getAlignment() != null)
399 int seqIndex = av.getAlignment().findIndex(results);
404 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
406 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
415 * To centre results, scroll to positions half the visible width
416 * left/right of the start/end positions
420 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2
422 start = Math.max(start - offset, 0);
423 end = end + offset - 1;
429 if (end == seq.getEnd())
433 if (av.hasHiddenColumns())
435 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
436 start = hidden.findColumnPosition(start);
437 end = hidden.findColumnPosition(end);
440 if (!hidden.isVisible(r[0]))
442 // don't scroll - position isn't visible
449 * allow for offset of target sequence (actually scroll to one above it)
451 seqIndex = Math.max(0, seqIndex - verticalOffset);
453 if (!av.getWrapAlignment())
455 if ((startv = vpRanges.getStartRes()) >= start)
458 * Scroll left to make start of search results visible
460 setScrollValues(start, seqIndex);
462 else if ((endv = vpRanges.getEndRes()) <= end)
465 * Scroll right to make end of search results visible
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);
494 paintAlignment(redrawOverview);
501 * @return DOCUMENT ME!
503 public OverviewPanel getOverviewPanel()
505 return overviewPanel;
514 public void setOverviewPanel(OverviewPanel op)
522 * Hide or show annotation panel
525 public void setAnnotationVisible(boolean b)
527 if (!av.getWrapAlignment())
529 annotationSpaceFillerHolder.setVisible(b);
530 annotationScroller.setVisible(b);
536 * automatically adjust annotation panel height for new annotation whilst
537 * ensuring the alignment is still visible.
540 public void adjustAnnotationHeight()
542 // TODO: display vertical annotation scrollbar if necessary
543 // this is called after loading new annotation onto alignment
544 if (alignFrame.getHeight() == 0)
546 System.out.println("NEEDS FIXING");
548 validateAnnotationDimensions(true);
550 paintAlignment(true);
554 * calculate the annotation dimensions and refresh slider values accordingly.
555 * need to do repaints/notifys afterwards.
557 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
559 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
561 if (adjustPanelHeight)
563 int rowHeight = av.getCharHeight();
564 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
567 * Estimate available height in the AlignFrame for alignment +
568 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
569 * hscroll, status bar (as these are not laid out we can't inspect their
570 * actual heights). Insets gives frame borders.
572 int stuff = Platform.isAMac() ? 80 : 100;
573 Insets insets = alignFrame.getInsets();
574 int availableHeight = alignFrame.getHeight() - stuff - insets.top
578 * If not enough vertical space, maximize annotation height while keeping
579 * at least two rows of alignment visible
581 if (annotationHeight + alignmentHeight > availableHeight)
583 annotationHeight = Math.min(annotationHeight, availableHeight - 2
589 // maintain same window layout whilst updating sliders
590 annotationHeight = annotationScroller.getSize().height;
594 annotationScroller.setPreferredSize(new Dimension(annotationScroller
595 .getWidth(), annotationHeight));
597 Dimension e = idPanel.getSize();
598 alabels.setSize(new Dimension(e.width, annotationHeight));
600 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
601 annotationSpaceFillerHolder.getWidth(), annotationHeight));
602 annotationScroller.validate();
603 annotationScroller.addNotify();
607 * update alignment layout for viewport settings
612 public void updateLayout()
615 setAnnotationVisible(av.isShowAnnotation());
616 boolean wrap = av.getWrapAlignment();
617 vpRanges.setStartSeq(0);
618 scalePanelHolder.setVisible(!wrap);
619 hscroll.setVisible(!wrap);
620 idwidthAdjuster.setVisible(!wrap);
624 annotationScroller.setVisible(false);
625 annotationSpaceFillerHolder.setVisible(false);
627 else if (av.isShowAnnotation())
629 annotationScroller.setVisible(true);
630 annotationSpaceFillerHolder.setVisible(true);
635 int widthInRes = getSeqPanel().seqCanvas
636 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
637 vpRanges.setViewportWidth(widthInRes);
641 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
642 .getCharWidth()) - 1;
643 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
644 .getCharHeight()) - 1;
646 vpRanges.setViewportWidth(widthInRes);
647 vpRanges.setViewportHeight(heightInSeq);
650 idSpaceFillerPanel1.setVisible(!wrap);
657 * Adjust row/column scrollers to show a visible position in the alignment.
660 * visible column to scroll to
662 * visible row to scroll to
665 public void setScrollValues(int xpos, int ypos)
670 if (av == null || av.getAlignment() == null)
675 if (av.getWrapAlignment())
677 setScrollingForWrappedPanel(x);
681 int width = av.getAlignment().getWidth();
682 int height = av.getAlignment().getHeight();
684 if (av.hasHiddenColumns())
686 // reset the width to exclude hidden columns
687 width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
690 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
691 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
698 if (vextent > height)
703 if ((hextent + x) > width)
708 if ((vextent + y) > height)
710 y = height - vextent;
723 // update the scroll values
724 hscroll.setValues(x, hextent, 0, width);
725 vscroll.setValues(y, vextent, 0, height);
730 * Respond to adjustment event when horizontal or vertical scrollbar is
734 * adjustment event encoding whether hscroll or vscroll changed
737 public void adjustmentValueChanged(AdjustmentEvent evt)
739 int oldX = vpRanges.getStartRes();
740 int oldwidth = vpRanges.getViewportWidth();
741 int oldY = vpRanges.getStartSeq();
742 int oldheight = vpRanges.getViewportHeight();
744 if (av.getWrapAlignment())
746 if (evt.getSource() == hscroll)
748 return; // no horizontal scroll when wrapped
750 else if (evt.getSource() == vscroll)
752 int offy = vscroll.getValue();
753 int rowSize = getSeqPanel().seqCanvas
754 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
756 // if we're scrolling to the position we're already at, stop
757 // this prevents infinite recursion of events when the scroll/viewport
758 // ranges values are the same
759 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
765 vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
770 // This is only called if file loaded is a jar file that
771 // was wrapped when saved and user has wrap alignment true
772 // as preference setting
773 SwingUtilities.invokeLater(new Runnable()
778 // When updating scrolling to use ViewportChange events, this code
779 // could not be validated and it is not clear if it is now being
780 // called. Log warning here in case it is called and unforeseen
783 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
785 // scroll to start of panel
786 vpRanges.setStartRes(0);
787 vpRanges.setStartSeq(0);
796 if (evt.getSource() == hscroll)
798 int x = hscroll.getValue();
799 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
801 // if we're scrolling to the position we're already at, stop
802 // this prevents infinite recursion of events when the scroll/viewport
803 // ranges values are the same
804 if ((x == oldX) && (width == oldwidth))
808 vpRanges.setViewportStartAndWidth(x, width);
810 else if (evt.getSource() == vscroll)
812 int y = vscroll.getValue();
813 int height = getSeqPanel().seqCanvas.getHeight()
814 / av.getCharHeight();
816 // if we're scrolling to the position we're already at, stop
817 // this prevents infinite recursion of events when the scroll/viewport
818 // ranges values are the same
819 if ((y == oldY) && (height == oldheight))
823 vpRanges.setViewportStartAndHeight(y, height);
833 * Repaint the alignment including the annotations and overview panels (if
837 public void paintAlignment(boolean updateOverview)
839 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
840 av.isShowAutocalculatedAbove());
841 sorter.sort(getAlignment().getAlignmentAnnotation(),
842 av.getSortAnnotationsBy());
847 // TODO: determine if this paintAlignment changed structure colours
848 av.getStructureSelectionManager().sequenceColoursChanged(this);
850 if (overviewPanel != null)
852 overviewPanel.updateOverviewImage();
864 public void paintComponent(Graphics g)
868 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
869 idPanelHolder.setPreferredSize(d);
870 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
874 * set scroll bar positions
876 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
880 * Set vertical scroll bar parameters for wrapped panel
882 * the residue to scroll to
884 private void setScrollingForWrappedPanel(int res)
886 // get the width of the alignment in residues
887 int maxwidth = av.getAlignment().getWidth();
888 if (av.hasHiddenColumns())
890 maxwidth = av.getAlignment().getHiddenColumns()
891 .findColumnPosition(maxwidth) - 1;
894 // get the width of the canvas in residues
895 int canvasWidth = getSeqPanel().seqCanvas
896 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
899 // position we want to scroll to is number of canvasWidth's to get there
900 int current = res / canvasWidth;
902 // max scroll position: add one because extent is 1 and scrollbar value
903 // can only be set to at most max - extent
904 int max = maxwidth / canvasWidth + 1;
905 vscroll.setUnitIncrement(1);
906 vscroll.setValues(current, 1, 0, max);
920 * @return DOCUMENT ME!
922 * @throws PrinterException
926 public int print(Graphics pg, PageFormat pf, int pi)
927 throws PrinterException
929 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
931 int pwidth = (int) pf.getImageableWidth();
932 int pheight = (int) pf.getImageableHeight();
934 if (av.getWrapAlignment())
936 return printWrappedAlignment(pwidth, pheight, pi, pg);
940 return printUnwrapped(pwidth, pheight, pi, pg, pg);
956 * @return DOCUMENT ME!
958 * @throws PrinterException
962 * Draws the alignment image, including sequence ids, sequences, and
963 * annotation labels and annotations if shown, on either one or two Graphics
970 * the graphics context for sequence ids and annotation labels
971 * @param alignmentGraphics
972 * the graphics context for sequences and annotations (may or may not
973 * be the same context as idGraphics)
975 * @throws PrinterException
977 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
978 Graphics idGraphics, Graphics alignmentGraphics)
979 throws PrinterException
981 final int idWidth = getVisibleIdWidth(false);
984 * Get the horizontal offset to where we draw the sequences.
985 * This is idWidth if using a single Graphics context, else zero.
987 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
989 FontMetrics fm = getFontMetrics(av.getFont());
990 int charHeight = av.getCharHeight();
991 int scaleHeight = charHeight + fm.getDescent();
993 idGraphics.setColor(Color.white);
994 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
995 idGraphics.setFont(av.getFont());
998 * How many sequences and residues can we fit on a printable page?
1000 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1002 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1004 int alignmentWidth = av.getAlignment().getWidth();
1005 int pagesWide = (alignmentWidth / totalRes) + 1;
1007 final int startRes = (pi % pagesWide) * totalRes;
1008 int endRes = (startRes + totalRes) - 1;
1010 if (endRes > (alignmentWidth - 1))
1012 endRes = alignmentWidth - 1;
1015 final int startSeq = (pi / pagesWide) * totalSeq;
1016 int endSeq = startSeq + totalSeq;
1018 int alignmentHeight = av.getAlignment().getHeight();
1019 if (endSeq > alignmentHeight)
1021 endSeq = alignmentHeight;
1024 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1027 if (av.isShowAnnotation())
1029 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1032 pagesHigh /= pageHeight;
1034 if (pi >= (pagesWide * pagesHigh))
1036 return Printable.NO_SUCH_PAGE;
1038 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1042 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1044 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1045 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1046 pageWidth - idWidth, scaleHeight);
1047 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1050 * Draw the sequence ids, offset for scale height,
1051 * then reset to top left (0, 0)
1053 idGraphics.translate(0, scaleHeight);
1054 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1055 Color currentColor = null;
1056 Color currentTextColor = null;
1059 for (int i = startSeq; i < endSeq; i++)
1061 seq = av.getAlignment().getSequenceAt(i);
1062 if ((av.getSelectionGroup() != null)
1063 && av.getSelectionGroup().getSequences(null).contains(seq))
1066 * gray out ids of sequences in selection group (if any)
1068 currentColor = Color.gray;
1069 currentTextColor = Color.black;
1073 currentColor = av.getSequenceColour(seq);
1074 currentTextColor = Color.black;
1077 idGraphics.setColor(currentColor);
1078 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1081 idGraphics.setColor(currentTextColor);
1084 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1085 if (av.isRightAlignIds())
1087 fm = idGraphics.getFontMetrics();
1089 - fm.stringWidth(displayId)
1093 idGraphics.drawString(displayId, xPos,
1094 (((i - startSeq) * charHeight) + charHeight)
1095 - (charHeight / 5));
1097 idGraphics.setFont(av.getFont());
1098 idGraphics.translate(0, -scaleHeight);
1101 * draw the sequences, offset for scale height, and id width (if using a
1102 * single graphics context), then reset to (0, scale height)
1104 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1105 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1106 startSeq, endSeq, 0);
1107 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1109 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1112 * draw annotation labels; drawComponent() translates by
1113 * getScrollOffset(), so compensate for that first;
1114 * then reset to (0, scale height)
1116 int offset = getAlabels().getScrollOffset();
1117 idGraphics.translate(0, -offset);
1118 idGraphics.translate(0, alignmentDrawnHeight);
1119 getAlabels().drawComponent(idGraphics, idWidth);
1120 idGraphics.translate(0, -alignmentDrawnHeight);
1123 * draw the annotations starting at
1124 * (idOffset, alignmentHeight) from (0, scaleHeight)
1126 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1127 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1128 alignmentGraphics, -1, startRes, endRes + 1);
1131 return Printable.PAGE_EXISTS;
1146 * @return DOCUMENT ME!
1148 * @throws PrinterException
1151 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1152 Graphics pg) throws PrinterException
1154 int annotationHeight = 0;
1155 AnnotationLabels labels = null;
1156 if (av.isShowAnnotation())
1158 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1159 labels = new AnnotationLabels(av);
1162 int hgap = av.getCharHeight();
1163 if (av.getScaleAboveWrapped())
1165 hgap += av.getCharHeight();
1168 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1171 int idWidth = getVisibleIdWidth(false);
1173 int maxwidth = av.getAlignment().getWidth();
1174 if (av.hasHiddenColumns())
1176 maxwidth = av.getAlignment().getHiddenColumns()
1177 .findColumnPosition(maxwidth) - 1;
1180 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1183 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1185 pg.setColor(Color.white);
1186 pg.fillRect(0, 0, pwidth, pheight);
1187 pg.setFont(av.getFont());
1191 pg.setColor(Color.black);
1193 pg.translate(0, -pi * pheight);
1195 pg.setClip(0, pi * pheight, pwidth, pheight);
1201 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1203 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1204 SequenceI s = av.getAlignment().getSequenceAt(i);
1205 String string = s.getDisplayId(av.getShowJVSuffix());
1207 if (av.isRightAlignIds())
1209 FontMetrics fm = pg.getFontMetrics();
1210 xPos = idWidth - fm.stringWidth(string) - 4;
1212 pg.drawString(string, xPos,
1213 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1214 - (av.getCharHeight() / 5));
1219 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1221 pg.setFont(av.getFont());
1222 labels.drawComponent(pg, idWidth);
1226 - (av.getAlignment().getHeight() * av
1231 } while (ypos < totalHeight);
1233 pg.translate(idWidth, 0);
1235 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1238 if ((pi * pheight) < totalHeight)
1240 return Printable.PAGE_EXISTS;
1245 return Printable.NO_SUCH_PAGE;
1250 * get current sequence ID panel width, or nominal value if panel were to be
1251 * displayed using default settings
1255 public int getVisibleIdWidth()
1257 return getVisibleIdWidth(true);
1261 * get current sequence ID panel width, or nominal value if panel were to be
1262 * displayed using default settings
1265 * indicate if the Id width for onscreen or offscreen display should
1269 public int getVisibleIdWidth(boolean onscreen)
1271 // see if rendering offscreen - check preferences and calc width accordingly
1272 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1274 return calculateIdWidth(-1).width + 4;
1276 Integer idwidth = null;
1278 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1280 int w = getIdPanel().getWidth();
1281 return (w > 0 ? w : calculateIdWidth().width + 4);
1283 return idwidth.intValue() + 4;
1286 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1288 int boarderBottomOffset = 5;
1289 long pSessionId = System.currentTimeMillis();
1290 headless = (System.getProperty("java.awt.headless") != null && System
1291 .getProperty("java.awt.headless").equals("true"));
1292 if (alignFrame != null && !headless)
1296 alignFrame.setProgressBar(MessageManager.formatMessage(
1297 "status.saving_file", new Object[] { type.getLabel() }),
1303 AlignmentDimension aDimension = getAlignmentDimension();
1306 jalview.util.ImageMaker im;
1307 final String imageAction, imageTitle;
1308 if (type == jalview.util.ImageMaker.TYPE.PNG)
1310 imageAction = "Create PNG image from alignment";
1313 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1315 imageAction = "Create EPS file from alignment";
1316 imageTitle = alignFrame.getTitle();
1320 imageAction = "Create SVG file from alignment";
1321 imageTitle = alignFrame.getTitle();
1324 im = new jalview.util.ImageMaker(this, type, imageAction,
1325 aDimension.getWidth(), aDimension.getHeight()
1326 + boarderBottomOffset, file, imageTitle,
1327 alignFrame, pSessionId, headless);
1328 Graphics graphics = im.getGraphics();
1329 if (av.getWrapAlignment())
1331 if (graphics != null)
1333 printWrappedAlignment(aDimension.getWidth(),
1334 aDimension.getHeight() + boarderBottomOffset, 0,
1341 if (graphics != null)
1343 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1344 0, graphics, graphics);
1349 } catch (OutOfMemoryError err)
1352 System.out.println("########################\n" + "OUT OF MEMORY "
1353 + file + "\n" + "########################");
1354 new OOMWarning("Creating Image for " + file, err);
1355 // System.out.println("Create IMAGE: " + err);
1356 } catch (Exception ex)
1358 ex.printStackTrace();
1366 public AlignmentDimension getAlignmentDimension()
1368 int maxwidth = av.getAlignment().getWidth();
1369 if (av.hasHiddenColumns())
1371 maxwidth = av.getAlignment().getHiddenColumns()
1372 .findColumnPosition(maxwidth);
1375 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1376 + getScalePanel().getHeight();
1377 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1379 if (av.getWrapAlignment())
1381 height = getWrappedHeight();
1384 // need to obtain default alignment width and then add in any
1385 // additional allowance for id margin
1386 // this duplicates the calculation in getWrappedHeight but adjusts for
1388 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1389 - alignFrame.getInsets().left
1390 - alignFrame.getInsets().right - getVisibleIdWidth()
1391 + getVisibleIdWidth(false);
1395 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1399 else if (av.isShowAnnotation())
1401 height += getAnnotationPanel().adjustPanelHeight() + 3;
1403 return new AlignmentDimension(width, height);
1410 public void makeEPS(File epsFile)
1412 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1418 public void makePNG(File pngFile)
1420 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1423 public void makeSVG(File svgFile)
1425 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1428 public void makePNGImageMap(File imgMapFile, String imageName)
1430 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1431 // ////////////////////////////////////////////
1432 int idWidth = getVisibleIdWidth(false);
1433 FontMetrics fm = getFontMetrics(av.getFont());
1434 int scaleHeight = av.getCharHeight() + fm.getDescent();
1437 // ////////////////////////////////
1438 if (imgMapFile != null)
1442 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1443 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1444 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1445 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1446 out.println("<img src=\"" + imageName
1447 + "\" border=\"0\" usemap=\"#Map\" >"
1448 + "<map name=\"Map\">");
1450 for (s = 0; s < sSize; s++)
1452 sy = s * av.getCharHeight() + scaleHeight;
1454 SequenceI seq = av.getAlignment().getSequenceAt(s);
1455 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1456 for (res = 0; res < alwidth; res++)
1458 StringBuilder text = new StringBuilder(512);
1459 String triplet = null;
1460 if (av.getAlignment().isNucleotide())
1462 triplet = ResidueProperties.nucleotideName.get(seq
1463 .getCharAt(res) + "");
1467 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1471 if (triplet == null)
1476 int seqPos = seq.findPosition(res);
1477 gSize = groups.length;
1478 for (g = 0; g < gSize; g++)
1480 if (text.length() < 1)
1482 text.append("<area shape=\"rect\" coords=\"")
1483 .append((idWidth + res * av.getCharWidth()))
1484 .append(",").append(sy).append(",")
1485 .append((idWidth + (res + 1) * av.getCharWidth()))
1486 .append(",").append((av.getCharHeight() + sy))
1487 .append("\"").append(" onMouseOver=\"toolTip('")
1488 .append(seqPos).append(" ").append(triplet);
1491 if (groups[g].getStartRes() < res
1492 && groups[g].getEndRes() > res)
1494 text.append("<br><em>").append(groups[g].getName())
1499 if (text.length() < 1)
1501 text.append("<area shape=\"rect\" coords=\"")
1502 .append((idWidth + res * av.getCharWidth()))
1503 .append(",").append(sy).append(",")
1504 .append((idWidth + (res + 1) * av.getCharWidth()))
1505 .append(",").append((av.getCharHeight() + sy))
1506 .append("\"").append(" onMouseOver=\"toolTip('")
1507 .append(seqPos).append(" ").append(triplet);
1509 if (!Comparison.isGap(seq.getCharAt(res)))
1511 List<SequenceFeature> features = seq.findFeatures(seqPos,
1513 for (SequenceFeature sf : features)
1515 if (sf.isContactFeature())
1517 text.append("<br>").append(sf.getType()).append(" ")
1518 .append(sf.getBegin()).append(":")
1519 .append(sf.getEnd());
1523 text.append("<br>");
1524 text.append(sf.getType());
1525 String description = sf.getDescription();
1526 if (description != null
1527 && !sf.getType().equals(description))
1529 description = description.replace("\"", """);
1530 text.append(" ").append(description);
1533 String status = sf.getStatus();
1534 if (status != null && !"".equals(status))
1536 text.append(" (").append(status).append(")");
1539 if (text.length() > 1)
1541 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1542 out.println(text.toString());
1547 out.println("</map></body></html>");
1550 } catch (Exception ex)
1552 ex.printStackTrace();
1554 } // /////////END OF IMAGE MAP
1558 int getWrappedHeight()
1560 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1562 if (System.getProperty("java.awt.headless") != null
1563 && System.getProperty("java.awt.headless").equals("true"))
1565 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1566 - vscroll.getPreferredSize().width
1567 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1570 int chunkWidth = getSeqPanel().seqCanvas
1571 .getWrappedCanvasWidth(seqPanelWidth);
1573 int hgap = av.getCharHeight();
1574 if (av.getScaleAboveWrapped())
1576 hgap += av.getCharHeight();
1579 int annotationHeight = 0;
1580 if (av.isShowAnnotation())
1582 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1585 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1588 int maxwidth = av.getAlignment().getWidth();
1589 if (av.hasHiddenColumns())
1591 maxwidth = av.getAlignment().getHiddenColumns()
1592 .findColumnPosition(maxwidth) - 1;
1595 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1601 * close the panel - deregisters all listeners and nulls any references to
1604 public void closePanel()
1606 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1607 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1608 PaintRefresher.RemoveComponent(this);
1613 * try to ensure references are nulled
1615 if (annotationPanel != null)
1617 annotationPanel.dispose();
1622 av.removePropertyChangeListener(propertyChangeListener);
1623 jalview.structure.StructureSelectionManager ssm = av
1624 .getStructureSelectionManager();
1625 ssm.removeStructureViewerListener(getSeqPanel(), null);
1626 ssm.removeSelectionListener(getSeqPanel());
1627 ssm.removeCommandListener(av);
1628 ssm.removeStructureViewerListener(getSeqPanel(), null);
1629 ssm.removeSelectionListener(getSeqPanel());
1635 if (Cache.log.isDebugEnabled())
1637 Cache.log.warn("Closing alignment panel which is already closed.");
1643 * Close any open dialogs that would be orphaned when this one is closed
1645 protected void closeChildFrames()
1647 if (calculationDialog != null)
1649 calculationDialog.closeFrame();
1654 * hides or shows dynamic annotation rows based on groups and av state flags
1656 public void updateAnnotation()
1658 updateAnnotation(false, false);
1661 public void updateAnnotation(boolean applyGlobalSettings)
1663 updateAnnotation(applyGlobalSettings, false);
1666 public void updateAnnotation(boolean applyGlobalSettings,
1667 boolean preserveNewGroupSettings)
1669 av.updateGroupAnnotationSettings(applyGlobalSettings,
1670 preserveNewGroupSettings);
1671 adjustAnnotationHeight();
1675 public AlignmentI getAlignment()
1677 return av == null ? null : av.getAlignment();
1681 public String getViewName()
1687 * Make/Unmake this alignment panel the current input focus
1691 public void setSelected(boolean b)
1695 if (alignFrame.getSplitViewContainer() != null)
1698 * bring enclosing SplitFrame to front first if there is one
1700 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1702 alignFrame.setSelected(b);
1703 } catch (Exception ex)
1709 alignFrame.setDisplayedView(this);
1714 public StructureSelectionManager getStructureSelectionManager()
1716 return av.getStructureSelectionManager();
1720 public void raiseOOMWarning(String string, OutOfMemoryError error)
1722 new OOMWarning(string, error, this);
1726 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1729 return new FeatureRenderer(this);
1733 public jalview.api.FeatureRenderer getFeatureRenderer()
1735 return seqPanel.seqCanvas.getFeatureRenderer();
1738 public void updateFeatureRenderer(
1739 jalview.renderer.seqfeatures.FeatureRenderer fr)
1741 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1744 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1746 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1748 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1752 public ScalePanel getScalePanel()
1757 public void setScalePanel(ScalePanel scalePanel)
1759 this.scalePanel = scalePanel;
1762 public SeqPanel getSeqPanel()
1767 public void setSeqPanel(SeqPanel seqPanel)
1769 this.seqPanel = seqPanel;
1772 public AnnotationPanel getAnnotationPanel()
1774 return annotationPanel;
1777 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1779 this.annotationPanel = annotationPanel;
1782 public AnnotationLabels getAlabels()
1787 public void setAlabels(AnnotationLabels alabels)
1789 this.alabels = alabels;
1792 public IdPanel getIdPanel()
1797 public void setIdPanel(IdPanel idPanel)
1799 this.idPanel = idPanel;
1803 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1804 * The aim is to keep the two alignments 'lined up' on their centre columns.
1807 * holds mapped region(s) of this alignment that we are scrolling
1808 * 'to'; may be modified for sequence offset by this method
1809 * @param verticalOffset
1810 * the number of visible sequences to show above the mapped region
1812 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1815 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1816 * mapped), we can make the scroll-to location a sequence above the one
1819 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1820 List<SequenceI> seqs = av.getAlignment().getSequences();
1823 * This is like AlignmentI.findIndex(seq) but here we are matching the
1824 * dataset sequence not the aligned sequence
1826 boolean matched = false;
1827 for (SequenceI seq : seqs)
1829 if (mappedTo == seq.getDatasetSequence())
1837 return; // failsafe, shouldn't happen
1841 * Scroll to position but centring the target residue.
1843 scrollToPosition(sr, verticalOffset, true, true);
1847 * Set a flag to say do not scroll any (cDNA/protein) complement.
1851 protected void setToScrollComplementPanel(boolean b)
1853 this.scrollComplementaryPanel = b;
1857 * Get whether to scroll complement panel
1859 * @return true if cDNA/protein complement panels should be scrolled
1861 protected boolean isSetToScrollComplementPanel()
1863 return this.scrollComplementaryPanel;
1869 * @adjustHeight if true, try to recalculate panel height for visible
1872 protected void refresh(boolean adjustHeight)
1874 validateAnnotationDimensions(adjustHeight);
1878 // sort, repaint, update overview
1879 paintAlignment(true);
1883 // lightweight repaint
1890 * Property change event fired when a change is made to the viewport ranges
1891 * object associated with this alignment panel's viewport
1893 public void propertyChange(PropertyChangeEvent evt)
1895 // update this panel's scroll values based on the new viewport ranges values
1896 int x = vpRanges.getStartRes();
1897 int y = vpRanges.getStartSeq();
1898 setScrollValues(x, y);
1900 // now update any complementary alignment (its viewport ranges object
1901 // is different so does not get automatically updated)
1902 if (isSetToScrollComplementPanel())
1904 setToScrollComplementPanel(false);
1905 av.scrollComplementaryAlignment();
1906 setToScrollComplementPanel(true);
1911 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1912 * reference should be nulled when the dialog is closed.
1914 * @param calculationChooser
1916 public void setCalculationDialog(CalculationChooser calculationChooser)
1918 calculationDialog = calculationChooser;
1922 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1925 public CalculationChooser getCalculationDialog()
1927 return calculationDialog;