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.io.exceptions.ImageOutputException;
62 import jalview.jbgui.GAlignmentPanel;
63 import jalview.math.AlignmentDimension;
64 import jalview.schemes.ResidueProperties;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.Comparison;
67 import jalview.util.ImageMaker;
68 import jalview.util.MessageManager;
69 import jalview.util.imagemaker.BitmapImageSizing;
70 import jalview.viewmodel.ViewportListenerI;
71 import jalview.viewmodel.ViewportRanges;
77 * @version $Revision: 1.161 $
79 @SuppressWarnings("serial")
80 public class AlignmentPanel extends GAlignmentPanel implements
81 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
84 * spare space in pixels between sequence id and alignment panel
86 private static final int ID_WIDTH_PADDING = 4;
88 public AlignViewport av;
90 OverviewPanel overviewPanel;
92 private SeqPanel seqPanel;
94 private IdPanel idPanel;
96 IdwidthAdjuster idwidthAdjuster;
98 public AlignFrame alignFrame;
100 private ScalePanel scalePanel;
102 private AnnotationPanel annotationPanel;
104 private AnnotationLabels alabels;
106 private int hextent = 0;
108 private int vextent = 0;
111 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
112 * false, suppresses invoking the same method recursively.
114 private boolean scrollComplementaryPanel = true;
116 private PropertyChangeListener propertyChangeListener;
118 private CalculationChooser calculationDialog;
121 * Creates a new AlignmentPanel object.
126 public AlignmentPanel(AlignFrame af, final AlignViewport av)
128 // 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);
146 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
147 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
149 setScrollValues(0, 0);
151 hscroll.addAdjustmentListener(this);
152 vscroll.addAdjustmentListener(this);
154 addComponentListener(new ComponentAdapter()
157 public void componentResized(ComponentEvent evt)
159 // reset the viewport ranges when the alignment panel is resized
160 // in particular, this initialises the end residue value when Jalview
162 ViewportRanges ranges = av.getRanges();
163 if (av.getWrapAlignment())
165 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
166 getSeqPanel().seqCanvas.getWidth());
167 ranges.setViewportWidth(widthInRes);
171 int widthInRes = getSeqPanel().seqCanvas.getWidth()
173 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
174 / av.getCharHeight();
176 ranges.setViewportWidth(widthInRes);
177 ranges.setViewportHeight(heightInSeq);
183 final AlignmentPanel ap = this;
184 propertyChangeListener = new PropertyChangeListener()
187 public void propertyChange(PropertyChangeEvent evt)
189 if (evt.getPropertyName().equals("alignment"))
191 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
196 av.addPropertyChangeListener(propertyChangeListener);
198 av.getRanges().addPropertyChangeListener(this);
200 adjustAnnotationHeight();
205 public AlignViewportI getAlignViewport()
210 public void alignmentChanged()
212 av.alignmentChanged(this);
214 if (getCalculationDialog() != null)
216 getCalculationDialog().validateCalcTypes();
219 alignFrame.updateEditMenuBar();
221 // no idea if we need to update structure
222 paintAlignment(true, true);
229 public void fontChanged()
231 // set idCanvas bufferedImage to null
232 // to prevent drawing old image
233 FontMetrics fm = getFontMetrics(av.getFont());
235 // update the flag controlling whether the grid is too small to render the
237 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
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();
250 getIdPanel().getIdCanvas().setPreferredSize(d);
251 hscrollFillerPanel.setPreferredSize(d);
257 * Calculates the width of the alignment labels based on the displayed names
258 * and any bounds on label width set in preferences. The calculated width is
259 * also set as a property of the viewport.
261 * @return Dimension giving the maximum width of the alignment label panel
262 * that should be used.
264 public Dimension calculateIdWidth()
266 int oldWidth = av.getIdWidth();
268 // calculate sensible default width when no preference is available
270 if (av.getIdWidth() < 0)
272 r = calculateDefaultAlignmentIdWidth();
273 av.setIdWidth(r.width);
278 r.width = av.getIdWidth();
283 * fudge: if desired width has changed, update layout
284 * (see also paintComponent - updates layout on a repaint)
286 if (r.width != oldWidth)
288 idPanelHolder.setPreferredSize(r);
294 public Dimension calculateDefaultAlignmentIdWidth()
296 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
297 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
298 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
299 return calculateIdWidth(-1);
303 * Calculate the width of the alignment labels based on the displayed names
304 * and any bounds on label width set in preferences.
307 * -1 or maximum width allowed for IdWidth
308 * @return Dimension giving the maximum width of the alignment label panel
309 * that should be used.
311 protected Dimension calculateIdWidth(int maxwidth)
313 Container c = new Container();
315 FontMetrics fm = c.getFontMetrics(
316 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
318 AlignmentI al = av.getAlignment();
322 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
324 SequenceI s = al.getSequenceAt(i);
325 String id = s.getDisplayId(av.getShowJVSuffix());
326 int stringWidth = fm.stringWidth(id);
327 idWidth = Math.max(idWidth, stringWidth);
331 // Also check annotation label widths
334 if (al.getAlignmentAnnotation() != null)
336 fm = c.getFontMetrics(getAlabels().getFont());
338 while (i < al.getAlignmentAnnotation().length)
340 String label = al.getAlignmentAnnotation()[i].label;
341 int stringWidth = fm.stringWidth(label);
342 idWidth = Math.max(idWidth, stringWidth);
347 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
348 w += ID_WIDTH_PADDING;
350 return new Dimension(w, 12);
354 * Highlight the given results on the alignment
357 public void highlightSearchResults(SearchResultsI results)
359 boolean scrolled = scrollToPosition(results, 0, false);
361 boolean fastPaint = !(scrolled && av.getWrapAlignment());
363 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
367 * Scroll the view to show the position of the highlighted region in results
370 * @param searchResults
373 public boolean scrollToPosition(SearchResultsI searchResults)
375 return scrollToPosition(searchResults, 0, false);
379 * Scrolls the view (if necessary) to show the position of the first
380 * highlighted region in results (if any). Answers true if the view was
381 * scrolled, or false if no matched region was found, or it is already
385 * @param verticalOffset
386 * if greater than zero, allows scrolling to a position below the
387 * first displayed sequence
389 * if true, try to centre the search results horizontally in the view
392 protected boolean scrollToPosition(SearchResultsI results,
393 int verticalOffset, boolean centre)
395 int startv, endv, starts, ends;
396 ViewportRanges ranges = av.getRanges();
398 if (results == null || results.isEmpty() || av == null
399 || av.getAlignment() == null)
403 int seqIndex = av.getAlignment().findIndex(results);
408 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
410 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
419 * To centre results, scroll to positions half the visible width
420 * left/right of the start/end positions
424 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
425 start = Math.max(start - offset, 0);
426 end = end + offset - 1;
432 if (end == seq.getEnd())
437 if (av.hasHiddenColumns())
439 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
440 start = hidden.absoluteToVisibleColumn(start);
441 end = hidden.absoluteToVisibleColumn(end);
444 if (!hidden.isVisible(r[0]))
446 // don't scroll - position isn't visible
453 * allow for offset of target sequence (actually scroll to one above it)
455 seqIndex = Math.max(0, seqIndex - verticalOffset);
456 boolean scrollNeeded = true;
458 if (!av.getWrapAlignment())
460 if ((startv = ranges.getStartRes()) >= start)
463 * Scroll left to make start of search results visible
465 setScrollValues(start, seqIndex);
467 else if ((endv = ranges.getEndRes()) <= end)
470 * Scroll right to make end of search results visible
472 setScrollValues(startv + end - endv, seqIndex);
474 else if ((starts = ranges.getStartSeq()) > seqIndex)
477 * Scroll up to make start of search results visible
479 setScrollValues(ranges.getStartRes(), seqIndex);
481 else if ((ends = ranges.getEndSeq()) <= seqIndex)
484 * Scroll down to make end of search results visible
486 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
489 * Else results are already visible - no need to scroll
491 scrollNeeded = false;
495 scrollNeeded = ranges.scrollToWrappedVisible(start);
498 paintAlignment(false, false);
506 * @return DOCUMENT ME!
508 public OverviewPanel getOverviewPanel()
510 return overviewPanel;
519 public void setOverviewPanel(OverviewPanel op)
527 * Hide or show annotation panel
530 public void setAnnotationVisible(boolean b)
532 if (!av.getWrapAlignment())
534 annotationSpaceFillerHolder.setVisible(b);
535 annotationScroller.setVisible(b);
541 * automatically adjust annotation panel height for new annotation whilst
542 * ensuring the alignment is still visible.
545 public void adjustAnnotationHeight()
547 // TODO: display vertical annotation scrollbar if necessary
548 // this is called after loading new annotation onto alignment
549 if (alignFrame.getHeight() == 0)
551 System.out.println("NEEDS FIXING");
553 validateAnnotationDimensions(true);
555 // TODO: many places call this method and also paintAlignment with various
556 // different settings. this means multiple redraws are triggered...
557 paintAlignment(true, av.needToUpdateStructureViews());
561 * calculate the annotation dimensions and refresh slider values accordingly.
562 * need to do repaints/notifys afterwards.
564 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
566 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
567 // are not changing ancestors, and keyboard action listeners do
568 // not need to be reset. addNotify() is a very expensive operation,
569 // requiring a full re-layout of all parents and children.
570 // Note in JComponent:
571 // This method is called by the toolkit internally and should
572 // not be called directly by programs.
573 // I note that addNotify() is called in several areas of Jalview.
575 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
576 annotationHeight = getAnnotationPanel()
577 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
580 annotationScroller.setPreferredSize(
581 new Dimension(annotationScroller.getWidth(), annotationHeight));
583 Dimension e = idPanel.getSize();
584 alabels.setSize(new Dimension(e.width, annotationHeight));
586 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
587 annotationSpaceFillerHolder.getWidth(), annotationHeight));
588 annotationScroller.validate();
589 annotationScroller.addNotify();
593 * update alignment layout for viewport settings
598 public void updateLayout()
601 setAnnotationVisible(av.isShowAnnotation());
602 boolean wrap = av.getWrapAlignment();
603 ViewportRanges ranges = av.getRanges();
604 ranges.setStartSeq(0);
605 scalePanelHolder.setVisible(!wrap);
606 hscroll.setVisible(!wrap);
607 idwidthAdjuster.setVisible(!wrap);
611 annotationScroller.setVisible(false);
612 annotationSpaceFillerHolder.setVisible(false);
614 else if (av.isShowAnnotation())
616 annotationScroller.setVisible(true);
617 annotationSpaceFillerHolder.setVisible(true);
618 validateAnnotationDimensions(false);
621 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
623 { // may not yet be laid out
626 int widthInRes = getSeqPanel().seqCanvas
627 .getWrappedCanvasWidth(canvasWidth);
628 ranges.setViewportWidth(widthInRes);
632 int widthInRes = (canvasWidth / av.getCharWidth());
633 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
634 / av.getCharHeight());
636 ranges.setViewportWidth(widthInRes);
637 ranges.setViewportHeight(heightInSeq);
641 idSpaceFillerPanel1.setVisible(!wrap);
647 * Adjust row/column scrollers to show a visible position in the alignment.
650 * visible column to scroll to
652 * visible row to scroll to
655 public void setScrollValues(int xpos, int ypos)
660 if (av == null || av.getAlignment() == null)
665 if (av.getWrapAlignment())
667 setScrollingForWrappedPanel(x);
671 int width = av.getAlignment().getVisibleWidth();
672 int height = av.getAlignment().getHeight();
674 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
675 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
682 if (vextent > height)
687 if ((hextent + x) > width)
692 if ((vextent + y) > height)
694 y = height - vextent;
707 // update the scroll values
708 hscroll.setValues(x, hextent, 0, width);
709 vscroll.setValues(y, vextent, 0, height);
714 * Respond to adjustment event when horizontal or vertical scrollbar is
718 * adjustment event encoding whether hscroll or vscroll changed
721 public void adjustmentValueChanged(AdjustmentEvent evt)
723 if (av.getWrapAlignment())
725 adjustScrollingWrapped(evt);
729 ViewportRanges ranges = av.getRanges();
731 if (evt.getSource() == hscroll)
733 int oldX = ranges.getStartRes();
734 int oldwidth = ranges.getViewportWidth();
735 int x = hscroll.getValue();
736 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
738 // if we're scrolling to the position we're already at, stop
739 // this prevents infinite recursion of events when the scroll/viewport
740 // ranges values are the same
741 if ((x == oldX) && (width == oldwidth))
745 ranges.setViewportStartAndWidth(x, width);
747 else if (evt.getSource() == vscroll)
749 int oldY = ranges.getStartSeq();
750 int oldheight = ranges.getViewportHeight();
751 int y = vscroll.getValue();
752 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
754 // if we're scrolling to the position we're already at, stop
755 // this prevents infinite recursion of events when the scroll/viewport
756 // ranges values are the same
757 if ((y == oldY) && (height == oldheight))
761 ranges.setViewportStartAndHeight(y, height);
767 * Responds to a scroll change by setting the start position of the viewport.
772 protected void adjustScrollingWrapped(AdjustmentEvent evt)
774 if (evt.getSource() == hscroll)
776 return; // no horizontal scroll when wrapped
778 final ViewportRanges ranges = av.getRanges();
780 if (evt.getSource() == vscroll)
782 int newY = vscroll.getValue();
785 * if we're scrolling to the position we're already at, stop
786 * this prevents infinite recursion of events when the scroll/viewport
787 * ranges values are the same
789 int oldX = ranges.getStartRes();
790 int oldY = ranges.getWrappedScrollPosition(oldX);
798 * limit page up/down to one width's worth of positions
800 int rowSize = ranges.getViewportWidth();
801 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
802 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
807 // This is only called if file loaded is a jar file that
808 // was wrapped when saved and user has wrap alignment true
809 // as preference setting
810 SwingUtilities.invokeLater(new Runnable()
815 // When updating scrolling to use ViewportChange events, this code
816 // could not be validated and it is not clear if it is now being
817 // called. Log warning here in case it is called and unforeseen
820 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
822 // scroll to start of panel
823 ranges.setStartRes(0);
824 ranges.setStartSeq(0);
832 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
835 public void paintAlignment(boolean updateOverview,
836 boolean updateStructures)
838 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
839 av.isShowAutocalculatedAbove());
840 sorter.sort(getAlignment().getAlignmentAnnotation(),
841 av.getSortAnnotationsBy());
844 if (updateStructures)
846 av.getStructureSelectionManager().sequenceColoursChanged(this);
851 if (overviewPanel != null)
853 overviewPanel.updateOverviewImage();
859 public void paintComponent(Graphics g)
861 invalidate(); // needed so that the id width adjuster works correctly
863 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
864 idPanelHolder.setPreferredSize(d);
865 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
867 validate(); // needed so that the id width adjuster works correctly
870 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
871 * though I still think this call should be elsewhere.
873 ViewportRanges ranges = av.getRanges();
874 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
875 super.paintComponent(g);
879 * Set vertical scroll bar position, and number of increments, for wrapped
882 * @param topLeftColumn
883 * the column position at top left (0..)
885 private void setScrollingForWrappedPanel(int topLeftColumn)
887 ViewportRanges ranges = av.getRanges();
888 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
889 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
892 * a scrollbar's value can be set to at most (maximum-extent)
893 * so we add extent (1) to the maxScroll value
895 vscroll.setUnitIncrement(1);
896 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
909 * @return DOCUMENT ME!
911 * @throws PrinterException
915 public int print(Graphics pg, PageFormat pf, int pi)
916 throws PrinterException
918 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
920 int pwidth = (int) pf.getImageableWidth();
921 int pheight = (int) pf.getImageableHeight();
923 if (av.getWrapAlignment())
925 return printWrappedAlignment(pwidth, pheight, pi, pg);
929 return printUnwrapped(pwidth, pheight, pi, pg, pg);
934 * Draws the alignment image, including sequence ids, sequences, and
935 * annotation labels and annotations if shown, on either one or two Graphics
945 * the graphics context for sequence ids and annotation labels
946 * @param alignmentGraphics
947 * the graphics context for sequences and annotations (may or may not
948 * be the same context as idGraphics)
950 * @throws PrinterException
952 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
953 Graphics idGraphics, Graphics alignmentGraphics)
954 throws PrinterException
956 final int idWidth = getVisibleIdWidth(false);
959 * Get the horizontal offset to where we draw the sequences.
960 * This is idWidth if using a single Graphics context, else zero.
962 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
965 FontMetrics fm = getFontMetrics(av.getFont());
966 final int charHeight = av.getCharHeight();
967 final int scaleHeight = charHeight + fm.getDescent();
969 idGraphics.setColor(Color.white);
970 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
971 idGraphics.setFont(av.getFont());
974 * How many sequences and residues can we fit on a printable page?
976 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
978 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
980 final int alignmentWidth = av.getAlignment().getVisibleWidth();
981 int pagesWide = (alignmentWidth / totalRes) + 1;
983 final int startRes = (pageIndex % pagesWide) * totalRes;
984 final int endRes = Math.min(startRes + totalRes - 1,
987 final int startSeq = (pageIndex / pagesWide) * totalSeq;
988 final int alignmentHeight = av.getAlignment().getHeight();
989 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
991 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
993 if (av.isShowAnnotation())
995 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
998 pagesHigh /= pageHeight;
1000 if (pageIndex >= (pagesWide * pagesHigh))
1002 return Printable.NO_SUCH_PAGE;
1004 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1007 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1009 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1010 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1011 pageWidth - idWidth, scaleHeight);
1012 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1015 * Draw the sequence ids, offset for scale height,
1016 * then reset to top left (0, 0)
1018 idGraphics.translate(0, scaleHeight);
1019 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1020 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1021 : av.getSelectionGroup().getSequences(null);
1022 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1025 idGraphics.setFont(av.getFont());
1026 idGraphics.translate(0, -scaleHeight);
1029 * draw the sequences, offset for scale height, and id width (if using a
1030 * single graphics context), then reset to (0, scale height)
1032 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1033 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1034 startRes, endRes, startSeq, endSeq - 1);
1035 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1037 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1040 * draw annotation labels; drawComponent() translates by
1041 * getScrollOffset(), so compensate for that first;
1042 * then reset to (0, scale height)
1044 int offset = getAlabels().getScrollOffset();
1045 idGraphics.translate(0, -offset);
1046 idGraphics.translate(0, alignmentDrawnHeight);
1047 getAlabels().drawComponent(idGraphics, idWidth);
1048 idGraphics.translate(0, -alignmentDrawnHeight);
1051 * draw the annotations starting at
1052 * (idOffset, alignmentHeight) from (0, scaleHeight)
1054 alignmentGraphics.translate(alignmentGraphicsOffset,
1055 alignmentDrawnHeight);
1057 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1058 alignmentGraphics, -1, startRes, endRes + 1);
1061 return Printable.PAGE_EXISTS;
1065 * Prints one page of an alignment in wrapped mode. Returns
1066 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1067 * no page could be drawn (page number out of range).
1077 * @throws PrinterException
1079 public int printWrappedAlignment(int pageWidth, int pageHeight,
1080 int pageNumber, Graphics g) throws PrinterException
1082 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1084 int annotationHeight = 0;
1085 if (av.isShowAnnotation())
1087 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1090 int hgap = av.getCharHeight();
1091 if (av.getScaleAboveWrapped())
1093 hgap += av.getCharHeight();
1096 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1099 int idWidth = getVisibleIdWidth(false);
1101 int maxwidth = av.getAlignment().getVisibleWidth();
1103 int resWidth = getSeqPanel().seqCanvas
1104 .getWrappedCanvasWidth(pageWidth - idWidth);
1105 av.getRanges().setViewportStartAndWidth(0, resWidth);
1107 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1109 g.setColor(Color.white);
1110 g.fillRect(0, 0, pageWidth, pageHeight);
1111 g.setFont(av.getFont());
1112 g.setColor(Color.black);
1115 * method: print the whole wrapped alignment, but with a clip region that
1116 * is restricted to the requested page; this supports selective print of
1117 * single pages or ranges, (at the cost of repeated processing in the
1118 * 'normal' case, when all pages are printed)
1120 g.translate(0, -pageNumber * pageHeight);
1122 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1125 * draw sequence ids and annotation labels (if shown)
1127 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1128 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1130 g.translate(idWidth, 0);
1132 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1133 pageWidth - idWidth, totalHeight, 0);
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 protected int getVisibleIdWidth(boolean onscreen)
1167 // see if rendering offscreen - check preferences and calc width accordingly
1168 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1170 return calculateIdWidth(-1).width;
1172 Integer idwidth = onscreen ? null
1173 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1174 if (idwidth != null)
1176 return idwidth.intValue() + ID_WIDTH_PADDING;
1179 int w = getIdPanel().getWidth();
1180 return (w > 0 ? w : calculateIdWidth().width);
1183 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1184 throws ImageOutputException
1186 makeAlignmentImage(type, file, renderer,
1187 BitmapImageSizing.nullBitmapImageSizing());
1191 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1192 * writes it to the specified file
1196 * @param textrenderer
1197 * @param bitmapscale
1199 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1200 BitmapImageSizing userBis) throws ImageOutputException
1202 final int borderBottomOffset = 5;
1204 AlignmentDimension aDimension = getAlignmentDimension();
1205 // todo use a lambda function in place of callback here?
1206 ImageWriterI writer = new ImageWriterI()
1209 public void exportImage(Graphics graphics) throws Exception
1211 if (av.getWrapAlignment())
1213 printWrappedAlignment(aDimension.getWidth(),
1214 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1218 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1219 graphics, graphics);
1224 String fileTitle = alignFrame.getTitle();
1225 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1227 int imageWidth = aDimension.getWidth();
1228 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1229 String of = MessageManager.getString("label.alignment");
1230 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1235 * Calculates and returns a suitable width and height (in pixels) for an
1240 public AlignmentDimension getAlignmentDimension()
1242 int maxwidth = av.getAlignment().getVisibleWidth();
1244 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1245 + getScalePanel().getHeight();
1246 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1248 if (av.getWrapAlignment())
1250 height = getWrappedHeight();
1251 if (Jalview.isHeadlessMode())
1253 // need to obtain default alignment width and then add in any
1254 // additional allowance for id margin
1255 // this duplicates the calculation in getWrappedHeight but adjusts for
1257 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1258 - alignFrame.getInsets().left - alignFrame.getInsets().right
1259 - getVisibleIdWidth() + getVisibleIdWidth(false);
1263 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1267 else if (av.isShowAnnotation())
1269 height += getAnnotationPanel().adjustPanelHeight() + 3;
1271 return new AlignmentDimension(width, height);
1275 public void makePNGImageMap(File imgMapFile, String imageName)
1276 throws ImageOutputException
1278 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1279 // ////////////////////////////////////////////
1280 int idWidth = getVisibleIdWidth(false);
1281 FontMetrics fm = getFontMetrics(av.getFont());
1282 int scaleHeight = av.getCharHeight() + fm.getDescent();
1285 // ////////////////////////////////
1286 if (imgMapFile != null)
1290 int sSize = av.getAlignment().getHeight();
1291 int alwidth = av.getAlignment().getWidth();
1292 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1293 out.println(HTMLOutput.getImageMapHTML());
1294 out.println("<img src=\"" + imageName
1295 + "\" border=\"0\" usemap=\"#Map\" >"
1296 + "<map name=\"Map\">");
1298 for (int s = 0; s < sSize; s++)
1300 int sy = s * av.getCharHeight() + scaleHeight;
1302 SequenceI seq = av.getAlignment().getSequenceAt(s);
1303 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1304 for (int column = 0; column < alwidth; column++)
1306 StringBuilder text = new StringBuilder(512);
1307 String triplet = null;
1308 if (av.getAlignment().isNucleotide())
1310 triplet = ResidueProperties.nucleotideName
1311 .get(seq.getCharAt(column) + "");
1315 triplet = ResidueProperties.aa2Triplet
1316 .get(seq.getCharAt(column) + "");
1319 if (triplet == null)
1324 int seqPos = seq.findPosition(column);
1325 int gSize = groups.length;
1326 for (int g = 0; g < gSize; g++)
1328 if (text.length() < 1)
1330 text.append("<area shape=\"rect\" coords=\"")
1331 .append((idWidth + column * av.getCharWidth()))
1332 .append(",").append(sy).append(",")
1334 + (column + 1) * av.getCharWidth()))
1335 .append(",").append((av.getCharHeight() + sy))
1336 .append("\"").append(" onMouseOver=\"toolTip('")
1337 .append(seqPos).append(" ").append(triplet);
1340 if (groups[g].getStartRes() < column
1341 && groups[g].getEndRes() > column)
1343 text.append("<br><em>").append(groups[g].getName())
1348 if (text.length() < 1)
1350 text.append("<area shape=\"rect\" coords=\"")
1351 .append((idWidth + column * av.getCharWidth()))
1352 .append(",").append(sy).append(",")
1353 .append((idWidth + (column + 1) * av.getCharWidth()))
1354 .append(",").append((av.getCharHeight() + sy))
1355 .append("\"").append(" onMouseOver=\"toolTip('")
1356 .append(seqPos).append(" ").append(triplet);
1358 if (!Comparison.isGap(seq.getCharAt(column)))
1360 List<SequenceFeature> features = seq.findFeatures(column,
1362 for (SequenceFeature sf : features)
1364 if (sf.isContactFeature())
1366 text.append("<br>").append(sf.getType()).append(" ")
1367 .append(sf.getBegin()).append(":")
1368 .append(sf.getEnd());
1372 text.append("<br>");
1373 text.append(sf.getType());
1374 String description = sf.getDescription();
1375 if (description != null
1376 && !sf.getType().equals(description))
1378 description = description.replace("\"", """);
1379 text.append(" ").append(description);
1382 String status = sf.getStatus();
1383 if (status != null && !"".equals(status))
1385 text.append(" (").append(status).append(")");
1388 if (text.length() > 1)
1390 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1391 out.println(text.toString());
1396 out.println("</map></body></html>");
1399 } catch (Exception ex)
1401 throw new ImageOutputException(
1402 "couldn't write ImageMap due to unexpected error", ex);
1404 } // /////////END OF IMAGE MAP
1409 * Answers the height of the entire alignment in pixels, assuming it is in
1414 int getWrappedHeight()
1416 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1418 if (System.getProperty("java.awt.headless") != null
1419 && System.getProperty("java.awt.headless").equals("true"))
1421 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1422 - vscroll.getPreferredSize().width
1423 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1426 int chunkWidth = getSeqPanel().seqCanvas
1427 .getWrappedCanvasWidth(seqPanelWidth);
1429 int hgap = av.getCharHeight();
1430 if (av.getScaleAboveWrapped())
1432 hgap += av.getCharHeight();
1435 int annotationHeight = 0;
1436 if (av.isShowAnnotation())
1438 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1439 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1442 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1445 int maxwidth = av.getAlignment().getWidth();
1446 if (av.hasHiddenColumns())
1448 maxwidth = av.getAlignment().getHiddenColumns()
1449 .absoluteToVisibleColumn(maxwidth) - 1;
1452 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1458 * close the panel - deregisters all listeners and nulls any references to
1461 public void closePanel()
1463 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1464 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1465 PaintRefresher.RemoveComponent(this);
1470 * try to ensure references are nulled
1472 if (annotationPanel != null)
1474 annotationPanel.dispose();
1475 annotationPanel = null;
1480 av.removePropertyChangeListener(propertyChangeListener);
1481 propertyChangeListener = null;
1482 StructureSelectionManager ssm = av.getStructureSelectionManager();
1483 ssm.removeStructureViewerListener(getSeqPanel(), null);
1484 ssm.removeSelectionListener(getSeqPanel());
1485 ssm.removeCommandListener(av);
1486 ssm.removeStructureViewerListener(getSeqPanel(), null);
1487 ssm.removeSelectionListener(getSeqPanel());
1493 if (Console.isDebugEnabled())
1495 Console.warn("Closing alignment panel which is already closed.");
1501 * Close any open dialogs that would be orphaned when this one is closed
1503 protected void closeChildFrames()
1505 if (overviewPanel != null)
1507 overviewPanel.dispose();
1508 overviewPanel = null;
1510 if (calculationDialog != null)
1512 calculationDialog.closeFrame();
1513 calculationDialog = null;
1518 * hides or shows dynamic annotation rows based on groups and av state flags
1520 public void updateAnnotation()
1522 updateAnnotation(false, false);
1525 public void updateAnnotation(boolean applyGlobalSettings)
1527 updateAnnotation(applyGlobalSettings, false);
1530 public void updateAnnotation(boolean applyGlobalSettings,
1531 boolean preserveNewGroupSettings)
1533 av.updateGroupAnnotationSettings(applyGlobalSettings,
1534 preserveNewGroupSettings);
1535 adjustAnnotationHeight();
1539 public AlignmentI getAlignment()
1541 return av == null ? null : av.getAlignment();
1545 public String getViewName()
1547 return av.getViewName();
1551 * Make/Unmake this alignment panel the current input focus
1555 public void setSelected(boolean b)
1559 if (alignFrame.getSplitViewContainer() != null)
1562 * bring enclosing SplitFrame to front first if there is one
1564 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1566 alignFrame.setSelected(b);
1567 } catch (Exception ex)
1572 setAlignFrameView();
1576 public void setAlignFrameView()
1578 alignFrame.setDisplayedView(this);
1582 public StructureSelectionManager getStructureSelectionManager()
1584 return av.getStructureSelectionManager();
1588 public void raiseOOMWarning(String string, OutOfMemoryError error)
1590 new OOMWarning(string, error, this);
1594 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1597 return new FeatureRenderer(this);
1601 public jalview.api.FeatureRenderer getFeatureRenderer()
1603 return seqPanel.seqCanvas.getFeatureRenderer();
1606 public void updateFeatureRenderer(
1607 jalview.renderer.seqfeatures.FeatureRenderer fr)
1609 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1612 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1614 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1616 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1620 public ScalePanel getScalePanel()
1625 public void setScalePanel(ScalePanel scalePanel)
1627 this.scalePanel = scalePanel;
1630 public SeqPanel getSeqPanel()
1635 public void setSeqPanel(SeqPanel seqPanel)
1637 this.seqPanel = seqPanel;
1640 public AnnotationPanel getAnnotationPanel()
1642 return annotationPanel;
1645 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1647 this.annotationPanel = annotationPanel;
1650 public AnnotationLabels getAlabels()
1655 public void setAlabels(AnnotationLabels alabels)
1657 this.alabels = alabels;
1660 public IdPanel getIdPanel()
1665 public void setIdPanel(IdPanel idPanel)
1667 this.idPanel = idPanel;
1671 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1672 * The aim is to keep the two alignments 'lined up' on their centre columns.
1675 * holds mapped region(s) of this alignment that we are scrolling
1676 * 'to'; may be modified for sequence offset by this method
1677 * @param verticalOffset
1678 * the number of visible sequences to show above the mapped region
1680 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1682 scrollToPosition(sr, verticalOffset, true);
1686 * Set a flag to say do not scroll any (cDNA/protein) complement.
1690 protected void setToScrollComplementPanel(boolean b)
1692 this.scrollComplementaryPanel = b;
1696 * Get whether to scroll complement panel
1698 * @return true if cDNA/protein complement panels should be scrolled
1700 protected boolean isSetToScrollComplementPanel()
1702 return this.scrollComplementaryPanel;
1708 * @adjustHeight if true, try to recalculate panel height for visible
1711 protected void refresh(boolean adjustHeight)
1713 validateAnnotationDimensions(adjustHeight);
1717 // sort, repaint, update overview
1718 paintAlignment(true, false);
1722 // lightweight repaint
1729 * Property change event fired when a change is made to the viewport ranges
1730 * object associated with this alignment panel's viewport
1732 public void propertyChange(PropertyChangeEvent evt)
1734 // update this panel's scroll values based on the new viewport ranges values
1735 ViewportRanges ranges = av.getRanges();
1736 int x = ranges.getStartRes();
1737 int y = ranges.getStartSeq();
1738 setScrollValues(x, y);
1740 // now update any complementary alignment (its viewport ranges object
1741 // is different so does not get automatically updated)
1742 if (isSetToScrollComplementPanel())
1744 setToScrollComplementPanel(false);
1745 av.scrollComplementaryAlignment();
1746 setToScrollComplementPanel(true);
1751 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1752 * reference should be nulled when the dialog is closed.
1754 * @param calculationChooser
1756 public void setCalculationDialog(CalculationChooser calculationChooser)
1758 calculationDialog = calculationChooser;
1762 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1765 public CalculationChooser getCalculationDialog()
1767 return calculationDialog;
1771 * Constructs and sets the title for the Overview window (if there is one),
1772 * including the align frame's title, and view name (if applicable). Returns
1773 * the title, or null if this panel has no Overview window open.
1778 public String setOverviewTitle(AlignFrame alignFrame)
1780 if (this.overviewPanel == null)
1784 String overviewTitle = MessageManager
1785 .formatMessage("label.overview_params", new Object[]
1786 { alignFrame.getTitle() });
1787 String viewName = getViewName();
1788 if (viewName != null)
1790 overviewTitle += (" " + viewName);
1792 overviewPanel.setTitle(overviewTitle);
1793 return overviewTitle;
1797 * If this alignment panel has an Overview panel open, closes it
1799 public void closeOverviewPanel()
1801 if (overviewPanel != null)
1803 overviewPanel.close();
1804 overviewPanel = null;