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.api.SequenceRenderer;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.ImageExporter.ImageWriterI;
36 import jalview.io.HTMLOutput;
37 import jalview.jbgui.GAlignmentPanel;
38 import jalview.math.AlignmentDimension;
39 import jalview.schemes.ResidueProperties;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.Comparison;
42 import jalview.util.ImageMaker;
43 import jalview.util.MessageManager;
44 import jalview.viewmodel.ViewportListenerI;
45 import jalview.viewmodel.ViewportRanges;
47 import java.awt.BorderLayout;
48 import java.awt.Color;
49 import java.awt.Container;
50 import java.awt.Dimension;
52 import java.awt.FontMetrics;
53 import java.awt.Graphics;
54 import java.awt.Graphics2D;
55 import java.awt.event.AdjustmentEvent;
56 import java.awt.event.AdjustmentListener;
57 import java.awt.event.ComponentAdapter;
58 import java.awt.event.ComponentEvent;
59 import java.awt.image.BufferedImage;
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;
71 * The main panel of an AlignFrame, containing holders for the IdPanel,
72 * SeqPanel, AnnotationLabels (a JPanel), and AnnotationPanel.
74 * Additional holders contain an IdPanelWidthAdjuster space above the idPanel,
75 * AnnotationScroller (JScrollPane for AnnotationPanel), and vertical and
76 * horizontal scrollbars.
81 * @version $Revision: 1.161 $
83 @SuppressWarnings("serial")
84 public class AlignmentPanel extends GAlignmentPanel implements
85 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
87 public AlignViewport av;
89 OverviewPanel overviewPanel;
91 private SeqPanel seqPanel;
93 private IdPanel idPanel;
95 IdwidthAdjuster idwidthAdjuster;
97 public AlignFrame alignFrame;
99 private ScalePanel scalePanel;
101 private AnnotationPanel annotationPanel;
103 private AnnotationLabels alabels;
105 private int hextent = 0;
107 private int vextent = 0;
110 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
111 * false, suppresses invoking the same method recursively.
113 private boolean scrollComplementaryPanel = true;
115 private PropertyChangeListener propertyChangeListener;
117 private CalculationChooser calculationDialog;
120 * Creates a new AlignmentPanel object.
125 public AlignmentPanel(AlignFrame af, final AlignViewport av)
127 setBackground(Color.white); // BH 2019
131 setSeqPanel(new SeqPanel(av, this));
132 setIdPanel(new IdPanel(av, this));
134 setScalePanel(new ScalePanel(av, this));
136 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
137 idwidthAdjuster = new IdwidthAdjuster(this);
138 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
140 setAnnotationPanel(new AnnotationPanel(this));
141 setAlabels(new AnnotationLabels(this));
143 annotationScroller.setViewportView(getAnnotationPanel());
144 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
145 if (!av.isShowAnnotation())
147 annotationScroller.setVisible(false);
148 annotationSpaceFillerHolder.setVisible(false);
150 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
151 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
153 setScrollValues(0, 0);
155 hscroll.addAdjustmentListener(this);
156 vscroll.addAdjustmentListener(this);
158 addComponentListener(new ComponentAdapter()
161 public void componentResized(ComponentEvent evt)
163 // reset the viewport ranges when the alignment panel is resized
164 // in particular, this initialises the end residue value when Jalview
166 ViewportRanges ranges = av.getRanges();
167 if (av.getWrapAlignment())
169 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
170 getSeqPanel().seqCanvas.getWidth());
171 ranges.setViewportWidth(widthInRes);
175 int widthInRes = getSeqPanel().seqCanvas.getWidth()
177 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
178 / av.getCharHeight();
180 ranges.setViewportWidth(widthInRes);
181 ranges.setViewportHeight(heightInSeq);
187 final AlignmentPanel ap = this;
188 propertyChangeListener = new PropertyChangeListener()
191 public void propertyChange(PropertyChangeEvent evt)
193 if (evt.getPropertyName().equals("alignment"))
195 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
200 av.addPropertyChangeListener(propertyChangeListener);
202 av.getRanges().addPropertyChangeListener(this);
204 adjustAnnotationHeight();
209 public AlignViewportI getAlignViewport()
214 public void alignmentChanged()
216 av.alignmentChanged(this);
218 if (getCalculationDialog() != null)
220 getCalculationDialog().validateCalcTypes();
223 alignFrame.updateEditMenuBar();
225 // no idea if we need to update structure
226 paintAlignment(true, true);
233 public void fontChanged()
235 // set idCanvas bufferedImage to null
236 // to prevent drawing old image
237 FontMetrics fm = getFontMetrics(av.getFont());
239 scalePanelHolder.setPreferredSize(
240 new Dimension(10, av.getCharHeight() + fm.getDescent()));
241 idSpaceFillerPanel1.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idwidthAdjuster.invalidate();
244 scalePanelHolder.invalidate();
245 // BH 2018 getIdPanel().getIdCanvas().gg = null;
246 getSeqPanel().seqCanvas.img = null;
247 getAnnotationPanel().adjustPanelHeight();
249 Dimension d = calculateIdWidth();
251 d.setSize(d.width + 4, d.height);
252 getIdPanel().getIdCanvas().setPreferredSize(d);
253 hscrollFillerPanel.setPreferredSize(d);
259 * Calculate the width of the alignment labels based on the displayed names
260 * and any bounds on label width set in preferences.
262 * @return Dimension giving the maximum width of the alignment label panel
263 * that should be used.
265 public Dimension calculateIdWidth()
267 // calculate sensible default width when no preference is available
269 if (av.getIdWidth() < 0)
271 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
272 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
273 r = calculateIdWidth(maxwidth);
274 av.setIdWidth(r.width);
279 r.width = av.getIdWidth();
286 * Calculate the width of the alignment labels based on the displayed names
287 * and any bounds on label width set in preferences.
290 * -1 or maximum width allowed for IdWidth
291 * @return Dimension giving the maximum width of the alignment label panel
292 * that should be used.
294 public Dimension calculateIdWidth(int maxwidth)
296 Container c = new Container();
298 FontMetrics fm = c.getFontMetrics(
299 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
301 AlignmentI al = av.getAlignment();
306 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
308 SequenceI s = al.getSequenceAt(i);
310 id = s.getDisplayId(av.getShowJVSuffix());
312 if (fm.stringWidth(id) > idWidth)
314 idWidth = fm.stringWidth(id);
320 // Also check annotation label widths
323 if (al.getAlignmentAnnotation() != null)
325 fm = c.getFontMetrics(getAlabels().getFont());
327 while (i < al.getAlignmentAnnotation().length)
329 String label = al.getAlignmentAnnotation()[i].label;
331 if (fm.stringWidth(label) > idWidth)
333 idWidth = fm.stringWidth(label);
340 return new Dimension(
341 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
345 * Highlight the given results on the alignment
348 public void highlightSearchResults(SearchResultsI results)
350 boolean scrolled = scrollToPosition(results, 0, false);
352 boolean fastPaint = !(scrolled && av.getWrapAlignment());
354 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
358 * Scroll the view to show the position of the highlighted region in results
361 * @param searchResults
364 public boolean scrollToPosition(SearchResultsI searchResults)
366 return scrollToPosition(searchResults, 0, false);
370 * Scrolls the view (if necessary) to show the position of the first
371 * highlighted region in results (if any). Answers true if the view was
372 * scrolled, or false if no matched region was found, or it is already
376 * @param verticalOffset
377 * if greater than zero, allows scrolling to a position below the
378 * first displayed sequence
380 * if true, try to centre the search results horizontally in the view
383 protected boolean scrollToPosition(SearchResultsI results,
384 int verticalOffset, boolean centre)
386 int startv, endv, starts, ends;
387 ViewportRanges ranges = av.getRanges();
389 if (results == null || results.isEmpty() || av == null
390 || av.getAlignment() == null)
394 int seqIndex = av.getAlignment().findIndex(results);
399 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
401 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
410 * To centre results, scroll to positions half the visible width
411 * left/right of the start/end positions
415 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
416 start = Math.max(start - offset, 0);
417 end = end + offset - 1;
423 if (end == seq.getEnd())
428 if (av.hasHiddenColumns())
430 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
431 start = hidden.absoluteToVisibleColumn(start);
432 end = hidden.absoluteToVisibleColumn(end);
435 if (!hidden.isVisible(r[0]))
437 // don't scroll - position isn't visible
444 * allow for offset of target sequence (actually scroll to one above it)
446 seqIndex = Math.max(0, seqIndex - verticalOffset);
447 boolean scrollNeeded = true;
449 if (!av.getWrapAlignment())
451 if ((startv = ranges.getStartRes()) >= start)
454 * Scroll left to make start of search results visible
456 setScrollValues(start, seqIndex);
458 else if ((endv = ranges.getEndRes()) <= end)
461 * Scroll right to make end of search results visible
463 setScrollValues(startv + end - endv, seqIndex);
465 else if ((starts = ranges.getStartSeq()) > seqIndex)
468 * Scroll up to make start of search results visible
470 setScrollValues(ranges.getStartRes(), seqIndex);
472 else if ((ends = ranges.getEndSeq()) <= seqIndex)
475 * Scroll down to make end of search results visible
477 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
481 * Else results are already visible - no need to scroll
483 scrollNeeded = false;
487 scrollNeeded = ranges.scrollToWrappedVisible(start);
490 paintAlignment(false, false);
498 * @return DOCUMENT ME!
500 public OverviewPanel getOverviewPanel()
502 return overviewPanel;
511 public void setOverviewPanel(OverviewPanel op)
519 * Hide or show annotation panel
522 public void setAnnotationVisible(boolean b)
524 if (!av.getWrapAlignment())
526 annotationSpaceFillerHolder.setVisible(b);
527 annotationScroller.setVisible(b);
533 * automatically adjust annotation panel height for new annotation whilst
534 * ensuring the alignment is still visible.
537 public void adjustAnnotationHeight()
539 // TODO: display vertical annotation scrollbar if necessary
540 // this is called after loading new annotation onto alignment
541 if (alignFrame.getHeight() == 0)
543 System.out.println("NEEDS FIXING");
545 validateAnnotationDimensions(true);
547 // TODO: many places call this method and also paintAlignment with various
548 // different settings. this means multiple redraws are triggered...
549 paintAlignment(true, av.needToUpdateStructureViews());
553 * calculate the annotation dimensions and refresh slider values accordingly.
554 * need to do repaints/notifys afterwards.
556 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
558 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
559 // are not changing ancestors, and keyboard action listeners do
560 // not need to be reset. addNotify() is a very expensive operation,
561 // requiring a full re-layout of all parents and children.
562 // Note in JComponent:
563 // This method is called by the toolkit internally and should
564 // not be called directly by programs.
565 // I note that addNotify() is called in several areas of Jalview.
567 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
568 annotationHeight = getAnnotationPanel()
569 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
572 annotationScroller.setPreferredSize(
573 new Dimension(annotationScroller.getWidth(), annotationHeight));
575 Dimension e = idPanel.getSize();
576 alabels.setSize(new Dimension(e.width, annotationHeight));
579 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
580 annotationSpaceFillerHolder.getWidth(), annotationHeight));
581 annotationScroller.validate();
582 annotationScroller.addNotify();
586 * update alignment layout for viewport settings
591 public void updateLayout()
593 fontChanged(); // fires repaint
594 setAnnotationVisible(av.isShowAnnotation());
595 boolean wrap = av.getWrapAlignment();
596 ViewportRanges ranges = av.getRanges();
597 ranges.setStartSeq(0);
598 scalePanelHolder.setVisible(!wrap);
599 hscroll.setVisible(!wrap);
600 idwidthAdjuster.setVisible(!wrap);
604 annotationScroller.setVisible(false);
605 annotationSpaceFillerHolder.setVisible(false);
607 else if (av.isShowAnnotation())
609 annotationScroller.setVisible(true);
610 annotationSpaceFillerHolder.setVisible(true);
611 validateAnnotationDimensions(false);
614 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
616 { // may not yet be laid out
619 int widthInRes = getSeqPanel().seqCanvas
620 .getWrappedCanvasWidth(canvasWidth);
621 ranges.setViewportWidth(widthInRes);
625 int widthInRes = (canvasWidth / av.getCharWidth());
626 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
627 / av.getCharHeight());
629 ranges.setViewportWidth(widthInRes);
630 ranges.setViewportHeight(heightInSeq);
634 idSpaceFillerPanel1.setVisible(!wrap);
640 * Adjust row/column scrollers to show a visible position in the alignment.
643 * visible column to scroll to
645 * visible row to scroll to
648 public void setScrollValues(int xpos, int ypos)
653 if (av == null || av.getAlignment() == null)
658 if (av.getWrapAlignment())
660 setScrollingForWrappedPanel(x);
664 int width = av.getAlignment().getVisibleWidth();
665 int height = av.getAlignment().getHeight();
667 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
668 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
675 if (vextent > height)
680 if ((hextent + x) > width)
685 if ((vextent + y) > height)
687 y = height - vextent;
700 // update the scroll values
701 hscroll.setValues(x, hextent, 0, width);
702 vscroll.setValues(y, vextent, 0, height);
707 * Respond to adjustment event when horizontal or vertical scrollbar is
711 * adjustment event encoding whether hscroll or vscroll changed
714 public void adjustmentValueChanged(AdjustmentEvent evt)
716 if (av.getWrapAlignment())
718 adjustScrollingWrapped(evt);
722 ViewportRanges ranges = av.getRanges();
724 if (evt.getSource() == hscroll)
726 int oldX = ranges.getStartRes();
727 int oldwidth = ranges.getViewportWidth();
728 int x = hscroll.getValue();
729 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
731 // if we're scrolling to the position we're already at, stop
732 // this prevents infinite recursion of events when the scroll/viewport
733 // ranges values are the same
734 if ((x == oldX) && (width == oldwidth))
738 ranges.setViewportStartAndWidth(x, width);
740 else if (evt.getSource() == vscroll)
742 int oldY = ranges.getStartSeq();
743 int oldheight = ranges.getViewportHeight();
744 int y = vscroll.getValue();
745 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
747 // if we're scrolling to the position we're already at, stop
748 // this prevents infinite recursion of events when the scroll/viewport
749 // ranges values are the same
750 if ((y == oldY) && (height == oldheight))
754 ranges.setViewportStartAndHeight(y, height);
760 * Responds to a scroll change by setting the start position of the viewport.
765 protected void adjustScrollingWrapped(AdjustmentEvent evt)
767 if (evt.getSource() == hscroll)
769 return; // no horizontal scroll when wrapped
771 final ViewportRanges ranges = av.getRanges();
773 if (evt.getSource() == vscroll)
775 int newY = vscroll.getValue();
778 * if we're scrolling to the position we're already at, stop
779 * this prevents infinite recursion of events when the scroll/viewport
780 * ranges values are the same
782 int oldX = ranges.getStartRes();
783 int oldY = ranges.getWrappedScrollPosition(oldX);
791 * limit page up/down to one width's worth of positions
793 int rowSize = ranges.getViewportWidth();
794 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
795 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
800 // This is only called if file loaded is a jar file that
801 // was wrapped when saved and user has wrap alignment true
802 // as preference setting
803 Jalview.execRunnable(new Runnable()
808 // When updating scrolling to use ViewportChange events, this code
809 // could not be validated and it is not clear if it is now being
810 // called. Log warning here in case it is called and unforeseen
813 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
815 // scroll to start of panel
816 ranges.setStartRes(0);
817 ranges.setStartSeq(0);
825 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
828 public void paintAlignment(boolean updateOverview,
829 boolean updateStructures)
831 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
832 av.isShowAutocalculatedAbove());
833 sorter.sort(getAlignment().getAlignmentAnnotation(),
834 av.getSortAnnotationsBy());
837 if (updateStructures)
839 av.getStructureSelectionManager().sequenceColoursChanged(this);
843 if (overviewPanel != null)
845 overviewPanel.updateOverviewImage();
857 public void paintComponent(Graphics g)
860 invalidate(); // needed so that the id width adjuster works correctly
862 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
863 idPanelHolder.setPreferredSize(d);
864 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
866 validate(); // needed so that the id width adjuster works correctly
869 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
870 * though I still think this call should be elsewhere.
872 ViewportRanges ranges = av.getRanges();
873 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
874 super.paintComponent(g);
878 * Set vertical scroll bar position, and number of increments, for wrapped
881 * @param topLeftColumn
882 * the column position at top left (0..)
884 private void setScrollingForWrappedPanel(int topLeftColumn)
886 ViewportRanges ranges = av.getRanges();
887 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
888 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
891 * a scrollbar's value can be set to at most (maximum-extent)
892 * so we add extent (1) to the maxScroll value
894 vscroll.setUnitIncrement(1);
895 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
908 * @return DOCUMENT ME!
910 * @throws PrinterException
914 public int print(Graphics pg, PageFormat pf, int pi)
915 throws PrinterException
917 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
919 int pwidth = (int) pf.getImageableWidth();
920 int pheight = (int) pf.getImageableHeight();
922 if (av.getWrapAlignment())
924 return printWrappedAlignment(pwidth, pheight, pi, pg);
928 return printUnwrapped(pwidth, pheight, pi, pg, pg);
933 * Draws the alignment image, including sequence ids, sequences, and
934 * annotation labels and annotations if shown, on either one or two Graphics
944 * the graphics context for sequence ids and annotation labels
945 * @param alignmentGraphics
946 * the graphics context for sequences and annotations (may or may not
947 * be the same context as idGraphics)
949 * @throws PrinterException
951 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
952 Graphics idGraphics, Graphics alignmentGraphics)
953 throws PrinterException
955 final int idWidth = getVisibleIdWidth(false);
958 * Get the horizontal offset to where we draw the sequences.
959 * This is idWidth if using a single Graphics context, else zero.
961 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
964 FontMetrics fm = getFontMetrics(av.getFont());
965 final int charHeight = av.getCharHeight();
966 final int scaleHeight = charHeight + fm.getDescent();
968 idGraphics.setColor(Color.white);
969 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
970 idGraphics.setFont(av.getFont());
973 * How many sequences and residues can we fit on a printable page?
975 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
977 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
979 final int alignmentWidth = av.getAlignment().getVisibleWidth();
980 int pagesWide = (alignmentWidth / totalRes) + 1;
982 final int startRes = (pageIndex % pagesWide) * totalRes;
983 final int endRes = Math.min(startRes + totalRes - 1,
986 final int startSeq = (pageIndex / pagesWide) * totalSeq;
987 final int alignmentHeight = av.getAlignment().getHeight();
988 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
990 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
992 if (av.isShowAnnotation())
994 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
997 pagesHigh /= pageHeight;
999 if (pageIndex >= (pagesWide * pagesHigh))
1001 return Printable.NO_SUCH_PAGE;
1003 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1006 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1008 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1009 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1010 pageWidth - idWidth, scaleHeight);
1011 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1014 * Draw the sequence ids, offset for scale height,
1015 * then reset to top left (0, 0)
1017 idGraphics.translate(0, scaleHeight);
1018 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1019 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1020 : av.getSelectionGroup().getSequences(null);
1021 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1024 idGraphics.setFont(av.getFont());
1025 idGraphics.translate(0, -scaleHeight);
1028 * draw the sequences, offset for scale height, and id width (if using a
1029 * single graphics context), then reset to (0, scale height)
1031 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1032 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1033 endRes, startSeq, endSeq - 1);
1034 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1036 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1039 * draw annotation labels; drawComponent() translates by
1040 * getScrollOffset(), so compensate for that first;
1041 * then reset to (0, scale height)
1043 int offset = getAlabels().getScrollOffset();
1044 idGraphics.translate(0, -offset);
1045 idGraphics.translate(0, alignmentDrawnHeight);
1046 getAlabels().drawComponent(idGraphics, idWidth);
1047 idGraphics.translate(0, -alignmentDrawnHeight);
1050 * draw the annotations starting at
1051 * (idOffset, alignmentHeight) from (0, scaleHeight)
1053 alignmentGraphics.translate(alignmentGraphicsOffset,
1054 alignmentDrawnHeight);
1055 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1056 alignmentGraphics, -1, startRes, endRes + 1);
1059 return Printable.PAGE_EXISTS;
1063 * Prints one page of an alignment in wrapped mode. Returns
1064 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1065 * no page could be drawn (page number out of range).
1075 * @throws PrinterException
1077 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1078 Graphics g) throws PrinterException
1081 int annotationHeight = 0;
1082 if (av.isShowAnnotation())
1084 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1087 int hgap = av.getCharHeight();
1088 if (av.getScaleAboveWrapped())
1090 hgap += av.getCharHeight();
1093 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1096 int idWidth = getVisibleIdWidth(false);
1098 int maxwidth = av.getAlignment().getVisibleWidth();
1100 int resWidth = getSeqPanel().seqCanvas
1101 .getWrappedCanvasWidth(pageWidth - idWidth);
1103 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1107 g.setColor(Color.white);
1108 g.fillRect(0, 0, pageWidth, pageHeight);
1109 g.setFont(av.getFont());
1110 g.setColor(Color.black);
1113 * method: print the whole wrapped alignment, but with a clip region that
1114 * is restricted to the requested page; this supports selective print of
1115 * single pages or ranges, (at the cost of some repeated processing in
1116 * the 'normal' case, when all pages are printed)
1118 g.translate(0, -pageNumber * pageHeight);
1120 // BH 2020.03.19 avoiding g.setClip
1121 g.clipRect(0, pageNumber * pageHeight, pageWidth, pageHeight);
1124 * draw sequence ids and annotation labels (if shown)
1126 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1127 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1129 g.translate(idWidth, 0);
1131 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1135 if ((pageNumber * pageHeight) < totalHeight)
1137 return Printable.PAGE_EXISTS;
1141 return Printable.NO_SUCH_PAGE;
1146 * get current sequence ID panel width, or nominal value if panel were to be
1147 * displayed using default settings
1151 public int getVisibleIdWidth()
1153 return getVisibleIdWidth(true);
1157 * get current sequence ID panel width, or nominal value if panel were to be
1158 * displayed using default settings
1161 * indicate if the Id width for onscreen or offscreen display should
1165 public int getVisibleIdWidth(boolean onscreen)
1167 // see if rendering offscreen - check preferences and calc width accordingly
1168 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1170 return calculateIdWidth(-1).width + 4;
1172 Integer idwidth = null;
1173 if (onscreen || (idwidth = Cache
1174 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1176 int w = getIdPanel().getWidth();
1177 return (w > 0 ? w : calculateIdWidth().width + 4);
1179 return idwidth.intValue() + 4;
1183 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1184 * writes it to the specified file
1189 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1191 final int borderBottomOffset = 5;
1193 AlignmentDimension aDimension = getAlignmentDimension();
1194 // todo use a lambda function in place of callback here?
1195 ImageWriterI writer = new ImageWriterI()
1198 public void exportImage(Graphics graphics) throws Exception
1200 if (av.getWrapAlignment())
1202 printWrappedAlignment(aDimension.getWidth(),
1203 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1207 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1208 graphics, graphics);
1213 String fileTitle = alignFrame.getTitle();
1214 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1216 int imageWidth = aDimension.getWidth();
1217 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1218 String of = MessageManager.getString("label.alignment");
1219 exporter.doExport(file, this, imageWidth, imageHeight, of);
1223 * Calculates and returns a suitable width and height (in pixels) for an
1228 public AlignmentDimension getAlignmentDimension()
1230 int maxwidth = av.getAlignment().getVisibleWidth();
1232 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1233 + getScalePanel().getHeight();
1234 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1236 if (av.getWrapAlignment())
1238 height = getWrappedHeight();
1239 if (Jalview.isHeadlessMode())
1241 // need to obtain default alignment width and then add in any
1242 // additional allowance for id margin
1243 // this duplicates the calculation in getWrappedHeight but adjusts for
1245 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1246 - alignFrame.getInsets().left - alignFrame.getInsets().right
1247 - getVisibleIdWidth() + getVisibleIdWidth(false);
1251 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1255 else if (av.isShowAnnotation())
1257 height += getAnnotationPanel().adjustPanelHeight() + 3;
1259 return new AlignmentDimension(width, height);
1263 public void makePNGImageMap(File imgMapFile, String imageName)
1265 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1266 // ////////////////////////////////////////////
1267 int idWidth = getVisibleIdWidth(false);
1268 FontMetrics fm = getFontMetrics(av.getFont());
1269 int scaleHeight = av.getCharHeight() + fm.getDescent();
1272 // ////////////////////////////////
1273 if (imgMapFile != null)
1277 int sSize = av.getAlignment().getHeight();
1278 int alwidth = av.getAlignment().getWidth();
1279 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1280 out.println(HTMLOutput.getImageMapHTML());
1281 out.println("<img src=\"" + imageName
1282 + "\" border=\"0\" usemap=\"#Map\" >"
1283 + "<map name=\"Map\">");
1285 for (int s = 0; s < sSize; s++)
1287 int sy = s * av.getCharHeight() + scaleHeight;
1289 SequenceI seq = av.getAlignment().getSequenceAt(s);
1290 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1291 for (int column = 0; column < alwidth; column++)
1293 StringBuilder text = new StringBuilder(512);
1294 String triplet = null;
1295 if (av.getAlignment().isNucleotide())
1297 triplet = ResidueProperties.nucleotideName.get(seq
1298 .getCharAt(column) + "");
1302 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1306 if (triplet == null)
1311 int seqPos = seq.findPosition(column);
1312 int gSize = groups.length;
1313 for (int g = 0; g < gSize; g++)
1315 if (text.length() < 1)
1317 text.append("<area shape=\"rect\" coords=\"")
1318 .append((idWidth + column * av.getCharWidth()))
1319 .append(",").append(sy).append(",")
1320 .append((idWidth + (column + 1) * av.getCharWidth()))
1321 .append(",").append((av.getCharHeight() + sy))
1322 .append("\"").append(" onMouseOver=\"toolTip('")
1323 .append(seqPos).append(" ").append(triplet);
1326 if (groups[g].getStartRes() < column
1327 && groups[g].getEndRes() > column)
1329 text.append("<br><em>").append(groups[g].getName())
1334 if (text.length() < 1)
1336 text.append("<area shape=\"rect\" coords=\"")
1337 .append((idWidth + column * av.getCharWidth()))
1338 .append(",").append(sy).append(",")
1339 .append((idWidth + (column + 1) * av.getCharWidth()))
1340 .append(",").append((av.getCharHeight() + sy))
1341 .append("\"").append(" onMouseOver=\"toolTip('")
1342 .append(seqPos).append(" ").append(triplet);
1344 if (!Comparison.isGap(seq.getCharAt(column)))
1346 List<SequenceFeature> features = seq.findFeatures(column, column);
1347 for (SequenceFeature sf : features)
1349 if (sf.isContactFeature())
1351 text.append("<br>").append(sf.getType()).append(" ")
1352 .append(sf.getBegin()).append(":")
1353 .append(sf.getEnd());
1357 text.append("<br>");
1358 text.append(sf.getType());
1359 String description = sf.getDescription();
1360 if (description != null
1361 && !sf.getType().equals(description))
1363 description = description.replace("\"", """);
1364 text.append(" ").append(description);
1367 String status = sf.getStatus();
1368 if (status != null && !"".equals(status))
1370 text.append(" (").append(status).append(")");
1373 if (text.length() > 1)
1375 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1376 out.println(text.toString());
1381 out.println("</map></body></html>");
1384 } catch (Exception ex)
1386 ex.printStackTrace();
1388 } // /////////END OF IMAGE MAP
1392 int getWrappedHeight()
1394 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1396 if (Jalview.isHeadlessMode())
1398 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1399 - vscroll.getPreferredSize().width
1400 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1403 int chunkWidth = getSeqPanel().seqCanvas
1404 .getWrappedCanvasWidth(seqPanelWidth);
1406 int hgap = av.getCharHeight();
1407 if (av.getScaleAboveWrapped())
1409 hgap += av.getCharHeight();
1412 int annotationHeight = 0;
1413 if (av.isShowAnnotation())
1415 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1418 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1421 int maxwidth = av.getAlignment().getWidth();
1422 if (av.hasHiddenColumns())
1424 maxwidth = av.getAlignment().getHiddenColumns()
1425 .absoluteToVisibleColumn(maxwidth) - 1;
1428 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1434 * close the panel - deregisters all listeners and nulls any references to
1437 public void closePanel()
1439 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1440 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1441 PaintRefresher.RemoveComponent(this);
1446 * try to ensure references are nulled
1448 if (annotationPanel != null)
1450 annotationPanel.dispose();
1451 annotationPanel = null;
1456 av.removePropertyChangeListener(propertyChangeListener);
1457 propertyChangeListener = null;
1458 StructureSelectionManager ssm = av.getStructureSelectionManager();
1459 ssm.removeStructureViewerListener(getSeqPanel(), null);
1460 ssm.removeSelectionListener(getSeqPanel());
1461 ssm.removeCommandListener(av);
1462 ssm.removeStructureViewerListener(getSeqPanel(), null);
1463 ssm.removeSelectionListener(getSeqPanel());
1469 if (Cache.log.isDebugEnabled())
1471 Cache.log.warn("Closing alignment panel which is already closed.");
1477 * Close any open dialogs that would be orphaned when this one is closed
1479 protected void closeChildFrames()
1481 if (overviewPanel != null)
1483 overviewPanel.dispose();
1484 overviewPanel = null;
1486 if (calculationDialog != null)
1488 calculationDialog.closeFrame();
1489 calculationDialog = null;
1494 * hides or shows dynamic annotation rows based on groups and av state flags
1496 public void updateAnnotation()
1498 updateAnnotation(false, false);
1501 public void updateAnnotation(boolean applyGlobalSettings)
1503 updateAnnotation(applyGlobalSettings, false);
1506 public void updateAnnotation(boolean applyGlobalSettings,
1507 boolean preserveNewGroupSettings)
1509 av.updateGroupAnnotationSettings(applyGlobalSettings,
1510 preserveNewGroupSettings);
1511 adjustAnnotationHeight();
1515 public AlignmentI getAlignment()
1517 return av == null ? null : av.getAlignment();
1521 public String getViewName()
1523 return av.getViewName();
1527 * Make/Unmake this alignment panel the current input focus
1531 public void setSelected(boolean b)
1535 if (alignFrame.getSplitViewContainer() != null)
1538 * bring enclosing SplitFrame to front first if there is one
1540 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1542 alignFrame.setSelected(b);
1543 } catch (Exception ex)
1549 alignFrame.setDisplayedView(this);
1554 public StructureSelectionManager getStructureSelectionManager()
1556 return av.getStructureSelectionManager();
1560 public void raiseOOMWarning(String string, OutOfMemoryError error)
1562 new OOMWarning(string, error, this);
1566 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1569 return new FeatureRenderer(this);
1573 public jalview.api.FeatureRenderer getFeatureRenderer()
1575 return seqPanel.seqCanvas.getFeatureRenderer();
1578 public void updateFeatureRenderer(
1579 jalview.renderer.seqfeatures.FeatureRenderer fr)
1581 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1584 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1586 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1588 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1592 public ScalePanel getScalePanel()
1597 public void setScalePanel(ScalePanel scalePanel)
1599 this.scalePanel = scalePanel;
1602 public SeqPanel getSeqPanel()
1607 public void setSeqPanel(SeqPanel seqPanel)
1609 this.seqPanel = seqPanel;
1612 public AnnotationPanel getAnnotationPanel()
1614 return annotationPanel;
1617 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1619 this.annotationPanel = annotationPanel;
1622 public AnnotationLabels getAlabels()
1627 public void setAlabels(AnnotationLabels alabels)
1629 this.alabels = alabels;
1632 public IdPanel getIdPanel()
1637 public void setIdPanel(IdPanel idPanel)
1639 this.idPanel = idPanel;
1643 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1644 * The aim is to keep the two alignments 'lined up' on their centre columns.
1647 * holds mapped region(s) of this alignment that we are scrolling
1648 * 'to'; may be modified for sequence offset by this method
1649 * @param verticalOffset
1650 * the number of visible sequences to show above the mapped region
1652 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1654 scrollToPosition(sr, verticalOffset, true);
1658 * Set a flag to say do not scroll any (cDNA/protein) complement.
1662 protected void setToScrollComplementPanel(boolean b)
1664 this.scrollComplementaryPanel = b;
1668 * Get whether to scroll complement panel
1670 * @return true if cDNA/protein complement panels should be scrolled
1672 protected boolean isSetToScrollComplementPanel()
1674 return this.scrollComplementaryPanel;
1680 * @adjustHeight if true, try to recalculate panel height for visible
1683 protected void refresh(boolean adjustHeight)
1685 validateAnnotationDimensions(adjustHeight);
1689 // sort, repaint, update overview
1690 paintAlignment(true, false);
1694 // lightweight repaint
1701 * Property change event fired when a change is made to the viewport ranges
1702 * object associated with this alignment panel's viewport
1704 public void propertyChange(PropertyChangeEvent evt)
1706 // update this panel's scroll values based on the new viewport ranges values
1707 ViewportRanges ranges = av.getRanges();
1708 int x = ranges.getStartRes();
1709 int y = ranges.getStartSeq();
1710 setScrollValues(x, y);
1712 // now update any complementary alignment (its viewport ranges object
1713 // is different so does not get automatically updated)
1714 if (isSetToScrollComplementPanel())
1716 setToScrollComplementPanel(false);
1717 av.scrollComplementaryAlignment();
1718 setToScrollComplementPanel(true);
1723 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1724 * reference should be nulled when the dialog is closed.
1726 * @param calculationChooser
1728 public void setCalculationDialog(CalculationChooser calculationChooser)
1730 calculationDialog = calculationChooser;
1734 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1737 public CalculationChooser getCalculationDialog()
1739 return calculationDialog;
1743 public SequenceRenderer getSequenceRenderer()
1745 return seqPanel.seqCanvas.getSequenceRenderer();
1748 public boolean scrollTo(int ostart, int end, int seqIndex,
1749 boolean scrollToNearest, boolean redrawOverview)
1751 int startv, endv, starts, ends;// , width;
1754 if (av.hasHiddenColumns())
1756 AlignmentI al = av.getAlignment();
1757 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1758 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1761 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1763 // don't scroll - position isn't visible
1773 ViewportRanges ranges = av.getRanges();
1774 if (!av.getWrapAlignment())
1777 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1778 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1779 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1780 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1781 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1782 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1783 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1784 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1787 // below is scrolling logic up to Jalview 2.8.2
1788 // if ((av.getStartRes() > end)
1789 // || (av.getEndRes() < start)
1790 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1792 // if (start > av.getAlignment().getWidth() - hextent)
1794 // start = av.getAlignment().getWidth() - hextent;
1801 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1803 // seqIndex = av.getAlignment().getHeight() - vextent;
1804 // if (seqIndex < 0)
1809 // setScrollValues(start, seqIndex);
1811 // logic copied from jalview.gui.AlignmentPanel:
1812 if ((startv = ranges.getStartRes()) >= start)
1815 * Scroll left to make start of search results visible
1817 setScrollValues(start - 1, seqIndex);
1819 else if ((endv = ranges.getEndRes()) <= end)
1822 * Scroll right to make end of search results visible
1824 setScrollValues(startv + 1 + end - endv, seqIndex);
1826 else if ((starts = ranges.getStartSeq()) > seqIndex)
1829 * Scroll up to make start of search results visible
1831 setScrollValues(ranges.getStartRes(), seqIndex);
1833 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1836 * Scroll down to make end of search results visible
1838 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1841 * Else results are already visible - no need to scroll
1846 ranges.scrollToWrappedVisible(start);
1849 paintAlignment(redrawOverview, false);
1854 public void overviewDone(BufferedImage miniMe)
1856 overviewPanel.canvas.finalizeDraw(miniMe);
1860 private boolean holdRepaint = false;
1862 public boolean getHoldRepaint()
1867 public void setHoldRepaint(boolean b)
1869 if (holdRepaint == b)
1881 public void repaint()
1885 // System.out.println("AP repaint holding");
1886 // Platform.stackTrace();