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.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.HiddenColumns;
56 import jalview.datamodel.SearchResultsI;
57 import jalview.datamodel.SequenceFeature;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.gui.ImageExporter.ImageWriterI;
61 import jalview.io.HTMLOutput;
62 import jalview.io.exceptions.ImageOutputException;
63 import jalview.jbgui.GAlignmentPanel;
64 import jalview.math.AlignmentDimension;
65 import jalview.schemes.ResidueProperties;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.ImageMaker;
69 import jalview.util.MessageManager;
70 import jalview.util.imagemaker.BitmapImageSizing;
71 import jalview.viewmodel.ViewportListenerI;
72 import jalview.viewmodel.ViewportRanges;
78 * @version $Revision: 1.161 $
80 @SuppressWarnings("serial")
81 public class AlignmentPanel extends GAlignmentPanel implements
82 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
85 * spare space in pixels between sequence id and alignment panel
87 private static final int ID_WIDTH_PADDING = 4;
89 public AlignViewport av;
91 OverviewPanel overviewPanel;
93 private SeqPanel seqPanel;
95 private IdPanel idPanel;
97 IdwidthAdjuster idwidthAdjuster;
99 public AlignFrame alignFrame;
101 private ScalePanel scalePanel;
103 private AnnotationPanel annotationPanel;
105 private AnnotationLabels alabels;
107 private int hextent = 0;
109 private int vextent = 0;
112 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
113 * false, suppresses invoking the same method recursively.
115 private boolean scrollComplementaryPanel = true;
117 private PropertyChangeListener propertyChangeListener;
119 private CalculationChooser calculationDialog;
122 * Creates a new AlignmentPanel object.
127 public AlignmentPanel(AlignFrame af, final AlignViewport av)
129 // setBackground(Color.white); // BH 2019
132 setSeqPanel(new SeqPanel(av, this));
133 setIdPanel(new IdPanel(av, this));
135 setScalePanel(new ScalePanel(av, this));
137 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
138 idwidthAdjuster = new IdwidthAdjuster(this);
139 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
141 setAnnotationPanel(new AnnotationPanel(this));
142 setAlabels(new AnnotationLabels(this));
144 annotationScroller.setViewportView(getAnnotationPanel());
145 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
147 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
148 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
150 setScrollValues(0, 0);
152 hscroll.addAdjustmentListener(this);
153 vscroll.addAdjustmentListener(this);
155 addComponentListener(new ComponentAdapter()
158 public void componentResized(ComponentEvent evt)
160 // reset the viewport ranges when the alignment panel is resized
161 // in particular, this initialises the end residue value when Jalview
163 ViewportRanges ranges = av.getRanges();
164 if (av.getWrapAlignment())
166 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
167 getSeqPanel().seqCanvas.getWidth());
168 ranges.setViewportWidth(widthInRes);
172 int widthInRes = getSeqPanel().seqCanvas.getWidth()
174 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
175 / av.getCharHeight();
177 ranges.setViewportWidth(widthInRes);
178 ranges.setViewportHeight(heightInSeq);
184 final AlignmentPanel ap = this;
185 propertyChangeListener = new PropertyChangeListener()
188 public void propertyChange(PropertyChangeEvent evt)
190 if (evt.getPropertyName().equals("alignment"))
192 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
197 av.addPropertyChangeListener(propertyChangeListener);
199 av.getRanges().addPropertyChangeListener(this);
201 adjustAnnotationHeight();
206 public AlignViewportI getAlignViewport()
211 public void alignmentChanged()
213 av.alignmentChanged(this);
215 if (getCalculationDialog() != null)
217 getCalculationDialog().validateCalcTypes();
220 alignFrame.updateEditMenuBar();
222 // no idea if we need to update structure
223 paintAlignment(true, true);
230 public void fontChanged()
232 // set idCanvas bufferedImage to null
233 // to prevent drawing old image
234 FontMetrics fm = getFontMetrics(av.getFont());
236 // update the flag controlling whether the grid is too small to render the
238 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
240 scalePanelHolder.setPreferredSize(
241 new Dimension(10, av.getCharHeight() + fm.getDescent()));
242 idSpaceFillerPanel1.setPreferredSize(
243 new Dimension(10, av.getCharHeight() + fm.getDescent()));
244 idwidthAdjuster.invalidate();
245 scalePanelHolder.invalidate();
246 // BH 2018 getIdPanel().getIdCanvas().gg = null;
247 getSeqPanel().seqCanvas.img = null;
248 getAnnotationPanel().adjustPanelHeight();
250 Dimension d = calculateIdWidth();
251 getIdPanel().getIdCanvas().setPreferredSize(d);
252 hscrollFillerPanel.setPreferredSize(d);
258 * Calculates the width of the alignment labels based on the displayed names
259 * and any bounds on label width set in preferences. The calculated width is
260 * also set as a property of the viewport.
262 * @return Dimension giving the maximum width of the alignment label panel
263 * that should be used.
265 public Dimension calculateIdWidth()
267 int oldWidth = av.getIdWidth();
269 // calculate sensible default width when no preference is available
271 if (av.getIdWidth() < 0)
273 r = calculateDefaultAlignmentIdWidth();
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);
295 public Dimension calculateDefaultAlignmentIdWidth()
297 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
298 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
299 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
300 return calculateIdWidth(-1, false, false);
304 * Calculate the width of the alignment labels based on the displayed names
305 * and any bounds on label width set in preferences.
308 * -1 or maximum width allowed for IdWidth
309 * @return Dimension giving the maximum width of the alignment label panel
310 * that should be used.
312 protected Dimension calculateIdWidth(int maxwidth)
314 return calculateIdWidth(maxwidth, true, false);
317 public Dimension calculateIdWidth(int maxwidth,
318 boolean includeAnnotations, boolean visibleOnly)
320 Container c = new Container();
322 FontMetrics fm = c.getFontMetrics(
323 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
325 AlignmentI al = av.getAlignment();
329 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
331 SequenceI s = al.getSequenceAt(i);
332 String id = s.getDisplayId(av.getShowJVSuffix());
333 int stringWidth = fm.stringWidth(id);
334 idWidth = Math.max(idWidth, stringWidth);
338 // Also check annotation label widths
339 if (includeAnnotations && al.getAlignmentAnnotation() != null)
341 if (Jalview.isHeadlessMode())
343 AnnotationLabels aal = getAlabels();
344 int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
346 idWidth = Math.max(idWidth, stringWidth);
350 fm = c.getFontMetrics(getAlabels().getFont());
352 for (i = 0; i < al.getAlignmentAnnotation().length; i++)
354 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
355 if (visibleOnly && !aa.visible)
359 String label = aa.label;
360 int stringWidth = fm.stringWidth(label);
361 idWidth = Math.max(idWidth, stringWidth);
366 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
367 w += ID_WIDTH_PADDING;
369 return new Dimension(w, 12);
373 * Highlight the given results on the alignment
376 public void highlightSearchResults(SearchResultsI results)
378 boolean scrolled = scrollToPosition(results, 0, false);
380 boolean fastPaint = !(scrolled && av.getWrapAlignment());
382 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
386 * Scroll the view to show the position of the highlighted region in results
389 * @param searchResults
392 public boolean scrollToPosition(SearchResultsI searchResults)
394 return scrollToPosition(searchResults, 0, false);
398 * Scrolls the view (if necessary) to show the position of the first
399 * highlighted region in results (if any). Answers true if the view was
400 * scrolled, or false if no matched region was found, or it is already
404 * @param verticalOffset
405 * if greater than zero, allows scrolling to a position below the
406 * first displayed sequence
408 * if true, try to centre the search results horizontally in the view
411 protected boolean scrollToPosition(SearchResultsI results,
412 int verticalOffset, boolean centre)
414 int startv, endv, starts, ends;
415 ViewportRanges ranges = av.getRanges();
417 if (results == null || results.isEmpty() || av == null
418 || av.getAlignment() == null)
422 int seqIndex = av.getAlignment().findIndex(results);
427 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
429 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
438 * To centre results, scroll to positions half the visible width
439 * left/right of the start/end positions
443 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
444 start = Math.max(start - offset, 0);
445 end = end + offset - 1;
451 if (end == seq.getEnd())
456 if (av.hasHiddenColumns())
458 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
459 start = hidden.absoluteToVisibleColumn(start);
460 end = hidden.absoluteToVisibleColumn(end);
463 if (!hidden.isVisible(r[0]))
465 // don't scroll - position isn't visible
472 * allow for offset of target sequence (actually scroll to one above it)
474 seqIndex = Math.max(0, seqIndex - verticalOffset);
475 boolean scrollNeeded = true;
477 if (!av.getWrapAlignment())
479 if ((startv = ranges.getStartRes()) >= start)
482 * Scroll left to make start of search results visible
484 setScrollValues(start, seqIndex);
486 else if ((endv = ranges.getEndRes()) <= end)
489 * Scroll right to make end of search results visible
491 setScrollValues(startv + end - endv, seqIndex);
493 else if ((starts = ranges.getStartSeq()) > seqIndex)
496 * Scroll up to make start of search results visible
498 setScrollValues(ranges.getStartRes(), seqIndex);
500 else if ((ends = ranges.getEndSeq()) <= seqIndex)
503 * Scroll down to make end of search results visible
505 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
508 * Else results are already visible - no need to scroll
510 scrollNeeded = false;
514 scrollNeeded = ranges.scrollToWrappedVisible(start);
517 paintAlignment(false, false);
525 * @return DOCUMENT ME!
527 public OverviewPanel getOverviewPanel()
529 return overviewPanel;
538 public void setOverviewPanel(OverviewPanel op)
546 * Hide or show annotation panel
549 public void setAnnotationVisible(boolean b)
551 if (!av.getWrapAlignment())
553 annotationSpaceFillerHolder.setVisible(b);
554 annotationScroller.setVisible(b);
560 * automatically adjust annotation panel height for new annotation whilst
561 * ensuring the alignment is still visible.
564 public void adjustAnnotationHeight()
566 // TODO: display vertical annotation scrollbar if necessary
567 // this is called after loading new annotation onto alignment
568 if (alignFrame.getHeight() == 0)
570 jalview.bin.Console.outPrintln("NEEDS FIXING");
572 validateAnnotationDimensions(true);
574 // TODO: many places call this method and also paintAlignment with various
575 // different settings. this means multiple redraws are triggered...
576 paintAlignment(true, av.needToUpdateStructureViews());
580 * calculate the annotation dimensions and refresh slider values accordingly.
581 * need to do repaints/notifys afterwards.
583 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
585 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
586 // are not changing ancestors, and keyboard action listeners do
587 // not need to be reset. addNotify() is a very expensive operation,
588 // requiring a full re-layout of all parents and children.
589 // Note in JComponent:
590 // This method is called by the toolkit internally and should
591 // not be called directly by programs.
592 // I note that addNotify() is called in several areas of Jalview.
594 AnnotationPanel ap = getAnnotationPanel();
595 int annotationHeight = ap.adjustPanelHeight();
596 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
600 Dimension e = idPanel.getSize();
601 int idWidth = e.width;
602 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
604 annotationScroller.setPreferredSize(new Dimension(
605 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
608 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
610 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
611 manuallyAdjusted ? idWidth
612 : annotationSpaceFillerHolder.getWidth(),
614 annotationScroller.validate();
615 annotationScroller.addNotify();
620 * update alignment layout for viewport settings
625 public void updateLayout()
628 setAnnotationVisible(av.isShowAnnotation());
629 boolean wrap = av.getWrapAlignment();
630 ViewportRanges ranges = av.getRanges();
631 ranges.setStartSeq(0);
632 // scalePanelHolder.setVisible(!wrap);
633 hscroll.setVisible(!wrap);
634 // Allow idPanel width adjustment in wrap mode
635 idwidthAdjuster.setVisible(true);
639 annotationScroller.setVisible(false);
640 annotationSpaceFillerHolder.setVisible(false);
642 else if (av.isShowAnnotation())
644 annotationScroller.setVisible(true);
645 annotationSpaceFillerHolder.setVisible(true);
646 validateAnnotationDimensions(false);
649 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
651 { // may not yet be laid out
654 int widthInRes = getSeqPanel().seqCanvas
655 .getWrappedCanvasWidth(canvasWidth);
656 ranges.setViewportWidth(widthInRes);
660 int widthInRes = (canvasWidth / av.getCharWidth());
661 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
662 / av.getCharHeight());
664 ranges.setViewportWidth(widthInRes);
665 ranges.setViewportHeight(heightInSeq);
669 // idSpaceFillerPanel1.setVisible(!wrap);
675 * Adjust row/column scrollers to show a visible position in the alignment.
678 * visible column to scroll to
680 * visible row to scroll to
683 public void setScrollValues(int xpos, int ypos)
688 if (av == null || av.getAlignment() == null)
693 if (av.getWrapAlignment())
695 setScrollingForWrappedPanel(x);
699 int width = av.getAlignment().getVisibleWidth();
700 int height = av.getAlignment().getHeight();
702 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
703 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
710 if (vextent > height)
715 if ((hextent + x) > width)
720 if ((vextent + y) > height)
722 y = height - vextent;
735 // update the scroll values
736 hscroll.setValues(x, hextent, 0, width);
737 vscroll.setValues(y, vextent, 0, height);
742 * Respond to adjustment event when horizontal or vertical scrollbar is
746 * adjustment event encoding whether hscroll or vscroll changed
749 public void adjustmentValueChanged(AdjustmentEvent evt)
751 if (av.getWrapAlignment())
753 adjustScrollingWrapped(evt);
757 ViewportRanges ranges = av.getRanges();
759 if (evt.getSource() == hscroll)
761 int oldX = ranges.getStartRes();
762 int oldwidth = ranges.getViewportWidth();
763 int x = hscroll.getValue();
764 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
766 // if we're scrolling to the position we're already at, stop
767 // this prevents infinite recursion of events when the scroll/viewport
768 // ranges values are the same
769 if ((x == oldX) && (width == oldwidth))
773 ranges.setViewportStartAndWidth(x, width);
775 else if (evt.getSource() == vscroll)
777 int oldY = ranges.getStartSeq();
778 int oldheight = ranges.getViewportHeight();
779 int y = vscroll.getValue();
780 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
782 // if we're scrolling to the position we're already at, stop
783 // this prevents infinite recursion of events when the scroll/viewport
784 // ranges values are the same
785 if ((y == oldY) && (height == oldheight))
789 ranges.setViewportStartAndHeight(y, height);
795 * Responds to a scroll change by setting the start position of the viewport.
800 protected void adjustScrollingWrapped(AdjustmentEvent evt)
802 if (evt.getSource() == hscroll)
804 return; // no horizontal scroll when wrapped
806 final ViewportRanges ranges = av.getRanges();
808 if (evt.getSource() == vscroll)
810 int newY = vscroll.getValue();
813 * if we're scrolling to the position we're already at, stop
814 * this prevents infinite recursion of events when the scroll/viewport
815 * ranges values are the same
817 int oldX = ranges.getStartRes();
818 int oldY = ranges.getWrappedScrollPosition(oldX);
826 * limit page up/down to one width's worth of positions
828 int rowSize = ranges.getViewportWidth();
829 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
830 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
835 // This is only called if file loaded is a jar file that
836 // was wrapped when saved and user has wrap alignment true
837 // as preference setting
838 SwingUtilities.invokeLater(new Runnable()
843 // When updating scrolling to use ViewportChange events, this code
844 // could not be validated and it is not clear if it is now being
845 // called. Log warning here in case it is called and unforeseen
848 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
850 // scroll to start of panel
851 ranges.setStartRes(0);
852 ranges.setStartSeq(0);
860 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
863 public void paintAlignment(boolean updateOverview,
864 boolean updateStructures)
866 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
867 av.isShowAutocalculatedAbove());
868 sorter.sort(getAlignment().getAlignmentAnnotation(),
869 av.getSortAnnotationsBy());
872 if (updateStructures)
874 av.getStructureSelectionManager().sequenceColoursChanged(this);
879 if (overviewPanel != null)
881 overviewPanel.updateOverviewImage();
887 public void paintComponent(Graphics g)
889 invalidate(); // needed so that the id width adjuster works correctly
890 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
891 int idWidth = d.width;
893 // check wrapped alignment as at least 1 residue width
894 if (av.getWrapAlignment())
896 SeqCanvas sc = this.getSeqPanel().seqCanvas;
897 if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
899 // need to make some adjustments
900 idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
901 av.setIdWidth(idWidth);
902 av.getAlignPanel().getIdPanel().getIdCanvas()
903 .setManuallyAdjusted(true);
905 validateAnnotationDimensions(false);
909 idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
910 hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
912 validate(); // needed so that the id width adjuster works correctly
915 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
916 * though I still think this call should be elsewhere.
918 ViewportRanges ranges = av.getRanges();
919 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
920 super.paintComponent(g);
924 * Set vertical scroll bar position, and number of increments, for wrapped
927 * @param topLeftColumn
928 * the column position at top left (0..)
930 private void setScrollingForWrappedPanel(int topLeftColumn)
932 ViewportRanges ranges = av.getRanges();
933 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
934 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
937 * a scrollbar's value can be set to at most (maximum-extent)
938 * so we add extent (1) to the maxScroll value
940 vscroll.setUnitIncrement(1);
941 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
954 * @return DOCUMENT ME!
956 * @throws PrinterException
960 public int print(Graphics pg, PageFormat pf, int pi)
961 throws PrinterException
963 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
965 int pwidth = (int) pf.getImageableWidth();
966 int pheight = (int) pf.getImageableHeight();
968 if (av.getWrapAlignment())
970 return printWrappedAlignment(pwidth, pheight, pi, pg);
974 return printUnwrapped(pwidth, pheight, pi, pg, pg);
979 * Draws the alignment image, including sequence ids, sequences, and
980 * annotation labels and annotations if shown, on either one or two Graphics
990 * the graphics context for sequence ids and annotation labels
991 * @param alignmentGraphics
992 * the graphics context for sequences and annotations (may or may not
993 * be the same context as idGraphics)
995 * @throws PrinterException
997 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
998 Graphics idGraphics, Graphics alignmentGraphics)
999 throws PrinterException
1001 final int idWidth = getVisibleIdWidth(false);
1004 * Get the horizontal offset to where we draw the sequences.
1005 * This is idWidth if using a single Graphics context, else zero.
1007 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1010 FontMetrics fm = getFontMetrics(av.getFont());
1011 final int charHeight = av.getCharHeight();
1012 final int scaleHeight = charHeight + fm.getDescent();
1014 idGraphics.setColor(Color.white);
1015 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1016 idGraphics.setFont(av.getFont());
1019 * How many sequences and residues can we fit on a printable page?
1021 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1023 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1025 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1026 int pagesWide = (alignmentWidth / totalRes) + 1;
1028 final int startRes = (pageIndex % pagesWide) * totalRes;
1029 final int endRes = Math.min(startRes + totalRes - 1,
1030 alignmentWidth - 1);
1032 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1033 final int alignmentHeight = av.getAlignment().getHeight();
1034 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1036 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1038 if (av.isShowAnnotation())
1040 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1043 pagesHigh /= pageHeight;
1045 if (pageIndex >= (pagesWide * pagesHigh))
1047 return Printable.NO_SUCH_PAGE;
1049 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1052 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1054 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1055 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1056 pageWidth - idWidth, scaleHeight);
1057 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1060 * Draw the sequence ids, offset for scale height,
1061 * then reset to top left (0, 0)
1063 idGraphics.translate(0, scaleHeight);
1064 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1065 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1066 : av.getSelectionGroup().getSequences(null);
1067 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1070 idGraphics.setFont(av.getFont());
1071 idGraphics.translate(0, -scaleHeight);
1074 * draw the sequences, offset for scale height, and id width (if using a
1075 * single graphics context), then reset to (0, scale height)
1077 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1078 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1079 startRes, endRes, startSeq, endSeq - 1);
1080 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1082 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1085 * draw annotation labels; drawComponent() translates by
1086 * getScrollOffset(), so compensate for that first;
1087 * then reset to (0, scale height)
1089 int offset = getAlabels().getScrollOffset();
1090 idGraphics.translate(0, -offset);
1091 idGraphics.translate(0, alignmentDrawnHeight);
1092 getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1093 idGraphics.translate(0, -alignmentDrawnHeight);
1096 * draw the annotations starting at
1097 * (idOffset, alignmentHeight) from (0, scaleHeight)
1099 alignmentGraphics.translate(alignmentGraphicsOffset,
1100 alignmentDrawnHeight);
1102 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1103 alignmentGraphics, -1, startRes, endRes + 1);
1106 return Printable.PAGE_EXISTS;
1110 * Prints one page of an alignment in wrapped mode. Returns
1111 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1112 * no page could be drawn (page number out of range).
1122 * @throws PrinterException
1124 public int printWrappedAlignment(int pageWidth, int pageHeight,
1125 int pageNumber, Graphics g) throws PrinterException
1127 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1129 int annotationHeight = 0;
1130 if (av.isShowAnnotation())
1132 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1135 int hgap = av.getCharHeight();
1136 if (av.getScaleAboveWrapped())
1138 hgap += av.getCharHeight();
1141 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1144 int idWidth = getVisibleIdWidth(false);
1146 int maxwidth = av.getAlignment().getVisibleWidth();
1148 int resWidth = getSeqPanel().seqCanvas
1149 .getWrappedCanvasWidth(pageWidth - idWidth);
1150 av.getRanges().setViewportStartAndWidth(0, resWidth);
1152 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1154 g.setColor(Color.white);
1155 g.fillRect(0, 0, pageWidth, pageHeight);
1156 g.setFont(av.getFont());
1157 g.setColor(Color.black);
1160 * method: print the whole wrapped alignment, but with a clip region that
1161 * is restricted to the requested page; this supports selective print of
1162 * single pages or ranges, (at the cost of repeated processing in the
1163 * 'normal' case, when all pages are printed)
1165 g.translate(0, -pageNumber * pageHeight);
1167 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1170 * draw sequence ids and annotation labels (if shown)
1172 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1173 idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1175 g.translate(idWidth, 0);
1177 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1178 pageWidth - idWidth, totalHeight, 0);
1180 if ((pageNumber * pageHeight) < totalHeight)
1182 return Printable.PAGE_EXISTS;
1186 return Printable.NO_SUCH_PAGE;
1191 * get current sequence ID panel width, or nominal value if panel were to be
1192 * displayed using default settings
1196 public int getVisibleIdWidth()
1198 return getVisibleIdWidth(true);
1202 * get current sequence ID panel width, or nominal value if panel were to be
1203 * displayed using default settings
1206 * indicate if the Id width for onscreen or offscreen display should
1210 protected int getVisibleIdWidth(boolean onscreen)
1212 // see if rendering offscreen - check preferences and calc width accordingly
1213 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1215 return calculateIdWidth(-1).width;
1217 Integer idwidth = onscreen ? null
1218 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1219 if (idwidth != null)
1221 return idwidth.intValue() + ID_WIDTH_PADDING;
1224 int w = getIdPanel().getWidth();
1225 w = this.calculateIdWidth(-1, true, true).width;
1226 return (w > 0 ? w : calculateIdWidth().width);
1229 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1230 throws ImageOutputException
1232 makeAlignmentImage(type, file, renderer,
1233 BitmapImageSizing.defaultBitmapImageSizing());
1237 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1238 * writes it to the specified file
1242 * @param textrenderer
1243 * @param bitmapscale
1245 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1246 BitmapImageSizing userBis) throws ImageOutputException
1248 final int borderBottomOffset = 5;
1250 AlignmentDimension aDimension = getAlignmentDimension();
1252 // todo use a lambda function in place of callback here?
1253 ImageWriterI writer = new ImageWriterI()
1256 public void exportImage(Graphics graphics) throws Exception
1258 if (av.getWrapAlignment())
1260 printWrappedAlignment(aDimension.getWidth(),
1261 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1265 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1266 graphics, graphics);
1271 String fileTitle = alignFrame.getTitle();
1272 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1274 int imageWidth = aDimension.getWidth();
1275 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1276 String of = MessageManager.getString("label.alignment");
1277 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1282 * Calculates and returns a suitable width and height (in pixels) for an
1287 public AlignmentDimension getAlignmentDimension()
1289 int maxwidth = av.getAlignment().getVisibleWidth();
1291 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1292 + getScalePanel().getHeight();
1293 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1295 if (av.getWrapAlignment())
1297 height = getWrappedHeight();
1298 if (Jalview.isHeadlessMode())
1300 // need to obtain default alignment width and then add in any
1301 // additional allowance for id margin
1302 // this duplicates the calculation in getWrappedHeight but adjusts for
1304 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1305 - alignFrame.getInsets().left - alignFrame.getInsets().right
1306 - getVisibleIdWidth() + getVisibleIdWidth(false);
1310 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1314 else if (av.isShowAnnotation())
1316 height += getAnnotationPanel().adjustPanelHeight() + 3;
1318 return new AlignmentDimension(width, height);
1322 public void makePNGImageMap(File imgMapFile, String imageName)
1323 throws ImageOutputException
1325 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1326 // ////////////////////////////////////////////
1327 int idWidth = getVisibleIdWidth(false);
1328 FontMetrics fm = getFontMetrics(av.getFont());
1329 int scaleHeight = av.getCharHeight() + fm.getDescent();
1332 // ////////////////////////////////
1333 if (imgMapFile != null)
1337 int sSize = av.getAlignment().getHeight();
1338 int alwidth = av.getAlignment().getWidth();
1339 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1340 out.println(HTMLOutput.getImageMapHTML());
1341 out.println("<img src=\"" + imageName
1342 + "\" border=\"0\" usemap=\"#Map\" >"
1343 + "<map name=\"Map\">");
1345 for (int s = 0; s < sSize; s++)
1347 int sy = s * av.getCharHeight() + scaleHeight;
1349 SequenceI seq = av.getAlignment().getSequenceAt(s);
1350 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1351 for (int column = 0; column < alwidth; column++)
1353 StringBuilder text = new StringBuilder(512);
1354 String triplet = null;
1355 if (av.getAlignment().isNucleotide())
1357 triplet = ResidueProperties.nucleotideName
1358 .get(seq.getCharAt(column) + "");
1362 triplet = ResidueProperties.aa2Triplet
1363 .get(seq.getCharAt(column) + "");
1366 if (triplet == null)
1371 int seqPos = seq.findPosition(column);
1372 int gSize = groups.length;
1373 for (int g = 0; g < gSize; g++)
1375 if (text.length() < 1)
1377 text.append("<area shape=\"rect\" coords=\"")
1378 .append((idWidth + column * av.getCharWidth()))
1379 .append(",").append(sy).append(",")
1381 + (column + 1) * av.getCharWidth()))
1382 .append(",").append((av.getCharHeight() + sy))
1383 .append("\"").append(" onMouseOver=\"toolTip('")
1384 .append(seqPos).append(" ").append(triplet);
1387 if (groups[g].getStartRes() < column
1388 && groups[g].getEndRes() > column)
1390 text.append("<br><em>").append(groups[g].getName())
1395 if (text.length() < 1)
1397 text.append("<area shape=\"rect\" coords=\"")
1398 .append((idWidth + column * av.getCharWidth()))
1399 .append(",").append(sy).append(",")
1400 .append((idWidth + (column + 1) * av.getCharWidth()))
1401 .append(",").append((av.getCharHeight() + sy))
1402 .append("\"").append(" onMouseOver=\"toolTip('")
1403 .append(seqPos).append(" ").append(triplet);
1405 if (!Comparison.isGap(seq.getCharAt(column)))
1407 List<SequenceFeature> features = seq.findFeatures(column,
1409 for (SequenceFeature sf : features)
1411 if (sf.isContactFeature())
1413 text.append("<br>").append(sf.getType()).append(" ")
1414 .append(sf.getBegin()).append(":")
1415 .append(sf.getEnd());
1419 text.append("<br>");
1420 text.append(sf.getType());
1421 String description = sf.getDescription();
1422 if (description != null
1423 && !sf.getType().equals(description))
1425 description = description.replace("\"", """);
1426 text.append(" ").append(description);
1429 String status = sf.getStatus();
1430 if (status != null && !"".equals(status))
1432 text.append(" (").append(status).append(")");
1435 if (text.length() > 1)
1437 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1438 out.println(text.toString());
1443 out.println("</map></body></html>");
1446 } catch (Exception ex)
1448 throw new ImageOutputException(
1449 "couldn't write ImageMap due to unexpected error", ex);
1451 } // /////////END OF IMAGE MAP
1456 * Answers the height of the entire alignment in pixels, assuming it is in
1461 int getWrappedHeight()
1463 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1465 if (Jalview.isHeadlessMode())
1467 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1468 - vscroll.getPreferredSize().width
1469 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1472 int chunkWidth = getSeqPanel().seqCanvas
1473 .getWrappedCanvasWidth(seqPanelWidth);
1475 int hgap = av.getCharHeight();
1476 if (av.getScaleAboveWrapped())
1478 hgap += av.getCharHeight();
1481 int annotationHeight = 0;
1482 if (av.isShowAnnotation())
1484 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1485 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1488 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1491 int maxwidth = av.getAlignment().getWidth();
1492 if (av.hasHiddenColumns())
1494 maxwidth = av.getAlignment().getHiddenColumns()
1495 .absoluteToVisibleColumn(maxwidth) - 1;
1498 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1504 * close the panel - deregisters all listeners and nulls any references to
1507 public void closePanel()
1509 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1510 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1511 PaintRefresher.RemoveComponent(this);
1516 * try to ensure references are nulled
1518 if (annotationPanel != null)
1520 annotationPanel.dispose();
1521 annotationPanel = null;
1526 av.removePropertyChangeListener(propertyChangeListener);
1527 propertyChangeListener = null;
1528 StructureSelectionManager ssm = av.getStructureSelectionManager();
1529 ssm.removeStructureViewerListener(getSeqPanel(), null);
1530 ssm.removeSelectionListener(getSeqPanel());
1531 ssm.removeCommandListener(av);
1532 ssm.removeStructureViewerListener(getSeqPanel(), null);
1533 ssm.removeSelectionListener(getSeqPanel());
1539 if (Console.isDebugEnabled())
1541 Console.warn("Closing alignment panel which is already closed.");
1547 * Close any open dialogs that would be orphaned when this one is closed
1549 protected void closeChildFrames()
1551 if (overviewPanel != null)
1553 overviewPanel.dispose();
1554 overviewPanel = null;
1556 if (calculationDialog != null)
1558 calculationDialog.closeFrame();
1559 calculationDialog = null;
1564 * hides or shows dynamic annotation rows based on groups and av state flags
1566 public void updateAnnotation()
1568 updateAnnotation(false, false);
1571 public void updateAnnotation(boolean applyGlobalSettings)
1573 updateAnnotation(applyGlobalSettings, false);
1576 public void updateAnnotation(boolean applyGlobalSettings,
1577 boolean preserveNewGroupSettings)
1579 av.updateGroupAnnotationSettings(applyGlobalSettings,
1580 preserveNewGroupSettings);
1581 adjustAnnotationHeight();
1585 public AlignmentI getAlignment()
1587 return av == null ? null : av.getAlignment();
1591 public String getViewName()
1593 return av.getViewName();
1597 * Make/Unmake this alignment panel the current input focus
1601 public void setSelected(boolean b)
1605 if (alignFrame.getSplitViewContainer() != null)
1608 * bring enclosing SplitFrame to front first if there is one
1610 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1612 alignFrame.setSelected(b);
1613 } catch (Exception ex)
1618 setAlignFrameView();
1622 public void setAlignFrameView()
1624 alignFrame.setDisplayedView(this);
1628 public StructureSelectionManager getStructureSelectionManager()
1630 return av.getStructureSelectionManager();
1634 public void raiseOOMWarning(String string, OutOfMemoryError error)
1636 new OOMWarning(string, error, this);
1640 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1643 return new FeatureRenderer(this);
1647 public jalview.api.FeatureRenderer getFeatureRenderer()
1649 return seqPanel.seqCanvas.getFeatureRenderer();
1652 public void updateFeatureRenderer(
1653 jalview.renderer.seqfeatures.FeatureRenderer fr)
1655 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1658 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1660 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1662 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1666 public ScalePanel getScalePanel()
1671 public void setScalePanel(ScalePanel scalePanel)
1673 this.scalePanel = scalePanel;
1676 public SeqPanel getSeqPanel()
1681 public void setSeqPanel(SeqPanel seqPanel)
1683 this.seqPanel = seqPanel;
1686 public AnnotationPanel getAnnotationPanel()
1688 return annotationPanel;
1691 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1693 this.annotationPanel = annotationPanel;
1696 public AnnotationLabels getAlabels()
1701 public void setAlabels(AnnotationLabels alabels)
1703 this.alabels = alabels;
1706 public IdPanel getIdPanel()
1711 public void setIdPanel(IdPanel idPanel)
1713 this.idPanel = idPanel;
1717 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1718 * The aim is to keep the two alignments 'lined up' on their centre columns.
1721 * holds mapped region(s) of this alignment that we are scrolling
1722 * 'to'; may be modified for sequence offset by this method
1723 * @param verticalOffset
1724 * the number of visible sequences to show above the mapped region
1726 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1728 scrollToPosition(sr, verticalOffset, true);
1732 * Set a flag to say do not scroll any (cDNA/protein) complement.
1736 protected void setToScrollComplementPanel(boolean b)
1738 this.scrollComplementaryPanel = b;
1742 * Get whether to scroll complement panel
1744 * @return true if cDNA/protein complement panels should be scrolled
1746 protected boolean isSetToScrollComplementPanel()
1748 return this.scrollComplementaryPanel;
1754 * @adjustHeight if true, try to recalculate panel height for visible
1757 protected void refresh(boolean adjustHeight)
1759 validateAnnotationDimensions(adjustHeight);
1763 // sort, repaint, update overview
1764 paintAlignment(true, false);
1768 // lightweight repaint
1775 * Property change event fired when a change is made to the viewport ranges
1776 * object associated with this alignment panel's viewport
1778 public void propertyChange(PropertyChangeEvent evt)
1780 // update this panel's scroll values based on the new viewport ranges values
1781 ViewportRanges ranges = av.getRanges();
1782 int x = ranges.getStartRes();
1783 int y = ranges.getStartSeq();
1784 setScrollValues(x, y);
1786 // now update any complementary alignment (its viewport ranges object
1787 // is different so does not get automatically updated)
1788 if (isSetToScrollComplementPanel())
1790 setToScrollComplementPanel(false);
1791 av.scrollComplementaryAlignment();
1792 setToScrollComplementPanel(true);
1797 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1798 * reference should be nulled when the dialog is closed.
1800 * @param calculationChooser
1802 public void setCalculationDialog(CalculationChooser calculationChooser)
1804 calculationDialog = calculationChooser;
1808 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1811 public CalculationChooser getCalculationDialog()
1813 return calculationDialog;
1817 * Constructs and sets the title for the Overview window (if there is one),
1818 * including the align frame's title, and view name (if applicable). Returns
1819 * the title, or null if this panel has no Overview window open.
1824 public String setOverviewTitle(AlignFrame alignFrame)
1826 if (this.overviewPanel == null)
1830 String overviewTitle = MessageManager
1831 .formatMessage("label.overview_params", new Object[]
1832 { alignFrame.getTitle() });
1833 String viewName = getViewName();
1834 if (viewName != null)
1836 overviewTitle += (" " + viewName);
1838 overviewPanel.setTitle(overviewTitle);
1839 return overviewTitle;
1843 * If this alignment panel has an Overview panel open, closes it
1845 public void closeOverviewPanel()
1847 if (overviewPanel != null)
1849 overviewPanel.close();
1850 overviewPanel = null;