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.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
66 import javax.swing.SwingUtilities;
72 * @version $Revision: 1.161 $
74 public class AlignmentPanel extends GAlignmentPanel implements
75 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
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 private int hextent = 0;
102 private int vextent = 0;
105 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
106 * false, suppresses invoking the same method recursively.
108 private boolean scrollComplementaryPanel = true;
110 private PropertyChangeListener propertyChangeListener;
112 private CalculationChooser calculationDialog;
115 * Creates a new AlignmentPanel object.
120 public AlignmentPanel(AlignFrame af, final AlignViewport av)
124 vpRanges = av.getRanges();
125 setSeqPanel(new SeqPanel(av, this));
126 setIdPanel(new IdPanel(av, this));
128 setScalePanel(new ScalePanel(av, this));
130 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
131 idwidthAdjuster = new IdwidthAdjuster(this);
132 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
134 setAnnotationPanel(new AnnotationPanel(this));
135 setAlabels(new AnnotationLabels(this));
137 annotationScroller.setViewportView(getAnnotationPanel());
138 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
140 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
141 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
143 setScrollValues(0, 0);
145 hscroll.addAdjustmentListener(this);
146 vscroll.addAdjustmentListener(this);
148 addComponentListener(new ComponentAdapter()
151 public void componentResized(ComponentEvent evt)
153 // reset the viewport ranges when the alignment panel is resized
154 // in particular, this initialises the end residue value when Jalview
156 if (av.getWrapAlignment())
158 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
159 getSeqPanel().seqCanvas.getWidth());
160 vpRanges.setViewportWidth(widthInRes);
164 int widthInRes = getSeqPanel().seqCanvas.getWidth()
166 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
167 / av.getCharHeight();
169 vpRanges.setViewportWidth(widthInRes);
170 vpRanges.setViewportHeight(heightInSeq);
176 final AlignmentPanel ap = this;
177 propertyChangeListener = new PropertyChangeListener()
180 public void propertyChange(PropertyChangeEvent evt)
182 if (evt.getPropertyName().equals("alignment"))
184 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
189 av.addPropertyChangeListener(propertyChangeListener);
191 av.getRanges().addPropertyChangeListener(this);
193 adjustAnnotationHeight();
198 public AlignViewportI getAlignViewport()
203 public void alignmentChanged()
205 av.alignmentChanged(this);
207 if (getCalculationDialog() != null)
209 getCalculationDialog().validateCalcTypes();
212 alignFrame.updateEditMenuBar();
214 // no idea if we need to update structure
215 paintAlignment(true, true);
222 public void fontChanged()
224 // set idCanvas bufferedImage to null
225 // to prevent drawing old image
226 FontMetrics fm = getFontMetrics(av.getFont());
228 scalePanelHolder.setPreferredSize(
229 new Dimension(10, av.getCharHeight() + fm.getDescent()));
230 idSpaceFillerPanel1.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idwidthAdjuster.invalidate();
233 scalePanelHolder.invalidate();
234 getIdPanel().getIdCanvas().gg = null;
235 getSeqPanel().seqCanvas.img = null;
236 getAnnotationPanel().adjustPanelHeight();
238 Dimension d = calculateIdWidth();
240 d.setSize(d.width + 4, d.height);
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
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(
288 new Font(av.font.getName(), 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(
330 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
334 * Highlight the given results on the alignment.
337 public void highlightSearchResults(SearchResultsI results)
339 boolean scrolled = scrollToPosition(results, 0, true, false);
341 boolean noFastPaint = scrolled && av.getWrapAlignment();
343 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
347 * Scroll the view to show the position of the highlighted region in results
350 * @param searchResults
351 * @param redrawOverview
354 public boolean scrollToPosition(SearchResultsI searchResults,
355 boolean redrawOverview)
357 return scrollToPosition(searchResults, 0, redrawOverview, false);
361 * Scrolls the view (if necessary) to show the position of the first
362 * highlighted region in results (if any). Answers true if the view was
363 * scrolled, or false if no matched region was found, or it is already
367 * @param verticalOffset
368 * if greater than zero, allows scrolling to a position below the
369 * first displayed sequence
370 * @param redrawOverview
371 * - when set, the overview will be recalculated (takes longer)
373 * if true, try to centre the search results horizontally in the view
376 protected boolean scrollToPosition(SearchResultsI results,
377 int verticalOffset, boolean redrawOverview, boolean centre)
379 int startv, endv, starts, ends;
381 if (results == null || results.isEmpty() || av == null
382 || av.getAlignment() == null)
386 int seqIndex = av.getAlignment().findIndex(results);
391 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
393 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
402 * To centre results, scroll to positions half the visible width
403 * left/right of the start/end positions
407 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
408 start = Math.max(start - offset, 0);
409 end = end + offset - 1;
415 if (end == seq.getEnd())
420 if (av.hasHiddenColumns())
422 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
423 start = hidden.findColumnPosition(start);
424 end = hidden.findColumnPosition(end);
427 if (!hidden.isVisible(r[0]))
429 // don't scroll - position isn't visible
436 * allow for offset of target sequence (actually scroll to one above it)
438 seqIndex = Math.max(0, seqIndex - verticalOffset);
439 boolean scrollNeeded = true;
441 if (!av.getWrapAlignment())
443 if ((startv = vpRanges.getStartRes()) >= start)
446 * Scroll left to make start of search results visible
448 setScrollValues(start, seqIndex);
450 else if ((endv = vpRanges.getEndRes()) <= end)
453 * Scroll right to make end of search results visible
455 setScrollValues(startv + end - endv, seqIndex);
457 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
460 * Scroll up to make start of search results visible
462 setScrollValues(vpRanges.getStartRes(), seqIndex);
464 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
467 * Scroll down to make end of search results visible
469 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
473 * Else results are already visible - no need to scroll
475 scrollNeeded = false;
479 scrollNeeded = vpRanges.scrollToWrappedVisible(start);
482 paintAlignment(redrawOverview, false);
490 * @return DOCUMENT ME!
492 public OverviewPanel getOverviewPanel()
494 return overviewPanel;
503 public void setOverviewPanel(OverviewPanel op)
511 * Hide or show annotation panel
514 public void setAnnotationVisible(boolean b)
516 if (!av.getWrapAlignment())
518 annotationSpaceFillerHolder.setVisible(b);
519 annotationScroller.setVisible(b);
525 * automatically adjust annotation panel height for new annotation whilst
526 * ensuring the alignment is still visible.
529 public void adjustAnnotationHeight()
531 // TODO: display vertical annotation scrollbar if necessary
532 // this is called after loading new annotation onto alignment
533 if (alignFrame.getHeight() == 0)
535 System.out.println("NEEDS FIXING");
537 validateAnnotationDimensions(true);
539 // TODO: many places call this method and also paintAlignment with various
540 // different settings. this means multiple redraws are triggered...
541 paintAlignment(true, false);
545 * calculate the annotation dimensions and refresh slider values accordingly.
546 * need to do repaints/notifys afterwards.
548 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
550 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
552 if (adjustPanelHeight)
554 int rowHeight = av.getCharHeight();
555 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
558 * Estimate available height in the AlignFrame for alignment +
559 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
560 * hscroll, status bar (as these are not laid out we can't inspect their
561 * actual heights). Insets gives frame borders.
563 int stuff = Platform.isAMac() ? 80 : 100;
564 Insets insets = alignFrame.getInsets();
565 int availableHeight = alignFrame.getHeight() - stuff - insets.top
569 * If not enough vertical space, maximize annotation height while keeping
570 * at least two rows of alignment visible
572 if (annotationHeight + alignmentHeight > availableHeight)
574 annotationHeight = Math.min(annotationHeight,
575 availableHeight - 2 * rowHeight);
580 // maintain same window layout whilst updating sliders
581 annotationHeight = annotationScroller.getSize().height;
585 annotationScroller.setPreferredSize(
586 new Dimension(annotationScroller.getWidth(), annotationHeight));
588 Dimension e = idPanel.getSize();
589 alabels.setSize(new Dimension(e.width, annotationHeight));
591 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
592 annotationSpaceFillerHolder.getWidth(), annotationHeight));
593 annotationScroller.validate();
594 annotationScroller.addNotify();
598 * update alignment layout for viewport settings
603 public void updateLayout()
606 setAnnotationVisible(av.isShowAnnotation());
607 boolean wrap = av.getWrapAlignment();
608 vpRanges.setStartSeq(0);
609 scalePanelHolder.setVisible(!wrap);
610 hscroll.setVisible(!wrap);
611 idwidthAdjuster.setVisible(!wrap);
615 annotationScroller.setVisible(false);
616 annotationSpaceFillerHolder.setVisible(false);
618 else if (av.isShowAnnotation())
620 annotationScroller.setVisible(true);
621 annotationSpaceFillerHolder.setVisible(true);
624 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
626 { // may not yet be laid out
629 int widthInRes = getSeqPanel().seqCanvas
630 .getWrappedCanvasWidth(canvasWidth);
631 vpRanges.setViewportWidth(widthInRes);
635 int widthInRes = (canvasWidth / av.getCharWidth()) - 1;
636 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
637 / av.getCharHeight()) - 1;
639 vpRanges.setViewportWidth(widthInRes);
640 vpRanges.setViewportHeight(heightInSeq);
644 idSpaceFillerPanel1.setVisible(!wrap);
650 * Adjust row/column scrollers to show a visible position in the alignment.
653 * visible column to scroll to
655 * visible row to scroll to
658 public void setScrollValues(int xpos, int ypos)
663 if (av == null || av.getAlignment() == null)
668 if (av.getWrapAlignment())
670 setScrollingForWrappedPanel(x);
674 int width = av.getAlignment().getWidth();
675 int height = av.getAlignment().getHeight();
677 if (av.hasHiddenColumns())
679 // reset the width to exclude hidden columns
680 width = av.getAlignment().getHiddenColumns()
681 .findColumnPosition(width);
684 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
685 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
692 if (vextent > height)
697 if ((hextent + x) > width)
702 if ((vextent + y) > height)
704 y = height - vextent;
717 // update the scroll values
718 hscroll.setValues(x, hextent, 0, width);
719 vscroll.setValues(y, vextent, 0, height);
724 * Respond to adjustment event when horizontal or vertical scrollbar is
728 * adjustment event encoding whether hscroll or vscroll changed
731 public void adjustmentValueChanged(AdjustmentEvent evt)
733 if (av.getWrapAlignment())
735 adjustScrollingWrapped(evt);
739 if (evt.getSource() == hscroll)
741 int oldX = vpRanges.getStartRes();
742 int oldwidth = vpRanges.getViewportWidth();
743 int x = hscroll.getValue();
744 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
746 // if we're scrolling to the position we're already at, stop
747 // this prevents infinite recursion of events when the scroll/viewport
748 // ranges values are the same
749 if ((x == oldX) && (width == oldwidth))
753 vpRanges.setViewportStartAndWidth(x, width);
755 else if (evt.getSource() == vscroll)
757 int oldY = vpRanges.getStartSeq();
758 int oldheight = vpRanges.getViewportHeight();
759 int y = vscroll.getValue();
760 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
762 // if we're scrolling to the position we're already at, stop
763 // this prevents infinite recursion of events when the scroll/viewport
764 // ranges values are the same
765 if ((y == oldY) && (height == oldheight))
769 vpRanges.setViewportStartAndHeight(y, height);
775 * Responds to a scroll change by setting the start position of the viewport.
780 protected void adjustScrollingWrapped(AdjustmentEvent evt)
782 if (evt.getSource() == hscroll)
784 return; // no horizontal scroll when wrapped
786 if (evt.getSource() == vscroll)
788 int newY = vscroll.getValue();
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
795 int oldX = vpRanges.getStartRes();
796 int oldY = vpRanges.getWrappedScrollPosition(oldX);
804 * limit page up/down to one width's worth of positions
806 int rowSize = vpRanges.getViewportWidth();
807 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
808 vpRanges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
813 // This is only called if file loaded is a jar file that
814 // was wrapped when saved and user has wrap alignment true
815 // as preference setting
816 SwingUtilities.invokeLater(new Runnable()
821 // When updating scrolling to use ViewportChange events, this code
822 // could not be validated and it is not clear if it is now being
823 // called. Log warning here in case it is called and unforeseen
826 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
828 // scroll to start of panel
829 vpRanges.setStartRes(0);
830 vpRanges.setStartSeq(0);
838 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
841 public void paintAlignment(boolean updateOverview,
842 boolean updateStructures)
844 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
845 av.isShowAutocalculatedAbove());
846 sorter.sort(getAlignment().getAlignmentAnnotation(),
847 av.getSortAnnotationsBy());
850 if (updateStructures)
852 av.getStructureSelectionManager().sequenceColoursChanged(this);
857 if (overviewPanel != null)
859 overviewPanel.updateOverviewImage();
871 public void paintComponent(Graphics g)
875 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
876 idPanelHolder.setPreferredSize(d);
877 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
881 * set scroll bar positions
883 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
887 * Set vertical scroll bar position, and number of increments, for wrapped
890 * @param topLeftColumn
891 * the column position at top left (0..)
893 private void setScrollingForWrappedPanel(int topLeftColumn)
895 int scrollPosition = vpRanges.getWrappedScrollPosition(topLeftColumn);
896 int maxScroll = vpRanges.getWrappedMaxScroll(topLeftColumn);
899 * a scrollbar's value can be set to at most (maximum-extent)
900 * so we add extent (1) to the maxScroll value
902 vscroll.setUnitIncrement(1);
903 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
916 * @return DOCUMENT ME!
918 * @throws PrinterException
922 public int print(Graphics pg, PageFormat pf, int pi)
923 throws PrinterException
925 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
927 int pwidth = (int) pf.getImageableWidth();
928 int pheight = (int) pf.getImageableHeight();
930 if (av.getWrapAlignment())
932 return printWrappedAlignment(pwidth, pheight, pi, pg);
936 return printUnwrapped(pwidth, pheight, pi, pg, pg);
952 * @return DOCUMENT ME!
954 * @throws PrinterException
958 * Draws the alignment image, including sequence ids, sequences, and
959 * annotation labels and annotations if shown, on either one or two Graphics
966 * the graphics context for sequence ids and annotation labels
967 * @param alignmentGraphics
968 * the graphics context for sequences and annotations (may or may not
969 * be the same context as idGraphics)
971 * @throws PrinterException
973 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
974 Graphics idGraphics, Graphics alignmentGraphics)
975 throws PrinterException
977 final int idWidth = getVisibleIdWidth(false);
980 * Get the horizontal offset to where we draw the sequences.
981 * This is idWidth if using a single Graphics context, else zero.
983 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
986 FontMetrics fm = getFontMetrics(av.getFont());
987 int charHeight = av.getCharHeight();
988 int scaleHeight = charHeight + fm.getDescent();
990 idGraphics.setColor(Color.white);
991 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
992 idGraphics.setFont(av.getFont());
995 * How many sequences and residues can we fit on a printable page?
997 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
999 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1001 int alignmentWidth = av.getAlignment().getWidth();
1002 int pagesWide = (alignmentWidth / totalRes) + 1;
1004 final int startRes = (pi % pagesWide) * totalRes;
1005 int endRes = (startRes + totalRes) - 1;
1007 if (endRes > (alignmentWidth - 1))
1009 endRes = alignmentWidth - 1;
1012 final int startSeq = (pi / pagesWide) * totalSeq;
1013 int endSeq = startSeq + totalSeq;
1015 int alignmentHeight = av.getAlignment().getHeight();
1016 if (endSeq > alignmentHeight)
1018 endSeq = alignmentHeight;
1021 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1023 if (av.isShowAnnotation())
1025 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1028 pagesHigh /= pageHeight;
1030 if (pi >= (pagesWide * pagesHigh))
1032 return Printable.NO_SUCH_PAGE;
1034 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1037 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1039 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1040 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1041 pageWidth - idWidth, scaleHeight);
1042 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1045 * Draw the sequence ids, offset for scale height,
1046 * then reset to top left (0, 0)
1048 idGraphics.translate(0, scaleHeight);
1049 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1050 Color currentColor = null;
1051 Color currentTextColor = null;
1054 for (int i = startSeq; i < endSeq; i++)
1056 seq = av.getAlignment().getSequenceAt(i);
1057 if ((av.getSelectionGroup() != null)
1058 && av.getSelectionGroup().getSequences(null).contains(seq))
1061 * gray out ids of sequences in selection group (if any)
1063 currentColor = Color.gray;
1064 currentTextColor = Color.black;
1068 currentColor = av.getSequenceColour(seq);
1069 currentTextColor = Color.black;
1072 idGraphics.setColor(currentColor);
1073 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1076 idGraphics.setColor(currentTextColor);
1079 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1080 if (av.isRightAlignIds())
1082 fm = idGraphics.getFontMetrics();
1083 xPos = idWidth - fm.stringWidth(displayId) - 4;
1086 idGraphics.drawString(displayId, xPos,
1087 (((i - startSeq) * charHeight) + charHeight)
1088 - (charHeight / 5));
1090 idGraphics.setFont(av.getFont());
1091 idGraphics.translate(0, -scaleHeight);
1094 * draw the sequences, offset for scale height, and id width (if using a
1095 * single graphics context), then reset to (0, scale height)
1097 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1098 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1099 endRes, startSeq, endSeq);
1100 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1102 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1105 * draw annotation labels; drawComponent() translates by
1106 * getScrollOffset(), so compensate for that first;
1107 * then reset to (0, scale height)
1109 int offset = getAlabels().getScrollOffset();
1110 idGraphics.translate(0, -offset);
1111 idGraphics.translate(0, alignmentDrawnHeight);
1112 getAlabels().drawComponent(idGraphics, idWidth);
1113 idGraphics.translate(0, -alignmentDrawnHeight);
1116 * draw the annotations starting at
1117 * (idOffset, alignmentHeight) from (0, scaleHeight)
1119 alignmentGraphics.translate(alignmentGraphicsOffset,
1120 alignmentDrawnHeight);
1121 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1122 alignmentGraphics, -1, startRes, endRes + 1);
1125 return Printable.PAGE_EXISTS;
1140 * @return DOCUMENT ME!
1142 * @throws PrinterException
1145 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1146 Graphics pg) throws PrinterException
1148 int annotationHeight = 0;
1149 AnnotationLabels labels = null;
1150 if (av.isShowAnnotation())
1152 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1153 labels = new AnnotationLabels(av);
1156 int hgap = av.getCharHeight();
1157 if (av.getScaleAboveWrapped())
1159 hgap += av.getCharHeight();
1162 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1165 int idWidth = getVisibleIdWidth(false);
1167 int maxwidth = av.getAlignment().getWidth();
1168 if (av.hasHiddenColumns())
1170 maxwidth = av.getAlignment().getHiddenColumns()
1171 .findColumnPosition(maxwidth) - 1;
1174 int resWidth = getSeqPanel().seqCanvas
1175 .getWrappedCanvasWidth(pwidth - idWidth);
1177 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1179 pg.setColor(Color.white);
1180 pg.fillRect(0, 0, pwidth, pheight);
1181 pg.setFont(av.getFont());
1185 pg.setColor(Color.black);
1187 pg.translate(0, -pi * pheight);
1189 pg.setClip(0, pi * pheight, pwidth, pheight);
1195 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1197 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1198 SequenceI s = av.getAlignment().getSequenceAt(i);
1199 String string = s.getDisplayId(av.getShowJVSuffix());
1201 if (av.isRightAlignIds())
1203 FontMetrics fm = pg.getFontMetrics();
1204 xPos = idWidth - fm.stringWidth(string) - 4;
1206 pg.drawString(string, xPos,
1207 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1208 - (av.getCharHeight() / 5));
1212 pg.translate(-3, ypos
1213 + (av.getAlignment().getHeight() * av.getCharHeight()));
1215 pg.setFont(av.getFont());
1216 labels.drawComponent(pg, idWidth);
1217 pg.translate(+3, -ypos
1218 - (av.getAlignment().getHeight() * av.getCharHeight()));
1222 } while (ypos < totalHeight);
1224 pg.translate(idWidth, 0);
1226 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1229 if ((pi * pheight) < totalHeight)
1231 return Printable.PAGE_EXISTS;
1236 return Printable.NO_SUCH_PAGE;
1241 * get current sequence ID panel width, or nominal value if panel were to be
1242 * displayed using default settings
1246 public int getVisibleIdWidth()
1248 return getVisibleIdWidth(true);
1252 * get current sequence ID panel width, or nominal value if panel were to be
1253 * displayed using default settings
1256 * indicate if the Id width for onscreen or offscreen display should
1260 public int getVisibleIdWidth(boolean onscreen)
1262 // see if rendering offscreen - check preferences and calc width accordingly
1263 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1265 return calculateIdWidth(-1).width + 4;
1267 Integer idwidth = null;
1268 if (onscreen || (idwidth = Cache
1269 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1271 int w = getIdPanel().getWidth();
1272 return (w > 0 ? w : calculateIdWidth().width + 4);
1274 return idwidth.intValue() + 4;
1277 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1279 int boarderBottomOffset = 5;
1280 long pSessionId = System.currentTimeMillis();
1281 headless = (System.getProperty("java.awt.headless") != null
1282 && System.getProperty("java.awt.headless").equals("true"));
1283 if (alignFrame != null && !headless)
1287 alignFrame.setProgressBar(MessageManager
1288 .formatMessage("status.saving_file", new Object[]
1289 { type.getLabel() }), pSessionId);
1294 AlignmentDimension aDimension = getAlignmentDimension();
1297 jalview.util.ImageMaker im;
1298 final String imageAction, imageTitle;
1299 if (type == jalview.util.ImageMaker.TYPE.PNG)
1301 imageAction = "Create PNG image from alignment";
1304 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1306 imageAction = "Create EPS file from alignment";
1307 imageTitle = alignFrame.getTitle();
1311 imageAction = "Create SVG file from alignment";
1312 imageTitle = alignFrame.getTitle();
1315 im = new jalview.util.ImageMaker(this, type, imageAction,
1316 aDimension.getWidth(),
1317 aDimension.getHeight() + boarderBottomOffset, file,
1318 imageTitle, alignFrame, pSessionId, headless);
1319 Graphics graphics = im.getGraphics();
1320 if (av.getWrapAlignment())
1322 if (graphics != null)
1324 printWrappedAlignment(aDimension.getWidth(),
1325 aDimension.getHeight() + boarderBottomOffset, 0,
1332 if (graphics != null)
1334 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1335 graphics, graphics);
1340 } catch (OutOfMemoryError err)
1343 System.out.println("########################\n" + "OUT OF MEMORY "
1344 + file + "\n" + "########################");
1345 new OOMWarning("Creating Image for " + file, err);
1346 // System.out.println("Create IMAGE: " + err);
1347 } catch (Exception ex)
1349 ex.printStackTrace();
1357 public AlignmentDimension getAlignmentDimension()
1359 int maxwidth = av.getAlignment().getWidth();
1360 if (av.hasHiddenColumns())
1362 maxwidth = av.getAlignment().getHiddenColumns()
1363 .findColumnPosition(maxwidth);
1366 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1367 + getScalePanel().getHeight();
1368 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1370 if (av.getWrapAlignment())
1372 height = getWrappedHeight();
1375 // need to obtain default alignment width and then add in any
1376 // additional allowance for id margin
1377 // this duplicates the calculation in getWrappedHeight but adjusts for
1379 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1380 - alignFrame.getInsets().left - alignFrame.getInsets().right
1381 - getVisibleIdWidth() + getVisibleIdWidth(false);
1385 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1389 else if (av.isShowAnnotation())
1391 height += getAnnotationPanel().adjustPanelHeight() + 3;
1393 return new AlignmentDimension(width, height);
1400 public void makeEPS(File epsFile)
1402 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1408 public void makePNG(File pngFile)
1410 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1413 public void makeSVG(File svgFile)
1415 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1418 public void makePNGImageMap(File imgMapFile, String imageName)
1420 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1421 // ////////////////////////////////////////////
1422 int idWidth = getVisibleIdWidth(false);
1423 FontMetrics fm = getFontMetrics(av.getFont());
1424 int scaleHeight = av.getCharHeight() + fm.getDescent();
1427 // ////////////////////////////////
1428 if (imgMapFile != null)
1432 int sSize = av.getAlignment().getHeight();
1433 int alwidth = av.getAlignment().getWidth();
1434 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1435 out.println(HTMLOutput.getImageMapHTML());
1436 out.println("<img src=\"" + imageName
1437 + "\" border=\"0\" usemap=\"#Map\" >"
1438 + "<map name=\"Map\">");
1440 for (int s = 0; s < sSize; s++)
1442 int sy = s * av.getCharHeight() + scaleHeight;
1444 SequenceI seq = av.getAlignment().getSequenceAt(s);
1445 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1446 for (int column = 0; column < alwidth; column++)
1448 StringBuilder text = new StringBuilder(512);
1449 String triplet = null;
1450 if (av.getAlignment().isNucleotide())
1452 triplet = ResidueProperties.nucleotideName.get(seq
1453 .getCharAt(column) + "");
1457 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1461 if (triplet == null)
1466 int seqPos = seq.findPosition(column);
1467 int gSize = groups.length;
1468 for (int g = 0; g < gSize; g++)
1470 if (text.length() < 1)
1472 text.append("<area shape=\"rect\" coords=\"")
1473 .append((idWidth + column * av.getCharWidth()))
1474 .append(",").append(sy).append(",")
1475 .append((idWidth + (column + 1) * av.getCharWidth()))
1476 .append(",").append((av.getCharHeight() + sy))
1477 .append("\"").append(" onMouseOver=\"toolTip('")
1478 .append(seqPos).append(" ").append(triplet);
1481 if (groups[g].getStartRes() < column
1482 && groups[g].getEndRes() > column)
1484 text.append("<br><em>").append(groups[g].getName())
1489 if (text.length() < 1)
1491 text.append("<area shape=\"rect\" coords=\"")
1492 .append((idWidth + column * av.getCharWidth()))
1493 .append(",").append(sy).append(",")
1494 .append((idWidth + (column + 1) * av.getCharWidth()))
1495 .append(",").append((av.getCharHeight() + sy))
1496 .append("\"").append(" onMouseOver=\"toolTip('")
1497 .append(seqPos).append(" ").append(triplet);
1499 if (!Comparison.isGap(seq.getCharAt(column)))
1501 List<SequenceFeature> features = seq.findFeatures(column, column);
1502 for (SequenceFeature sf : features)
1504 if (sf.isContactFeature())
1506 text.append("<br>").append(sf.getType()).append(" ")
1507 .append(sf.getBegin()).append(":")
1508 .append(sf.getEnd());
1512 text.append("<br>");
1513 text.append(sf.getType());
1514 String description = sf.getDescription();
1515 if (description != null
1516 && !sf.getType().equals(description))
1518 description = description.replace("\"", """);
1519 text.append(" ").append(description);
1522 String status = sf.getStatus();
1523 if (status != null && !"".equals(status))
1525 text.append(" (").append(status).append(")");
1528 if (text.length() > 1)
1530 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1531 out.println(text.toString());
1536 out.println("</map></body></html>");
1539 } catch (Exception ex)
1541 ex.printStackTrace();
1543 } // /////////END OF IMAGE MAP
1547 int getWrappedHeight()
1549 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1551 if (System.getProperty("java.awt.headless") != null
1552 && System.getProperty("java.awt.headless").equals("true"))
1554 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1555 - vscroll.getPreferredSize().width
1556 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1559 int chunkWidth = getSeqPanel().seqCanvas
1560 .getWrappedCanvasWidth(seqPanelWidth);
1562 int hgap = av.getCharHeight();
1563 if (av.getScaleAboveWrapped())
1565 hgap += av.getCharHeight();
1568 int annotationHeight = 0;
1569 if (av.isShowAnnotation())
1571 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1574 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1577 int maxwidth = av.getAlignment().getWidth();
1578 if (av.hasHiddenColumns())
1580 maxwidth = av.getAlignment().getHiddenColumns()
1581 .findColumnPosition(maxwidth) - 1;
1584 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1590 * close the panel - deregisters all listeners and nulls any references to
1593 public void closePanel()
1595 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1596 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1597 PaintRefresher.RemoveComponent(this);
1602 * try to ensure references are nulled
1604 if (annotationPanel != null)
1606 annotationPanel.dispose();
1611 av.removePropertyChangeListener(propertyChangeListener);
1612 jalview.structure.StructureSelectionManager ssm = av
1613 .getStructureSelectionManager();
1614 ssm.removeStructureViewerListener(getSeqPanel(), null);
1615 ssm.removeSelectionListener(getSeqPanel());
1616 ssm.removeCommandListener(av);
1617 ssm.removeStructureViewerListener(getSeqPanel(), null);
1618 ssm.removeSelectionListener(getSeqPanel());
1624 if (Cache.log.isDebugEnabled())
1626 Cache.log.warn("Closing alignment panel which is already closed.");
1632 * Close any open dialogs that would be orphaned when this one is closed
1634 protected void closeChildFrames()
1636 if (calculationDialog != null)
1638 calculationDialog.closeFrame();
1643 * hides or shows dynamic annotation rows based on groups and av state flags
1645 public void updateAnnotation()
1647 updateAnnotation(false, false);
1650 public void updateAnnotation(boolean applyGlobalSettings)
1652 updateAnnotation(applyGlobalSettings, false);
1655 public void updateAnnotation(boolean applyGlobalSettings,
1656 boolean preserveNewGroupSettings)
1658 av.updateGroupAnnotationSettings(applyGlobalSettings,
1659 preserveNewGroupSettings);
1660 adjustAnnotationHeight();
1664 public AlignmentI getAlignment()
1666 return av == null ? null : av.getAlignment();
1670 public String getViewName()
1676 * Make/Unmake this alignment panel the current input focus
1680 public void setSelected(boolean b)
1684 if (alignFrame.getSplitViewContainer() != null)
1687 * bring enclosing SplitFrame to front first if there is one
1689 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1691 alignFrame.setSelected(b);
1692 } catch (Exception ex)
1698 alignFrame.setDisplayedView(this);
1703 public StructureSelectionManager getStructureSelectionManager()
1705 return av.getStructureSelectionManager();
1709 public void raiseOOMWarning(String string, OutOfMemoryError error)
1711 new OOMWarning(string, error, this);
1715 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1718 return new FeatureRenderer(this);
1722 public jalview.api.FeatureRenderer getFeatureRenderer()
1724 return seqPanel.seqCanvas.getFeatureRenderer();
1727 public void updateFeatureRenderer(
1728 jalview.renderer.seqfeatures.FeatureRenderer fr)
1730 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1733 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1735 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1737 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1741 public ScalePanel getScalePanel()
1746 public void setScalePanel(ScalePanel scalePanel)
1748 this.scalePanel = scalePanel;
1751 public SeqPanel getSeqPanel()
1756 public void setSeqPanel(SeqPanel seqPanel)
1758 this.seqPanel = seqPanel;
1761 public AnnotationPanel getAnnotationPanel()
1763 return annotationPanel;
1766 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1768 this.annotationPanel = annotationPanel;
1771 public AnnotationLabels getAlabels()
1776 public void setAlabels(AnnotationLabels alabels)
1778 this.alabels = alabels;
1781 public IdPanel getIdPanel()
1786 public void setIdPanel(IdPanel idPanel)
1788 this.idPanel = idPanel;
1792 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1793 * The aim is to keep the two alignments 'lined up' on their centre columns.
1796 * holds mapped region(s) of this alignment that we are scrolling
1797 * 'to'; may be modified for sequence offset by this method
1798 * @param verticalOffset
1799 * the number of visible sequences to show above the mapped region
1801 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1804 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1805 * mapped), we can make the scroll-to location a sequence above the one
1808 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1809 List<SequenceI> seqs = av.getAlignment().getSequences();
1812 * This is like AlignmentI.findIndex(seq) but here we are matching the
1813 * dataset sequence not the aligned sequence
1815 boolean matched = false;
1816 for (SequenceI seq : seqs)
1818 if (mappedTo == seq.getDatasetSequence())
1826 return; // failsafe, shouldn't happen
1830 * Scroll to position but centring the target residue.
1832 scrollToPosition(sr, verticalOffset, true, true);
1836 * Set a flag to say do not scroll any (cDNA/protein) complement.
1840 protected void setToScrollComplementPanel(boolean b)
1842 this.scrollComplementaryPanel = b;
1846 * Get whether to scroll complement panel
1848 * @return true if cDNA/protein complement panels should be scrolled
1850 protected boolean isSetToScrollComplementPanel()
1852 return this.scrollComplementaryPanel;
1858 * @adjustHeight if true, try to recalculate panel height for visible
1861 protected void refresh(boolean adjustHeight)
1863 validateAnnotationDimensions(adjustHeight);
1867 // sort, repaint, update overview
1868 paintAlignment(true, false);
1872 // lightweight repaint
1879 * Property change event fired when a change is made to the viewport ranges
1880 * object associated with this alignment panel's viewport
1882 public void propertyChange(PropertyChangeEvent evt)
1884 // update this panel's scroll values based on the new viewport ranges values
1885 int x = vpRanges.getStartRes();
1886 int y = vpRanges.getStartSeq();
1887 setScrollValues(x, y);
1889 // now update any complementary alignment (its viewport ranges object
1890 // is different so does not get automatically updated)
1891 if (isSetToScrollComplementPanel())
1893 setToScrollComplementPanel(false);
1894 av.scrollComplementaryAlignment();
1895 setToScrollComplementPanel(true);
1900 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1901 * reference should be nulled when the dialog is closed.
1903 * @param calculationChooser
1905 public void setCalculationDialog(CalculationChooser calculationChooser)
1907 calculationDialog = calculationChooser;
1911 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1914 public CalculationChooser getCalculationDialog()
1916 return calculationDialog;