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 = this.getAlabels();
344 int stringWidth = aal.drawLabels(null, false, idWidth, false, fm);
345 idWidth = Math.max(idWidth, stringWidth);
349 fm = c.getFontMetrics(getAlabels().getFont());
351 for (i = 0; i < al.getAlignmentAnnotation().length; i++)
353 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
354 if (visibleOnly && !aa.visible)
358 String label = aa.label;
359 int stringWidth = fm.stringWidth(label);
360 idWidth = Math.max(idWidth, stringWidth);
365 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
366 w += ID_WIDTH_PADDING;
368 return new Dimension(w, 12);
372 * Highlight the given results on the alignment
375 public void highlightSearchResults(SearchResultsI results)
377 boolean scrolled = scrollToPosition(results, 0, false);
379 boolean fastPaint = !(scrolled && av.getWrapAlignment());
381 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
385 * Scroll the view to show the position of the highlighted region in results
388 * @param searchResults
391 public boolean scrollToPosition(SearchResultsI searchResults)
393 return scrollToPosition(searchResults, 0, false);
397 * Scrolls the view (if necessary) to show the position of the first
398 * highlighted region in results (if any). Answers true if the view was
399 * scrolled, or false if no matched region was found, or it is already
403 * @param verticalOffset
404 * if greater than zero, allows scrolling to a position below the
405 * first displayed sequence
407 * if true, try to centre the search results horizontally in the view
410 protected boolean scrollToPosition(SearchResultsI results,
411 int verticalOffset, boolean centre)
413 int startv, endv, starts, ends;
414 ViewportRanges ranges = av.getRanges();
416 if (results == null || results.isEmpty() || av == null
417 || av.getAlignment() == null)
421 int seqIndex = av.getAlignment().findIndex(results);
426 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
428 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
437 * To centre results, scroll to positions half the visible width
438 * left/right of the start/end positions
442 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
443 start = Math.max(start - offset, 0);
444 end = end + offset - 1;
450 if (end == seq.getEnd())
455 if (av.hasHiddenColumns())
457 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
458 start = hidden.absoluteToVisibleColumn(start);
459 end = hidden.absoluteToVisibleColumn(end);
462 if (!hidden.isVisible(r[0]))
464 // don't scroll - position isn't visible
471 * allow for offset of target sequence (actually scroll to one above it)
473 seqIndex = Math.max(0, seqIndex - verticalOffset);
474 boolean scrollNeeded = true;
476 if (!av.getWrapAlignment())
478 if ((startv = ranges.getStartRes()) >= start)
481 * Scroll left to make start of search results visible
483 setScrollValues(start, seqIndex);
485 else if ((endv = ranges.getEndRes()) <= end)
488 * Scroll right to make end of search results visible
490 setScrollValues(startv + end - endv, seqIndex);
492 else if ((starts = ranges.getStartSeq()) > seqIndex)
495 * Scroll up to make start of search results visible
497 setScrollValues(ranges.getStartRes(), seqIndex);
499 else if ((ends = ranges.getEndSeq()) <= seqIndex)
502 * Scroll down to make end of search results visible
504 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
507 * Else results are already visible - no need to scroll
509 scrollNeeded = false;
513 scrollNeeded = ranges.scrollToWrappedVisible(start);
516 paintAlignment(false, false);
524 * @return DOCUMENT ME!
526 public OverviewPanel getOverviewPanel()
528 return overviewPanel;
537 public void setOverviewPanel(OverviewPanel op)
545 * Hide or show annotation panel
548 public void setAnnotationVisible(boolean b)
550 if (!av.getWrapAlignment())
552 annotationSpaceFillerHolder.setVisible(b);
553 annotationScroller.setVisible(b);
559 * automatically adjust annotation panel height for new annotation whilst
560 * ensuring the alignment is still visible.
563 public void adjustAnnotationHeight()
565 // TODO: display vertical annotation scrollbar if necessary
566 // this is called after loading new annotation onto alignment
567 if (alignFrame.getHeight() == 0)
569 System.out.println("NEEDS FIXING");
571 validateAnnotationDimensions(true);
573 // TODO: many places call this method and also paintAlignment with various
574 // different settings. this means multiple redraws are triggered...
575 paintAlignment(true, av.needToUpdateStructureViews());
579 * calculate the annotation dimensions and refresh slider values accordingly.
580 * need to do repaints/notifys afterwards.
582 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
584 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
585 // are not changing ancestors, and keyboard action listeners do
586 // not need to be reset. addNotify() is a very expensive operation,
587 // requiring a full re-layout of all parents and children.
588 // Note in JComponent:
589 // This method is called by the toolkit internally and should
590 // not be called directly by programs.
591 // I note that addNotify() is called in several areas of Jalview.
593 AnnotationPanel ap = getAnnotationPanel();
594 int annotationHeight = ap.adjustPanelHeight();
595 annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
599 Dimension e = idPanel.getSize();
600 int idWidth = e.width;
601 boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
603 annotationScroller.setPreferredSize(new Dimension(
604 manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
607 alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
609 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
610 manuallyAdjusted ? idWidth
611 : annotationSpaceFillerHolder.getWidth(),
613 annotationScroller.validate();
614 annotationScroller.addNotify();
619 * update alignment layout for viewport settings
624 public void updateLayout()
627 setAnnotationVisible(av.isShowAnnotation());
628 boolean wrap = av.getWrapAlignment();
629 ViewportRanges ranges = av.getRanges();
630 ranges.setStartSeq(0);
631 scalePanelHolder.setVisible(!wrap);
632 hscroll.setVisible(!wrap);
633 // Allow idPanel width adjustment in wrap mode
634 idwidthAdjuster.setVisible(true);
638 annotationScroller.setVisible(false);
639 annotationSpaceFillerHolder.setVisible(false);
641 else if (av.isShowAnnotation())
643 annotationScroller.setVisible(true);
644 annotationSpaceFillerHolder.setVisible(true);
645 validateAnnotationDimensions(false);
648 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
650 { // may not yet be laid out
653 int widthInRes = getSeqPanel().seqCanvas
654 .getWrappedCanvasWidth(canvasWidth);
655 ranges.setViewportWidth(widthInRes);
659 int widthInRes = (canvasWidth / av.getCharWidth());
660 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
661 / av.getCharHeight());
663 ranges.setViewportWidth(widthInRes);
664 ranges.setViewportHeight(heightInSeq);
668 // idSpaceFillerPanel1.setVisible(!wrap);
674 * Adjust row/column scrollers to show a visible position in the alignment.
677 * visible column to scroll to
679 * visible row to scroll to
682 public void setScrollValues(int xpos, int ypos)
687 if (av == null || av.getAlignment() == null)
692 if (av.getWrapAlignment())
694 setScrollingForWrappedPanel(x);
698 int width = av.getAlignment().getVisibleWidth();
699 int height = av.getAlignment().getHeight();
701 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
702 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
709 if (vextent > height)
714 if ((hextent + x) > width)
719 if ((vextent + y) > height)
721 y = height - vextent;
734 // update the scroll values
735 hscroll.setValues(x, hextent, 0, width);
736 vscroll.setValues(y, vextent, 0, height);
741 * Respond to adjustment event when horizontal or vertical scrollbar is
745 * adjustment event encoding whether hscroll or vscroll changed
748 public void adjustmentValueChanged(AdjustmentEvent evt)
750 if (av.getWrapAlignment())
752 adjustScrollingWrapped(evt);
756 ViewportRanges ranges = av.getRanges();
758 if (evt.getSource() == hscroll)
760 int oldX = ranges.getStartRes();
761 int oldwidth = ranges.getViewportWidth();
762 int x = hscroll.getValue();
763 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
765 // if we're scrolling to the position we're already at, stop
766 // this prevents infinite recursion of events when the scroll/viewport
767 // ranges values are the same
768 if ((x == oldX) && (width == oldwidth))
772 ranges.setViewportStartAndWidth(x, width);
774 else if (evt.getSource() == vscroll)
776 int oldY = ranges.getStartSeq();
777 int oldheight = ranges.getViewportHeight();
778 int y = vscroll.getValue();
779 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
781 // if we're scrolling to the position we're already at, stop
782 // this prevents infinite recursion of events when the scroll/viewport
783 // ranges values are the same
784 if ((y == oldY) && (height == oldheight))
788 ranges.setViewportStartAndHeight(y, height);
794 * Responds to a scroll change by setting the start position of the viewport.
799 protected void adjustScrollingWrapped(AdjustmentEvent evt)
801 if (evt.getSource() == hscroll)
803 return; // no horizontal scroll when wrapped
805 final ViewportRanges ranges = av.getRanges();
807 if (evt.getSource() == vscroll)
809 int newY = vscroll.getValue();
812 * if we're scrolling to the position we're already at, stop
813 * this prevents infinite recursion of events when the scroll/viewport
814 * ranges values are the same
816 int oldX = ranges.getStartRes();
817 int oldY = ranges.getWrappedScrollPosition(oldX);
825 * limit page up/down to one width's worth of positions
827 int rowSize = ranges.getViewportWidth();
828 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
829 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
834 // This is only called if file loaded is a jar file that
835 // was wrapped when saved and user has wrap alignment true
836 // as preference setting
837 SwingUtilities.invokeLater(new Runnable()
842 // When updating scrolling to use ViewportChange events, this code
843 // could not be validated and it is not clear if it is now being
844 // called. Log warning here in case it is called and unforeseen
847 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
849 // scroll to start of panel
850 ranges.setStartRes(0);
851 ranges.setStartSeq(0);
859 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
862 public void paintAlignment(boolean updateOverview,
863 boolean updateStructures)
865 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
866 av.isShowAutocalculatedAbove());
867 sorter.sort(getAlignment().getAlignmentAnnotation(),
868 av.getSortAnnotationsBy());
871 if (updateStructures)
873 av.getStructureSelectionManager().sequenceColoursChanged(this);
878 if (overviewPanel != null)
880 overviewPanel.updateOverviewImage();
886 public void paintComponent(Graphics g)
888 invalidate(); // needed so that the id width adjuster works correctly
890 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
891 idPanelHolder.setPreferredSize(d);
892 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
894 validate(); // needed so that the id width adjuster works correctly
897 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
898 * though I still think this call should be elsewhere.
900 ViewportRanges ranges = av.getRanges();
901 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
902 super.paintComponent(g);
906 * Set vertical scroll bar position, and number of increments, for wrapped
909 * @param topLeftColumn
910 * the column position at top left (0..)
912 private void setScrollingForWrappedPanel(int topLeftColumn)
914 ViewportRanges ranges = av.getRanges();
915 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
916 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
919 * a scrollbar's value can be set to at most (maximum-extent)
920 * so we add extent (1) to the maxScroll value
922 vscroll.setUnitIncrement(1);
923 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
936 * @return DOCUMENT ME!
938 * @throws PrinterException
942 public int print(Graphics pg, PageFormat pf, int pi)
943 throws PrinterException
945 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
947 int pwidth = (int) pf.getImageableWidth();
948 int pheight = (int) pf.getImageableHeight();
950 if (av.getWrapAlignment())
952 return printWrappedAlignment(pwidth, pheight, pi, pg);
956 return printUnwrapped(pwidth, pheight, pi, pg, pg);
961 * Draws the alignment image, including sequence ids, sequences, and
962 * annotation labels and annotations if shown, on either one or two Graphics
972 * the graphics context for sequence ids and annotation labels
973 * @param alignmentGraphics
974 * the graphics context for sequences and annotations (may or may not
975 * be the same context as idGraphics)
977 * @throws PrinterException
979 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
980 Graphics idGraphics, Graphics alignmentGraphics)
981 throws PrinterException
983 final int idWidth = getVisibleIdWidth(false);
986 * Get the horizontal offset to where we draw the sequences.
987 * This is idWidth if using a single Graphics context, else zero.
989 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
992 FontMetrics fm = getFontMetrics(av.getFont());
993 final int charHeight = av.getCharHeight();
994 final int scaleHeight = charHeight + fm.getDescent();
996 idGraphics.setColor(Color.white);
997 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
998 idGraphics.setFont(av.getFont());
1001 * How many sequences and residues can we fit on a printable page?
1003 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1005 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1007 final int alignmentWidth = av.getAlignment().getVisibleWidth();
1008 int pagesWide = (alignmentWidth / totalRes) + 1;
1010 final int startRes = (pageIndex % pagesWide) * totalRes;
1011 final int endRes = Math.min(startRes + totalRes - 1,
1012 alignmentWidth - 1);
1014 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1015 final int alignmentHeight = av.getAlignment().getHeight();
1016 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1018 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1020 if (av.isShowAnnotation())
1022 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1025 pagesHigh /= pageHeight;
1027 if (pageIndex >= (pagesWide * pagesHigh))
1029 return Printable.NO_SUCH_PAGE;
1031 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1034 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1036 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1037 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1038 pageWidth - idWidth, scaleHeight);
1039 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1042 * Draw the sequence ids, offset for scale height,
1043 * then reset to top left (0, 0)
1045 idGraphics.translate(0, scaleHeight);
1046 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1047 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1048 : av.getSelectionGroup().getSequences(null);
1049 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1052 idGraphics.setFont(av.getFont());
1053 idGraphics.translate(0, -scaleHeight);
1056 * draw the sequences, offset for scale height, and id width (if using a
1057 * single graphics context), then reset to (0, scale height)
1059 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1060 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1061 startRes, endRes, startSeq, endSeq - 1);
1062 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1064 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1067 * draw annotation labels; drawComponent() translates by
1068 * getScrollOffset(), so compensate for that first;
1069 * then reset to (0, scale height)
1071 int offset = getAlabels().getScrollOffset();
1072 idGraphics.translate(0, -offset);
1073 idGraphics.translate(0, alignmentDrawnHeight);
1074 getAlabels().drawComponent(idGraphics, idWidth);
1075 idGraphics.translate(0, -alignmentDrawnHeight);
1078 * draw the annotations starting at
1079 * (idOffset, alignmentHeight) from (0, scaleHeight)
1081 alignmentGraphics.translate(alignmentGraphicsOffset,
1082 alignmentDrawnHeight);
1084 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1085 alignmentGraphics, -1, startRes, endRes + 1);
1088 return Printable.PAGE_EXISTS;
1092 * Prints one page of an alignment in wrapped mode. Returns
1093 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1094 * no page could be drawn (page number out of range).
1104 * @throws PrinterException
1106 public int printWrappedAlignment(int pageWidth, int pageHeight,
1107 int pageNumber, Graphics g) throws PrinterException
1109 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1111 int annotationHeight = 0;
1112 if (av.isShowAnnotation())
1114 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1117 int hgap = av.getCharHeight();
1118 if (av.getScaleAboveWrapped())
1120 hgap += av.getCharHeight();
1123 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1126 int idWidth = getVisibleIdWidth(false);
1128 int maxwidth = av.getAlignment().getVisibleWidth();
1130 int resWidth = getSeqPanel().seqCanvas
1131 .getWrappedCanvasWidth(pageWidth - idWidth);
1132 av.getRanges().setViewportStartAndWidth(0, resWidth);
1134 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1136 g.setColor(Color.white);
1137 g.fillRect(0, 0, pageWidth, pageHeight);
1138 g.setFont(av.getFont());
1139 g.setColor(Color.black);
1142 * method: print the whole wrapped alignment, but with a clip region that
1143 * is restricted to the requested page; this supports selective print of
1144 * single pages or ranges, (at the cost of repeated processing in the
1145 * 'normal' case, when all pages are printed)
1147 g.translate(0, -pageNumber * pageHeight);
1149 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1152 * draw sequence ids and annotation labels (if shown)
1154 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1155 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1157 g.translate(idWidth, 0);
1159 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1160 pageWidth - idWidth, totalHeight, 0);
1162 if ((pageNumber * pageHeight) < totalHeight)
1164 return Printable.PAGE_EXISTS;
1168 return Printable.NO_SUCH_PAGE;
1173 * get current sequence ID panel width, or nominal value if panel were to be
1174 * displayed using default settings
1178 public int getVisibleIdWidth()
1180 return getVisibleIdWidth(true);
1184 * get current sequence ID panel width, or nominal value if panel were to be
1185 * displayed using default settings
1188 * indicate if the Id width for onscreen or offscreen display should
1192 protected int getVisibleIdWidth(boolean onscreen)
1194 // see if rendering offscreen - check preferences and calc width accordingly
1195 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1197 return calculateIdWidth(-1).width;
1199 Integer idwidth = onscreen ? null
1200 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1201 if (idwidth != null)
1203 return idwidth.intValue() + ID_WIDTH_PADDING;
1206 int w = getIdPanel().getWidth();
1207 w = this.calculateIdWidth(-1, true, true).width;
1208 return (w > 0 ? w : calculateIdWidth().width);
1211 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1212 throws ImageOutputException
1214 makeAlignmentImage(type, file, renderer,
1215 BitmapImageSizing.nullBitmapImageSizing());
1219 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1220 * writes it to the specified file
1224 * @param textrenderer
1225 * @param bitmapscale
1227 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1228 BitmapImageSizing userBis) throws ImageOutputException
1230 final int borderBottomOffset = 5;
1232 AlignmentDimension aDimension = getAlignmentDimension();
1234 // todo use a lambda function in place of callback here?
1235 ImageWriterI writer = new ImageWriterI()
1238 public void exportImage(Graphics graphics) throws Exception
1240 if (av.getWrapAlignment())
1242 printWrappedAlignment(aDimension.getWidth(),
1243 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1247 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1248 graphics, graphics);
1253 String fileTitle = alignFrame.getTitle();
1254 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1256 int imageWidth = aDimension.getWidth();
1257 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1258 String of = MessageManager.getString("label.alignment");
1259 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1264 * Calculates and returns a suitable width and height (in pixels) for an
1269 public AlignmentDimension getAlignmentDimension()
1271 int maxwidth = av.getAlignment().getVisibleWidth();
1273 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1274 + getScalePanel().getHeight();
1275 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1277 if (av.getWrapAlignment())
1279 height = getWrappedHeight();
1280 if (Jalview.isHeadlessMode())
1282 // need to obtain default alignment width and then add in any
1283 // additional allowance for id margin
1284 // this duplicates the calculation in getWrappedHeight but adjusts for
1286 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1287 - alignFrame.getInsets().left - alignFrame.getInsets().right
1288 - getVisibleIdWidth() + getVisibleIdWidth(false);
1292 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1296 else if (av.isShowAnnotation())
1298 height += getAnnotationPanel().adjustPanelHeight() + 3;
1300 return new AlignmentDimension(width, height);
1304 public void makePNGImageMap(File imgMapFile, String imageName)
1305 throws ImageOutputException
1307 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1308 // ////////////////////////////////////////////
1309 int idWidth = getVisibleIdWidth(false);
1310 FontMetrics fm = getFontMetrics(av.getFont());
1311 int scaleHeight = av.getCharHeight() + fm.getDescent();
1314 // ////////////////////////////////
1315 if (imgMapFile != null)
1319 int sSize = av.getAlignment().getHeight();
1320 int alwidth = av.getAlignment().getWidth();
1321 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1322 out.println(HTMLOutput.getImageMapHTML());
1323 out.println("<img src=\"" + imageName
1324 + "\" border=\"0\" usemap=\"#Map\" >"
1325 + "<map name=\"Map\">");
1327 for (int s = 0; s < sSize; s++)
1329 int sy = s * av.getCharHeight() + scaleHeight;
1331 SequenceI seq = av.getAlignment().getSequenceAt(s);
1332 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1333 for (int column = 0; column < alwidth; column++)
1335 StringBuilder text = new StringBuilder(512);
1336 String triplet = null;
1337 if (av.getAlignment().isNucleotide())
1339 triplet = ResidueProperties.nucleotideName
1340 .get(seq.getCharAt(column) + "");
1344 triplet = ResidueProperties.aa2Triplet
1345 .get(seq.getCharAt(column) + "");
1348 if (triplet == null)
1353 int seqPos = seq.findPosition(column);
1354 int gSize = groups.length;
1355 for (int g = 0; g < gSize; g++)
1357 if (text.length() < 1)
1359 text.append("<area shape=\"rect\" coords=\"")
1360 .append((idWidth + column * av.getCharWidth()))
1361 .append(",").append(sy).append(",")
1363 + (column + 1) * av.getCharWidth()))
1364 .append(",").append((av.getCharHeight() + sy))
1365 .append("\"").append(" onMouseOver=\"toolTip('")
1366 .append(seqPos).append(" ").append(triplet);
1369 if (groups[g].getStartRes() < column
1370 && groups[g].getEndRes() > column)
1372 text.append("<br><em>").append(groups[g].getName())
1377 if (text.length() < 1)
1379 text.append("<area shape=\"rect\" coords=\"")
1380 .append((idWidth + column * av.getCharWidth()))
1381 .append(",").append(sy).append(",")
1382 .append((idWidth + (column + 1) * av.getCharWidth()))
1383 .append(",").append((av.getCharHeight() + sy))
1384 .append("\"").append(" onMouseOver=\"toolTip('")
1385 .append(seqPos).append(" ").append(triplet);
1387 if (!Comparison.isGap(seq.getCharAt(column)))
1389 List<SequenceFeature> features = seq.findFeatures(column,
1391 for (SequenceFeature sf : features)
1393 if (sf.isContactFeature())
1395 text.append("<br>").append(sf.getType()).append(" ")
1396 .append(sf.getBegin()).append(":")
1397 .append(sf.getEnd());
1401 text.append("<br>");
1402 text.append(sf.getType());
1403 String description = sf.getDescription();
1404 if (description != null
1405 && !sf.getType().equals(description))
1407 description = description.replace("\"", """);
1408 text.append(" ").append(description);
1411 String status = sf.getStatus();
1412 if (status != null && !"".equals(status))
1414 text.append(" (").append(status).append(")");
1417 if (text.length() > 1)
1419 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1420 out.println(text.toString());
1425 out.println("</map></body></html>");
1428 } catch (Exception ex)
1430 throw new ImageOutputException(
1431 "couldn't write ImageMap due to unexpected error", ex);
1433 } // /////////END OF IMAGE MAP
1438 * Answers the height of the entire alignment in pixels, assuming it is in
1443 int getWrappedHeight()
1445 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1447 if (Jalview.isHeadlessMode())
1449 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1450 - vscroll.getPreferredSize().width
1451 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1454 int chunkWidth = getSeqPanel().seqCanvas
1455 .getWrappedCanvasWidth(seqPanelWidth);
1457 int hgap = av.getCharHeight();
1458 if (av.getScaleAboveWrapped())
1460 hgap += av.getCharHeight();
1463 int annotationHeight = 0;
1464 if (av.isShowAnnotation())
1466 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1467 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1470 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1473 int maxwidth = av.getAlignment().getWidth();
1474 if (av.hasHiddenColumns())
1476 maxwidth = av.getAlignment().getHiddenColumns()
1477 .absoluteToVisibleColumn(maxwidth) - 1;
1480 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1486 * close the panel - deregisters all listeners and nulls any references to
1489 public void closePanel()
1491 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1492 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1493 PaintRefresher.RemoveComponent(this);
1498 * try to ensure references are nulled
1500 if (annotationPanel != null)
1502 annotationPanel.dispose();
1503 annotationPanel = null;
1508 av.removePropertyChangeListener(propertyChangeListener);
1509 propertyChangeListener = null;
1510 StructureSelectionManager ssm = av.getStructureSelectionManager();
1511 ssm.removeStructureViewerListener(getSeqPanel(), null);
1512 ssm.removeSelectionListener(getSeqPanel());
1513 ssm.removeCommandListener(av);
1514 ssm.removeStructureViewerListener(getSeqPanel(), null);
1515 ssm.removeSelectionListener(getSeqPanel());
1521 if (Console.isDebugEnabled())
1523 Console.warn("Closing alignment panel which is already closed.");
1529 * Close any open dialogs that would be orphaned when this one is closed
1531 protected void closeChildFrames()
1533 if (overviewPanel != null)
1535 overviewPanel.dispose();
1536 overviewPanel = null;
1538 if (calculationDialog != null)
1540 calculationDialog.closeFrame();
1541 calculationDialog = null;
1546 * hides or shows dynamic annotation rows based on groups and av state flags
1548 public void updateAnnotation()
1550 updateAnnotation(false, false);
1553 public void updateAnnotation(boolean applyGlobalSettings)
1555 updateAnnotation(applyGlobalSettings, false);
1558 public void updateAnnotation(boolean applyGlobalSettings,
1559 boolean preserveNewGroupSettings)
1561 av.updateGroupAnnotationSettings(applyGlobalSettings,
1562 preserveNewGroupSettings);
1563 adjustAnnotationHeight();
1567 public AlignmentI getAlignment()
1569 return av == null ? null : av.getAlignment();
1573 public String getViewName()
1575 return av.getViewName();
1579 * Make/Unmake this alignment panel the current input focus
1583 public void setSelected(boolean b)
1587 if (alignFrame.getSplitViewContainer() != null)
1590 * bring enclosing SplitFrame to front first if there is one
1592 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1594 alignFrame.setSelected(b);
1595 } catch (Exception ex)
1600 setAlignFrameView();
1604 public void setAlignFrameView()
1606 alignFrame.setDisplayedView(this);
1610 public StructureSelectionManager getStructureSelectionManager()
1612 return av.getStructureSelectionManager();
1616 public void raiseOOMWarning(String string, OutOfMemoryError error)
1618 new OOMWarning(string, error, this);
1622 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1625 return new FeatureRenderer(this);
1629 public jalview.api.FeatureRenderer getFeatureRenderer()
1631 return seqPanel.seqCanvas.getFeatureRenderer();
1634 public void updateFeatureRenderer(
1635 jalview.renderer.seqfeatures.FeatureRenderer fr)
1637 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1640 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1642 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1644 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1648 public ScalePanel getScalePanel()
1653 public void setScalePanel(ScalePanel scalePanel)
1655 this.scalePanel = scalePanel;
1658 public SeqPanel getSeqPanel()
1663 public void setSeqPanel(SeqPanel seqPanel)
1665 this.seqPanel = seqPanel;
1668 public AnnotationPanel getAnnotationPanel()
1670 return annotationPanel;
1673 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1675 this.annotationPanel = annotationPanel;
1678 public AnnotationLabels getAlabels()
1683 public void setAlabels(AnnotationLabels alabels)
1685 this.alabels = alabels;
1688 public IdPanel getIdPanel()
1693 public void setIdPanel(IdPanel idPanel)
1695 this.idPanel = idPanel;
1699 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1700 * The aim is to keep the two alignments 'lined up' on their centre columns.
1703 * holds mapped region(s) of this alignment that we are scrolling
1704 * 'to'; may be modified for sequence offset by this method
1705 * @param verticalOffset
1706 * the number of visible sequences to show above the mapped region
1708 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1710 scrollToPosition(sr, verticalOffset, true);
1714 * Set a flag to say do not scroll any (cDNA/protein) complement.
1718 protected void setToScrollComplementPanel(boolean b)
1720 this.scrollComplementaryPanel = b;
1724 * Get whether to scroll complement panel
1726 * @return true if cDNA/protein complement panels should be scrolled
1728 protected boolean isSetToScrollComplementPanel()
1730 return this.scrollComplementaryPanel;
1736 * @adjustHeight if true, try to recalculate panel height for visible
1739 protected void refresh(boolean adjustHeight)
1741 validateAnnotationDimensions(adjustHeight);
1745 // sort, repaint, update overview
1746 paintAlignment(true, false);
1750 // lightweight repaint
1757 * Property change event fired when a change is made to the viewport ranges
1758 * object associated with this alignment panel's viewport
1760 public void propertyChange(PropertyChangeEvent evt)
1762 // update this panel's scroll values based on the new viewport ranges values
1763 ViewportRanges ranges = av.getRanges();
1764 int x = ranges.getStartRes();
1765 int y = ranges.getStartSeq();
1766 setScrollValues(x, y);
1768 // now update any complementary alignment (its viewport ranges object
1769 // is different so does not get automatically updated)
1770 if (isSetToScrollComplementPanel())
1772 setToScrollComplementPanel(false);
1773 av.scrollComplementaryAlignment();
1774 setToScrollComplementPanel(true);
1779 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1780 * reference should be nulled when the dialog is closed.
1782 * @param calculationChooser
1784 public void setCalculationDialog(CalculationChooser calculationChooser)
1786 calculationDialog = calculationChooser;
1790 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1793 public CalculationChooser getCalculationDialog()
1795 return calculationDialog;
1799 * Constructs and sets the title for the Overview window (if there is one),
1800 * including the align frame's title, and view name (if applicable). Returns
1801 * the title, or null if this panel has no Overview window open.
1806 public String setOverviewTitle(AlignFrame alignFrame)
1808 if (this.overviewPanel == null)
1812 String overviewTitle = MessageManager
1813 .formatMessage("label.overview_params", new Object[]
1814 { alignFrame.getTitle() });
1815 String viewName = getViewName();
1816 if (viewName != null)
1818 overviewTitle += (" " + viewName);
1820 overviewPanel.setTitle(overviewTitle);
1821 return overviewTitle;
1825 * If this alignment panel has an Overview panel open, closes it
1827 public void closeOverviewPanel()
1829 if (overviewPanel != null)
1831 overviewPanel.close();
1832 overviewPanel = null;