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. Also includes annotations
306 * not actually visible.
308 * FIXME JAL-244 JAL-4091 - doesn't include sequence associated annotation
309 * label decorators and only called during tests
312 * -1 or maximum width allowed for IdWidth
313 * @return Dimension giving the maximum width of the alignment label panel
314 * that should be used.
316 protected Dimension calculateIdWidth(int maxwidth)
318 return calculateIdWidth(maxwidth, true, false);
321 public Dimension calculateIdWidth(int maxwidth,
322 boolean includeAnnotations, boolean visibleOnly)
324 Container c = new Container();
326 FontMetrics fm = c.getFontMetrics(
327 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
329 AlignmentI al = av.getAlignment();
333 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
335 SequenceI s = al.getSequenceAt(i);
336 String id = s.getDisplayId(av.getShowJVSuffix());
337 int stringWidth = fm.stringWidth(id);
338 idWidth = Math.max(idWidth, stringWidth);
342 // Also check annotation label widths
343 if (includeAnnotations && al.getAlignmentAnnotation() != null)
345 if (Jalview.isHeadlessMode())
347 AnnotationLabels aal = getAlabels();
348 int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
350 idWidth = Math.max(idWidth, stringWidth);
354 fm = c.getFontMetrics(getAlabels().getFont());
356 for (i = 0; i < al.getAlignmentAnnotation().length; i++)
358 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
359 if (visibleOnly && !aa.visible)
363 String label = aa.label;
364 int stringWidth = fm.stringWidth(label);
365 idWidth = Math.max(idWidth, stringWidth);
370 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
371 w += ID_WIDTH_PADDING;
373 return new Dimension(w, 12);
377 * Highlight the given results on the alignment
380 public void highlightSearchResults(SearchResultsI results)
382 boolean scrolled = scrollToPosition(results, 0, false);
384 boolean fastPaint = !(scrolled && av.getWrapAlignment());
386 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
390 * Scroll the view to show the position of the highlighted region in results
393 * @param searchResults
396 public boolean scrollToPosition(SearchResultsI searchResults)
398 return scrollToPosition(searchResults, 0, false);
402 * Scrolls the view (if necessary) to show the position of the first
403 * highlighted region in results (if any). Answers true if the view was
404 * scrolled, or false if no matched region was found, or it is already
408 * @param verticalOffset
409 * if greater than zero, allows scrolling to a position below the
410 * first displayed sequence
412 * if true, try to centre the search results horizontally in the view
415 protected boolean scrollToPosition(SearchResultsI results,
416 int verticalOffset, boolean centre)
418 int startv, endv, starts, ends;
419 ViewportRanges ranges = av.getRanges();
421 if (results == null || results.isEmpty() || av == null
422 || av.getAlignment() == null)
426 int seqIndex = av.getAlignment().findIndex(results);
431 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
433 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
442 * To centre results, scroll to positions half the visible width
443 * left/right of the start/end positions
447 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
448 start = Math.max(start - offset, 0);
449 end = end + offset - 1;
455 if (end == seq.getEnd())
460 if (av.hasHiddenColumns())
462 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
463 start = hidden.absoluteToVisibleColumn(start);
464 end = hidden.absoluteToVisibleColumn(end);
467 if (!hidden.isVisible(r[0]))
469 // don't scroll - position isn't visible
476 * allow for offset of target sequence (actually scroll to one above it)
478 seqIndex = Math.max(0, seqIndex - verticalOffset);
479 boolean scrollNeeded = true;
481 if (!av.getWrapAlignment())
483 if ((startv = ranges.getStartRes()) >= start)
486 * Scroll left to make start of search results visible
488 setScrollValues(start, seqIndex);
490 else if ((endv = ranges.getEndRes()) <= end)
493 * Scroll right to make end of search results visible
495 setScrollValues(startv + end - endv, seqIndex);
497 else if ((starts = ranges.getStartSeq()) > seqIndex)
500 * Scroll up to make start of search results visible
502 setScrollValues(ranges.getStartRes(), seqIndex);
504 else if ((ends = ranges.getEndSeq()) <= seqIndex)
507 * Scroll down to make end of search results visible
509 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
512 * Else results are already visible - no need to scroll
514 scrollNeeded = false;
518 scrollNeeded = ranges.scrollToWrappedVisible(start);
521 paintAlignment(false, false);
529 * @return DOCUMENT ME!
531 public OverviewPanel getOverviewPanel()
533 return overviewPanel;
542 public void setOverviewPanel(OverviewPanel op)
550 * Hide or show annotation panel
553 public void setAnnotationVisible(boolean b)
555 if (!av.getWrapAlignment())
557 annotationSpaceFillerHolder.setVisible(b);
558 annotationScroller.setVisible(b);
564 * automatically adjust annotation panel height for new annotation whilst
565 * ensuring the alignment is still visible.
568 public void adjustAnnotationHeight()
570 // TODO: display vertical annotation scrollbar if necessary
571 // this is called after loading new annotation onto alignment
572 if (alignFrame.getHeight() == 0)
574 jalview.bin.Console.outPrintln("NEEDS FIXING");
576 validateAnnotationDimensions(true);
578 // TODO: many places call this method and also paintAlignment with various
579 // different settings. this means multiple redraws are triggered...
580 paintAlignment(true, av.needToUpdateStructureViews());
584 * calculate the annotation dimensions and refresh slider values accordingly.
585 * need to do repaints/notifys afterwards.
587 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
589 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
590 // are not changing ancestors, and keyboard action listeners do
591 // not need to be reset. addNotify() is a very expensive operation,
592 // requiring a full re-layout of all parents and children.
593 // Note in JComponent:
594 // This method is called by the toolkit internally and should
595 // not be called directly by programs.
596 // I note that addNotify() is called in several areas of Jalview.
598 AnnotationPanel ap = getAnnotationPanel();
599 int annotationHeight = ap.adjustPanelHeight();
600 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
604 Dimension e = idPanel.getSize();
605 int idWidth = e.width;
606 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
608 annotationScroller.setPreferredSize(new Dimension(
609 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
612 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
614 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
615 manuallyAdjusted ? idWidth
616 : annotationSpaceFillerHolder.getWidth(),
618 annotationScroller.validate();
619 annotationScroller.addNotify();
624 * update alignment layout for viewport settings
629 public void updateLayout()
632 setAnnotationVisible(av.isShowAnnotation());
633 boolean wrap = av.getWrapAlignment();
634 ViewportRanges ranges = av.getRanges();
635 ranges.setStartSeq(0);
636 // scalePanelHolder.setVisible(!wrap);
637 hscroll.setVisible(!wrap);
638 // Allow idPanel width adjustment in wrap mode
639 idwidthAdjuster.setVisible(true);
643 annotationScroller.setVisible(false);
644 annotationSpaceFillerHolder.setVisible(false);
646 else if (av.isShowAnnotation())
648 annotationScroller.setVisible(true);
649 annotationSpaceFillerHolder.setVisible(true);
650 validateAnnotationDimensions(false);
653 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
655 { // may not yet be laid out
658 int widthInRes = getSeqPanel().seqCanvas
659 .getWrappedCanvasWidth(canvasWidth);
660 ranges.setViewportWidth(widthInRes);
664 int widthInRes = (canvasWidth / av.getCharWidth());
665 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
666 / av.getCharHeight());
668 ranges.setViewportWidth(widthInRes);
669 ranges.setViewportHeight(heightInSeq);
673 // idSpaceFillerPanel1.setVisible(!wrap);
679 * Adjust row/column scrollers to show a visible position in the alignment.
682 * visible column to scroll to
684 * visible row to scroll to
687 public void setScrollValues(int xpos, int ypos)
692 if (av == null || av.getAlignment() == null)
697 if (av.getWrapAlignment())
699 setScrollingForWrappedPanel(x);
703 int width = av.getAlignment().getVisibleWidth();
704 int height = av.getAlignment().getHeight();
706 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
707 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
714 if (vextent > height)
719 if ((hextent + x) > width)
724 if ((vextent + y) > height)
726 y = height - vextent;
739 // update the scroll values
740 hscroll.setValues(x, hextent, 0, width);
741 vscroll.setValues(y, vextent, 0, height);
746 * Respond to adjustment event when horizontal or vertical scrollbar is
750 * adjustment event encoding whether hscroll or vscroll changed
753 public void adjustmentValueChanged(AdjustmentEvent evt)
755 if (av.getWrapAlignment())
757 adjustScrollingWrapped(evt);
761 ViewportRanges ranges = av.getRanges();
763 if (evt.getSource() == hscroll)
765 int oldX = ranges.getStartRes();
766 int oldwidth = ranges.getViewportWidth();
767 int x = hscroll.getValue();
768 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
770 // if we're scrolling to the position we're already at, stop
771 // this prevents infinite recursion of events when the scroll/viewport
772 // ranges values are the same
773 if ((x == oldX) && (width == oldwidth))
777 ranges.setViewportStartAndWidth(x, width);
779 else if (evt.getSource() == vscroll)
781 int oldY = ranges.getStartSeq();
782 int oldheight = ranges.getViewportHeight();
783 int y = vscroll.getValue();
784 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
786 // if we're scrolling to the position we're already at, stop
787 // this prevents infinite recursion of events when the scroll/viewport
788 // ranges values are the same
789 if ((y == oldY) && (height == oldheight))
793 ranges.setViewportStartAndHeight(y, height);
799 * Responds to a scroll change by setting the start position of the viewport.
804 protected void adjustScrollingWrapped(AdjustmentEvent evt)
806 if (evt.getSource() == hscroll)
808 return; // no horizontal scroll when wrapped
810 final ViewportRanges ranges = av.getRanges();
812 if (evt.getSource() == vscroll)
814 int newY = vscroll.getValue();
817 * if we're scrolling to the position we're already at, stop
818 * this prevents infinite recursion of events when the scroll/viewport
819 * ranges values are the same
821 int oldX = ranges.getStartRes();
822 int oldY = ranges.getWrappedScrollPosition(oldX);
830 * limit page up/down to one width's worth of positions
832 int rowSize = ranges.getViewportWidth();
833 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
834 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
839 // This is only called if file loaded is a jar file that
840 // was wrapped when saved and user has wrap alignment true
841 // as preference setting
842 SwingUtilities.invokeLater(new Runnable()
847 // When updating scrolling to use ViewportChange events, this code
848 // could not be validated and it is not clear if it is now being
849 // called. Log warning here in case it is called and unforeseen
852 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
854 // scroll to start of panel
855 ranges.setStartRes(0);
856 ranges.setStartSeq(0);
864 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
867 public void paintAlignment(boolean updateOverview,
868 boolean updateStructures)
870 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
871 av.isShowAutocalculatedAbove());
872 sorter.sort(getAlignment().getAlignmentAnnotation(),
873 av.getSortAnnotationsBy());
876 if (updateStructures)
878 av.getStructureSelectionManager().sequenceColoursChanged(this);
883 if (overviewPanel != null)
885 overviewPanel.updateOverviewImage();
891 public void paintComponent(Graphics g)
893 invalidate(); // needed so that the id width adjuster works correctly
894 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
895 int idWidth = d.width;
897 // check wrapped alignment as at least 1 residue width
898 if (av.getWrapAlignment())
900 SeqCanvas sc = this.getSeqPanel().seqCanvas;
901 if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
903 // need to make some adjustments
904 idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
905 av.setIdWidth(idWidth);
906 av.getAlignPanel().getIdPanel().getIdCanvas()
907 .setManuallyAdjusted(true);
909 validateAnnotationDimensions(false);
913 idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
914 hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
916 validate(); // needed so that the id width adjuster works correctly
919 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
920 * though I still think this call should be elsewhere.
922 ViewportRanges ranges = av.getRanges();
923 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
924 super.paintComponent(g);
928 * Set vertical scroll bar position, and number of increments, for wrapped
931 * @param topLeftColumn
932 * the column position at top left (0..)
934 private void setScrollingForWrappedPanel(int topLeftColumn)
936 ViewportRanges ranges = av.getRanges();
937 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
938 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
941 * a scrollbar's value can be set to at most (maximum-extent)
942 * so we add extent (1) to the maxScroll value
944 vscroll.setUnitIncrement(1);
945 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
958 * @return DOCUMENT ME!
960 * @throws PrinterException
964 public int print(Graphics pg, PageFormat pf, int pi)
965 throws PrinterException
967 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
969 int pwidth = (int) pf.getImageableWidth();
970 int pheight = (int) pf.getImageableHeight();
972 if (av.getWrapAlignment())
974 return printWrappedAlignment(pwidth, pheight, pi, pg);
978 return printUnwrapped(pwidth, pheight, pi, pg, pg);
983 * Draws the alignment image, including sequence ids, sequences, and
984 * annotation labels and annotations if shown, on either one or two Graphics
994 * the graphics context for sequence ids and annotation labels
995 * @param alignmentGraphics
996 * the graphics context for sequences and annotations (may or may not
997 * be the same context as idGraphics)
999 * @throws PrinterException
1001 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
1002 Graphics idGraphics, Graphics alignmentGraphics)
1003 throws PrinterException
1006 if (getIdPanel()!=null && getIdPanel().getWidth()>0)
1008 // use the current IdPanel's width, if its set and non-zero
1009 idWidth = getIdPanel().getWidth();
1011 // otherwise calculate it
1012 idWidth = getVisibleIdWidth(false);
1016 * Get the horizontal offset to where we draw the sequences.
1017 * This is idWidth if using a single Graphics context, else zero.
1019 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1022 FontMetrics fm = getFontMetrics(av.getFont());
1023 final int charHeight = av.getCharHeight();
1024 final int scaleHeight = charHeight + fm.getDescent();
1026 idGraphics.setColor(Color.white);
1027 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1028 idGraphics.setFont(av.getFont());
1031 * How many sequences and residues can we fit on a printable page?
1033 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1035 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1037 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1038 int pagesWide = (alignmentWidth / totalRes) + 1;
1040 final int startRes = (pageIndex % pagesWide) * totalRes;
1041 final int endRes = Math.min(startRes + totalRes - 1,
1042 alignmentWidth - 1);
1044 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1045 final int alignmentHeight = av.getAlignment().getHeight();
1046 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1048 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1050 if (av.isShowAnnotation())
1052 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1055 pagesHigh /= pageHeight;
1057 if (pageIndex >= (pagesWide * pagesHigh))
1059 return Printable.NO_SUCH_PAGE;
1061 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1064 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1066 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1067 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1068 pageWidth - idWidth, scaleHeight);
1069 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1072 * Draw the sequence ids, offset for scale height,
1073 * then reset to top left (0, 0)
1075 idGraphics.translate(0, scaleHeight);
1076 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1077 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1078 : av.getSelectionGroup().getSequences(null);
1079 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1082 idGraphics.setFont(av.getFont());
1083 idGraphics.translate(0, -scaleHeight);
1086 * draw the sequences, offset for scale height, and id width (if using a
1087 * single graphics context), then reset to (0, scale height)
1089 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1090 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1091 startRes, endRes, startSeq, endSeq - 1);
1092 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1094 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1097 * draw annotation labels; drawComponent() translates by
1098 * getScrollOffset(), so compensate for that first;
1099 * then reset to (0, scale height)
1101 int offset = getAlabels().getScrollOffset();
1102 idGraphics.translate(0, -offset);
1103 idGraphics.translate(0, alignmentDrawnHeight);
1104 getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1105 idGraphics.translate(0, -alignmentDrawnHeight);
1108 * draw the annotations starting at
1109 * (idOffset, alignmentHeight) from (0, scaleHeight)
1111 alignmentGraphics.translate(alignmentGraphicsOffset,
1112 alignmentDrawnHeight);
1114 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1115 alignmentGraphics, -1, startRes, endRes + 1);
1118 return Printable.PAGE_EXISTS;
1122 * Prints one page of an alignment in wrapped mode. Returns
1123 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1124 * no page could be drawn (page number out of range).
1134 * @throws PrinterException
1136 public int printWrappedAlignment(int pageWidth, int pageHeight,
1137 int pageNumber, Graphics g) throws PrinterException
1139 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1141 int annotationHeight = 0;
1142 if (av.isShowAnnotation())
1144 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1147 int hgap = av.getCharHeight();
1148 if (av.getScaleAboveWrapped())
1150 hgap += av.getCharHeight();
1153 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1156 int idWidth = getVisibleIdWidth(false);
1158 int maxwidth = av.getAlignment().getVisibleWidth();
1160 int resWidth = getSeqPanel().seqCanvas
1161 .getWrappedCanvasWidth(pageWidth - idWidth);
1162 av.getRanges().setViewportStartAndWidth(0, resWidth);
1164 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1166 g.setColor(Color.white);
1167 g.fillRect(0, 0, pageWidth, pageHeight);
1168 g.setFont(av.getFont());
1169 g.setColor(Color.black);
1172 * method: print the whole wrapped alignment, but with a clip region that
1173 * is restricted to the requested page; this supports selective print of
1174 * single pages or ranges, (at the cost of repeated processing in the
1175 * 'normal' case, when all pages are printed)
1177 g.translate(0, -pageNumber * pageHeight);
1179 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1182 * draw sequence ids and annotation labels (if shown)
1184 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1185 idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1187 g.translate(idWidth, 0);
1189 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1190 pageWidth - idWidth, totalHeight, 0);
1192 if ((pageNumber * pageHeight) < totalHeight)
1194 return Printable.PAGE_EXISTS;
1198 return Printable.NO_SUCH_PAGE;
1203 * get current sequence ID panel width, or nominal value if panel were to be
1204 * displayed using default settings
1208 public int getVisibleIdWidth()
1210 return getVisibleIdWidth(true);
1214 * get current sequence ID panel width, or nominal value if panel were to be
1215 * displayed using default settings
1218 * indicate if the Id width for onscreen or offscreen display should
1222 protected int getVisibleIdWidth(boolean onscreen)
1224 // see if rendering offscreen - check preferences and calc width accordingly
1225 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1227 return calculateIdWidth(-1).width;
1229 Integer idwidth = onscreen ? null
1230 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1231 if (idwidth != null)
1233 return idwidth.intValue() + ID_WIDTH_PADDING;
1236 int w = getIdPanel().getWidth();
1237 w = this.calculateIdWidth(-1, true, true).width;
1238 return (w > 0 ? w : calculateIdWidth().width);
1241 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1242 throws ImageOutputException
1244 makeAlignmentImage(type, file, renderer,
1245 BitmapImageSizing.defaultBitmapImageSizing());
1249 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1250 * writes it to the specified file
1254 * @param textrenderer
1255 * @param bitmapscale
1257 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1258 BitmapImageSizing userBis) throws ImageOutputException
1260 final int borderBottomOffset = 5;
1262 AlignmentDimension aDimension = getAlignmentDimension();
1264 // todo use a lambda function in place of callback here?
1265 ImageWriterI writer = new ImageWriterI()
1268 public void exportImage(Graphics graphics) throws Exception
1270 if (av.getWrapAlignment())
1272 printWrappedAlignment(aDimension.getWidth(),
1273 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1277 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1278 graphics, graphics);
1283 String fileTitle = alignFrame.getTitle();
1284 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1286 int imageWidth = aDimension.getWidth();
1287 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1288 String of = MessageManager.getString("label.alignment");
1289 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1294 * Calculates and returns a suitable width and height (in pixels) for an
1299 public AlignmentDimension getAlignmentDimension()
1301 int maxwidth = av.getAlignment().getVisibleWidth();
1303 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1304 + getScalePanel().getHeight();
1305 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1307 if (av.getWrapAlignment())
1309 height = getWrappedHeight();
1310 if (Jalview.isHeadlessMode())
1312 // need to obtain default alignment width and then add in any
1313 // additional allowance for id margin
1314 // this duplicates the calculation in getWrappedHeight but adjusts for
1316 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1317 - alignFrame.getInsets().left - alignFrame.getInsets().right
1318 - getVisibleIdWidth() + getVisibleIdWidth(false);
1322 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1326 else if (av.isShowAnnotation())
1328 height += getAnnotationPanel().adjustPanelHeight() + 3;
1330 return new AlignmentDimension(width, height);
1334 public void makePNGImageMap(File imgMapFile, String imageName)
1335 throws ImageOutputException
1337 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1338 // ////////////////////////////////////////////
1339 int idWidth = getVisibleIdWidth(false);
1340 FontMetrics fm = getFontMetrics(av.getFont());
1341 int scaleHeight = av.getCharHeight() + fm.getDescent();
1344 // ////////////////////////////////
1345 if (imgMapFile != null)
1349 int sSize = av.getAlignment().getHeight();
1350 int alwidth = av.getAlignment().getWidth();
1351 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1352 out.println(HTMLOutput.getImageMapHTML());
1353 out.println("<img src=\"" + imageName
1354 + "\" border=\"0\" usemap=\"#Map\" >"
1355 + "<map name=\"Map\">");
1357 for (int s = 0; s < sSize; s++)
1359 int sy = s * av.getCharHeight() + scaleHeight;
1361 SequenceI seq = av.getAlignment().getSequenceAt(s);
1362 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1363 for (int column = 0; column < alwidth; column++)
1365 StringBuilder text = new StringBuilder(512);
1366 String triplet = null;
1367 if (av.getAlignment().isNucleotide())
1369 triplet = ResidueProperties.nucleotideName
1370 .get(seq.getCharAt(column) + "");
1374 triplet = ResidueProperties.aa2Triplet
1375 .get(seq.getCharAt(column) + "");
1378 if (triplet == null)
1383 int seqPos = seq.findPosition(column);
1384 int gSize = groups.length;
1385 for (int g = 0; g < gSize; g++)
1387 if (text.length() < 1)
1389 text.append("<area shape=\"rect\" coords=\"")
1390 .append((idWidth + column * av.getCharWidth()))
1391 .append(",").append(sy).append(",")
1393 + (column + 1) * av.getCharWidth()))
1394 .append(",").append((av.getCharHeight() + sy))
1395 .append("\"").append(" onMouseOver=\"toolTip('")
1396 .append(seqPos).append(" ").append(triplet);
1399 if (groups[g].getStartRes() < column
1400 && groups[g].getEndRes() > column)
1402 text.append("<br><em>").append(groups[g].getName())
1407 if (text.length() < 1)
1409 text.append("<area shape=\"rect\" coords=\"")
1410 .append((idWidth + column * av.getCharWidth()))
1411 .append(",").append(sy).append(",")
1412 .append((idWidth + (column + 1) * av.getCharWidth()))
1413 .append(",").append((av.getCharHeight() + sy))
1414 .append("\"").append(" onMouseOver=\"toolTip('")
1415 .append(seqPos).append(" ").append(triplet);
1417 if (!Comparison.isGap(seq.getCharAt(column)))
1419 List<SequenceFeature> features = seq.findFeatures(column,
1421 for (SequenceFeature sf : features)
1423 if (sf.isContactFeature())
1425 text.append("<br>").append(sf.getType()).append(" ")
1426 .append(sf.getBegin()).append(":")
1427 .append(sf.getEnd());
1431 text.append("<br>");
1432 text.append(sf.getType());
1433 String description = sf.getDescription();
1434 if (description != null
1435 && !sf.getType().equals(description))
1437 description = description.replace("\"", """);
1438 text.append(" ").append(description);
1441 String status = sf.getStatus();
1442 if (status != null && !"".equals(status))
1444 text.append(" (").append(status).append(")");
1447 if (text.length() > 1)
1449 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1450 out.println(text.toString());
1455 out.println("</map></body></html>");
1458 } catch (Exception ex)
1460 throw new ImageOutputException(
1461 "couldn't write ImageMap due to unexpected error", ex);
1463 } // /////////END OF IMAGE MAP
1468 * Answers the height of the entire alignment in pixels, assuming it is in
1473 int getWrappedHeight()
1475 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1477 if (Jalview.isHeadlessMode())
1479 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1480 - vscroll.getPreferredSize().width
1481 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1484 int chunkWidth = getSeqPanel().seqCanvas
1485 .getWrappedCanvasWidth(seqPanelWidth);
1487 int hgap = av.getCharHeight();
1488 if (av.getScaleAboveWrapped())
1490 hgap += av.getCharHeight();
1493 int annotationHeight = 0;
1494 if (av.isShowAnnotation())
1496 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1497 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1500 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1503 int maxwidth = av.getAlignment().getWidth();
1504 if (av.hasHiddenColumns())
1506 maxwidth = av.getAlignment().getHiddenColumns()
1507 .absoluteToVisibleColumn(maxwidth) - 1;
1510 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1516 * close the panel - deregisters all listeners and nulls any references to
1519 public void closePanel()
1521 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1522 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1523 PaintRefresher.RemoveComponent(this);
1528 * try to ensure references are nulled
1530 if (annotationPanel != null)
1532 annotationPanel.dispose();
1533 annotationPanel = null;
1538 av.removePropertyChangeListener(propertyChangeListener);
1539 propertyChangeListener = null;
1540 StructureSelectionManager ssm = av.getStructureSelectionManager();
1541 ssm.removeStructureViewerListener(getSeqPanel(), null);
1542 ssm.removeSelectionListener(getSeqPanel());
1543 ssm.removeCommandListener(av);
1544 ssm.removeStructureViewerListener(getSeqPanel(), null);
1545 ssm.removeSelectionListener(getSeqPanel());
1551 if (Console.isDebugEnabled())
1553 Console.warn("Closing alignment panel which is already closed.");
1559 * Close any open dialogs that would be orphaned when this one is closed
1561 protected void closeChildFrames()
1563 if (overviewPanel != null)
1565 overviewPanel.dispose();
1566 overviewPanel = null;
1568 if (calculationDialog != null)
1570 calculationDialog.closeFrame();
1571 calculationDialog = null;
1576 * hides or shows dynamic annotation rows based on groups and av state flags
1578 public void updateAnnotation()
1580 updateAnnotation(false, false);
1583 public void updateAnnotation(boolean applyGlobalSettings)
1585 updateAnnotation(applyGlobalSettings, false);
1588 public void updateAnnotation(boolean applyGlobalSettings,
1589 boolean preserveNewGroupSettings)
1591 av.updateGroupAnnotationSettings(applyGlobalSettings,
1592 preserveNewGroupSettings);
1593 adjustAnnotationHeight();
1597 public AlignmentI getAlignment()
1599 return av == null ? null : av.getAlignment();
1603 public String getViewName()
1605 return av.getViewName();
1609 * Make/Unmake this alignment panel the current input focus
1613 public void setSelected(boolean b)
1617 if (alignFrame.getSplitViewContainer() != null)
1620 * bring enclosing SplitFrame to front first if there is one
1622 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1624 alignFrame.setSelected(b);
1625 } catch (Exception ex)
1630 setAlignFrameView();
1634 public void setAlignFrameView()
1636 alignFrame.setDisplayedView(this);
1640 public StructureSelectionManager getStructureSelectionManager()
1642 return av.getStructureSelectionManager();
1646 public void raiseOOMWarning(String string, OutOfMemoryError error)
1648 new OOMWarning(string, error, this);
1652 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1655 return new FeatureRenderer(this);
1659 public jalview.api.FeatureRenderer getFeatureRenderer()
1661 return seqPanel.seqCanvas.getFeatureRenderer();
1664 public void updateFeatureRenderer(
1665 jalview.renderer.seqfeatures.FeatureRenderer fr)
1667 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1670 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1672 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1674 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1678 public ScalePanel getScalePanel()
1683 public void setScalePanel(ScalePanel scalePanel)
1685 this.scalePanel = scalePanel;
1688 public SeqPanel getSeqPanel()
1693 public void setSeqPanel(SeqPanel seqPanel)
1695 this.seqPanel = seqPanel;
1698 public AnnotationPanel getAnnotationPanel()
1700 return annotationPanel;
1703 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1705 this.annotationPanel = annotationPanel;
1708 public AnnotationLabels getAlabels()
1713 public void setAlabels(AnnotationLabels alabels)
1715 this.alabels = alabels;
1718 public IdPanel getIdPanel()
1723 public void setIdPanel(IdPanel idPanel)
1725 this.idPanel = idPanel;
1729 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1730 * The aim is to keep the two alignments 'lined up' on their centre columns.
1733 * holds mapped region(s) of this alignment that we are scrolling
1734 * 'to'; may be modified for sequence offset by this method
1735 * @param verticalOffset
1736 * the number of visible sequences to show above the mapped region
1738 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1740 scrollToPosition(sr, verticalOffset, true);
1744 * Set a flag to say do not scroll any (cDNA/protein) complement.
1748 protected void setToScrollComplementPanel(boolean b)
1750 this.scrollComplementaryPanel = b;
1754 * Get whether to scroll complement panel
1756 * @return true if cDNA/protein complement panels should be scrolled
1758 protected boolean isSetToScrollComplementPanel()
1760 return this.scrollComplementaryPanel;
1766 * @adjustHeight if true, try to recalculate panel height for visible
1769 protected void refresh(boolean adjustHeight)
1771 validateAnnotationDimensions(adjustHeight);
1775 // sort, repaint, update overview
1776 paintAlignment(true, false);
1780 // lightweight repaint
1787 * Property change event fired when a change is made to the viewport ranges
1788 * object associated with this alignment panel's viewport
1790 public void propertyChange(PropertyChangeEvent evt)
1792 // update this panel's scroll values based on the new viewport ranges values
1793 ViewportRanges ranges = av.getRanges();
1794 int x = ranges.getStartRes();
1795 int y = ranges.getStartSeq();
1796 setScrollValues(x, y);
1798 // now update any complementary alignment (its viewport ranges object
1799 // is different so does not get automatically updated)
1800 if (isSetToScrollComplementPanel())
1802 setToScrollComplementPanel(false);
1803 av.scrollComplementaryAlignment();
1804 setToScrollComplementPanel(true);
1809 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1810 * reference should be nulled when the dialog is closed.
1812 * @param calculationChooser
1814 public void setCalculationDialog(CalculationChooser calculationChooser)
1816 calculationDialog = calculationChooser;
1820 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1823 public CalculationChooser getCalculationDialog()
1825 return calculationDialog;
1829 * Constructs and sets the title for the Overview window (if there is one),
1830 * including the align frame's title, and view name (if applicable). Returns
1831 * the title, or null if this panel has no Overview window open.
1836 public String setOverviewTitle(AlignFrame alignFrame)
1838 if (this.overviewPanel == null)
1842 String overviewTitle = MessageManager
1843 .formatMessage("label.overview_params", new Object[]
1844 { alignFrame.getTitle() });
1845 String viewName = getViewName();
1846 if (viewName != null)
1848 overviewTitle += (" " + viewName);
1850 overviewPanel.setTitle(overviewTitle);
1851 return overviewTitle;
1855 * If this alignment panel has an Overview panel open, closes it
1857 public void closeOverviewPanel()
1859 if (overviewPanel != null)
1861 overviewPanel.close();
1862 overviewPanel = null;