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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
45 import javax.swing.SwingUtilities;
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.HiddenColumns;
55 import jalview.datamodel.SearchResultsI;
56 import jalview.datamodel.SequenceFeature;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ImageExporter.ImageWriterI;
60 import jalview.io.HTMLOutput;
61 import jalview.jbgui.GAlignmentPanel;
62 import jalview.math.AlignmentDimension;
63 import jalview.schemes.ResidueProperties;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.Comparison;
66 import jalview.util.ImageMaker;
67 import jalview.util.MessageManager;
68 import jalview.viewmodel.ViewportListenerI;
69 import jalview.viewmodel.ViewportRanges;
75 * @version $Revision: 1.161 $
77 @SuppressWarnings("serial")
78 public class AlignmentPanel extends GAlignmentPanel implements
79 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
82 * spare space in pixels between sequence id and alignment panel
84 private static final int ID_WIDTH_PADDING = 4;
86 public AlignViewport av;
88 OverviewPanel overviewPanel;
90 private SeqPanel seqPanel;
92 private IdPanel idPanel;
94 IdwidthAdjuster idwidthAdjuster;
96 public AlignFrame alignFrame;
98 private ScalePanel scalePanel;
100 private AnnotationPanel annotationPanel;
102 private AnnotationLabels alabels;
104 private int hextent = 0;
106 private int vextent = 0;
109 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110 * false, suppresses invoking the same method recursively.
112 private boolean scrollComplementaryPanel = true;
114 private PropertyChangeListener propertyChangeListener;
116 private CalculationChooser calculationDialog;
119 * Creates a new AlignmentPanel object.
124 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 // setBackground(Color.white); // BH 2019
129 setSeqPanel(new SeqPanel(av, this));
130 setIdPanel(new IdPanel(av, this));
132 setScalePanel(new ScalePanel(av, this));
134 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135 idwidthAdjuster = new IdwidthAdjuster(this);
136 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
138 setAnnotationPanel(new AnnotationPanel(this));
139 setAlabels(new AnnotationLabels(this));
141 annotationScroller.setViewportView(getAnnotationPanel());
142 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
144 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
147 setScrollValues(0, 0);
149 hscroll.addAdjustmentListener(this);
150 vscroll.addAdjustmentListener(this);
152 addComponentListener(new ComponentAdapter()
155 public void componentResized(ComponentEvent evt)
157 // reset the viewport ranges when the alignment panel is resized
158 // in particular, this initialises the end residue value when Jalview
160 ViewportRanges ranges = av.getRanges();
161 if (av.getWrapAlignment())
163 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
164 getSeqPanel().seqCanvas.getWidth());
165 ranges.setViewportWidth(widthInRes);
169 int widthInRes = getSeqPanel().seqCanvas.getWidth()
171 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
172 / av.getCharHeight();
174 ranges.setViewportWidth(widthInRes);
175 ranges.setViewportHeight(heightInSeq);
181 final AlignmentPanel ap = this;
182 propertyChangeListener = new PropertyChangeListener()
185 public void propertyChange(PropertyChangeEvent evt)
187 if (evt.getPropertyName().equals("alignment"))
189 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
194 av.addPropertyChangeListener(propertyChangeListener);
196 av.getRanges().addPropertyChangeListener(this);
198 adjustAnnotationHeight();
203 public AlignViewportI getAlignViewport()
208 public void alignmentChanged()
210 av.alignmentChanged(this);
212 if (getCalculationDialog() != null)
214 getCalculationDialog().validateCalcTypes();
217 alignFrame.updateEditMenuBar();
219 // no idea if we need to update structure
220 paintAlignment(true, true);
227 public void fontChanged()
229 // set idCanvas bufferedImage to null
230 // to prevent drawing old image
231 FontMetrics fm = getFontMetrics(av.getFont());
233 // update the flag controlling whether the grid is too small to render the
235 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
237 scalePanelHolder.setPreferredSize(
238 new Dimension(10, av.getCharHeight() + fm.getDescent()));
239 idSpaceFillerPanel1.setPreferredSize(
240 new Dimension(10, av.getCharHeight() + fm.getDescent()));
241 idwidthAdjuster.invalidate();
242 scalePanelHolder.invalidate();
243 // BH 2018 getIdPanel().getIdCanvas().gg = null;
244 getSeqPanel().seqCanvas.img = null;
245 getAnnotationPanel().adjustPanelHeight();
247 Dimension d = calculateIdWidth();
248 getIdPanel().getIdCanvas().setPreferredSize(d);
249 hscrollFillerPanel.setPreferredSize(d);
255 * Calculates the width of the alignment labels based on the displayed names
256 * and any bounds on label width set in preferences. The calculated width is
257 * also set as a property of the viewport.
259 * @return Dimension giving the maximum width of the alignment label panel
260 * that should be used.
262 public Dimension calculateIdWidth()
264 int oldWidth = av.getIdWidth();
266 // calculate sensible default width when no preference is available
268 if (av.getIdWidth() < 0)
270 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
271 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
272 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
273 r = calculateIdWidth(maxwidth);
274 av.setIdWidth(r.width);
279 r.width = av.getIdWidth();
284 * fudge: if desired width has changed, update layout
285 * (see also paintComponent - updates layout on a repaint)
287 if (r.width != oldWidth)
289 idPanelHolder.setPreferredSize(r);
296 * Calculate the width of the alignment labels based on the displayed names
297 * and any bounds on label width set in preferences.
300 * -1 or maximum width allowed for IdWidth
301 * @return Dimension giving the maximum width of the alignment label panel
302 * that should be used.
304 protected Dimension calculateIdWidth(int maxwidth)
306 Container c = new Container();
308 FontMetrics fm = c.getFontMetrics(
309 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
311 AlignmentI al = av.getAlignment();
315 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
317 SequenceI s = al.getSequenceAt(i);
318 String id = s.getDisplayId(av.getShowJVSuffix());
319 int stringWidth = fm.stringWidth(id);
320 idWidth = Math.max(idWidth, stringWidth);
324 // Also check annotation label widths
327 if (al.getAlignmentAnnotation() != null)
329 fm = c.getFontMetrics(getAlabels().getFont());
331 while (i < al.getAlignmentAnnotation().length)
333 String label = al.getAlignmentAnnotation()[i].label;
334 int stringWidth = fm.stringWidth(label);
335 idWidth = Math.max(idWidth, stringWidth);
340 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
341 w += ID_WIDTH_PADDING;
343 return new Dimension(w, 12);
347 * Highlight the given results on the alignment
350 public void highlightSearchResults(SearchResultsI results)
352 boolean scrolled = scrollToPosition(results, 0, false);
354 boolean fastPaint = !(scrolled && av.getWrapAlignment());
356 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
360 * Scroll the view to show the position of the highlighted region in results
363 * @param searchResults
366 public boolean scrollToPosition(SearchResultsI searchResults)
368 return scrollToPosition(searchResults, 0, false);
372 * Scrolls the view (if necessary) to show the position of the first
373 * highlighted region in results (if any). Answers true if the view was
374 * scrolled, or false if no matched region was found, or it is already
378 * @param verticalOffset
379 * if greater than zero, allows scrolling to a position below the
380 * first displayed sequence
382 * if true, try to centre the search results horizontally in the view
385 protected boolean scrollToPosition(SearchResultsI results,
386 int verticalOffset, boolean centre)
388 int startv, endv, starts, ends;
389 ViewportRanges ranges = av.getRanges();
391 if (results == null || results.isEmpty() || av == null
392 || av.getAlignment() == null)
396 int seqIndex = av.getAlignment().findIndex(results);
401 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
403 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
412 * To centre results, scroll to positions half the visible width
413 * left/right of the start/end positions
417 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
418 start = Math.max(start - offset, 0);
419 end = end + offset - 1;
425 if (end == seq.getEnd())
430 if (av.hasHiddenColumns())
432 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
433 start = hidden.absoluteToVisibleColumn(start);
434 end = hidden.absoluteToVisibleColumn(end);
437 if (!hidden.isVisible(r[0]))
439 // don't scroll - position isn't visible
446 * allow for offset of target sequence (actually scroll to one above it)
448 seqIndex = Math.max(0, seqIndex - verticalOffset);
449 boolean scrollNeeded = true;
451 if (!av.getWrapAlignment())
453 if ((startv = ranges.getStartRes()) >= start)
456 * Scroll left to make start of search results visible
458 setScrollValues(start, seqIndex);
460 else if ((endv = ranges.getEndRes()) <= end)
463 * Scroll right to make end of search results visible
465 setScrollValues(startv + end - endv, seqIndex);
467 else if ((starts = ranges.getStartSeq()) > seqIndex)
470 * Scroll up to make start of search results visible
472 setScrollValues(ranges.getStartRes(), seqIndex);
474 else if ((ends = ranges.getEndSeq()) <= seqIndex)
477 * Scroll down to make end of search results visible
479 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
482 * Else results are already visible - no need to scroll
484 scrollNeeded = false;
488 scrollNeeded = ranges.scrollToWrappedVisible(start);
491 paintAlignment(false, false);
499 * @return DOCUMENT ME!
501 public OverviewPanel getOverviewPanel()
503 return overviewPanel;
512 public void setOverviewPanel(OverviewPanel op)
520 * Hide or show annotation panel
523 public void setAnnotationVisible(boolean b)
525 if (!av.getWrapAlignment())
527 annotationSpaceFillerHolder.setVisible(b);
528 annotationScroller.setVisible(b);
534 * automatically adjust annotation panel height for new annotation whilst
535 * ensuring the alignment is still visible.
538 public void adjustAnnotationHeight()
540 // TODO: display vertical annotation scrollbar if necessary
541 // this is called after loading new annotation onto alignment
542 if (alignFrame.getHeight() == 0)
544 System.out.println("NEEDS FIXING");
546 validateAnnotationDimensions(true);
548 // TODO: many places call this method and also paintAlignment with various
549 // different settings. this means multiple redraws are triggered...
550 paintAlignment(true, av.needToUpdateStructureViews());
554 * calculate the annotation dimensions and refresh slider values accordingly.
555 * need to do repaints/notifys afterwards.
557 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
559 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
560 // are not changing ancestors, and keyboard action listeners do
561 // not need to be reset. addNotify() is a very expensive operation,
562 // requiring a full re-layout of all parents and children.
563 // Note in JComponent:
564 // This method is called by the toolkit internally and should
565 // not be called directly by programs.
566 // I note that addNotify() is called in several areas of Jalview.
568 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
569 annotationHeight = getAnnotationPanel()
570 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
573 annotationScroller.setPreferredSize(
574 new Dimension(annotationScroller.getWidth(), annotationHeight));
576 Dimension e = idPanel.getSize();
577 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()
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 SwingUtilities.invokeLater(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);
844 if (overviewPanel != null)
846 overviewPanel.updateOverviewImage();
852 public void paintComponent(Graphics g)
854 invalidate(); // needed so that the id width adjuster works correctly
856 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
857 idPanelHolder.setPreferredSize(d);
858 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
860 validate(); // needed so that the id width adjuster works correctly
863 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
864 * though I still think this call should be elsewhere.
866 ViewportRanges ranges = av.getRanges();
867 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
868 super.paintComponent(g);
872 * Set vertical scroll bar position, and number of increments, for wrapped
875 * @param topLeftColumn
876 * the column position at top left (0..)
878 private void setScrollingForWrappedPanel(int topLeftColumn)
880 ViewportRanges ranges = av.getRanges();
881 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
882 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
885 * a scrollbar's value can be set to at most (maximum-extent)
886 * so we add extent (1) to the maxScroll value
888 vscroll.setUnitIncrement(1);
889 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
902 * @return DOCUMENT ME!
904 * @throws PrinterException
908 public int print(Graphics pg, PageFormat pf, int pi)
909 throws PrinterException
911 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
913 int pwidth = (int) pf.getImageableWidth();
914 int pheight = (int) pf.getImageableHeight();
916 if (av.getWrapAlignment())
918 return printWrappedAlignment(pwidth, pheight, pi, pg);
922 return printUnwrapped(pwidth, pheight, pi, pg, pg);
927 * Draws the alignment image, including sequence ids, sequences, and
928 * annotation labels and annotations if shown, on either one or two Graphics
938 * the graphics context for sequence ids and annotation labels
939 * @param alignmentGraphics
940 * the graphics context for sequences and annotations (may or may not
941 * be the same context as idGraphics)
943 * @throws PrinterException
945 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
946 Graphics idGraphics, Graphics alignmentGraphics)
947 throws PrinterException
949 final int idWidth = getVisibleIdWidth(false);
952 * Get the horizontal offset to where we draw the sequences.
953 * This is idWidth if using a single Graphics context, else zero.
955 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
958 FontMetrics fm = getFontMetrics(av.getFont());
959 final int charHeight = av.getCharHeight();
960 final int scaleHeight = charHeight + fm.getDescent();
962 idGraphics.setColor(Color.white);
963 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
964 idGraphics.setFont(av.getFont());
967 * How many sequences and residues can we fit on a printable page?
969 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
971 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
973 final int alignmentWidth = av.getAlignment().getVisibleWidth();
974 int pagesWide = (alignmentWidth / totalRes) + 1;
976 final int startRes = (pageIndex % pagesWide) * totalRes;
977 final int endRes = Math.min(startRes + totalRes - 1,
980 final int startSeq = (pageIndex / pagesWide) * totalSeq;
981 final int alignmentHeight = av.getAlignment().getHeight();
982 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
984 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
986 if (av.isShowAnnotation())
988 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
991 pagesHigh /= pageHeight;
993 if (pageIndex >= (pagesWide * pagesHigh))
995 return Printable.NO_SUCH_PAGE;
997 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1000 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1002 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1003 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1004 pageWidth - idWidth, scaleHeight);
1005 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1008 * Draw the sequence ids, offset for scale height,
1009 * then reset to top left (0, 0)
1011 idGraphics.translate(0, scaleHeight);
1012 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1013 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1014 : av.getSelectionGroup().getSequences(null);
1015 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1018 idGraphics.setFont(av.getFont());
1019 idGraphics.translate(0, -scaleHeight);
1022 * draw the sequences, offset for scale height, and id width (if using a
1023 * single graphics context), then reset to (0, scale height)
1025 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1026 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1027 startRes, endRes, startSeq, endSeq - 1);
1028 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1030 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1033 * draw annotation labels; drawComponent() translates by
1034 * getScrollOffset(), so compensate for that first;
1035 * then reset to (0, scale height)
1037 int offset = getAlabels().getScrollOffset();
1038 idGraphics.translate(0, -offset);
1039 idGraphics.translate(0, alignmentDrawnHeight);
1040 getAlabels().drawComponent(idGraphics, idWidth);
1041 idGraphics.translate(0, -alignmentDrawnHeight);
1044 * draw the annotations starting at
1045 * (idOffset, alignmentHeight) from (0, scaleHeight)
1047 alignmentGraphics.translate(alignmentGraphicsOffset,
1048 alignmentDrawnHeight);
1050 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1051 alignmentGraphics, -1, startRes, endRes + 1);
1054 return Printable.PAGE_EXISTS;
1058 * Prints one page of an alignment in wrapped mode. Returns
1059 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1060 * no page could be drawn (page number out of range).
1070 * @throws PrinterException
1072 public int printWrappedAlignment(int pageWidth, int pageHeight,
1073 int pageNumber, Graphics g) throws PrinterException
1075 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1077 int annotationHeight = 0;
1078 if (av.isShowAnnotation())
1080 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1083 int hgap = av.getCharHeight();
1084 if (av.getScaleAboveWrapped())
1086 hgap += av.getCharHeight();
1089 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1092 int idWidth = getVisibleIdWidth(false);
1094 int maxwidth = av.getAlignment().getVisibleWidth();
1096 int resWidth = getSeqPanel().seqCanvas
1097 .getWrappedCanvasWidth(pageWidth - idWidth);
1098 av.getRanges().setViewportStartAndWidth(0, resWidth);
1100 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1102 g.setColor(Color.white);
1103 g.fillRect(0, 0, pageWidth, pageHeight);
1104 g.setFont(av.getFont());
1105 g.setColor(Color.black);
1108 * method: print the whole wrapped alignment, but with a clip region that
1109 * is restricted to the requested page; this supports selective print of
1110 * single pages or ranges, (at the cost of repeated processing in the
1111 * 'normal' case, when all pages are printed)
1113 g.translate(0, -pageNumber * pageHeight);
1115 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1118 * draw sequence ids and annotation labels (if shown)
1120 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1121 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1123 g.translate(idWidth, 0);
1125 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1126 pageWidth - idWidth, totalHeight, 0);
1128 if ((pageNumber * pageHeight) < totalHeight)
1130 return Printable.PAGE_EXISTS;
1134 return Printable.NO_SUCH_PAGE;
1139 * get current sequence ID panel width, or nominal value if panel were to be
1140 * displayed using default settings
1144 public int getVisibleIdWidth()
1146 return getVisibleIdWidth(true);
1150 * get current sequence ID panel width, or nominal value if panel were to be
1151 * displayed using default settings
1154 * indicate if the Id width for onscreen or offscreen display should
1158 protected int getVisibleIdWidth(boolean onscreen)
1160 // see if rendering offscreen - check preferences and calc width accordingly
1161 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1163 return calculateIdWidth(-1).width;
1165 Integer idwidth = onscreen ? null
1166 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1167 if (idwidth != null)
1169 return idwidth.intValue() + ID_WIDTH_PADDING;
1172 int w = getIdPanel().getWidth();
1173 return (w > 0 ? w : calculateIdWidth().width);
1177 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1178 * writes it to the specified file
1183 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1185 final int borderBottomOffset = 5;
1187 AlignmentDimension aDimension = getAlignmentDimension();
1188 // todo use a lambda function in place of callback here?
1189 ImageWriterI writer = new ImageWriterI()
1192 public void exportImage(Graphics graphics) throws Exception
1194 if (av.getWrapAlignment())
1196 printWrappedAlignment(aDimension.getWidth(),
1197 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1201 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1202 graphics, graphics);
1207 String fileTitle = alignFrame.getTitle();
1208 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1210 int imageWidth = aDimension.getWidth();
1211 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1212 String of = MessageManager.getString("label.alignment");
1213 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer);
1217 * Calculates and returns a suitable width and height (in pixels) for an
1222 public AlignmentDimension getAlignmentDimension()
1224 int maxwidth = av.getAlignment().getVisibleWidth();
1226 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1227 + getScalePanel().getHeight();
1228 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1230 if (av.getWrapAlignment())
1232 height = getWrappedHeight();
1233 if (Jalview.isHeadlessMode())
1235 // need to obtain default alignment width and then add in any
1236 // additional allowance for id margin
1237 // this duplicates the calculation in getWrappedHeight but adjusts for
1239 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1240 - alignFrame.getInsets().left - alignFrame.getInsets().right
1241 - getVisibleIdWidth() + getVisibleIdWidth(false);
1245 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1249 else if (av.isShowAnnotation())
1251 height += getAnnotationPanel().adjustPanelHeight() + 3;
1253 return new AlignmentDimension(width, height);
1257 public void makePNGImageMap(File imgMapFile, String imageName)
1259 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1260 // ////////////////////////////////////////////
1261 int idWidth = getVisibleIdWidth(false);
1262 FontMetrics fm = getFontMetrics(av.getFont());
1263 int scaleHeight = av.getCharHeight() + fm.getDescent();
1266 // ////////////////////////////////
1267 if (imgMapFile != null)
1271 int sSize = av.getAlignment().getHeight();
1272 int alwidth = av.getAlignment().getWidth();
1273 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1274 out.println(HTMLOutput.getImageMapHTML());
1275 out.println("<img src=\"" + imageName
1276 + "\" border=\"0\" usemap=\"#Map\" >"
1277 + "<map name=\"Map\">");
1279 for (int s = 0; s < sSize; s++)
1281 int sy = s * av.getCharHeight() + scaleHeight;
1283 SequenceI seq = av.getAlignment().getSequenceAt(s);
1284 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1285 for (int column = 0; column < alwidth; column++)
1287 StringBuilder text = new StringBuilder(512);
1288 String triplet = null;
1289 if (av.getAlignment().isNucleotide())
1291 triplet = ResidueProperties.nucleotideName
1292 .get(seq.getCharAt(column) + "");
1296 triplet = ResidueProperties.aa2Triplet
1297 .get(seq.getCharAt(column) + "");
1300 if (triplet == null)
1305 int seqPos = seq.findPosition(column);
1306 int gSize = groups.length;
1307 for (int g = 0; g < gSize; g++)
1309 if (text.length() < 1)
1311 text.append("<area shape=\"rect\" coords=\"")
1312 .append((idWidth + column * av.getCharWidth()))
1313 .append(",").append(sy).append(",")
1315 + (column + 1) * av.getCharWidth()))
1316 .append(",").append((av.getCharHeight() + sy))
1317 .append("\"").append(" onMouseOver=\"toolTip('")
1318 .append(seqPos).append(" ").append(triplet);
1321 if (groups[g].getStartRes() < column
1322 && groups[g].getEndRes() > column)
1324 text.append("<br><em>").append(groups[g].getName())
1329 if (text.length() < 1)
1331 text.append("<area shape=\"rect\" coords=\"")
1332 .append((idWidth + column * av.getCharWidth()))
1333 .append(",").append(sy).append(",")
1334 .append((idWidth + (column + 1) * av.getCharWidth()))
1335 .append(",").append((av.getCharHeight() + sy))
1336 .append("\"").append(" onMouseOver=\"toolTip('")
1337 .append(seqPos).append(" ").append(triplet);
1339 if (!Comparison.isGap(seq.getCharAt(column)))
1341 List<SequenceFeature> features = seq.findFeatures(column,
1343 for (SequenceFeature sf : features)
1345 if (sf.isContactFeature())
1347 text.append("<br>").append(sf.getType()).append(" ")
1348 .append(sf.getBegin()).append(":")
1349 .append(sf.getEnd());
1353 text.append("<br>");
1354 text.append(sf.getType());
1355 String description = sf.getDescription();
1356 if (description != null
1357 && !sf.getType().equals(description))
1359 description = description.replace("\"", """);
1360 text.append(" ").append(description);
1363 String status = sf.getStatus();
1364 if (status != null && !"".equals(status))
1366 text.append(" (").append(status).append(")");
1369 if (text.length() > 1)
1371 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1372 out.println(text.toString());
1377 out.println("</map></body></html>");
1380 } catch (Exception ex)
1382 ex.printStackTrace();
1384 } // /////////END OF IMAGE MAP
1389 * Answers the height of the entire alignment in pixels, assuming it is in
1394 int getWrappedHeight()
1396 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1398 if (System.getProperty("java.awt.headless") != null
1399 && System.getProperty("java.awt.headless").equals("true"))
1401 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1402 - vscroll.getPreferredSize().width
1403 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1406 int chunkWidth = getSeqPanel().seqCanvas
1407 .getWrappedCanvasWidth(seqPanelWidth);
1409 int hgap = av.getCharHeight();
1410 if (av.getScaleAboveWrapped())
1412 hgap += av.getCharHeight();
1415 int annotationHeight = 0;
1416 if (av.isShowAnnotation())
1418 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1419 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1422 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1425 int maxwidth = av.getAlignment().getWidth();
1426 if (av.hasHiddenColumns())
1428 maxwidth = av.getAlignment().getHiddenColumns()
1429 .absoluteToVisibleColumn(maxwidth) - 1;
1432 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1438 * close the panel - deregisters all listeners and nulls any references to
1441 public void closePanel()
1443 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1444 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1445 PaintRefresher.RemoveComponent(this);
1450 * try to ensure references are nulled
1452 if (annotationPanel != null)
1454 annotationPanel.dispose();
1455 annotationPanel = null;
1460 av.removePropertyChangeListener(propertyChangeListener);
1461 propertyChangeListener = null;
1462 StructureSelectionManager ssm = av.getStructureSelectionManager();
1463 ssm.removeStructureViewerListener(getSeqPanel(), null);
1464 ssm.removeSelectionListener(getSeqPanel());
1465 ssm.removeCommandListener(av);
1466 ssm.removeStructureViewerListener(getSeqPanel(), null);
1467 ssm.removeSelectionListener(getSeqPanel());
1473 if (Console.isDebugEnabled())
1475 Console.warn("Closing alignment panel which is already closed.");
1481 * Close any open dialogs that would be orphaned when this one is closed
1483 protected void closeChildFrames()
1485 if (overviewPanel != null)
1487 overviewPanel.dispose();
1488 overviewPanel = null;
1490 if (calculationDialog != null)
1492 calculationDialog.closeFrame();
1493 calculationDialog = null;
1498 * hides or shows dynamic annotation rows based on groups and av state flags
1500 public void updateAnnotation()
1502 updateAnnotation(false, false);
1505 public void updateAnnotation(boolean applyGlobalSettings)
1507 updateAnnotation(applyGlobalSettings, false);
1510 public void updateAnnotation(boolean applyGlobalSettings,
1511 boolean preserveNewGroupSettings)
1513 av.updateGroupAnnotationSettings(applyGlobalSettings,
1514 preserveNewGroupSettings);
1515 adjustAnnotationHeight();
1519 public AlignmentI getAlignment()
1521 return av == null ? null : av.getAlignment();
1525 public String getViewName()
1527 return av.getViewName();
1531 * Make/Unmake this alignment panel the current input focus
1535 public void setSelected(boolean b)
1539 if (alignFrame.getSplitViewContainer() != null)
1542 * bring enclosing SplitFrame to front first if there is one
1544 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1546 alignFrame.setSelected(b);
1547 } catch (Exception ex)
1552 setAlignFrameView();
1556 public void setAlignFrameView()
1558 alignFrame.setDisplayedView(this);
1562 public StructureSelectionManager getStructureSelectionManager()
1564 return av.getStructureSelectionManager();
1568 public void raiseOOMWarning(String string, OutOfMemoryError error)
1570 new OOMWarning(string, error, this);
1574 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1577 return new FeatureRenderer(this);
1581 public jalview.api.FeatureRenderer getFeatureRenderer()
1583 return seqPanel.seqCanvas.getFeatureRenderer();
1586 public void updateFeatureRenderer(
1587 jalview.renderer.seqfeatures.FeatureRenderer fr)
1589 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1592 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1594 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1596 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1600 public ScalePanel getScalePanel()
1605 public void setScalePanel(ScalePanel scalePanel)
1607 this.scalePanel = scalePanel;
1610 public SeqPanel getSeqPanel()
1615 public void setSeqPanel(SeqPanel seqPanel)
1617 this.seqPanel = seqPanel;
1620 public AnnotationPanel getAnnotationPanel()
1622 return annotationPanel;
1625 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1627 this.annotationPanel = annotationPanel;
1630 public AnnotationLabels getAlabels()
1635 public void setAlabels(AnnotationLabels alabels)
1637 this.alabels = alabels;
1640 public IdPanel getIdPanel()
1645 public void setIdPanel(IdPanel idPanel)
1647 this.idPanel = idPanel;
1651 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1652 * The aim is to keep the two alignments 'lined up' on their centre columns.
1655 * holds mapped region(s) of this alignment that we are scrolling
1656 * 'to'; may be modified for sequence offset by this method
1657 * @param verticalOffset
1658 * the number of visible sequences to show above the mapped region
1660 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1662 scrollToPosition(sr, verticalOffset, true);
1666 * Set a flag to say do not scroll any (cDNA/protein) complement.
1670 protected void setToScrollComplementPanel(boolean b)
1672 this.scrollComplementaryPanel = b;
1676 * Get whether to scroll complement panel
1678 * @return true if cDNA/protein complement panels should be scrolled
1680 protected boolean isSetToScrollComplementPanel()
1682 return this.scrollComplementaryPanel;
1688 * @adjustHeight if true, try to recalculate panel height for visible
1691 protected void refresh(boolean adjustHeight)
1693 validateAnnotationDimensions(adjustHeight);
1697 // sort, repaint, update overview
1698 paintAlignment(true, false);
1702 // lightweight repaint
1709 * Property change event fired when a change is made to the viewport ranges
1710 * object associated with this alignment panel's viewport
1712 public void propertyChange(PropertyChangeEvent evt)
1714 // update this panel's scroll values based on the new viewport ranges values
1715 ViewportRanges ranges = av.getRanges();
1716 int x = ranges.getStartRes();
1717 int y = ranges.getStartSeq();
1718 setScrollValues(x, y);
1720 // now update any complementary alignment (its viewport ranges object
1721 // is different so does not get automatically updated)
1722 if (isSetToScrollComplementPanel())
1724 setToScrollComplementPanel(false);
1725 av.scrollComplementaryAlignment();
1726 setToScrollComplementPanel(true);
1731 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1732 * reference should be nulled when the dialog is closed.
1734 * @param calculationChooser
1736 public void setCalculationDialog(CalculationChooser calculationChooser)
1738 calculationDialog = calculationChooser;
1742 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1745 public CalculationChooser getCalculationDialog()
1747 return calculationDialog;
1751 * Constructs and sets the title for the Overview window (if there is one),
1752 * including the align frame's title, and view name (if applicable). Returns
1753 * the title, or null if this panel has no Overview window open.
1758 public String setOverviewTitle(AlignFrame alignFrame)
1760 if (this.overviewPanel == null)
1764 String overviewTitle = MessageManager
1765 .formatMessage("label.overview_params", new Object[]
1766 { alignFrame.getTitle() });
1767 String viewName = getViewName();
1768 if (viewName != null)
1770 overviewTitle += (" " + viewName);
1772 overviewPanel.setTitle(overviewTitle);
1773 return overviewTitle;
1777 * If this alignment panel has an Overview panel open, closes it
1779 public void closeOverviewPanel()
1781 if (overviewPanel != null)
1783 overviewPanel.close();
1784 overviewPanel = null;