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.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.ImageExporter.ImageWriterI;
35 import jalview.io.HTMLOutput;
36 import jalview.jbgui.GAlignmentPanel;
37 import jalview.math.AlignmentDimension;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.ImageMaker;
42 import jalview.util.MessageManager;
43 import jalview.viewmodel.ViewportListenerI;
44 import jalview.viewmodel.ViewportRanges;
46 import java.awt.BorderLayout;
47 import java.awt.Color;
48 import java.awt.Container;
49 import java.awt.Dimension;
51 import java.awt.FontMetrics;
52 import java.awt.Graphics;
53 import java.awt.Graphics2D;
54 import java.awt.event.AdjustmentEvent;
55 import java.awt.event.AdjustmentListener;
56 import java.awt.event.ComponentAdapter;
57 import java.awt.event.ComponentEvent;
58 import java.awt.print.PageFormat;
59 import java.awt.print.Printable;
60 import java.awt.print.PrinterException;
61 import java.beans.PropertyChangeEvent;
62 import java.beans.PropertyChangeListener;
64 import java.io.FileWriter;
65 import java.io.PrintWriter;
66 import java.util.List;
68 import javax.swing.SwingUtilities;
74 * @version $Revision: 1.161 $
76 public class AlignmentPanel extends GAlignmentPanel implements
77 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
79 public AlignViewport av;
81 OverviewPanel overviewPanel;
83 private SeqPanel seqPanel;
85 private IdPanel idPanel;
87 IdwidthAdjuster idwidthAdjuster;
89 public AlignFrame alignFrame;
91 private ScalePanel scalePanel;
93 private AnnotationPanel annotationPanel;
95 private AnnotationLabels alabels;
97 private int hextent = 0;
99 private int vextent = 0;
102 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
103 * false, suppresses invoking the same method recursively.
105 private boolean scrollComplementaryPanel = true;
107 private PropertyChangeListener propertyChangeListener;
109 private CalculationChooser calculationDialog;
112 * Creates a new AlignmentPanel object.
117 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 setSeqPanel(new SeqPanel(av, this));
122 setIdPanel(new IdPanel(av, this));
124 setScalePanel(new ScalePanel(av, this));
126 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
127 idwidthAdjuster = new IdwidthAdjuster(this);
128 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
130 setAnnotationPanel(new AnnotationPanel(this));
131 setAlabels(new AnnotationLabels(this));
133 annotationScroller.setViewportView(getAnnotationPanel());
134 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
136 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
137 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
139 setScrollValues(0, 0);
141 hscroll.addAdjustmentListener(this);
142 vscroll.addAdjustmentListener(this);
144 addComponentListener(new ComponentAdapter()
147 public void componentResized(ComponentEvent evt)
149 // reset the viewport ranges when the alignment panel is resized
150 // in particular, this initialises the end residue value when Jalview
152 ViewportRanges ranges = av.getRanges();
153 if (av.getWrapAlignment())
155 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
156 getSeqPanel().seqCanvas.getWidth());
157 ranges.setViewportWidth(widthInRes);
161 int widthInRes = getSeqPanel().seqCanvas.getWidth()
163 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
164 / av.getCharHeight();
166 ranges.setViewportWidth(widthInRes);
167 ranges.setViewportHeight(heightInSeq);
173 final AlignmentPanel ap = this;
174 propertyChangeListener = new PropertyChangeListener()
177 public void propertyChange(PropertyChangeEvent evt)
179 if (evt.getPropertyName().equals("alignment"))
181 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
186 av.addPropertyChangeListener(propertyChangeListener);
188 av.getRanges().addPropertyChangeListener(this);
190 adjustAnnotationHeight();
195 public AlignViewportI getAlignViewport()
200 public void alignmentChanged()
202 av.alignmentChanged(this);
204 if (getCalculationDialog() != null)
206 getCalculationDialog().validateCalcTypes();
209 alignFrame.updateEditMenuBar();
211 // no idea if we need to update structure
212 paintAlignment(true, true);
219 public void fontChanged()
221 // set idCanvas bufferedImage to null
222 // to prevent drawing old image
223 FontMetrics fm = getFontMetrics(av.getFont());
225 scalePanelHolder.setPreferredSize(
226 new Dimension(10, av.getCharHeight() + fm.getDescent()));
227 idSpaceFillerPanel1.setPreferredSize(
228 new Dimension(10, av.getCharHeight() + fm.getDescent()));
229 idwidthAdjuster.invalidate();
230 scalePanelHolder.invalidate();
231 getIdPanel().getIdCanvas().gg = null;
232 getSeqPanel().seqCanvas.img = null;
233 getAnnotationPanel().adjustPanelHeight();
235 Dimension d = calculateIdWidth();
237 d.setSize(d.width + 4, d.height);
238 getIdPanel().getIdCanvas().setPreferredSize(d);
239 hscrollFillerPanel.setPreferredSize(d);
245 * Calculate the width of the alignment labels based on the displayed names
246 * and any bounds on label width set in preferences.
248 * @return Dimension giving the maximum width of the alignment label panel
249 * that should be used.
251 public Dimension calculateIdWidth()
253 // calculate sensible default width when no preference is available
255 if (av.getIdWidth() < 0)
257 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
258 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
259 r = calculateIdWidth(maxwidth);
260 av.setIdWidth(r.width);
265 r.width = av.getIdWidth();
272 * Calculate the width of the alignment labels based on the displayed names
273 * and any bounds on label width set in preferences.
276 * -1 or maximum width allowed for IdWidth
277 * @return Dimension giving the maximum width of the alignment label panel
278 * that should be used.
280 public Dimension calculateIdWidth(int maxwidth)
282 Container c = new Container();
284 FontMetrics fm = c.getFontMetrics(
285 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
287 AlignmentI al = av.getAlignment();
292 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
294 SequenceI s = al.getSequenceAt(i);
296 id = s.getDisplayId(av.getShowJVSuffix());
298 if (fm.stringWidth(id) > idWidth)
300 idWidth = fm.stringWidth(id);
306 // Also check annotation label widths
309 if (al.getAlignmentAnnotation() != null)
311 fm = c.getFontMetrics(getAlabels().getFont());
313 while (i < al.getAlignmentAnnotation().length)
315 String label = al.getAlignmentAnnotation()[i].label;
317 if (fm.stringWidth(label) > idWidth)
319 idWidth = fm.stringWidth(label);
326 return new Dimension(
327 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
331 * Highlight the given results on the alignment.
334 public void highlightSearchResults(SearchResultsI results)
336 boolean scrolled = scrollToPosition(results, 0, true, false);
338 boolean fastPaint = !(scrolled && av.getWrapAlignment());
340 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
344 * Scroll the view to show the position of the highlighted region in results
347 * @param searchResults
348 * @param redrawOverview
351 public boolean scrollToPosition(SearchResultsI searchResults,
352 boolean redrawOverview)
354 return scrollToPosition(searchResults, 0, redrawOverview, false);
358 * Scrolls the view (if necessary) to show the position of the first
359 * highlighted region in results (if any). Answers true if the view was
360 * scrolled, or false if no matched region was found, or it is already
364 * @param verticalOffset
365 * if greater than zero, allows scrolling to a position below the
366 * first displayed sequence
367 * @param redrawOverview
368 * - when set, the overview will be recalculated (takes longer)
370 * if true, try to centre the search results horizontally in the view
373 protected boolean scrollToPosition(SearchResultsI results,
374 int verticalOffset, boolean redrawOverview, boolean centre)
376 int startv, endv, starts, ends;
377 ViewportRanges ranges = av.getRanges();
379 if (results == null || results.isEmpty() || av == null
380 || av.getAlignment() == null)
384 int seqIndex = av.getAlignment().findIndex(results);
389 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
391 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
400 * To centre results, scroll to positions half the visible width
401 * left/right of the start/end positions
405 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
406 start = Math.max(start - offset, 0);
407 end = end + offset - 1;
413 if (end == seq.getEnd())
418 if (av.hasHiddenColumns())
420 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
421 start = hidden.absoluteToVisibleColumn(start);
422 end = hidden.absoluteToVisibleColumn(end);
425 if (!hidden.isVisible(r[0]))
427 // don't scroll - position isn't visible
434 * allow for offset of target sequence (actually scroll to one above it)
436 seqIndex = Math.max(0, seqIndex - verticalOffset);
437 boolean scrollNeeded = true;
439 if (!av.getWrapAlignment())
441 if ((startv = ranges.getStartRes()) >= start)
444 * Scroll left to make start of search results visible
446 setScrollValues(start, seqIndex);
448 else if ((endv = ranges.getEndRes()) <= end)
451 * Scroll right to make end of search results visible
453 setScrollValues(startv + end - endv, seqIndex);
455 else if ((starts = ranges.getStartSeq()) > seqIndex)
458 * Scroll up to make start of search results visible
460 setScrollValues(ranges.getStartRes(), seqIndex);
462 else if ((ends = ranges.getEndSeq()) <= seqIndex)
465 * Scroll down to make end of search results visible
467 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
471 * Else results are already visible - no need to scroll
473 scrollNeeded = false;
477 scrollNeeded = ranges.scrollToWrappedVisible(start);
480 paintAlignment(redrawOverview, false);
488 * @return DOCUMENT ME!
490 public OverviewPanel getOverviewPanel()
492 return overviewPanel;
501 public void setOverviewPanel(OverviewPanel op)
509 * Hide or show annotation panel
512 public void setAnnotationVisible(boolean b)
514 if (!av.getWrapAlignment())
516 annotationSpaceFillerHolder.setVisible(b);
517 annotationScroller.setVisible(b);
523 * automatically adjust annotation panel height for new annotation whilst
524 * ensuring the alignment is still visible.
527 public void adjustAnnotationHeight()
529 // TODO: display vertical annotation scrollbar if necessary
530 // this is called after loading new annotation onto alignment
531 if (alignFrame.getHeight() == 0)
533 System.out.println("NEEDS FIXING");
535 validateAnnotationDimensions(true);
537 // TODO: many places call this method and also paintAlignment with various
538 // different settings. this means multiple redraws are triggered...
539 paintAlignment(true, false);
543 * calculate the annotation dimensions and refresh slider values accordingly.
544 * need to do repaints/notifys afterwards.
546 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
548 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
549 annotationHeight = getAnnotationPanel()
550 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
553 annotationScroller.setPreferredSize(
554 new Dimension(annotationScroller.getWidth(), annotationHeight));
556 Dimension e = idPanel.getSize();
557 alabels.setSize(new Dimension(e.width, annotationHeight));
559 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
560 annotationSpaceFillerHolder.getWidth(), annotationHeight));
561 annotationScroller.validate();
562 annotationScroller.addNotify();
566 * update alignment layout for viewport settings
571 public void updateLayout()
574 setAnnotationVisible(av.isShowAnnotation());
575 boolean wrap = av.getWrapAlignment();
576 ViewportRanges ranges = av.getRanges();
577 ranges.setStartSeq(0);
578 scalePanelHolder.setVisible(!wrap);
579 hscroll.setVisible(!wrap);
580 idwidthAdjuster.setVisible(!wrap);
584 annotationScroller.setVisible(false);
585 annotationSpaceFillerHolder.setVisible(false);
587 else if (av.isShowAnnotation())
589 annotationScroller.setVisible(true);
590 annotationSpaceFillerHolder.setVisible(true);
591 validateAnnotationDimensions(false);
594 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
596 { // may not yet be laid out
599 int widthInRes = getSeqPanel().seqCanvas
600 .getWrappedCanvasWidth(canvasWidth);
601 ranges.setViewportWidth(widthInRes);
605 int widthInRes = (canvasWidth / av.getCharWidth());
606 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
607 / av.getCharHeight());
609 ranges.setViewportWidth(widthInRes);
610 ranges.setViewportHeight(heightInSeq);
614 idSpaceFillerPanel1.setVisible(!wrap);
620 * Adjust row/column scrollers to show a visible position in the alignment.
623 * visible column to scroll to
625 * visible row to scroll to
628 public void setScrollValues(int xpos, int ypos)
633 if (av == null || av.getAlignment() == null)
638 if (av.getWrapAlignment())
640 setScrollingForWrappedPanel(x);
644 int width = av.getAlignment().getWidth();
645 int height = av.getAlignment().getHeight();
647 if (av.hasHiddenColumns())
649 // reset the width to exclude hidden columns
650 width = av.getAlignment().getHiddenColumns()
651 .absoluteToVisibleColumn(width);
654 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
655 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
662 if (vextent > height)
667 if ((hextent + x) > width)
672 if ((vextent + y) > height)
674 y = height - vextent;
687 // update the scroll values
688 hscroll.setValues(x, hextent, 0, width);
689 vscroll.setValues(y, vextent, 0, height);
694 * Respond to adjustment event when horizontal or vertical scrollbar is
698 * adjustment event encoding whether hscroll or vscroll changed
701 public void adjustmentValueChanged(AdjustmentEvent evt)
703 if (av.getWrapAlignment())
705 adjustScrollingWrapped(evt);
709 ViewportRanges ranges = av.getRanges();
711 if (evt.getSource() == hscroll)
713 int oldX = ranges.getStartRes();
714 int oldwidth = ranges.getViewportWidth();
715 int x = hscroll.getValue();
716 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
718 // if we're scrolling to the position we're already at, stop
719 // this prevents infinite recursion of events when the scroll/viewport
720 // ranges values are the same
721 if ((x == oldX) && (width == oldwidth))
725 ranges.setViewportStartAndWidth(x, width);
727 else if (evt.getSource() == vscroll)
729 int oldY = ranges.getStartSeq();
730 int oldheight = ranges.getViewportHeight();
731 int y = vscroll.getValue();
732 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
734 // if we're scrolling to the position we're already at, stop
735 // this prevents infinite recursion of events when the scroll/viewport
736 // ranges values are the same
737 if ((y == oldY) && (height == oldheight))
741 ranges.setViewportStartAndHeight(y, height);
747 * Responds to a scroll change by setting the start position of the viewport.
752 protected void adjustScrollingWrapped(AdjustmentEvent evt)
754 if (evt.getSource() == hscroll)
756 return; // no horizontal scroll when wrapped
758 final ViewportRanges ranges = av.getRanges();
760 if (evt.getSource() == vscroll)
762 int newY = vscroll.getValue();
765 * if we're scrolling to the position we're already at, stop
766 * this prevents infinite recursion of events when the scroll/viewport
767 * ranges values are the same
769 int oldX = ranges.getStartRes();
770 int oldY = ranges.getWrappedScrollPosition(oldX);
778 * limit page up/down to one width's worth of positions
780 int rowSize = ranges.getViewportWidth();
781 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
782 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
787 // This is only called if file loaded is a jar file that
788 // was wrapped when saved and user has wrap alignment true
789 // as preference setting
790 SwingUtilities.invokeLater(new Runnable()
795 // When updating scrolling to use ViewportChange events, this code
796 // could not be validated and it is not clear if it is now being
797 // called. Log warning here in case it is called and unforeseen
800 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
802 // scroll to start of panel
803 ranges.setStartRes(0);
804 ranges.setStartSeq(0);
812 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
815 public void paintAlignment(boolean updateOverview,
816 boolean updateStructures)
818 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
819 av.isShowAutocalculatedAbove());
820 sorter.sort(getAlignment().getAlignmentAnnotation(),
821 av.getSortAnnotationsBy());
824 if (updateStructures)
826 av.getStructureSelectionManager().sequenceColoursChanged(this);
831 if (overviewPanel != null)
833 overviewPanel.updateOverviewImage();
845 public void paintComponent(Graphics g)
847 invalidate(); // needed so that the id width adjuster works correctly
849 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
850 idPanelHolder.setPreferredSize(d);
851 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
853 validate(); // needed so that the id width adjuster works correctly
856 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
857 * though I still think this call should be elsewhere.
859 ViewportRanges ranges = av.getRanges();
860 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
864 * Set vertical scroll bar position, and number of increments, for wrapped
867 * @param topLeftColumn
868 * the column position at top left (0..)
870 private void setScrollingForWrappedPanel(int topLeftColumn)
872 ViewportRanges ranges = av.getRanges();
873 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
874 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
877 * a scrollbar's value can be set to at most (maximum-extent)
878 * so we add extent (1) to the maxScroll value
880 vscroll.setUnitIncrement(1);
881 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
894 * @return DOCUMENT ME!
896 * @throws PrinterException
900 public int print(Graphics pg, PageFormat pf, int pi)
901 throws PrinterException
903 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
905 int pwidth = (int) pf.getImageableWidth();
906 int pheight = (int) pf.getImageableHeight();
908 if (av.getWrapAlignment())
910 return printWrappedAlignment(pwidth, pheight, pi, pg);
914 return printUnwrapped(pwidth, pheight, pi, pg, pg);
919 * Draws the alignment image, including sequence ids, sequences, and
920 * annotation labels and annotations if shown, on either one or two Graphics
930 * the graphics context for sequence ids and annotation labels
931 * @param alignmentGraphics
932 * the graphics context for sequences and annotations (may or may not
933 * be the same context as idGraphics)
935 * @throws PrinterException
937 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
938 Graphics idGraphics, Graphics alignmentGraphics)
939 throws PrinterException
941 final int idWidth = getVisibleIdWidth(false);
944 * Get the horizontal offset to where we draw the sequences.
945 * This is idWidth if using a single Graphics context, else zero.
947 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
950 FontMetrics fm = getFontMetrics(av.getFont());
951 final int charHeight = av.getCharHeight();
952 final int scaleHeight = charHeight + fm.getDescent();
954 idGraphics.setColor(Color.white);
955 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
956 idGraphics.setFont(av.getFont());
959 * How many sequences and residues can we fit on a printable page?
961 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
963 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
965 final int alignmentWidth = av.getAlignment().getWidth();
966 final int pagesWide = (alignmentWidth / totalRes) + 1;
968 final int startRes = (pageIndex % pagesWide) * totalRes;
969 final int endRes = Math.min(startRes + totalRes - 1,
972 final int startSeq = (pageIndex / pagesWide) * totalSeq;
973 final int alignmentHeight = av.getAlignment().getHeight();
974 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
976 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
978 if (av.isShowAnnotation())
980 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
983 pagesHigh /= pageHeight;
985 if (pageIndex >= (pagesWide * pagesHigh))
987 return Printable.NO_SUCH_PAGE;
989 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
992 * draw the Scale at horizontal offset, then reset to top left (0, 0)
994 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
995 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
996 pageWidth - idWidth, scaleHeight);
997 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1000 * Draw the sequence ids, offset for scale height,
1001 * then reset to top left (0, 0)
1003 idGraphics.translate(0, scaleHeight);
1004 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1005 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1006 : av.getSelectionGroup().getSequences(null);
1007 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1010 idGraphics.setFont(av.getFont());
1011 idGraphics.translate(0, -scaleHeight);
1014 * draw the sequences, offset for scale height, and id width (if using a
1015 * single graphics context), then reset to (0, scale height)
1017 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1018 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1019 endRes, startSeq, endSeq - 1);
1020 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1022 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1025 * draw annotation labels; drawComponent() translates by
1026 * getScrollOffset(), so compensate for that first;
1027 * then reset to (0, scale height)
1029 int offset = getAlabels().getScrollOffset();
1030 idGraphics.translate(0, -offset);
1031 idGraphics.translate(0, alignmentDrawnHeight);
1032 getAlabels().drawComponent(idGraphics, idWidth);
1033 idGraphics.translate(0, -alignmentDrawnHeight);
1036 * draw the annotations starting at
1037 * (idOffset, alignmentHeight) from (0, scaleHeight)
1039 alignmentGraphics.translate(alignmentGraphicsOffset,
1040 alignmentDrawnHeight);
1041 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1042 alignmentGraphics, -1, startRes, endRes + 1);
1045 return Printable.PAGE_EXISTS;
1049 * Prints one page of an alignment in wrapped mode. Returns
1050 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1051 * no page could be drawn (page number out of range).
1061 * @throws PrinterException
1063 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1064 Graphics g) throws PrinterException
1066 int annotationHeight = 0;
1067 if (av.isShowAnnotation())
1069 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1072 int hgap = av.getCharHeight();
1073 if (av.getScaleAboveWrapped())
1075 hgap += av.getCharHeight();
1078 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1081 int idWidth = getVisibleIdWidth(false);
1083 int maxwidth = av.getAlignment().getWidth();
1084 if (av.hasHiddenColumns())
1086 maxwidth = av.getAlignment().getHiddenColumns()
1087 .absoluteToVisibleColumn(maxwidth) - 1;
1090 int resWidth = getSeqPanel().seqCanvas
1091 .getWrappedCanvasWidth(pageWidth - idWidth);
1093 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1095 g.setColor(Color.white);
1096 g.fillRect(0, 0, pageWidth, pageHeight);
1097 g.setFont(av.getFont());
1098 g.setColor(Color.black);
1101 * method: print the whole wrapped alignment, but with a clip region that
1102 * is restricted to the requested page; this supports selective print of
1103 * single pages or ranges, (at the cost of some repeated processing in
1104 * the 'normal' case, when all pages are printed)
1106 g.translate(0, -pageNumber * pageHeight);
1108 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1111 * draw sequence ids and annotation labels (if shown)
1113 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1114 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1116 g.translate(idWidth, 0);
1118 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1121 if ((pageNumber * pageHeight) < totalHeight)
1123 return Printable.PAGE_EXISTS;
1127 return Printable.NO_SUCH_PAGE;
1132 * get current sequence ID panel width, or nominal value if panel were to be
1133 * displayed using default settings
1137 public int getVisibleIdWidth()
1139 return getVisibleIdWidth(true);
1143 * get current sequence ID panel width, or nominal value if panel were to be
1144 * displayed using default settings
1147 * indicate if the Id width for onscreen or offscreen display should
1151 public int getVisibleIdWidth(boolean onscreen)
1153 // see if rendering offscreen - check preferences and calc width accordingly
1154 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1156 return calculateIdWidth(-1).width + 4;
1158 Integer idwidth = null;
1159 if (onscreen || (idwidth = Cache
1160 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1162 int w = getIdPanel().getWidth();
1163 return (w > 0 ? w : calculateIdWidth().width + 4);
1165 return idwidth.intValue() + 4;
1169 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1170 * writes it to the specified file
1175 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1177 final int borderBottomOffset = 5;
1179 AlignmentDimension aDimension = getAlignmentDimension();
1180 // todo use a lambda function in place of callback here?
1181 ImageWriterI writer = new ImageWriterI()
1184 public void exportImage(Graphics graphics) throws Exception
1186 if (av.getWrapAlignment())
1188 printWrappedAlignment(aDimension.getWidth(),
1189 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1193 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1194 graphics, graphics);
1199 String fileTitle = alignFrame.getTitle();
1200 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1202 int imageWidth = aDimension.getWidth();
1203 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1204 String of = MessageManager.getString("label.alignment");
1205 exporter.doExport(file, this, imageWidth, imageHeight, of);
1209 * Calculates and returns a suitable width and height (in pixels) for an
1214 public AlignmentDimension getAlignmentDimension()
1216 int maxwidth = av.getAlignment().getWidth();
1217 if (av.hasHiddenColumns())
1219 maxwidth = av.getAlignment().getHiddenColumns()
1220 .absoluteToVisibleColumn(maxwidth);
1223 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1224 + getScalePanel().getHeight();
1225 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1227 if (av.getWrapAlignment())
1229 height = getWrappedHeight();
1230 if (Jalview.isHeadlessMode())
1232 // need to obtain default alignment width and then add in any
1233 // additional allowance for id margin
1234 // this duplicates the calculation in getWrappedHeight but adjusts for
1236 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1237 - alignFrame.getInsets().left - alignFrame.getInsets().right
1238 - getVisibleIdWidth() + getVisibleIdWidth(false);
1242 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1246 else if (av.isShowAnnotation())
1248 height += getAnnotationPanel().adjustPanelHeight() + 3;
1250 return new AlignmentDimension(width, height);
1254 public void makePNGImageMap(File imgMapFile, String imageName)
1256 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1257 // ////////////////////////////////////////////
1258 int idWidth = getVisibleIdWidth(false);
1259 FontMetrics fm = getFontMetrics(av.getFont());
1260 int scaleHeight = av.getCharHeight() + fm.getDescent();
1263 // ////////////////////////////////
1264 if (imgMapFile != null)
1268 int sSize = av.getAlignment().getHeight();
1269 int alwidth = av.getAlignment().getWidth();
1270 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1271 out.println(HTMLOutput.getImageMapHTML());
1272 out.println("<img src=\"" + imageName
1273 + "\" border=\"0\" usemap=\"#Map\" >"
1274 + "<map name=\"Map\">");
1276 for (int s = 0; s < sSize; s++)
1278 int sy = s * av.getCharHeight() + scaleHeight;
1280 SequenceI seq = av.getAlignment().getSequenceAt(s);
1281 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1282 for (int column = 0; column < alwidth; column++)
1284 StringBuilder text = new StringBuilder(512);
1285 String triplet = null;
1286 if (av.getAlignment().isNucleotide())
1288 triplet = ResidueProperties.nucleotideName.get(seq
1289 .getCharAt(column) + "");
1293 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1297 if (triplet == null)
1302 int seqPos = seq.findPosition(column);
1303 int gSize = groups.length;
1304 for (int g = 0; g < gSize; g++)
1306 if (text.length() < 1)
1308 text.append("<area shape=\"rect\" coords=\"")
1309 .append((idWidth + column * av.getCharWidth()))
1310 .append(",").append(sy).append(",")
1311 .append((idWidth + (column + 1) * av.getCharWidth()))
1312 .append(",").append((av.getCharHeight() + sy))
1313 .append("\"").append(" onMouseOver=\"toolTip('")
1314 .append(seqPos).append(" ").append(triplet);
1317 if (groups[g].getStartRes() < column
1318 && groups[g].getEndRes() > column)
1320 text.append("<br><em>").append(groups[g].getName())
1325 if (text.length() < 1)
1327 text.append("<area shape=\"rect\" coords=\"")
1328 .append((idWidth + column * av.getCharWidth()))
1329 .append(",").append(sy).append(",")
1330 .append((idWidth + (column + 1) * av.getCharWidth()))
1331 .append(",").append((av.getCharHeight() + sy))
1332 .append("\"").append(" onMouseOver=\"toolTip('")
1333 .append(seqPos).append(" ").append(triplet);
1335 if (!Comparison.isGap(seq.getCharAt(column)))
1337 List<SequenceFeature> features = seq.findFeatures(column, column);
1338 for (SequenceFeature sf : features)
1340 if (sf.isContactFeature())
1342 text.append("<br>").append(sf.getType()).append(" ")
1343 .append(sf.getBegin()).append(":")
1344 .append(sf.getEnd());
1348 text.append("<br>");
1349 text.append(sf.getType());
1350 String description = sf.getDescription();
1351 if (description != null
1352 && !sf.getType().equals(description))
1354 description = description.replace("\"", """);
1355 text.append(" ").append(description);
1358 String status = sf.getStatus();
1359 if (status != null && !"".equals(status))
1361 text.append(" (").append(status).append(")");
1364 if (text.length() > 1)
1366 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1367 out.println(text.toString());
1372 out.println("</map></body></html>");
1375 } catch (Exception ex)
1377 ex.printStackTrace();
1379 } // /////////END OF IMAGE MAP
1383 int getWrappedHeight()
1385 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1387 if (System.getProperty("java.awt.headless") != null
1388 && System.getProperty("java.awt.headless").equals("true"))
1390 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1391 - vscroll.getPreferredSize().width
1392 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1395 int chunkWidth = getSeqPanel().seqCanvas
1396 .getWrappedCanvasWidth(seqPanelWidth);
1398 int hgap = av.getCharHeight();
1399 if (av.getScaleAboveWrapped())
1401 hgap += av.getCharHeight();
1404 int annotationHeight = 0;
1405 if (av.isShowAnnotation())
1407 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1410 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1413 int maxwidth = av.getAlignment().getWidth();
1414 if (av.hasHiddenColumns())
1416 maxwidth = av.getAlignment().getHiddenColumns()
1417 .absoluteToVisibleColumn(maxwidth) - 1;
1420 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1426 * close the panel - deregisters all listeners and nulls any references to
1429 public void closePanel()
1431 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1432 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1433 PaintRefresher.RemoveComponent(this);
1438 * try to ensure references are nulled
1440 if (annotationPanel != null)
1442 annotationPanel.dispose();
1443 annotationPanel = null;
1448 av.removePropertyChangeListener(propertyChangeListener);
1449 propertyChangeListener = null;
1450 StructureSelectionManager ssm = av.getStructureSelectionManager();
1451 ssm.removeStructureViewerListener(getSeqPanel(), null);
1452 ssm.removeSelectionListener(getSeqPanel());
1453 ssm.removeCommandListener(av);
1454 ssm.removeStructureViewerListener(getSeqPanel(), null);
1455 ssm.removeSelectionListener(getSeqPanel());
1461 if (Cache.log.isDebugEnabled())
1463 Cache.log.warn("Closing alignment panel which is already closed.");
1469 * Close any open dialogs that would be orphaned when this one is closed
1471 protected void closeChildFrames()
1473 if (overviewPanel != null)
1475 overviewPanel.dispose();
1476 overviewPanel = null;
1478 if (calculationDialog != null)
1480 calculationDialog.closeFrame();
1481 calculationDialog = null;
1486 * hides or shows dynamic annotation rows based on groups and av state flags
1488 public void updateAnnotation()
1490 updateAnnotation(false, false);
1493 public void updateAnnotation(boolean applyGlobalSettings)
1495 updateAnnotation(applyGlobalSettings, false);
1498 public void updateAnnotation(boolean applyGlobalSettings,
1499 boolean preserveNewGroupSettings)
1501 av.updateGroupAnnotationSettings(applyGlobalSettings,
1502 preserveNewGroupSettings);
1503 adjustAnnotationHeight();
1507 public AlignmentI getAlignment()
1509 return av == null ? null : av.getAlignment();
1513 public String getViewName()
1515 return av.getViewName();
1519 * Make/Unmake this alignment panel the current input focus
1523 public void setSelected(boolean b)
1527 if (alignFrame.getSplitViewContainer() != null)
1530 * bring enclosing SplitFrame to front first if there is one
1532 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1534 alignFrame.setSelected(b);
1535 } catch (Exception ex)
1541 alignFrame.setDisplayedView(this);
1546 public StructureSelectionManager getStructureSelectionManager()
1548 return av.getStructureSelectionManager();
1552 public void raiseOOMWarning(String string, OutOfMemoryError error)
1554 new OOMWarning(string, error, this);
1558 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1561 return new FeatureRenderer(this);
1565 public jalview.api.FeatureRenderer getFeatureRenderer()
1567 return seqPanel.seqCanvas.getFeatureRenderer();
1570 public void updateFeatureRenderer(
1571 jalview.renderer.seqfeatures.FeatureRenderer fr)
1573 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1576 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1578 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1580 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1584 public ScalePanel getScalePanel()
1589 public void setScalePanel(ScalePanel scalePanel)
1591 this.scalePanel = scalePanel;
1594 public SeqPanel getSeqPanel()
1599 public void setSeqPanel(SeqPanel seqPanel)
1601 this.seqPanel = seqPanel;
1604 public AnnotationPanel getAnnotationPanel()
1606 return annotationPanel;
1609 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1611 this.annotationPanel = annotationPanel;
1614 public AnnotationLabels getAlabels()
1619 public void setAlabels(AnnotationLabels alabels)
1621 this.alabels = alabels;
1624 public IdPanel getIdPanel()
1629 public void setIdPanel(IdPanel idPanel)
1631 this.idPanel = idPanel;
1635 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1636 * The aim is to keep the two alignments 'lined up' on their centre columns.
1639 * holds mapped region(s) of this alignment that we are scrolling
1640 * 'to'; may be modified for sequence offset by this method
1641 * @param verticalOffset
1642 * the number of visible sequences to show above the mapped region
1644 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1646 scrollToPosition(sr, verticalOffset, true, true);
1650 * Set a flag to say do not scroll any (cDNA/protein) complement.
1654 protected void setToScrollComplementPanel(boolean b)
1656 this.scrollComplementaryPanel = b;
1660 * Get whether to scroll complement panel
1662 * @return true if cDNA/protein complement panels should be scrolled
1664 protected boolean isSetToScrollComplementPanel()
1666 return this.scrollComplementaryPanel;
1672 * @adjustHeight if true, try to recalculate panel height for visible
1675 protected void refresh(boolean adjustHeight)
1677 validateAnnotationDimensions(adjustHeight);
1681 // sort, repaint, update overview
1682 paintAlignment(true, false);
1686 // lightweight repaint
1693 * Property change event fired when a change is made to the viewport ranges
1694 * object associated with this alignment panel's viewport
1696 public void propertyChange(PropertyChangeEvent evt)
1698 // update this panel's scroll values based on the new viewport ranges values
1699 ViewportRanges ranges = av.getRanges();
1700 int x = ranges.getStartRes();
1701 int y = ranges.getStartSeq();
1702 setScrollValues(x, y);
1704 // now update any complementary alignment (its viewport ranges object
1705 // is different so does not get automatically updated)
1706 if (isSetToScrollComplementPanel())
1708 setToScrollComplementPanel(false);
1709 av.scrollComplementaryAlignment();
1710 setToScrollComplementPanel(true);
1715 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1716 * reference should be nulled when the dialog is closed.
1718 * @param calculationChooser
1720 public void setCalculationDialog(CalculationChooser calculationChooser)
1722 calculationDialog = calculationChooser;
1726 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1729 public CalculationChooser getCalculationDialog()
1731 return calculationDialog;