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 static jalview.util.ImageMaker.TYPE.EPS;
24 import static jalview.util.ImageMaker.TYPE.PNG;
25 import static jalview.util.ImageMaker.TYPE.SVG;
27 import jalview.analysis.AnnotationSorter;
28 import jalview.api.AlignViewportI;
29 import jalview.api.AlignmentViewPanel;
30 import jalview.bin.Cache;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.HiddenColumns;
33 import jalview.datamodel.SearchResultsI;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.HTMLOutput;
38 import jalview.jbgui.GAlignmentPanel;
39 import jalview.math.AlignmentDimension;
40 import jalview.schemes.ResidueProperties;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.Comparison;
43 import jalview.util.ImageMaker;
44 import jalview.util.MessageManager;
45 import jalview.viewmodel.ViewportListenerI;
46 import jalview.viewmodel.ViewportRanges;
48 import java.awt.BorderLayout;
49 import java.awt.Color;
50 import java.awt.Container;
51 import java.awt.Dimension;
53 import java.awt.FontMetrics;
54 import java.awt.Graphics;
55 import java.awt.Graphics2D;
56 import java.awt.event.AdjustmentEvent;
57 import java.awt.event.AdjustmentListener;
58 import java.awt.event.ComponentAdapter;
59 import java.awt.event.ComponentEvent;
60 import java.awt.print.PageFormat;
61 import java.awt.print.Printable;
62 import java.awt.print.PrinterException;
63 import java.beans.PropertyChangeEvent;
64 import java.beans.PropertyChangeListener;
66 import java.io.FileWriter;
67 import java.io.PrintWriter;
68 import java.util.List;
70 import javax.swing.SwingUtilities;
76 * @version $Revision: 1.161 $
78 public class AlignmentPanel extends GAlignmentPanel implements
79 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
81 public AlignViewport av;
83 OverviewPanel overviewPanel;
85 private SeqPanel seqPanel;
87 private IdPanel idPanel;
89 private boolean headless;
91 IdwidthAdjuster idwidthAdjuster;
94 public AlignFrame alignFrame;
96 private ScalePanel scalePanel;
98 private AnnotationPanel annotationPanel;
100 private AnnotationLabels alabels;
102 private int hextent = 0;
104 private int vextent = 0;
107 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
108 * false, suppresses invoking the same method recursively.
110 private boolean scrollComplementaryPanel = true;
112 private PropertyChangeListener propertyChangeListener;
114 private CalculationChooser calculationDialog;
117 * Creates a new AlignmentPanel object.
122 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 setSeqPanel(new SeqPanel(av, this));
127 setIdPanel(new IdPanel(av, this));
129 setScalePanel(new ScalePanel(av, this));
131 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
132 idwidthAdjuster = new IdwidthAdjuster(this);
133 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
135 setAnnotationPanel(new AnnotationPanel(this));
136 setAlabels(new AnnotationLabels(this));
138 annotationScroller.setViewportView(getAnnotationPanel());
139 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
141 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
142 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
144 setScrollValues(0, 0);
146 hscroll.addAdjustmentListener(this);
147 vscroll.addAdjustmentListener(this);
149 addComponentListener(new ComponentAdapter()
152 public void componentResized(ComponentEvent evt)
154 // reset the viewport ranges when the alignment panel is resized
155 // in particular, this initialises the end residue value when Jalview
157 ViewportRanges ranges = av.getRanges();
158 if (av.getWrapAlignment())
160 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
161 getSeqPanel().seqCanvas.getWidth());
162 ranges.setViewportWidth(widthInRes);
166 int widthInRes = getSeqPanel().seqCanvas.getWidth()
168 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
169 / av.getCharHeight();
171 ranges.setViewportWidth(widthInRes);
172 ranges.setViewportHeight(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 if (getCalculationDialog() != null)
211 getCalculationDialog().validateCalcTypes();
214 alignFrame.updateEditMenuBar();
216 // no idea if we need to update structure
217 paintAlignment(true, 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(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idSpaceFillerPanel1.setPreferredSize(
233 new Dimension(10, av.getCharHeight() + fm.getDescent()));
234 idwidthAdjuster.invalidate();
235 scalePanelHolder.invalidate();
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
242 d.setSize(d.width + 4, d.height);
243 getIdPanel().getIdCanvas().setPreferredSize(d);
244 hscrollFillerPanel.setPreferredSize(d);
250 * Calculate the width of the alignment labels based on the displayed names
251 * and any bounds on label width set in preferences.
253 * @return Dimension giving the maximum width of the alignment label panel
254 * that should be used.
256 public Dimension calculateIdWidth()
258 // calculate sensible default width when no preference is available
260 if (av.getIdWidth() < 0)
262 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
263 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
264 r = calculateIdWidth(maxwidth);
265 av.setIdWidth(r.width);
270 r.width = av.getIdWidth();
277 * Calculate the width of the alignment labels based on the displayed names
278 * and any bounds on label width set in preferences.
281 * -1 or maximum width allowed for IdWidth
282 * @return Dimension giving the maximum width of the alignment label panel
283 * that should be used.
285 public Dimension calculateIdWidth(int maxwidth)
287 Container c = new Container();
289 FontMetrics fm = c.getFontMetrics(
290 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
292 AlignmentI al = av.getAlignment();
297 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
299 SequenceI s = al.getSequenceAt(i);
301 id = s.getDisplayId(av.getShowJVSuffix());
303 if (fm.stringWidth(id) > idWidth)
305 idWidth = fm.stringWidth(id);
311 // Also check annotation label widths
314 if (al.getAlignmentAnnotation() != null)
316 fm = c.getFontMetrics(getAlabels().getFont());
318 while (i < al.getAlignmentAnnotation().length)
320 String label = al.getAlignmentAnnotation()[i].label;
322 if (fm.stringWidth(label) > idWidth)
324 idWidth = fm.stringWidth(label);
331 return new Dimension(
332 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
336 * Highlight the given results on the alignment
339 public void highlightSearchResults(SearchResultsI results)
341 boolean scrolled = scrollToPosition(results, 0, false);
343 boolean noFastPaint = scrolled && av.getWrapAlignment();
345 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
349 * Scroll the view to show the position of the highlighted region in results
352 * @param searchResults
355 public boolean scrollToPosition(SearchResultsI searchResults)
357 return scrollToPosition(searchResults, 0, 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
371 * if true, try to centre the search results horizontally in the view
374 protected boolean scrollToPosition(SearchResultsI results,
375 int verticalOffset, boolean centre)
377 int startv, endv, starts, ends;
378 ViewportRanges ranges = av.getRanges();
380 if (results == null || results.isEmpty() || av == null
381 || av.getAlignment() == null)
385 int seqIndex = av.getAlignment().findIndex(results);
390 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
392 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
401 * To centre results, scroll to positions half the visible width
402 * left/right of the start/end positions
406 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
407 start = Math.max(start - offset, 0);
408 end = end + offset - 1;
414 if (end == seq.getEnd())
419 if (av.hasHiddenColumns())
421 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
422 start = hidden.absoluteToVisibleColumn(start);
423 end = hidden.absoluteToVisibleColumn(end);
426 if (!hidden.isVisible(r[0]))
428 // don't scroll - position isn't visible
435 * allow for offset of target sequence (actually scroll to one above it)
437 seqIndex = Math.max(0, seqIndex - verticalOffset);
438 boolean scrollNeeded = true;
440 if (!av.getWrapAlignment())
442 if ((startv = ranges.getStartRes()) >= start)
445 * Scroll left to make start of search results visible
447 setScrollValues(start, seqIndex);
449 else if ((endv = ranges.getEndRes()) <= end)
452 * Scroll right to make end of search results visible
454 setScrollValues(startv + end - endv, seqIndex);
456 else if ((starts = ranges.getStartSeq()) > seqIndex)
459 * Scroll up to make start of search results visible
461 setScrollValues(ranges.getStartRes(), seqIndex);
463 else if ((ends = ranges.getEndSeq()) <= seqIndex)
466 * Scroll down to make end of search results visible
468 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
472 * Else results are already visible - no need to scroll
474 scrollNeeded = false;
478 scrollNeeded = ranges.scrollToWrappedVisible(start);
481 paintAlignment(false, false);
489 * @return DOCUMENT ME!
491 public OverviewPanel getOverviewPanel()
493 return overviewPanel;
502 public void setOverviewPanel(OverviewPanel op)
510 * Hide or show annotation panel
513 public void setAnnotationVisible(boolean b)
515 if (!av.getWrapAlignment())
517 annotationSpaceFillerHolder.setVisible(b);
518 annotationScroller.setVisible(b);
524 * automatically adjust annotation panel height for new annotation whilst
525 * ensuring the alignment is still visible.
528 public void adjustAnnotationHeight()
530 // TODO: display vertical annotation scrollbar if necessary
531 // this is called after loading new annotation onto alignment
532 if (alignFrame.getHeight() == 0)
534 System.out.println("NEEDS FIXING");
536 validateAnnotationDimensions(true);
538 // TODO: many places call this method and also paintAlignment with various
539 // different settings. this means multiple redraws are triggered...
540 paintAlignment(true, av.needToUpdateStructureViews());
544 * calculate the annotation dimensions and refresh slider values accordingly.
545 * need to do repaints/notifys afterwards.
547 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
549 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
550 annotationHeight = getAnnotationPanel()
551 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
554 annotationScroller.setPreferredSize(
555 new Dimension(annotationScroller.getWidth(), annotationHeight));
557 Dimension e = idPanel.getSize();
558 alabels.setSize(new Dimension(e.width, annotationHeight));
560 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
561 annotationSpaceFillerHolder.getWidth(), annotationHeight));
562 annotationScroller.validate();
563 annotationScroller.addNotify();
567 * update alignment layout for viewport settings
569 public void updateLayout()
572 setAnnotationVisible(av.isShowAnnotation());
573 boolean wrap = av.getWrapAlignment();
574 ViewportRanges ranges = av.getRanges();
575 ranges.setStartSeq(0);
576 scalePanelHolder.setVisible(!wrap);
577 hscroll.setVisible(!wrap);
578 idwidthAdjuster.setVisible(!wrap);
582 annotationScroller.setVisible(false);
583 annotationSpaceFillerHolder.setVisible(false);
585 else if (av.isShowAnnotation())
587 annotationScroller.setVisible(true);
588 annotationSpaceFillerHolder.setVisible(true);
589 validateAnnotationDimensions(false);
592 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
594 { // may not yet be laid out
597 int widthInRes = getSeqPanel().seqCanvas
598 .getWrappedCanvasWidth(canvasWidth);
599 ranges.setViewportWidth(widthInRes);
603 int widthInRes = (canvasWidth / av.getCharWidth());
604 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
605 / av.getCharHeight());
607 ranges.setViewportWidth(widthInRes);
608 ranges.setViewportHeight(heightInSeq);
612 idSpaceFillerPanel1.setVisible(!wrap);
614 AlignViewportI complement = av.getCodingComplement();
615 if (complement != null)
617 SplitFrame splitFrame = (SplitFrame) alignFrame
618 .getSplitViewContainer();
619 splitFrame.adjustLayout();
625 * Adjust row/column scrollers to show a visible position in the alignment.
628 * visible column to scroll to
630 * visible row to scroll to
633 public void setScrollValues(int xpos, int ypos)
638 if (av == null || av.getAlignment() == null)
643 if (av.getWrapAlignment())
645 setScrollingForWrappedPanel(x);
649 int width = av.getAlignment().getVisibleWidth();
650 int height = av.getAlignment().getHeight();
652 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
653 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
660 if (vextent > height)
665 if ((hextent + x) > width)
670 if ((vextent + y) > height)
672 y = height - vextent;
685 // update the scroll values
686 hscroll.setValues(x, hextent, 0, width);
687 vscroll.setValues(y, vextent, 0, height);
692 * Respond to adjustment event when horizontal or vertical scrollbar is
696 * adjustment event encoding whether hscroll or vscroll changed
699 public void adjustmentValueChanged(AdjustmentEvent evt)
701 if (av.getWrapAlignment())
703 adjustScrollingWrapped(evt);
707 ViewportRanges ranges = av.getRanges();
709 if (evt.getSource() == hscroll)
711 int oldX = ranges.getStartRes();
712 int oldwidth = ranges.getViewportWidth();
713 int x = hscroll.getValue();
714 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
716 // if we're scrolling to the position we're already at, stop
717 // this prevents infinite recursion of events when the scroll/viewport
718 // ranges values are the same
719 if ((x == oldX) && (width == oldwidth))
723 ranges.setViewportStartAndWidth(x, width);
725 else if (evt.getSource() == vscroll)
727 int oldY = ranges.getStartSeq();
728 int oldheight = ranges.getViewportHeight();
729 int y = vscroll.getValue();
730 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
732 // if we're scrolling to the position we're already at, stop
733 // this prevents infinite recursion of events when the scroll/viewport
734 // ranges values are the same
735 if ((y == oldY) && (height == oldheight))
739 ranges.setViewportStartAndHeight(y, height);
745 * Responds to a scroll change by setting the start position of the viewport.
750 protected void adjustScrollingWrapped(AdjustmentEvent evt)
752 if (evt.getSource() == hscroll)
754 return; // no horizontal scroll when wrapped
756 final ViewportRanges ranges = av.getRanges();
758 if (evt.getSource() == vscroll)
760 int newY = vscroll.getValue();
763 * if we're scrolling to the position we're already at, stop
764 * this prevents infinite recursion of events when the scroll/viewport
765 * ranges values are the same
767 int oldX = ranges.getStartRes();
768 int oldY = ranges.getWrappedScrollPosition(oldX);
776 * limit page up/down to one width's worth of positions
778 int rowSize = ranges.getViewportWidth();
779 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
780 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
785 // This is only called if file loaded is a jar file that
786 // was wrapped when saved and user has wrap alignment true
787 // as preference setting
788 SwingUtilities.invokeLater(new Runnable()
793 // When updating scrolling to use ViewportChange events, this code
794 // could not be validated and it is not clear if it is now being
795 // called. Log warning here in case it is called and unforeseen
798 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
800 // scroll to start of panel
801 ranges.setStartRes(0);
802 ranges.setStartSeq(0);
810 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
813 public void paintAlignment(boolean updateOverview,
814 boolean updateStructures)
816 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
817 av.isShowAutocalculatedAbove());
818 sorter.sort(getAlignment().getAlignmentAnnotation(),
819 av.getSortAnnotationsBy());
822 if (updateStructures)
824 av.getStructureSelectionManager().sequenceColoursChanged(this);
829 if (overviewPanel != null)
831 overviewPanel.updateOverviewImage();
843 public void paintComponent(Graphics g)
845 invalidate(); // needed so that the id width adjuster works correctly
847 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
848 idPanelHolder.setPreferredSize(d);
849 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
851 validate(); // needed so that the id width adjuster works correctly
854 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
855 * though I still think this call should be elsewhere.
857 ViewportRanges ranges = av.getRanges();
858 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
862 * Set vertical scroll bar position, and number of increments, for wrapped
865 * @param topLeftColumn
866 * the column position at top left (0..)
868 private void setScrollingForWrappedPanel(int topLeftColumn)
870 ViewportRanges ranges = av.getRanges();
871 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
872 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
875 * a scrollbar's value can be set to at most (maximum-extent)
876 * so we add extent (1) to the maxScroll value
878 vscroll.setUnitIncrement(1);
879 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
883 * Provides the implementation of Printable.print
892 * @return DOCUMENT ME!
894 * @throws PrinterException
897 public int print(Graphics pg, PageFormat pf, int pi)
898 throws PrinterException
900 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
902 int pwidth = (int) pf.getImageableWidth();
903 int pheight = (int) pf.getImageableHeight();
905 if (av.getWrapAlignment())
907 return printWrappedAlignment(pwidth, pheight, pi, pg, true);
911 return printUnwrapped(pwidth, pheight, pi, pg, pg);
916 * Draws the alignment image, including sequence ids, sequences, and
917 * annotation labels and annotations if shown, on either one or two Graphics
927 * the graphics context for sequence ids and annotation labels
928 * @param alignmentGraphics
929 * the graphics context for sequences and annotations (may or may not
930 * be the same context as idGraphics)
932 * @throws PrinterException
934 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
935 Graphics idGraphics, Graphics alignmentGraphics)
936 throws PrinterException
938 final int idWidth = getVisibleIdWidth(false);
941 * Get the horizontal offset to where we draw the sequences.
942 * This is idWidth if using a single Graphics context, else zero.
944 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
947 FontMetrics fm = getFontMetrics(av.getFont());
948 final int charHeight = av.getCharHeight();
949 final int scaleHeight = charHeight + fm.getDescent();
951 idGraphics.setColor(Color.white);
952 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
953 idGraphics.setFont(av.getFont());
956 * How many sequences and residues can we fit on a printable page?
958 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
960 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
962 final int alignmentWidth = av.getAlignment().getVisibleWidth();
963 int pagesWide = (alignmentWidth / totalRes) + 1;
965 final int startRes = (pageIndex % pagesWide) * totalRes;
966 final int endRes = Math.min(startRes + totalRes - 1,
969 final int startSeq = (pageIndex / pagesWide) * totalSeq;
970 final int alignmentHeight = av.getAlignment().getHeight();
971 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
973 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
975 if (av.isShowAnnotation())
977 pagesHigh += getAnnotationPanel().adjustPanelHeight()
978 + SeqCanvas.SEQS_ANNOTATION_GAP;
981 pagesHigh /= pageHeight;
983 if (pageIndex >= (pagesWide * pagesHigh))
985 return Printable.NO_SUCH_PAGE;
987 final int alignmentDrawnHeight = (endSeq - startSeq + 1) * charHeight;
990 * draw the Scale at horizontal offset, then reset to top left (0, 0)
992 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
993 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
994 pageWidth - idWidth, scaleHeight);
995 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
998 * Draw the sequence ids, offset for scale height,
999 * then reset to top left (0, 0)
1001 idGraphics.translate(0, scaleHeight);
1002 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1003 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1004 : av.getSelectionGroup().getSequences(null);
1005 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1008 idGraphics.setFont(av.getFont());
1009 idGraphics.translate(0, -scaleHeight);
1012 * draw the sequences, offset for scale height, and id width (if using a
1013 * single graphics context), then reset to (0, scale height)
1015 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1016 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1017 endRes, startSeq, endSeq - 1);
1018 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1020 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1023 * draw annotation labels; drawComponent() translates by
1024 * getScrollOffset(), so compensate for that first;
1025 * then reset to (0, scale height)
1027 int offset = getAlabels().getScrollOffset();
1028 int yShift = alignmentDrawnHeight + SeqCanvas.SEQS_ANNOTATION_GAP;
1029 idGraphics.translate(0, -offset);
1030 idGraphics.translate(0, yShift);
1031 getAlabels().drawComponent(idGraphics, idWidth);
1032 idGraphics.translate(0, -yShift);
1035 * draw the annotations starting at
1036 * (idOffset, alignmentHeight) from (0, scaleHeight)
1038 alignmentGraphics.translate(alignmentGraphicsOffset,
1040 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1041 alignmentGraphics, -1, startRes, endRes + 1);
1044 * reset to left margin below annotation
1046 int justDrawn = getAnnotationPanel().renderer.getLastDrawnHeight();
1047 alignmentGraphics.translate(-alignmentGraphicsOffset, justDrawn);
1052 * shift graphics to position after drawn sequences
1054 alignmentGraphics.translate(0, alignmentDrawnHeight);
1057 return Printable.PAGE_EXISTS;
1061 * Prints one page of an alignment in wrapped mode. Returns
1062 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1063 * no page could be drawn (page number out of range).
1065 * The method is to write the whole alignment, but set a clip region such that
1066 * only the specified page is written. This allows specified page(s) to be
1067 * printed from the print dialog. The whole image may be written simply by
1068 * making the page size match the image size. In this case, parameter
1069 * {@code clipToPage} should be set to {@code false}, so that more output (for
1070 * example the second panel of a split frame) can be written if wanted.
1081 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1082 Graphics g, boolean clipToPage)
1084 final SeqCanvas seqCanvas = getSeqPanel().seqCanvas;
1085 seqCanvas.calculateWrappedGeometry(seqCanvas.getWidth(),
1086 seqCanvas.getHeight());
1087 int annotationHeight = 0;
1088 if (av.isShowAnnotation())
1090 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1093 int hgap = av.getCharHeight();
1094 if (av.getScaleAboveWrapped())
1096 hgap += av.getCharHeight();
1099 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1102 int idWidth = getVisibleIdWidth(false);
1104 int maxwidth = av.getAlignment().getVisibleWidth();
1106 int resWidth = seqCanvas
1107 .getWrappedCanvasWidth(pageWidth - idWidth);
1108 av.getRanges().setViewportStartAndWidth(0, resWidth);
1110 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1112 g.setColor(Color.white);
1113 g.fillRect(0, 0, pageWidth, pageHeight);
1114 g.setFont(av.getFont());
1115 g.setColor(Color.black);
1118 * method: print the whole wrapped alignment, but with a clip region that
1119 * is restricted to the requested page; this supports selective print of
1120 * single pages or ranges, (at the cost of repeated processing in the
1121 * 'normal' case, when all pages are printed)
1123 g.translate(0, -pageNumber * pageHeight);
1127 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1131 * draw sequence ids and annotation labels (if shown)
1133 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1134 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1136 g.translate(idWidth, 0);
1137 seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1139 g.translate(-idWidth, 0);
1141 if ((pageNumber * pageHeight) < totalHeight)
1143 return Printable.PAGE_EXISTS;
1147 return Printable.NO_SUCH_PAGE;
1152 * get current sequence ID panel width, or nominal value if panel were to be
1153 * displayed using default settings
1157 public int getVisibleIdWidth()
1159 return getVisibleIdWidth(true);
1163 * get current sequence ID panel width, or nominal value if panel were to be
1164 * displayed using default settings
1167 * indicate if the Id width for onscreen or offscreen display should
1171 public int getVisibleIdWidth(boolean onscreen)
1173 // see if rendering offscreen - check preferences and calc width accordingly
1174 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1176 return calculateIdWidth(-1).width + 4;
1178 Integer idwidth = null;
1179 if (onscreen || (idwidth = Cache
1180 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1182 int w = getIdPanel().getWidth();
1183 return (w > 0 ? w : calculateIdWidth().width + 4);
1185 return idwidth.intValue() + 4;
1189 * Generates an image of the alignment panel of the specified type. If
1190 * {@code type} is not null, the image is written to the file, otherwise the
1191 * user is prompted to specify the output file before writing to it.
1195 * @param forSplitFrame
1197 void makeAlignmentImage(ImageMaker.TYPE type, File file,
1198 boolean forSplitFrame)
1200 int borderBottomOffset = 5;
1201 long pSessionId = System.currentTimeMillis();
1202 headless = (System.getProperty("java.awt.headless") != null
1203 && System.getProperty("java.awt.headless").equals("true"));
1204 if (alignFrame != null && !headless)
1208 alignFrame.setProgressBar(MessageManager
1209 .formatMessage("status.saving_file", new Object[]
1210 { type.getLabel() }), pSessionId);
1215 * cache preferences in case we need to fudge them for export of
1216 * split frame with 'protein scaled to codons' and 'auto id width'
1219 final String autoIdWidth = Cache.getProperty("FIGURE_AUTOIDWIDTH");
1220 final Integer fixedIdWidth = Cache
1221 .getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1226 * if exporting a split frame image, the graphics object has
1227 * width: maximum of the top and bottom image widths
1228 * height: sum of the top and bottom image heights
1229 * Any preferences for auto or fixed id width are overridden here
1230 * with the actual id widths, and restored after export
1232 AlignmentPanel complement = null;
1233 final int idWidth = getIdPanel().getWidth();
1234 int complementIdWidth = 0;
1238 complement = ((AlignViewport) av.getCodingComplement())
1240 Cache.setProperty("FIGURE_AUTOIDWIDTH", Boolean.FALSE.toString());
1241 Cache.setProperty("FIGURE_FIXEDIDWIDTH", String.valueOf(idWidth));
1243 AlignmentDimension dim1 = getAlignmentDimension();
1244 AlignmentDimension dim2 = new AlignmentDimension(0, 0);
1248 complementIdWidth = complement.getIdPanel().getWidth();
1249 Cache.setProperty("FIGURE_FIXEDIDWIDTH", String.valueOf(complementIdWidth));
1250 dim2 = complement.getAlignmentDimension();
1251 Cache.setProperty("FIGURE_FIXEDIDWIDTH", String.valueOf(idWidth));
1254 final int graphicsHeight = dim1.height + dim2.height
1255 + borderBottomOffset;
1256 final int graphicsWidth = Math.max(dim1.width, dim2.width);
1258 final String dialogTitle = MessageManager
1259 .formatMessage("label.make_alignment_image", type.getName());
1260 String imageTitle = type == PNG ? null : alignFrame.getTitle();
1262 ImageMaker im = new ImageMaker(this, type, dialogTitle,
1263 graphicsWidth, graphicsHeight, file,
1264 imageTitle, alignFrame, pSessionId, headless);
1265 Graphics graphics = im.getGraphics();
1266 if (graphics == null)
1270 graphics.setColor(Color.white);
1271 graphics.fillRect(0, 0, graphicsWidth, graphicsHeight);
1272 if (av.getWrapAlignment())
1274 printWrappedAlignment(dim1.width, dim1.height + borderBottomOffset,
1275 0, graphics, false);
1279 printUnwrapped(dim1.width, dim1.height, 0, graphics, graphics);
1285 * append coding complement image
1287 // to debug location of next write to Graphics:
1288 // graphics.drawString("Hello world", 0, 0);
1289 Cache.setProperty("FIGURE_FIXEDIDWIDTH",
1290 String.valueOf(complementIdWidth));
1291 if (av.getCodingComplement().getWrapAlignment())
1293 complement.printWrappedAlignment(dim2.width,
1294 dim2.height + borderBottomOffset, 0, graphics, false);
1298 complement.printUnwrapped(dim2.width, dim2.height, 0, graphics,
1304 } catch (OutOfMemoryError err)
1307 System.out.println("########################\n" + "OUT OF MEMORY "
1308 + file + "\n" + "########################");
1309 new OOMWarning("Creating Image for " + file, err);
1310 // System.out.println("Create IMAGE: " + err);
1311 } catch (Exception ex)
1313 ex.printStackTrace();
1317 * restore preference settings in case they were overridden
1319 if (autoIdWidth == null)
1321 Cache.removeProperty("FIGURE_AUTOIDWIDTH");
1325 Cache.setProperty("FIGURE_AUTOIDWIDTH", autoIdWidth);
1327 if (fixedIdWidth == null)
1329 Cache.removeProperty("FIGURE_FIXEDIDWIDTH");
1333 Cache.setProperty("FIGURE_FIXEDIDWIDTH",
1334 String.valueOf(fixedIdWidth));
1340 * Computes and answers the width and height of the alignment in pixels,
1343 * <li>sequence ids</li>
1344 * <li>scale above, left or right if shown</li>
1345 * <li>sequence rows, plus one spacer line</li>
1346 * <li>annotations, if shown</li>
1348 * The alignment may be in wrapped or unwrapped mode.
1353 public AlignmentDimension getAlignmentDimension()
1355 int maxwidth = av.getAlignment().getVisibleWidth();
1357 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1358 + getScalePanel().getHeight();
1359 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1361 if (av.getWrapAlignment())
1363 height = getWrappedHeight();
1366 // need to obtain default alignment width and then add in any
1367 // additional allowance for id margin
1368 // this duplicates the calculation in getWrappedHeight but adjusts for
1370 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1371 - alignFrame.getInsets().left - alignFrame.getInsets().right
1372 - getVisibleIdWidth() + getVisibleIdWidth(false);
1376 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1380 else if (av.isShowAnnotation())
1382 height += getAnnotationPanel().adjustPanelHeight() + 3;
1385 return new AlignmentDimension(width, height);
1389 * Creates and writes an EPS image of the alignment, to the given file if
1390 * specified, else after prompting for the output file
1393 * @param forSplitFrame
1395 public void makeEPS(File epsFile, boolean forSplitFrame)
1397 makeAlignmentImage(EPS, epsFile, forSplitFrame);
1401 * Creates and writes a PNG image of the alignment, to the given file if
1402 * specified, else after prompting for the output file
1405 * @param forSplitFrame
1407 public void makePNG(File pngFile, boolean forSplitFrame)
1409 makeAlignmentImage(PNG, pngFile, forSplitFrame);
1413 * Creates and writes an SVG image of the alignment, to the given file if
1414 * specified, else after prompting for the output file
1417 * @param forSplitFrame
1419 public void makeSVG(File svgFile, boolean forSplitFrame)
1421 makeAlignmentImage(SVG, svgFile, forSplitFrame);
1424 public void makePNGImageMap(File imgMapFile, String imageName)
1426 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1427 // ////////////////////////////////////////////
1428 int idWidth = getVisibleIdWidth(false);
1429 FontMetrics fm = getFontMetrics(av.getFont());
1430 int scaleHeight = av.getCharHeight() + fm.getDescent();
1433 // ////////////////////////////////
1434 if (imgMapFile != null)
1438 int sSize = av.getAlignment().getHeight();
1439 int alwidth = av.getAlignment().getWidth();
1440 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1441 out.println(HTMLOutput.getImageMapHTML());
1442 out.println("<img src=\"" + imageName
1443 + "\" border=\"0\" usemap=\"#Map\" >"
1444 + "<map name=\"Map\">");
1446 for (int s = 0; s < sSize; s++)
1448 int sy = s * av.getCharHeight() + scaleHeight;
1450 SequenceI seq = av.getAlignment().getSequenceAt(s);
1451 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1452 for (int column = 0; column < alwidth; column++)
1454 StringBuilder text = new StringBuilder(512);
1455 String triplet = null;
1456 if (av.getAlignment().isNucleotide())
1458 triplet = ResidueProperties.nucleotideName.get(seq
1459 .getCharAt(column) + "");
1463 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1467 if (triplet == null)
1472 int seqPos = seq.findPosition(column);
1473 int gSize = groups.length;
1474 for (int g = 0; g < gSize; g++)
1476 if (text.length() < 1)
1478 text.append("<area shape=\"rect\" coords=\"")
1479 .append((idWidth + column * av.getCharWidth()))
1480 .append(",").append(sy).append(",")
1481 .append((idWidth + (column + 1) * av.getCharWidth()))
1482 .append(",").append((av.getCharHeight() + sy))
1483 .append("\"").append(" onMouseOver=\"toolTip('")
1484 .append(seqPos).append(" ").append(triplet);
1487 if (groups[g].getStartRes() < column
1488 && groups[g].getEndRes() > column)
1490 text.append("<br><em>").append(groups[g].getName())
1495 if (text.length() < 1)
1497 text.append("<area shape=\"rect\" coords=\"")
1498 .append((idWidth + column * av.getCharWidth()))
1499 .append(",").append(sy).append(",")
1500 .append((idWidth + (column + 1) * av.getCharWidth()))
1501 .append(",").append((av.getCharHeight() + sy))
1502 .append("\"").append(" onMouseOver=\"toolTip('")
1503 .append(seqPos).append(" ").append(triplet);
1505 if (!Comparison.isGap(seq.getCharAt(column)))
1507 List<SequenceFeature> features = seq.findFeatures(column, column);
1508 for (SequenceFeature sf : features)
1510 if (sf.isContactFeature())
1512 text.append("<br>").append(sf.getType()).append(" ")
1513 .append(sf.getBegin()).append(":")
1514 .append(sf.getEnd());
1518 text.append("<br>");
1519 text.append(sf.getType());
1520 String description = sf.getDescription();
1521 if (description != null
1522 && !sf.getType().equals(description))
1524 description = description.replace("\"", """);
1525 text.append(" ").append(description);
1528 String status = sf.getStatus();
1529 if (status != null && !"".equals(status))
1531 text.append(" (").append(status).append(")");
1534 if (text.length() > 1)
1536 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1537 out.println(text.toString());
1542 out.println("</map></body></html>");
1545 } catch (Exception ex)
1547 ex.printStackTrace();
1549 } // /////////END OF IMAGE MAP
1554 * Answers the height of the entire alignment in pixels, assuming it is in
1559 int getWrappedHeight()
1561 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1563 if (System.getProperty("java.awt.headless") != null
1564 && System.getProperty("java.awt.headless").equals("true"))
1566 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1567 - vscroll.getPreferredSize().width
1568 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1571 int chunkWidth = getSeqPanel().seqCanvas
1572 .getWrappedCanvasWidth(seqPanelWidth);
1574 int hgap = av.getCharHeight();
1575 if (av.getScaleAboveWrapped())
1577 hgap += av.getCharHeight();
1580 int annotationHeight = 0;
1581 if (av.isShowAnnotation())
1583 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1584 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1587 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1590 int maxwidth = av.getAlignment().getWidth();
1591 if (av.hasHiddenColumns())
1593 maxwidth = av.getAlignment().getHiddenColumns()
1594 .absoluteToVisibleColumn(maxwidth) - 1;
1597 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1603 * close the panel - deregisters all listeners and nulls any references to
1606 public void closePanel()
1608 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1609 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1610 PaintRefresher.RemoveComponent(this);
1615 * try to ensure references are nulled
1617 if (annotationPanel != null)
1619 annotationPanel.dispose();
1620 annotationPanel = null;
1625 av.removePropertyChangeListener(propertyChangeListener);
1626 propertyChangeListener = null;
1627 StructureSelectionManager ssm = av.getStructureSelectionManager();
1628 ssm.removeStructureViewerListener(getSeqPanel(), null);
1629 ssm.removeSelectionListener(getSeqPanel());
1630 ssm.removeCommandListener(av);
1631 ssm.removeStructureViewerListener(getSeqPanel(), null);
1632 ssm.removeSelectionListener(getSeqPanel());
1638 if (Cache.log.isDebugEnabled())
1640 Cache.log.warn("Closing alignment panel which is already closed.");
1646 * Close any open dialogs that would be orphaned when this one is closed
1648 protected void closeChildFrames()
1650 if (overviewPanel != null)
1652 overviewPanel.dispose();
1653 overviewPanel = null;
1655 if (calculationDialog != null)
1657 calculationDialog.closeFrame();
1658 calculationDialog = null;
1663 * hides or shows dynamic annotation rows based on groups and av state flags
1665 public void updateAnnotation()
1667 updateAnnotation(false, false);
1670 public void updateAnnotation(boolean applyGlobalSettings)
1672 updateAnnotation(applyGlobalSettings, false);
1675 public void updateAnnotation(boolean applyGlobalSettings,
1676 boolean preserveNewGroupSettings)
1678 av.updateGroupAnnotationSettings(applyGlobalSettings,
1679 preserveNewGroupSettings);
1680 adjustAnnotationHeight();
1684 public AlignmentI getAlignment()
1686 return av == null ? null : av.getAlignment();
1690 public String getViewName()
1692 return av.getViewName();
1696 * Make/Unmake this alignment panel the current input focus
1700 public void setSelected(boolean b)
1704 if (alignFrame.getSplitViewContainer() != null)
1707 * bring enclosing SplitFrame to front first if there is one
1709 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1711 alignFrame.setSelected(b);
1712 } catch (Exception ex)
1718 alignFrame.setDisplayedView(this);
1723 public StructureSelectionManager getStructureSelectionManager()
1725 return av.getStructureSelectionManager();
1729 public void raiseOOMWarning(String string, OutOfMemoryError error)
1731 new OOMWarning(string, error, this);
1735 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1738 return new FeatureRenderer(this);
1742 public jalview.api.FeatureRenderer getFeatureRenderer()
1744 return seqPanel.seqCanvas.getFeatureRenderer();
1747 public void updateFeatureRenderer(
1748 jalview.renderer.seqfeatures.FeatureRenderer fr)
1750 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1753 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1755 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1757 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1761 public ScalePanel getScalePanel()
1766 public void setScalePanel(ScalePanel scalePanel)
1768 this.scalePanel = scalePanel;
1771 public SeqPanel getSeqPanel()
1776 public void setSeqPanel(SeqPanel seqPanel)
1778 this.seqPanel = seqPanel;
1781 public AnnotationPanel getAnnotationPanel()
1783 return annotationPanel;
1786 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1788 this.annotationPanel = annotationPanel;
1791 public AnnotationLabels getAlabels()
1796 public void setAlabels(AnnotationLabels alabels)
1798 this.alabels = alabels;
1801 public IdPanel getIdPanel()
1806 public void setIdPanel(IdPanel idPanel)
1808 this.idPanel = idPanel;
1812 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1813 * The aim is to keep the two alignments 'lined up' on their centre columns.
1816 * holds mapped region(s) of this alignment that we are scrolling
1817 * 'to'; may be modified for sequence offset by this method
1818 * @param verticalOffset
1819 * the number of visible sequences to show above the mapped region
1821 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1823 scrollToPosition(sr, verticalOffset, true);
1827 * Set a flag to say do not scroll any (cDNA/protein) complement.
1831 protected void setToScrollComplementPanel(boolean b)
1833 this.scrollComplementaryPanel = b;
1837 * Get whether to scroll complement panel
1839 * @return true if cDNA/protein complement panels should be scrolled
1841 protected boolean isSetToScrollComplementPanel()
1843 return this.scrollComplementaryPanel;
1849 * @adjustHeight if true, try to recalculate panel height for visible
1852 protected void refresh(boolean adjustHeight)
1854 validateAnnotationDimensions(adjustHeight);
1858 // sort, repaint, update overview
1859 paintAlignment(true, false);
1863 // lightweight repaint
1870 * Property change event fired when a change is made to the viewport ranges
1871 * object associated with this alignment panel's viewport
1873 public void propertyChange(PropertyChangeEvent evt)
1875 // update this panel's scroll values based on the new viewport ranges values
1876 ViewportRanges ranges = av.getRanges();
1877 int x = ranges.getStartRes();
1878 int y = ranges.getStartSeq();
1879 setScrollValues(x, y);
1881 // now update any complementary alignment (its viewport ranges object
1882 // is different so does not get automatically updated)
1883 if (isSetToScrollComplementPanel())
1885 setToScrollComplementPanel(false);
1886 av.scrollComplementaryAlignment();
1887 setToScrollComplementPanel(true);
1892 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1893 * reference should be nulled when the dialog is closed.
1895 * @param calculationChooser
1897 public void setCalculationDialog(CalculationChooser calculationChooser)
1899 calculationDialog = calculationChooser;
1903 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1906 public CalculationChooser getCalculationDialog()
1908 return calculationDialog;