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.Jalview;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.HiddenColumns;
54 import jalview.datamodel.SearchResultsI;
55 import jalview.datamodel.SequenceFeature;
56 import jalview.datamodel.SequenceGroup;
57 import jalview.datamodel.SequenceI;
58 import jalview.gui.ImageExporter.ImageWriterI;
59 import jalview.io.HTMLOutput;
60 import jalview.jbgui.GAlignmentPanel;
61 import jalview.math.AlignmentDimension;
62 import jalview.schemes.ResidueProperties;
63 import jalview.structure.StructureSelectionManager;
64 import jalview.util.Comparison;
65 import jalview.util.ImageMaker;
66 import jalview.util.MessageManager;
67 import jalview.viewmodel.AlignmentViewport;
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);
182 final AlignmentPanel ap = this;
183 propertyChangeListener = new PropertyChangeListener()
186 public void propertyChange(PropertyChangeEvent evt)
188 switch (evt.getPropertyName()) {
189 case AlignmentViewport.PROPERTY_SEQUENCE:
190 updateScrollBarsFromRanges();
191 if (annotationPanel != null)
192 annotationPanel.paintImmediately(0, 0, getWidth(), getHeight());
194 case AlignmentViewport.PROPERTY_ALIGNMENT:
195 updateScrollBarsFromRanges();
196 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
202 av.addPropertyChangeListener(propertyChangeListener);
204 av.getRanges().addPropertyChangeListener(this);
206 adjustAnnotationHeight();
211 public AlignViewportI getAlignViewport()
216 public void alignmentChanged()
218 av.alignmentChanged(this);
220 if (getCalculationDialog() != null)
222 getCalculationDialog().validateCalcTypes();
225 alignFrame.updateEditMenuBar();
227 // no idea if we need to update structure
228 paintAlignment(true, true);
235 public void fontChanged()
237 // set idCanvas bufferedImage to null
238 // to prevent drawing old image
239 FontMetrics fm = getFontMetrics(av.getFont());
241 scalePanelHolder.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idSpaceFillerPanel1.setPreferredSize(
244 new Dimension(10, av.getCharHeight() + fm.getDescent()));
245 idwidthAdjuster.invalidate();
246 scalePanelHolder.invalidate();
247 // BH 2018 getIdPanel().getIdCanvas().gg = null;
248 getSeqPanel().seqCanvas.img = null;
249 getAnnotationPanel().adjustPanelHeight();
251 Dimension d = calculateIdWidth();
252 getIdPanel().getIdCanvas().setPreferredSize(d);
253 hscrollFillerPanel.setPreferredSize(d);
259 * Calculates the width of the alignment labels based on the displayed names
260 * and any bounds on label width set in preferences. The calculated width is
261 * also set as a property of the viewport.
263 * @return Dimension giving the maximum width of the alignment label panel
264 * that should be used.
266 public Dimension calculateIdWidth()
268 int oldWidth = av.getIdWidth();
270 // calculate sensible default width when no preference is available
272 if (av.getIdWidth() < 0)
274 int maxWidth = getMaxWidth();
275 d = calculateIdWidth(maxWidth);
276 av.setIdWidth(d.width);
281 d.width = av.getIdWidth();
286 * fudge: if desired width has changed, update layout
287 * (see also paintComponent - updates layout on a repaint)
289 if (d.width != oldWidth)
291 idPanelHolder.setPreferredSize(d);
297 public int getMaxWidth()
299 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
300 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
301 return Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
305 * Calculate the width of the alignment labels based on the displayed names
306 * and any bounds on label width set in preferences.
309 * -1 or maximum width allowed for IdWidth
310 * @return Dimension giving the maximum width of the alignment label panel
311 * that should be used.
313 public Dimension calculateIdWidth(int maxwidth)
315 Container c = this;// new Container();
316 FontMetrics fm = c.getFontMetrics(
317 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
319 AlignmentI al = av.getAlignment();
323 boolean withSuffix = av.getShowJVSuffix();
325 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
327 SequenceI s = al.getSequenceAt(i);
328 String id = s.getDisplayId(withSuffix);
329 int stringWidth = fm.stringWidth(id);
330 idWidth = Math.max(idWidth, stringWidth);
334 // Also check annotation label widths
337 if (al.getAlignmentAnnotation() != null)
339 fm = c.getFontMetrics(getAlabels().getFont());
341 while (i < al.getAlignmentAnnotation().length)
343 String label = al.getAlignmentAnnotation()[i].label;
344 int stringWidth = fm.stringWidth(label);
345 idWidth = Math.max(idWidth, stringWidth);
350 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
351 w += ID_WIDTH_PADDING;
353 return new Dimension(w, 12);
357 * Highlight the given results on the alignment
360 public void highlightSearchResults(SearchResultsI results)
362 boolean scrolled = scrollToPosition(results, 0, false);
364 boolean fastPaint = !(scrolled && av.getWrapAlignment());
366 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
370 * Scroll the view to show the position of the highlighted region in results
373 * @param searchResults
376 public boolean scrollToPosition(SearchResultsI searchResults)
378 return scrollToPosition(searchResults, 0, false);
382 * Scrolls the view (if necessary) to show the position of the first
383 * highlighted region in results (if any). Answers true if the view was
384 * scrolled, or false if no matched region was found, or it is already
388 * @param verticalOffset
389 * if greater than zero, allows scrolling to a position below the
390 * first displayed sequence
392 * if true, try to centre the search results horizontally in the view
395 protected boolean scrollToPosition(SearchResultsI results,
396 int verticalOffset, boolean centre)
398 int startv, endv, starts, ends;
399 ViewportRanges ranges = av.getRanges();
401 if (results == null || results.isEmpty() || av == null
402 || av.getAlignment() == null)
406 int seqIndex = av.getAlignment().findIndex(results);
411 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
413 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
422 * To centre results, scroll to positions half the visible width
423 * left/right of the start/end positions
427 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
428 start = Math.max(start - offset, 0);
429 end = end + offset - 1;
435 if (end == seq.getEnd())
440 if (av.hasHiddenColumns())
442 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
443 start = hidden.absoluteToVisibleColumn(start);
444 end = hidden.absoluteToVisibleColumn(end);
447 if (!hidden.isVisible(r[0]))
449 // don't scroll - position isn't visible
456 * allow for offset of target sequence (actually scroll to one above it)
458 seqIndex = Math.max(0, seqIndex - verticalOffset);
459 boolean scrollNeeded = true;
461 if (!av.getWrapAlignment())
463 if ((startv = ranges.getStartRes()) >= start)
466 * Scroll left to make start of search results visible
468 setScrollValues(start, seqIndex);
470 else if ((endv = ranges.getEndRes()) <= end)
473 * Scroll right to make end of search results visible
475 setScrollValues(startv + end - endv, seqIndex);
477 else if ((starts = ranges.getStartSeq()) > seqIndex)
480 * Scroll up to make start of search results visible
482 setScrollValues(ranges.getStartRes(), seqIndex);
484 else if ((ends = ranges.getEndSeq()) <= seqIndex)
487 * Scroll down to make end of search results visible
489 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
492 * Else results are already visible - no need to scroll
494 scrollNeeded = false;
498 scrollNeeded = ranges.scrollToWrappedVisible(start);
501 paintAlignment(false, false);
509 * @return DOCUMENT ME!
511 public OverviewPanel getOverviewPanel()
513 return overviewPanel;
522 public void setOverviewPanel(OverviewPanel op)
530 * Hide or show annotation panel
533 public void setAnnotationVisible(boolean b)
535 if (!av.getWrapAlignment())
537 annotationSpaceFillerHolder.setVisible(b);
538 annotationScroller.setVisible(b);
544 * automatically adjust annotation panel height for new annotation whilst
545 * ensuring the alignment is still visible.
548 public void adjustAnnotationHeight()
550 // TODO: display vertical annotation scrollbar if necessary
551 // this is called after loading new annotation onto alignment
552 if (alignFrame.getHeight() == 0)
554 System.out.println("NEEDS FIXING");
556 validateAnnotationDimensions(true);
558 // TODO: many places call this method and also paintAlignment with various
559 // different settings. this means multiple redraws are triggered...
560 paintAlignment(true, av.needToUpdateStructureViews());
564 * calculate the annotation dimensions and refresh slider values accordingly.
565 * need to do repaints/notifys afterwards.
567 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
569 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
570 // are not changing ancestors, and keyboard action listeners do
571 // not need to be reset. addNotify() is a very expensive operation,
572 // requiring a full re-layout of all parents and children.
573 // Note in JComponent:
574 // This method is called by the toolkit internally and should
575 // not be called directly by programs.
576 // I note that addNotify() is called in several areas of Jalview.
578 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
579 annotationHeight = getAnnotationPanel()
580 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
583 annotationScroller.setPreferredSize(
584 new Dimension(annotationScroller.getWidth(), annotationHeight));
586 Dimension e = idPanel.getSize();
587 alabels.setSize(new Dimension(e.width, annotationHeight));
589 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
590 annotationSpaceFillerHolder.getWidth(), annotationHeight));
591 annotationScroller.validate();
592 annotationScroller.addNotify();
596 * update alignment layout for viewport settings
601 public void updateLayout()
603 ViewportRanges ranges = av.getRanges();
605 setAnnotationVisible(av.isShowAnnotation());
606 boolean wrap = av.getWrapAlignment();
607 ranges.setStartSeq(0);
608 scalePanelHolder.setVisible(!wrap);
609 hscroll.setVisible(!wrap);
610 idwidthAdjuster.setVisible(!wrap);
614 annotationScroller.setVisible(false);
615 annotationSpaceFillerHolder.setVisible(false);
617 else if (av.isShowAnnotation())
619 annotationScroller.setVisible(true);
620 annotationSpaceFillerHolder.setVisible(true);
621 validateAnnotationDimensions(false);
624 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
626 { // may not yet be laid out
629 int widthInRes = getSeqPanel().seqCanvas
630 .getWrappedCanvasWidth(canvasWidth);
631 ranges.setViewportWidth(widthInRes);
635 int widthInRes = (canvasWidth / av.getCharWidth());
636 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
637 / av.getCharHeight());
639 ranges.setViewportWidth(widthInRes);
640 ranges.setViewportHeight(heightInSeq);
644 idSpaceFillerPanel1.setVisible(!wrap);
650 * Adjust row/column scrollers to show a visible position in the alignment.
653 * visible column to scroll to
655 * visible row to scroll to
658 public void setScrollValues(int xpos, int ypos)
663 if (av == null || av.getAlignment() == null)
668 if (av.getWrapAlignment())
670 setScrollingForWrappedPanel(x);
674 int width = av.getAlignment().getVisibleWidth();
675 int height = av.getAlignment().getHeight();
677 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
678 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
685 if (vextent > height)
690 if ((hextent + x) > width)
695 if ((vextent + y) > height)
697 y = height - vextent;
711 updateScrollBars(x, y, width, height);
715 private void updateScrollBars(int x, int y, int width, int height)
717 hscroll.setValues(x, hextent, 0, width);
718 vscroll.setValues(y, vextent, 0, height);
722 * Respond to adjustment event when horizontal or vertical scrollbar is
726 * adjustment event encoding whether hscroll or vscroll changed
729 public void adjustmentValueChanged(AdjustmentEvent evt)
731 if (av.getWrapAlignment())
733 adjustScrollingWrapped(evt);
737 if (evt.getSource() == hscroll)
739 if (!updateRanges(hscroll.getValue(), Integer.MIN_VALUE))
742 else if (evt.getSource() == vscroll)
744 if (!updateRanges(Integer.MIN_VALUE, vscroll.getValue()))
750 private boolean updateRanges(int x, int y)
752 ViewportRanges ranges = av.getRanges();
753 boolean isChanged = false;
754 if (x != Integer.MIN_VALUE)
756 int oldX = ranges.getStartRes();
757 int oldwidth = ranges.getViewportWidth();
758 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
760 // if we're scrolling to the position we're already at, stop
761 // this prevents infinite recursion of events when the scroll/viewport
762 // ranges values are the same
763 if (width > 0 && (x != oldX || width != oldwidth))
765 ranges.setViewportStartAndWidth(x, width);
769 if (y != Integer.MIN_VALUE)
771 int oldY = ranges.getStartSeq();
772 int oldheight = ranges.getViewportHeight();
773 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
775 // if we're scrolling to the position we're already at, stop
776 // this prevents infinite recursion of events when the scroll/viewport
777 // ranges values are the same
778 if (height > 0 && (y != oldY || height != oldheight))
780 ranges.setViewportStartAndHeight(y, height);
788 * Responds to a scroll change by setting the start position of the viewport.
793 protected void adjustScrollingWrapped(AdjustmentEvent evt)
795 if (evt.getSource() == hscroll)
797 return; // no horizontal scroll when wrapped
799 final ViewportRanges ranges = av.getRanges();
801 if (evt.getSource() == vscroll)
803 int newY = vscroll.getValue();
806 * if we're scrolling to the position we're already at, stop
807 * this prevents infinite recursion of events when the scroll/viewport
808 * ranges values are the same
810 int oldX = ranges.getStartRes();
811 int oldY = ranges.getWrappedScrollPosition(oldX);
819 * limit page up/down to one width's worth of positions
821 int rowSize = ranges.getViewportWidth();
822 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
823 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
828 // This is only called if file loaded is a jar file that
829 // was wrapped when saved and user has wrap alignment true
830 // as preference setting
831 SwingUtilities.invokeLater(new Runnable()
836 // When updating scrolling to use ViewportChange events, this code
837 // could not be validated and it is not clear if it is now being
838 // called. Log warning here in case it is called and unforeseen
841 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
843 // scroll to start of panel
844 ranges.setStartRes(0);
845 ranges.setStartSeq(0);
853 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
856 public void paintAlignment(boolean updateOverview,
857 boolean updateStructures)
859 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
860 av.isShowAutocalculatedAbove());
861 sorter.sort(getAlignment().getAlignmentAnnotation(),
862 av.getSortAnnotationsBy());
864 if (updateStructures)
866 av.getStructureSelectionManager().sequenceColoursChanged(this);
870 alignFrame.repaint();
872 if (overviewPanel != null)
874 overviewPanel.updateOverviewImage();
882 public void paintComponent(Graphics g)
884 invalidate(); // needed so that the id width adjuster works correctly
886 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
887 idPanelHolder.setPreferredSize(d);
888 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
890 validate(); // needed so that the id width adjuster works correctly
893 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
894 * though I still think this call should be elsewhere.
896 ViewportRanges ranges = av.getRanges();
897 // setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
898 super.paintComponent(g);
902 * Set vertical scroll bar position, and number of increments, for wrapped
905 * @param topLeftColumn
906 * the column position at top left (0..)
908 private void setScrollingForWrappedPanel(int topLeftColumn)
910 ViewportRanges ranges = av.getRanges();
911 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
912 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
915 * a scrollbar's value can be set to at most (maximum-extent)
916 * so we add extent (1) to the maxScroll value
918 vscroll.setUnitIncrement(1);
919 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
932 * @return DOCUMENT ME!
934 * @throws PrinterException
938 public int print(Graphics pg, PageFormat pf, int pi)
939 throws PrinterException
941 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
943 int pwidth = (int) pf.getImageableWidth();
944 int pheight = (int) pf.getImageableHeight();
946 if (av.getWrapAlignment())
948 return printWrappedAlignment(pwidth, pheight, pi, pg);
952 return printUnwrapped(pwidth, pheight, pi, pg, pg);
957 * Draws the alignment image, including sequence ids, sequences, and
958 * annotation labels and annotations if shown, on either one or two Graphics
968 * the graphics context for sequence ids and annotation labels
969 * @param alignmentGraphics
970 * the graphics context for sequences and annotations (may or may not
971 * be the same context as idGraphics)
973 * @throws PrinterException
975 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
976 Graphics idGraphics, Graphics alignmentGraphics)
977 throws PrinterException
979 final int idWidth = getVisibleIdWidth(false);
982 * Get the horizontal offset to where we draw the sequences.
983 * This is idWidth if using a single Graphics context, else zero.
985 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
988 FontMetrics fm = getFontMetrics(av.getFont());
989 final int charHeight = av.getCharHeight();
990 final int scaleHeight = charHeight + fm.getDescent();
992 idGraphics.setColor(Color.white);
993 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
994 idGraphics.setFont(av.getFont());
997 * How many sequences and residues can we fit on a printable page?
999 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1001 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1003 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1004 int pagesWide = (alignmentWidth / totalRes) + 1;
1006 final int startRes = (pageIndex % pagesWide) * totalRes;
1007 final int endRes = Math.min(startRes + totalRes - 1,
1008 alignmentWidth - 1);
1010 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1011 final int alignmentHeight = av.getAlignment().getHeight();
1012 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1014 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1016 if (av.isShowAnnotation())
1018 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1021 pagesHigh /= pageHeight;
1023 if (pageIndex >= (pagesWide * pagesHigh))
1025 return Printable.NO_SUCH_PAGE;
1027 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1030 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1032 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1033 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1034 pageWidth - idWidth, scaleHeight);
1035 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1038 * Draw the sequence ids, offset for scale height,
1039 * then reset to top left (0, 0)
1041 idGraphics.translate(0, scaleHeight);
1042 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1043 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1044 : av.getSelectionGroup().getSequences(null);
1045 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1048 idGraphics.setFont(av.getFont());
1049 idGraphics.translate(0, -scaleHeight);
1052 * draw the sequences, offset for scale height, and id width (if using a
1053 * single graphics context), then reset to (0, scale height)
1055 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1056 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1057 startRes, endRes, startSeq, endSeq - 1);
1058 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1060 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1063 * draw annotation labels; drawComponent() translates by
1064 * getScrollOffset(), so compensate for that first;
1065 * then reset to (0, scale height)
1067 int offset = getAlabels().getScrollOffset();
1068 idGraphics.translate(0, -offset);
1069 idGraphics.translate(0, alignmentDrawnHeight);
1070 getAlabels().drawComponent(idGraphics, idWidth);
1071 idGraphics.translate(0, -alignmentDrawnHeight);
1074 * draw the annotations starting at
1075 * (idOffset, alignmentHeight) from (0, scaleHeight)
1077 alignmentGraphics.translate(alignmentGraphicsOffset,
1078 alignmentDrawnHeight);
1079 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1080 alignmentGraphics, -1, startRes, endRes + 1);
1083 return Printable.PAGE_EXISTS;
1087 * Prints one page of an alignment in wrapped mode. Returns
1088 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1089 * no page could be drawn (page number out of range).
1099 * @throws PrinterException
1101 public int printWrappedAlignment(int pageWidth, int pageHeight,
1102 int pageNumber, Graphics g) throws PrinterException
1104 getSeqPanel().seqCanvas.calculateWrappedGeometry();
1105 int annotationHeight = 0;
1106 if (av.isShowAnnotation())
1108 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1111 int hgap = av.getCharHeight();
1112 if (av.getScaleAboveWrapped())
1114 hgap += av.getCharHeight();
1117 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1120 int idWidth = getVisibleIdWidth(false);
1122 int maxwidth = av.getAlignment().getVisibleWidth();
1124 int resWidth = getSeqPanel().seqCanvas
1125 .getWrappedCanvasWidth(pageWidth - idWidth);
1126 av.getRanges().setViewportStartAndWidth(0, resWidth);
1128 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1130 g.setColor(Color.white);
1131 g.fillRect(0, 0, pageWidth, pageHeight);
1132 g.setFont(av.getFont());
1133 g.setColor(Color.black);
1136 * method: print the whole wrapped alignment, but with a clip region that
1137 * is restricted to the requested page; this supports selective print of
1138 * single pages or ranges, (at the cost of repeated processing in the
1139 * 'normal' case, when all pages are printed)
1141 g.translate(0, -pageNumber * pageHeight);
1143 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1146 * draw sequence ids and annotation labels (if shown)
1148 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1149 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1151 g.translate(idWidth, 0);
1153 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1154 pageWidth - idWidth, totalHeight, 0);
1156 if ((pageNumber * pageHeight) < totalHeight)
1158 return Printable.PAGE_EXISTS;
1162 return Printable.NO_SUCH_PAGE;
1167 * get current sequence ID panel width, or nominal value if panel were to be
1168 * displayed using default settings
1172 public int getVisibleIdWidth()
1174 return getVisibleIdWidth(true);
1178 * get current sequence ID panel width, or nominal value if panel were to be
1179 * displayed using default settings
1182 * indicate if the Id width for onscreen or offscreen display should
1186 protected int getVisibleIdWidth(boolean onscreen)
1188 // see if rendering offscreen - check preferences and calc width accordingly
1189 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1191 return calculateIdWidth(-1).width;
1193 Integer idwidth = onscreen ? null
1194 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1195 if (idwidth != null)
1197 return idwidth.intValue() + ID_WIDTH_PADDING;
1200 int w = getIdPanel().getWidth();
1201 return (w > 0 ? w : calculateIdWidth().width);
1205 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1206 * writes it to the specified file
1211 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1213 final int borderBottomOffset = 5;
1215 AlignmentDimension aDimension = getAlignmentDimension();
1216 // todo use a lambda function in place of callback here?
1217 ImageWriterI writer = new ImageWriterI()
1220 public void exportImage(Graphics graphics) throws Exception
1222 if (av.getWrapAlignment())
1224 printWrappedAlignment(aDimension.getWidth(),
1225 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1229 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1230 graphics, graphics);
1235 String fileTitle = alignFrame.getTitle();
1236 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1238 int imageWidth = aDimension.getWidth();
1239 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1240 String of = MessageManager.getString("label.alignment");
1241 exporter.doExport(file, this, imageWidth, imageHeight, of);
1245 * Calculates and returns a suitable width and height (in pixels) for an
1250 public AlignmentDimension getAlignmentDimension()
1252 int maxwidth = av.getAlignment().getVisibleWidth();
1254 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1255 + getScalePanel().getHeight();
1256 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1258 if (av.getWrapAlignment())
1260 height = getWrappedHeight();
1261 if (Jalview.isHeadlessMode())
1263 // need to obtain default alignment width and then add in any
1264 // additional allowance for id margin
1265 // this duplicates the calculation in getWrappedHeight but adjusts for
1267 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1268 - alignFrame.getInsets().left - alignFrame.getInsets().right
1269 - getVisibleIdWidth() + getVisibleIdWidth(false);
1273 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1277 else if (av.isShowAnnotation())
1279 height += getAnnotationPanel().adjustPanelHeight() + 3;
1281 return new AlignmentDimension(width, height);
1285 public void makePNGImageMap(File imgMapFile, String imageName)
1287 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1288 // ////////////////////////////////////////////
1289 int idWidth = getVisibleIdWidth(false);
1290 FontMetrics fm = getFontMetrics(av.getFont());
1291 int scaleHeight = av.getCharHeight() + fm.getDescent();
1294 // ////////////////////////////////
1295 if (imgMapFile != null)
1299 int sSize = av.getAlignment().getHeight();
1300 int alwidth = av.getAlignment().getWidth();
1301 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1302 out.println(HTMLOutput.getImageMapHTML());
1303 out.println("<img src=\"" + imageName
1304 + "\" border=\"0\" usemap=\"#Map\" >"
1305 + "<map name=\"Map\">");
1307 for (int s = 0; s < sSize; s++)
1309 int sy = s * av.getCharHeight() + scaleHeight;
1311 SequenceI seq = av.getAlignment().getSequenceAt(s);
1312 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1313 for (int column = 0; column < alwidth; column++)
1315 StringBuilder text = new StringBuilder(512);
1316 String triplet = null;
1317 if (av.getAlignment().isNucleotide())
1319 triplet = ResidueProperties.nucleotideName
1320 .get(seq.getCharAt(column) + "");
1324 triplet = ResidueProperties.aa2Triplet
1325 .get(seq.getCharAt(column) + "");
1328 if (triplet == null)
1333 int seqPos = seq.findPosition(column);
1334 int gSize = groups.length;
1335 for (int g = 0; g < gSize; g++)
1337 if (text.length() < 1)
1339 text.append("<area shape=\"rect\" coords=\"")
1340 .append((idWidth + column * av.getCharWidth()))
1341 .append(",").append(sy).append(",")
1343 + (column + 1) * av.getCharWidth()))
1344 .append(",").append((av.getCharHeight() + sy))
1345 .append("\"").append(" onMouseOver=\"toolTip('")
1346 .append(seqPos).append(" ").append(triplet);
1349 if (groups[g].getStartRes() < column
1350 && groups[g].getEndRes() > column)
1352 text.append("<br><em>").append(groups[g].getName())
1357 if (text.length() < 1)
1359 text.append("<area shape=\"rect\" coords=\"")
1360 .append((idWidth + column * av.getCharWidth()))
1361 .append(",").append(sy).append(",")
1362 .append((idWidth + (column + 1) * av.getCharWidth()))
1363 .append(",").append((av.getCharHeight() + sy))
1364 .append("\"").append(" onMouseOver=\"toolTip('")
1365 .append(seqPos).append(" ").append(triplet);
1367 if (!Comparison.isGap(seq.getCharAt(column)))
1369 List<SequenceFeature> features = seq.findFeatures(column,
1371 for (SequenceFeature sf : features)
1373 if (sf.isContactFeature())
1375 text.append("<br>").append(sf.getType()).append(" ")
1376 .append(sf.getBegin()).append(":")
1377 .append(sf.getEnd());
1381 text.append("<br>");
1382 text.append(sf.getType());
1383 String description = sf.getDescription();
1384 if (description != null
1385 && !sf.getType().equals(description))
1387 description = description.replace("\"", """);
1388 text.append(" ").append(description);
1391 String status = sf.getStatus();
1392 if (status != null && !"".equals(status))
1394 text.append(" (").append(status).append(")");
1397 if (text.length() > 1)
1399 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1400 out.println(text.toString());
1405 out.println("</map></body></html>");
1408 } catch (Exception ex)
1410 ex.printStackTrace();
1412 } // /////////END OF IMAGE MAP
1417 * Answers the height of the entire alignment in pixels, assuming it is in
1422 int getWrappedHeight()
1424 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1426 if (System.getProperty("java.awt.headless") != null
1427 && System.getProperty("java.awt.headless").equals("true"))
1429 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1430 - vscroll.getPreferredSize().width
1431 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1434 int chunkWidth = getSeqPanel().seqCanvas
1435 .getWrappedCanvasWidth(seqPanelWidth);
1437 int hgap = av.getCharHeight();
1438 if (av.getScaleAboveWrapped())
1440 hgap += av.getCharHeight();
1443 int annotationHeight = 0;
1444 if (av.isShowAnnotation())
1446 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1447 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1450 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1453 int maxwidth = av.getAlignment().getWidth();
1454 if (av.hasHiddenColumns())
1456 maxwidth = av.getAlignment().getHiddenColumns()
1457 .absoluteToVisibleColumn(maxwidth) - 1;
1460 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1466 * close the panel - deregisters all listeners and nulls any references to
1469 public void closePanel()
1471 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1472 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1473 PaintRefresher.RemoveComponent(this);
1478 * try to ensure references are nulled
1480 if (annotationPanel != null)
1482 annotationPanel.dispose();
1483 annotationPanel = null;
1488 av.removePropertyChangeListener(propertyChangeListener);
1489 propertyChangeListener = null;
1490 StructureSelectionManager ssm = av.getStructureSelectionManager();
1491 ssm.removeStructureViewerListener(getSeqPanel(), null);
1492 ssm.removeSelectionListener(getSeqPanel());
1493 ssm.removeCommandListener(av);
1494 ssm.removeStructureViewerListener(getSeqPanel(), null);
1495 ssm.removeSelectionListener(getSeqPanel());
1501 if (Cache.log.isDebugEnabled())
1503 Cache.log.warn("Closing alignment panel which is already closed.");
1509 * Close any open dialogs that would be orphaned when this one is closed
1511 protected void closeChildFrames()
1513 if (overviewPanel != null)
1515 overviewPanel.dispose();
1516 overviewPanel = null;
1518 if (calculationDialog != null)
1520 calculationDialog.closeFrame();
1521 calculationDialog = null;
1526 * hides or shows dynamic annotation rows based on groups and av state flags
1528 public void updateAnnotation()
1530 updateAnnotation(false, false);
1533 public void updateAnnotation(boolean applyGlobalSettings)
1535 updateAnnotation(applyGlobalSettings, false);
1538 public void updateAnnotation(boolean applyGlobalSettings,
1539 boolean preserveNewGroupSettings)
1541 av.updateGroupAnnotationSettings(applyGlobalSettings,
1542 preserveNewGroupSettings);
1543 adjustAnnotationHeight();
1547 public AlignmentI getAlignment()
1549 return av == null ? null : av.getAlignment();
1553 public String getViewName()
1555 return av.getViewName();
1559 * Make/Unmake this alignment panel the current input focus
1563 public void setSelected(boolean b)
1567 if (alignFrame.getSplitViewContainer() != null)
1570 * bring enclosing SplitFrame to front first if there is one
1572 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1574 alignFrame.setSelected(b);
1575 } catch (Exception ex)
1581 alignFrame.setDisplayedView(this);
1586 public StructureSelectionManager getStructureSelectionManager()
1588 return av.getStructureSelectionManager();
1592 public void raiseOOMWarning(String string, OutOfMemoryError error)
1594 new OOMWarning(string, error, this);
1598 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1601 return new FeatureRenderer(this);
1605 public jalview.api.FeatureRenderer getFeatureRenderer()
1607 return seqPanel.seqCanvas.getFeatureRenderer();
1610 public void updateFeatureRenderer(
1611 jalview.renderer.seqfeatures.FeatureRenderer fr)
1613 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1616 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1618 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1620 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1624 public ScalePanel getScalePanel()
1629 public void setScalePanel(ScalePanel scalePanel)
1631 this.scalePanel = scalePanel;
1634 public SeqPanel getSeqPanel()
1639 public void setSeqPanel(SeqPanel seqPanel)
1641 this.seqPanel = seqPanel;
1644 public AnnotationPanel getAnnotationPanel()
1646 return annotationPanel;
1649 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1651 this.annotationPanel = annotationPanel;
1654 public AnnotationLabels getAlabels()
1659 public void setAlabels(AnnotationLabels alabels)
1661 this.alabels = alabels;
1664 public IdPanel getIdPanel()
1669 public void setIdPanel(IdPanel idPanel)
1671 this.idPanel = idPanel;
1675 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1676 * The aim is to keep the two alignments 'lined up' on their centre columns.
1679 * holds mapped region(s) of this alignment that we are scrolling
1680 * 'to'; may be modified for sequence offset by this method
1681 * @param verticalOffset
1682 * the number of visible sequences to show above the mapped region
1684 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1686 scrollToPosition(sr, verticalOffset, true);
1690 * Set a flag to say do not scroll any (cDNA/protein) complement.
1694 protected void setToScrollComplementPanel(boolean b)
1696 this.scrollComplementaryPanel = b;
1700 * Get whether to scroll complement panel
1702 * @return true if cDNA/protein complement panels should be scrolled
1704 protected boolean isSetToScrollComplementPanel()
1706 return this.scrollComplementaryPanel;
1712 * @adjustHeight if true, try to recalculate panel height for visible
1715 protected void refresh(boolean adjustHeight)
1717 validateAnnotationDimensions(adjustHeight);
1721 // sort, repaint, update overview
1722 paintAlignment(true, false);
1726 // lightweight repaint
1733 * Property change event fired when a change is made to the viewport ranges
1734 * object associated with this alignment panel's viewport
1736 public void propertyChange(PropertyChangeEvent evt)
1738 // update this panel's scroll values based on the new viewport ranges values
1739 updateScrollBarsFromRanges();
1741 // now update any complementary alignment (its viewport ranges object
1742 // is different so does not get automatically updated)
1743 if (isSetToScrollComplementPanel())
1745 setToScrollComplementPanel(false);
1746 av.scrollComplementaryAlignment();
1747 setToScrollComplementPanel(true);
1751 void updateScrollBarsFromRanges()
1753 ViewportRanges ranges = av.getRanges();
1754 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
1758 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1759 * reference should be nulled when the dialog is closed.
1761 * @param calculationChooser
1763 public void setCalculationDialog(CalculationChooser calculationChooser)
1765 calculationDialog = calculationChooser;
1769 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1772 public CalculationChooser getCalculationDialog()
1774 return calculationDialog;
1778 * From appletgui, for JalviewJS JavaScript interface
1780 * preliminary - untested
1785 * @param scrollToNearest
1786 * @param redrawOverview
1789 public boolean scrollTo(int ostart, int end, int seqIndex,
1790 boolean scrollToNearest, boolean redrawOverview)
1792 int startv, endv, starts, ends;// , width;
1795 if (av.hasHiddenColumns())
1797 AlignmentI al = av.getAlignment();
1798 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1799 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1802 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1804 // don't scroll - position isn't visible
1814 ViewportRanges ranges = av.getRanges();
1815 if (!av.getWrapAlignment())
1818 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1819 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1820 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1821 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1822 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1823 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1824 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1825 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1828 // below is scrolling logic up to Jalview 2.8.2
1829 // if ((av.getStartRes() > end)
1830 // || (av.getEndRes() < start)
1831 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1833 // if (start > av.getAlignment().getWidth() - hextent)
1835 // start = av.getAlignment().getWidth() - hextent;
1842 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1844 // seqIndex = av.getAlignment().getHeight() - vextent;
1845 // if (seqIndex < 0)
1850 // setScrollValues(start, seqIndex);
1852 // logic copied from jalview.gui.AlignmentPanel:
1853 if ((startv = ranges.getStartRes()) >= start)
1856 * Scroll left to make start of search results visible
1858 setScrollValues(start - 1, seqIndex);
1860 else if ((endv = ranges.getEndRes()) <= end)
1863 * Scroll right to make end of search results visible
1865 setScrollValues(startv + 1 + end - endv, seqIndex);
1867 else if ((starts = ranges.getStartSeq()) > seqIndex)
1870 * Scroll up to make start of search results visible
1872 setScrollValues(ranges.getStartRes(), seqIndex);
1874 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1877 * Scroll down to make end of search results visible
1879 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1882 * Else results are already visible - no need to scroll
1887 ranges.scrollToWrappedVisible(start);
1890 paintAlignment(redrawOverview, false);
1894 private boolean holdRepaint = false;
1897 * Called by IdCanvas and SeqPanel to defer painting until after JVP loading.
1899 * @return true if holding
1901 public boolean getHoldRepaint()
1907 * Called by Jalview2xml while loading
1911 public void setHoldRepaint(boolean tf)
1913 if (holdRepaint == tf)
1925 public void repaint()
1929 // System.out.println("AP repaint holding");
1930 // Platform.stackTrace();
1936 public void selectAllSequences()
1938 selectSequences(av.getAlignment().getSequences());
1941 public void deselectAllSequences()
1945 getSeqPanel().keyboardNo1 = null;
1946 getSeqPanel().keyboardNo2 = null;
1948 av.setSelectionGroup(null);
1949 av.getColumnSelection().clear();
1950 av.setSelectionGroup(null);
1951 getIdPanel().getIdCanvas().searchResults = null;
1953 // JAL-2034 - should delegate to
1954 // alignPanel to decide if overview needs
1956 paintAlignment(false, false);
1957 PaintRefresher.Refresh(this, av.getSequenceSetId());
1960 public void selectSequences(List<SequenceI> seqs)
1962 SequenceGroup sg = new SequenceGroup(seqs);
1963 sg.setEndRes(av.getAlignment().getWidth() - 1);
1964 av.setSelectionGroup(sg);
1965 av.isSelectionGroupChanged(true);
1967 // JAL-2034 - should delegate to
1968 // alignPanel to decide if overview needs
1970 paintAlignment(false, false);
1971 PaintRefresher.Refresh(this, av.getSequenceSetId());