2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
45 import javax.swing.SwingUtilities;
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.HiddenColumns;
55 import jalview.datamodel.SearchResultsI;
56 import jalview.datamodel.SequenceFeature;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ImageExporter.ImageWriterI;
60 import jalview.io.HTMLOutput;
61 import jalview.jbgui.GAlignmentPanel;
62 import jalview.math.AlignmentDimension;
63 import jalview.schemes.ResidueProperties;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.Comparison;
66 import jalview.util.ImageMaker;
67 import jalview.util.MessageManager;
68 import jalview.util.imagemaker.BitmapImageSizing;
69 import jalview.viewmodel.ViewportListenerI;
70 import jalview.viewmodel.ViewportRanges;
76 * @version $Revision: 1.161 $
78 @SuppressWarnings("serial")
79 public class AlignmentPanel extends GAlignmentPanel implements
80 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
83 * spare space in pixels between sequence id and alignment panel
85 private static final int ID_WIDTH_PADDING = 4;
87 public AlignViewport av;
89 OverviewPanel overviewPanel;
91 private SeqPanel seqPanel;
93 private IdPanel idPanel;
95 IdwidthAdjuster idwidthAdjuster;
97 public AlignFrame alignFrame;
99 private ScalePanel scalePanel;
101 private AnnotationPanel annotationPanel;
103 private AnnotationLabels alabels;
105 private int hextent = 0;
107 private int vextent = 0;
110 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
111 * false, suppresses invoking the same method recursively.
113 private boolean scrollComplementaryPanel = true;
115 private PropertyChangeListener propertyChangeListener;
117 private CalculationChooser calculationDialog;
120 * Creates a new AlignmentPanel object.
125 public AlignmentPanel(AlignFrame af, final AlignViewport av)
127 // setBackground(Color.white); // BH 2019
130 setSeqPanel(new SeqPanel(av, this));
131 setIdPanel(new IdPanel(av, this));
133 setScalePanel(new ScalePanel(av, this));
135 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
136 idwidthAdjuster = new IdwidthAdjuster(this);
137 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
139 setAnnotationPanel(new AnnotationPanel(this));
140 setAlabels(new AnnotationLabels(this));
142 annotationScroller.setViewportView(getAnnotationPanel());
143 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
145 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
146 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
148 setScrollValues(0, 0);
150 hscroll.addAdjustmentListener(this);
151 vscroll.addAdjustmentListener(this);
153 addComponentListener(new ComponentAdapter()
156 public void componentResized(ComponentEvent evt)
158 // reset the viewport ranges when the alignment panel is resized
159 // in particular, this initialises the end residue value when Jalview
161 ViewportRanges ranges = av.getRanges();
162 if (av.getWrapAlignment())
164 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
165 getSeqPanel().seqCanvas.getWidth());
166 ranges.setViewportWidth(widthInRes);
170 int widthInRes = getSeqPanel().seqCanvas.getWidth()
172 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
173 / av.getCharHeight();
175 ranges.setViewportWidth(widthInRes);
176 ranges.setViewportHeight(heightInSeq);
182 final AlignmentPanel ap = this;
183 propertyChangeListener = new PropertyChangeListener()
186 public void propertyChange(PropertyChangeEvent evt)
188 if (evt.getPropertyName().equals("alignment"))
190 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
195 av.addPropertyChangeListener(propertyChangeListener);
197 av.getRanges().addPropertyChangeListener(this);
199 adjustAnnotationHeight();
204 public AlignViewportI getAlignViewport()
209 public void alignmentChanged()
211 av.alignmentChanged(this);
213 if (getCalculationDialog() != null)
215 getCalculationDialog().validateCalcTypes();
218 alignFrame.updateEditMenuBar();
220 // no idea if we need to update structure
221 paintAlignment(true, true);
228 public void fontChanged()
230 // set idCanvas bufferedImage to null
231 // to prevent drawing old image
232 FontMetrics fm = getFontMetrics(av.getFont());
234 // update the flag controlling whether the grid is too small to render the
236 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
238 scalePanelHolder.setPreferredSize(
239 new Dimension(10, av.getCharHeight() + fm.getDescent()));
240 idSpaceFillerPanel1.setPreferredSize(
241 new Dimension(10, av.getCharHeight() + fm.getDescent()));
242 idwidthAdjuster.invalidate();
243 scalePanelHolder.invalidate();
244 // BH 2018 getIdPanel().getIdCanvas().gg = null;
245 getSeqPanel().seqCanvas.img = null;
246 getAnnotationPanel().adjustPanelHeight();
248 Dimension d = calculateIdWidth();
249 getIdPanel().getIdCanvas().setPreferredSize(d);
250 hscrollFillerPanel.setPreferredSize(d);
256 * Calculates the width of the alignment labels based on the displayed names
257 * and any bounds on label width set in preferences. The calculated width is
258 * also set as a property of the viewport.
260 * @return Dimension giving the maximum width of the alignment label panel
261 * that should be used.
263 public Dimension calculateIdWidth()
265 int oldWidth = av.getIdWidth();
267 // calculate sensible default width when no preference is available
269 if (av.getIdWidth() < 0)
271 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
272 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
273 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
274 r = calculateIdWidth(maxwidth);
275 av.setIdWidth(r.width);
280 r.width = av.getIdWidth();
285 * fudge: if desired width has changed, update layout
286 * (see also paintComponent - updates layout on a repaint)
288 if (r.width != oldWidth)
290 idPanelHolder.setPreferredSize(r);
297 * Calculate the width of the alignment labels based on the displayed names
298 * and any bounds on label width set in preferences.
301 * -1 or maximum width allowed for IdWidth
302 * @return Dimension giving the maximum width of the alignment label panel
303 * that should be used.
305 protected Dimension calculateIdWidth(int maxwidth)
307 Container c = new Container();
309 FontMetrics fm = c.getFontMetrics(
310 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
312 AlignmentI al = av.getAlignment();
316 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
318 SequenceI s = al.getSequenceAt(i);
319 String id = s.getDisplayId(av.getShowJVSuffix());
320 int stringWidth = fm.stringWidth(id);
321 idWidth = Math.max(idWidth, stringWidth);
325 // Also check annotation label widths
328 if (al.getAlignmentAnnotation() != null)
330 fm = c.getFontMetrics(getAlabels().getFont());
332 while (i < al.getAlignmentAnnotation().length)
334 String label = al.getAlignmentAnnotation()[i].label;
335 int stringWidth = fm.stringWidth(label);
336 idWidth = Math.max(idWidth, stringWidth);
341 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
342 w += ID_WIDTH_PADDING;
344 return new Dimension(w, 12);
348 * Highlight the given results on the alignment
351 public void highlightSearchResults(SearchResultsI results)
353 boolean scrolled = scrollToPosition(results, 0, false);
355 boolean fastPaint = !(scrolled && av.getWrapAlignment());
357 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
361 * Scroll the view to show the position of the highlighted region in results
364 * @param searchResults
367 public boolean scrollToPosition(SearchResultsI searchResults)
369 return scrollToPosition(searchResults, 0, false);
373 * Scrolls the view (if necessary) to show the position of the first
374 * highlighted region in results (if any). Answers true if the view was
375 * scrolled, or false if no matched region was found, or it is already
379 * @param verticalOffset
380 * if greater than zero, allows scrolling to a position below the
381 * first displayed sequence
383 * if true, try to centre the search results horizontally in the view
386 protected boolean scrollToPosition(SearchResultsI results,
387 int verticalOffset, boolean centre)
389 int startv, endv, starts, ends;
390 ViewportRanges ranges = av.getRanges();
392 if (results == null || results.isEmpty() || av == null
393 || av.getAlignment() == null)
397 int seqIndex = av.getAlignment().findIndex(results);
402 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
404 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
413 * To centre results, scroll to positions half the visible width
414 * left/right of the start/end positions
418 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
419 start = Math.max(start - offset, 0);
420 end = end + offset - 1;
426 if (end == seq.getEnd())
431 if (av.hasHiddenColumns())
433 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
434 start = hidden.absoluteToVisibleColumn(start);
435 end = hidden.absoluteToVisibleColumn(end);
438 if (!hidden.isVisible(r[0]))
440 // don't scroll - position isn't visible
447 * allow for offset of target sequence (actually scroll to one above it)
449 seqIndex = Math.max(0, seqIndex - verticalOffset);
450 boolean scrollNeeded = true;
452 if (!av.getWrapAlignment())
454 if ((startv = ranges.getStartRes()) >= start)
457 * Scroll left to make start of search results visible
459 setScrollValues(start, seqIndex);
461 else if ((endv = ranges.getEndRes()) <= end)
464 * Scroll right to make end of search results visible
466 setScrollValues(startv + end - endv, seqIndex);
468 else if ((starts = ranges.getStartSeq()) > seqIndex)
471 * Scroll up to make start of search results visible
473 setScrollValues(ranges.getStartRes(), seqIndex);
475 else if ((ends = ranges.getEndSeq()) <= seqIndex)
478 * Scroll down to make end of search results visible
480 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
483 * Else results are already visible - no need to scroll
485 scrollNeeded = false;
489 scrollNeeded = ranges.scrollToWrappedVisible(start);
492 paintAlignment(false, false);
500 * @return DOCUMENT ME!
502 public OverviewPanel getOverviewPanel()
504 return overviewPanel;
513 public void setOverviewPanel(OverviewPanel op)
521 * Hide or show annotation panel
524 public void setAnnotationVisible(boolean b)
526 if (!av.getWrapAlignment())
528 annotationSpaceFillerHolder.setVisible(b);
529 annotationScroller.setVisible(b);
535 * automatically adjust annotation panel height for new annotation whilst
536 * ensuring the alignment is still visible.
539 public void adjustAnnotationHeight()
541 // TODO: display vertical annotation scrollbar if necessary
542 // this is called after loading new annotation onto alignment
543 if (alignFrame.getHeight() == 0)
545 System.out.println("NEEDS FIXING");
547 validateAnnotationDimensions(true);
549 // TODO: many places call this method and also paintAlignment with various
550 // different settings. this means multiple redraws are triggered...
551 paintAlignment(true, av.needToUpdateStructureViews());
555 * calculate the annotation dimensions and refresh slider values accordingly.
556 * need to do repaints/notifys afterwards.
558 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
560 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
561 // are not changing ancestors, and keyboard action listeners do
562 // not need to be reset. addNotify() is a very expensive operation,
563 // requiring a full re-layout of all parents and children.
564 // Note in JComponent:
565 // This method is called by the toolkit internally and should
566 // not be called directly by programs.
567 // I note that addNotify() is called in several areas of Jalview.
569 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
570 annotationHeight = getAnnotationPanel()
571 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
574 annotationScroller.setPreferredSize(
575 new Dimension(annotationScroller.getWidth(), annotationHeight));
577 Dimension e = idPanel.getSize();
578 alabels.setSize(new Dimension(e.width, annotationHeight));
580 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
581 annotationSpaceFillerHolder.getWidth(), annotationHeight));
582 annotationScroller.validate();
583 annotationScroller.addNotify();
587 * update alignment layout for viewport settings
592 public void updateLayout()
595 setAnnotationVisible(av.isShowAnnotation());
596 boolean wrap = av.getWrapAlignment();
597 ViewportRanges ranges = av.getRanges();
598 ranges.setStartSeq(0);
599 scalePanelHolder.setVisible(!wrap);
600 hscroll.setVisible(!wrap);
601 idwidthAdjuster.setVisible(!wrap);
605 annotationScroller.setVisible(false);
606 annotationSpaceFillerHolder.setVisible(false);
608 else if (av.isShowAnnotation())
610 annotationScroller.setVisible(true);
611 annotationSpaceFillerHolder.setVisible(true);
612 validateAnnotationDimensions(false);
615 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
617 { // may not yet be laid out
620 int widthInRes = getSeqPanel().seqCanvas
621 .getWrappedCanvasWidth(canvasWidth);
622 ranges.setViewportWidth(widthInRes);
626 int widthInRes = (canvasWidth / av.getCharWidth());
627 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
628 / av.getCharHeight());
630 ranges.setViewportWidth(widthInRes);
631 ranges.setViewportHeight(heightInSeq);
635 idSpaceFillerPanel1.setVisible(!wrap);
641 * Adjust row/column scrollers to show a visible position in the alignment.
644 * visible column to scroll to
646 * visible row to scroll to
649 public void setScrollValues(int xpos, int ypos)
654 if (av == null || av.getAlignment() == null)
659 if (av.getWrapAlignment())
661 setScrollingForWrappedPanel(x);
665 int width = av.getAlignment().getVisibleWidth();
666 int height = av.getAlignment().getHeight();
668 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
669 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
676 if (vextent > height)
681 if ((hextent + x) > width)
686 if ((vextent + y) > height)
688 y = height - vextent;
701 // update the scroll values
702 hscroll.setValues(x, hextent, 0, width);
703 vscroll.setValues(y, vextent, 0, height);
708 * Respond to adjustment event when horizontal or vertical scrollbar is
712 * adjustment event encoding whether hscroll or vscroll changed
715 public void adjustmentValueChanged(AdjustmentEvent evt)
717 if (av.getWrapAlignment())
719 adjustScrollingWrapped(evt);
723 ViewportRanges ranges = av.getRanges();
725 if (evt.getSource() == hscroll)
727 int oldX = ranges.getStartRes();
728 int oldwidth = ranges.getViewportWidth();
729 int x = hscroll.getValue();
730 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
732 // if we're scrolling to the position we're already at, stop
733 // this prevents infinite recursion of events when the scroll/viewport
734 // ranges values are the same
735 if ((x == oldX) && (width == oldwidth))
739 ranges.setViewportStartAndWidth(x, width);
741 else if (evt.getSource() == vscroll)
743 int oldY = ranges.getStartSeq();
744 int oldheight = ranges.getViewportHeight();
745 int y = vscroll.getValue();
746 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
748 // if we're scrolling to the position we're already at, stop
749 // this prevents infinite recursion of events when the scroll/viewport
750 // ranges values are the same
751 if ((y == oldY) && (height == oldheight))
755 ranges.setViewportStartAndHeight(y, height);
761 * Responds to a scroll change by setting the start position of the viewport.
766 protected void adjustScrollingWrapped(AdjustmentEvent evt)
768 if (evt.getSource() == hscroll)
770 return; // no horizontal scroll when wrapped
772 final ViewportRanges ranges = av.getRanges();
774 if (evt.getSource() == vscroll)
776 int newY = vscroll.getValue();
779 * if we're scrolling to the position we're already at, stop
780 * this prevents infinite recursion of events when the scroll/viewport
781 * ranges values are the same
783 int oldX = ranges.getStartRes();
784 int oldY = ranges.getWrappedScrollPosition(oldX);
792 * limit page up/down to one width's worth of positions
794 int rowSize = ranges.getViewportWidth();
795 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
796 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
801 // This is only called if file loaded is a jar file that
802 // was wrapped when saved and user has wrap alignment true
803 // as preference setting
804 SwingUtilities.invokeLater(new Runnable()
809 // When updating scrolling to use ViewportChange events, this code
810 // could not be validated and it is not clear if it is now being
811 // called. Log warning here in case it is called and unforeseen
814 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
816 // scroll to start of panel
817 ranges.setStartRes(0);
818 ranges.setStartSeq(0);
826 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
829 public void paintAlignment(boolean updateOverview,
830 boolean updateStructures)
832 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
833 av.isShowAutocalculatedAbove());
834 sorter.sort(getAlignment().getAlignmentAnnotation(),
835 av.getSortAnnotationsBy());
838 if (updateStructures)
840 av.getStructureSelectionManager().sequenceColoursChanged(this);
845 if (overviewPanel != null)
847 overviewPanel.updateOverviewImage();
853 public void paintComponent(Graphics g)
855 invalidate(); // needed so that the id width adjuster works correctly
857 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
858 idPanelHolder.setPreferredSize(d);
859 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
861 validate(); // needed so that the id width adjuster works correctly
864 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
865 * though I still think this call should be elsewhere.
867 ViewportRanges ranges = av.getRanges();
868 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
869 super.paintComponent(g);
873 * Set vertical scroll bar position, and number of increments, for wrapped
876 * @param topLeftColumn
877 * the column position at top left (0..)
879 private void setScrollingForWrappedPanel(int topLeftColumn)
881 ViewportRanges ranges = av.getRanges();
882 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
883 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
886 * a scrollbar's value can be set to at most (maximum-extent)
887 * so we add extent (1) to the maxScroll value
889 vscroll.setUnitIncrement(1);
890 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
903 * @return DOCUMENT ME!
905 * @throws PrinterException
909 public int print(Graphics pg, PageFormat pf, int pi)
910 throws PrinterException
912 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
914 int pwidth = (int) pf.getImageableWidth();
915 int pheight = (int) pf.getImageableHeight();
917 if (av.getWrapAlignment())
919 return printWrappedAlignment(pwidth, pheight, pi, pg);
923 return printUnwrapped(pwidth, pheight, pi, pg, pg);
928 * Draws the alignment image, including sequence ids, sequences, and
929 * annotation labels and annotations if shown, on either one or two Graphics
939 * the graphics context for sequence ids and annotation labels
940 * @param alignmentGraphics
941 * the graphics context for sequences and annotations (may or may not
942 * be the same context as idGraphics)
944 * @throws PrinterException
946 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
947 Graphics idGraphics, Graphics alignmentGraphics)
948 throws PrinterException
950 final int idWidth = getVisibleIdWidth(false);
953 * Get the horizontal offset to where we draw the sequences.
954 * This is idWidth if using a single Graphics context, else zero.
956 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
959 FontMetrics fm = getFontMetrics(av.getFont());
960 final int charHeight = av.getCharHeight();
961 final int scaleHeight = charHeight + fm.getDescent();
963 idGraphics.setColor(Color.white);
964 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
965 idGraphics.setFont(av.getFont());
968 * How many sequences and residues can we fit on a printable page?
970 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
972 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
974 final int alignmentWidth = av.getAlignment().getVisibleWidth();
975 int pagesWide = (alignmentWidth / totalRes) + 1;
977 final int startRes = (pageIndex % pagesWide) * totalRes;
978 final int endRes = Math.min(startRes + totalRes - 1,
981 final int startSeq = (pageIndex / pagesWide) * totalSeq;
982 final int alignmentHeight = av.getAlignment().getHeight();
983 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
985 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
987 if (av.isShowAnnotation())
989 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
992 pagesHigh /= pageHeight;
994 if (pageIndex >= (pagesWide * pagesHigh))
996 return Printable.NO_SUCH_PAGE;
998 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1001 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1003 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1004 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1005 pageWidth - idWidth, scaleHeight);
1006 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1009 * Draw the sequence ids, offset for scale height,
1010 * then reset to top left (0, 0)
1012 idGraphics.translate(0, scaleHeight);
1013 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1014 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1015 : av.getSelectionGroup().getSequences(null);
1016 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1019 idGraphics.setFont(av.getFont());
1020 idGraphics.translate(0, -scaleHeight);
1023 * draw the sequences, offset for scale height, and id width (if using a
1024 * single graphics context), then reset to (0, scale height)
1026 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1027 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1028 startRes, endRes, startSeq, endSeq - 1);
1029 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1031 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1034 * draw annotation labels; drawComponent() translates by
1035 * getScrollOffset(), so compensate for that first;
1036 * then reset to (0, scale height)
1038 int offset = getAlabels().getScrollOffset();
1039 idGraphics.translate(0, -offset);
1040 idGraphics.translate(0, alignmentDrawnHeight);
1041 getAlabels().drawComponent(idGraphics, idWidth);
1042 idGraphics.translate(0, -alignmentDrawnHeight);
1045 * draw the annotations starting at
1046 * (idOffset, alignmentHeight) from (0, scaleHeight)
1048 alignmentGraphics.translate(alignmentGraphicsOffset,
1049 alignmentDrawnHeight);
1051 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1052 alignmentGraphics, -1, startRes, endRes + 1);
1055 return Printable.PAGE_EXISTS;
1059 * Prints one page of an alignment in wrapped mode. Returns
1060 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1061 * no page could be drawn (page number out of range).
1071 * @throws PrinterException
1073 public int printWrappedAlignment(int pageWidth, int pageHeight,
1074 int pageNumber, Graphics g) throws PrinterException
1076 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1078 int annotationHeight = 0;
1079 if (av.isShowAnnotation())
1081 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1084 int hgap = av.getCharHeight();
1085 if (av.getScaleAboveWrapped())
1087 hgap += av.getCharHeight();
1090 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1093 int idWidth = getVisibleIdWidth(false);
1095 int maxwidth = av.getAlignment().getVisibleWidth();
1097 int resWidth = getSeqPanel().seqCanvas
1098 .getWrappedCanvasWidth(pageWidth - idWidth);
1099 av.getRanges().setViewportStartAndWidth(0, resWidth);
1101 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1103 g.setColor(Color.white);
1104 g.fillRect(0, 0, pageWidth, pageHeight);
1105 g.setFont(av.getFont());
1106 g.setColor(Color.black);
1109 * method: print the whole wrapped alignment, but with a clip region that
1110 * is restricted to the requested page; this supports selective print of
1111 * single pages or ranges, (at the cost of repeated processing in the
1112 * 'normal' case, when all pages are printed)
1114 g.translate(0, -pageNumber * pageHeight);
1116 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1119 * draw sequence ids and annotation labels (if shown)
1121 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1122 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1124 g.translate(idWidth, 0);
1126 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1127 pageWidth - idWidth, totalHeight, 0);
1129 if ((pageNumber * pageHeight) < totalHeight)
1131 return Printable.PAGE_EXISTS;
1135 return Printable.NO_SUCH_PAGE;
1140 * get current sequence ID panel width, or nominal value if panel were to be
1141 * displayed using default settings
1145 public int getVisibleIdWidth()
1147 return getVisibleIdWidth(true);
1151 * get current sequence ID panel width, or nominal value if panel were to be
1152 * displayed using default settings
1155 * indicate if the Id width for onscreen or offscreen display should
1159 protected int getVisibleIdWidth(boolean onscreen)
1161 // see if rendering offscreen - check preferences and calc width accordingly
1162 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1164 return calculateIdWidth(-1).width;
1166 Integer idwidth = onscreen ? null
1167 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1168 if (idwidth != null)
1170 return idwidth.intValue() + ID_WIDTH_PADDING;
1173 int w = getIdPanel().getWidth();
1174 return (w > 0 ? w : calculateIdWidth().width);
1177 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1179 makeAlignmentImage(type, file, renderer,
1180 BitmapImageSizing.nullBitmapImageSizing());
1184 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1185 * writes it to the specified file
1189 * @param textrenderer
1190 * @param bitmapscale
1192 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1193 BitmapImageSizing userBis)
1195 final int borderBottomOffset = 5;
1197 AlignmentDimension aDimension = getAlignmentDimension();
1198 // todo use a lambda function in place of callback here?
1199 ImageWriterI writer = new ImageWriterI()
1202 public void exportImage(Graphics graphics) throws Exception
1204 if (av.getWrapAlignment())
1206 printWrappedAlignment(aDimension.getWidth(),
1207 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1211 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1212 graphics, graphics);
1217 String fileTitle = alignFrame.getTitle();
1218 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1220 int imageWidth = aDimension.getWidth();
1221 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1222 String of = MessageManager.getString("label.alignment");
1223 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1228 * Calculates and returns a suitable width and height (in pixels) for an
1233 public AlignmentDimension getAlignmentDimension()
1235 int maxwidth = av.getAlignment().getVisibleWidth();
1237 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1238 + getScalePanel().getHeight();
1239 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1241 if (av.getWrapAlignment())
1243 height = getWrappedHeight();
1244 if (Jalview.isHeadlessMode())
1246 // need to obtain default alignment width and then add in any
1247 // additional allowance for id margin
1248 // this duplicates the calculation in getWrappedHeight but adjusts for
1250 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1251 - alignFrame.getInsets().left - alignFrame.getInsets().right
1252 - getVisibleIdWidth() + getVisibleIdWidth(false);
1256 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1260 else if (av.isShowAnnotation())
1262 height += getAnnotationPanel().adjustPanelHeight() + 3;
1264 return new AlignmentDimension(width, height);
1268 public void makePNGImageMap(File imgMapFile, String imageName)
1270 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1271 // ////////////////////////////////////////////
1272 int idWidth = getVisibleIdWidth(false);
1273 FontMetrics fm = getFontMetrics(av.getFont());
1274 int scaleHeight = av.getCharHeight() + fm.getDescent();
1277 // ////////////////////////////////
1278 if (imgMapFile != null)
1282 int sSize = av.getAlignment().getHeight();
1283 int alwidth = av.getAlignment().getWidth();
1284 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1285 out.println(HTMLOutput.getImageMapHTML());
1286 out.println("<img src=\"" + imageName
1287 + "\" border=\"0\" usemap=\"#Map\" >"
1288 + "<map name=\"Map\">");
1290 for (int s = 0; s < sSize; s++)
1292 int sy = s * av.getCharHeight() + scaleHeight;
1294 SequenceI seq = av.getAlignment().getSequenceAt(s);
1295 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1296 for (int column = 0; column < alwidth; column++)
1298 StringBuilder text = new StringBuilder(512);
1299 String triplet = null;
1300 if (av.getAlignment().isNucleotide())
1302 triplet = ResidueProperties.nucleotideName
1303 .get(seq.getCharAt(column) + "");
1307 triplet = ResidueProperties.aa2Triplet
1308 .get(seq.getCharAt(column) + "");
1311 if (triplet == null)
1316 int seqPos = seq.findPosition(column);
1317 int gSize = groups.length;
1318 for (int g = 0; g < gSize; g++)
1320 if (text.length() < 1)
1322 text.append("<area shape=\"rect\" coords=\"")
1323 .append((idWidth + column * av.getCharWidth()))
1324 .append(",").append(sy).append(",")
1326 + (column + 1) * av.getCharWidth()))
1327 .append(",").append((av.getCharHeight() + sy))
1328 .append("\"").append(" onMouseOver=\"toolTip('")
1329 .append(seqPos).append(" ").append(triplet);
1332 if (groups[g].getStartRes() < column
1333 && groups[g].getEndRes() > column)
1335 text.append("<br><em>").append(groups[g].getName())
1340 if (text.length() < 1)
1342 text.append("<area shape=\"rect\" coords=\"")
1343 .append((idWidth + column * av.getCharWidth()))
1344 .append(",").append(sy).append(",")
1345 .append((idWidth + (column + 1) * av.getCharWidth()))
1346 .append(",").append((av.getCharHeight() + sy))
1347 .append("\"").append(" onMouseOver=\"toolTip('")
1348 .append(seqPos).append(" ").append(triplet);
1350 if (!Comparison.isGap(seq.getCharAt(column)))
1352 List<SequenceFeature> features = seq.findFeatures(column,
1354 for (SequenceFeature sf : features)
1356 if (sf.isContactFeature())
1358 text.append("<br>").append(sf.getType()).append(" ")
1359 .append(sf.getBegin()).append(":")
1360 .append(sf.getEnd());
1364 text.append("<br>");
1365 text.append(sf.getType());
1366 String description = sf.getDescription();
1367 if (description != null
1368 && !sf.getType().equals(description))
1370 description = description.replace("\"", """);
1371 text.append(" ").append(description);
1374 String status = sf.getStatus();
1375 if (status != null && !"".equals(status))
1377 text.append(" (").append(status).append(")");
1380 if (text.length() > 1)
1382 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1383 out.println(text.toString());
1388 out.println("</map></body></html>");
1391 } catch (Exception ex)
1393 ex.printStackTrace();
1395 } // /////////END OF IMAGE MAP
1400 * Answers the height of the entire alignment in pixels, assuming it is in
1405 int getWrappedHeight()
1407 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1409 if (System.getProperty("java.awt.headless") != null
1410 && System.getProperty("java.awt.headless").equals("true"))
1412 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1413 - vscroll.getPreferredSize().width
1414 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1417 int chunkWidth = getSeqPanel().seqCanvas
1418 .getWrappedCanvasWidth(seqPanelWidth);
1420 int hgap = av.getCharHeight();
1421 if (av.getScaleAboveWrapped())
1423 hgap += av.getCharHeight();
1426 int annotationHeight = 0;
1427 if (av.isShowAnnotation())
1429 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1430 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1433 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1436 int maxwidth = av.getAlignment().getWidth();
1437 if (av.hasHiddenColumns())
1439 maxwidth = av.getAlignment().getHiddenColumns()
1440 .absoluteToVisibleColumn(maxwidth) - 1;
1443 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1449 * close the panel - deregisters all listeners and nulls any references to
1452 public void closePanel()
1454 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1455 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1456 PaintRefresher.RemoveComponent(this);
1461 * try to ensure references are nulled
1463 if (annotationPanel != null)
1465 annotationPanel.dispose();
1466 annotationPanel = null;
1471 av.removePropertyChangeListener(propertyChangeListener);
1472 propertyChangeListener = null;
1473 StructureSelectionManager ssm = av.getStructureSelectionManager();
1474 ssm.removeStructureViewerListener(getSeqPanel(), null);
1475 ssm.removeSelectionListener(getSeqPanel());
1476 ssm.removeCommandListener(av);
1477 ssm.removeStructureViewerListener(getSeqPanel(), null);
1478 ssm.removeSelectionListener(getSeqPanel());
1484 if (Console.isDebugEnabled())
1486 Console.warn("Closing alignment panel which is already closed.");
1492 * Close any open dialogs that would be orphaned when this one is closed
1494 protected void closeChildFrames()
1496 if (overviewPanel != null)
1498 overviewPanel.dispose();
1499 overviewPanel = null;
1501 if (calculationDialog != null)
1503 calculationDialog.closeFrame();
1504 calculationDialog = null;
1509 * hides or shows dynamic annotation rows based on groups and av state flags
1511 public void updateAnnotation()
1513 updateAnnotation(false, false);
1516 public void updateAnnotation(boolean applyGlobalSettings)
1518 updateAnnotation(applyGlobalSettings, false);
1521 public void updateAnnotation(boolean applyGlobalSettings,
1522 boolean preserveNewGroupSettings)
1524 av.updateGroupAnnotationSettings(applyGlobalSettings,
1525 preserveNewGroupSettings);
1526 adjustAnnotationHeight();
1530 public AlignmentI getAlignment()
1532 return av == null ? null : av.getAlignment();
1536 public String getViewName()
1538 return av.getViewName();
1542 * Make/Unmake this alignment panel the current input focus
1546 public void setSelected(boolean b)
1550 if (alignFrame.getSplitViewContainer() != null)
1553 * bring enclosing SplitFrame to front first if there is one
1555 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1557 alignFrame.setSelected(b);
1558 } catch (Exception ex)
1563 setAlignFrameView();
1567 public void setAlignFrameView()
1569 alignFrame.setDisplayedView(this);
1573 public StructureSelectionManager getStructureSelectionManager()
1575 return av.getStructureSelectionManager();
1579 public void raiseOOMWarning(String string, OutOfMemoryError error)
1581 new OOMWarning(string, error, this);
1585 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1588 return new FeatureRenderer(this);
1592 public jalview.api.FeatureRenderer getFeatureRenderer()
1594 return seqPanel.seqCanvas.getFeatureRenderer();
1597 public void updateFeatureRenderer(
1598 jalview.renderer.seqfeatures.FeatureRenderer fr)
1600 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1603 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1605 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1607 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1611 public ScalePanel getScalePanel()
1616 public void setScalePanel(ScalePanel scalePanel)
1618 this.scalePanel = scalePanel;
1621 public SeqPanel getSeqPanel()
1626 public void setSeqPanel(SeqPanel seqPanel)
1628 this.seqPanel = seqPanel;
1631 public AnnotationPanel getAnnotationPanel()
1633 return annotationPanel;
1636 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1638 this.annotationPanel = annotationPanel;
1641 public AnnotationLabels getAlabels()
1646 public void setAlabels(AnnotationLabels alabels)
1648 this.alabels = alabels;
1651 public IdPanel getIdPanel()
1656 public void setIdPanel(IdPanel idPanel)
1658 this.idPanel = idPanel;
1662 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1663 * The aim is to keep the two alignments 'lined up' on their centre columns.
1666 * holds mapped region(s) of this alignment that we are scrolling
1667 * 'to'; may be modified for sequence offset by this method
1668 * @param verticalOffset
1669 * the number of visible sequences to show above the mapped region
1671 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1673 scrollToPosition(sr, verticalOffset, true);
1677 * Set a flag to say do not scroll any (cDNA/protein) complement.
1681 protected void setToScrollComplementPanel(boolean b)
1683 this.scrollComplementaryPanel = b;
1687 * Get whether to scroll complement panel
1689 * @return true if cDNA/protein complement panels should be scrolled
1691 protected boolean isSetToScrollComplementPanel()
1693 return this.scrollComplementaryPanel;
1699 * @adjustHeight if true, try to recalculate panel height for visible
1702 protected void refresh(boolean adjustHeight)
1704 validateAnnotationDimensions(adjustHeight);
1708 // sort, repaint, update overview
1709 paintAlignment(true, false);
1713 // lightweight repaint
1720 * Property change event fired when a change is made to the viewport ranges
1721 * object associated with this alignment panel's viewport
1723 public void propertyChange(PropertyChangeEvent evt)
1725 // update this panel's scroll values based on the new viewport ranges values
1726 ViewportRanges ranges = av.getRanges();
1727 int x = ranges.getStartRes();
1728 int y = ranges.getStartSeq();
1729 setScrollValues(x, y);
1731 // now update any complementary alignment (its viewport ranges object
1732 // is different so does not get automatically updated)
1733 if (isSetToScrollComplementPanel())
1735 setToScrollComplementPanel(false);
1736 av.scrollComplementaryAlignment();
1737 setToScrollComplementPanel(true);
1742 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1743 * reference should be nulled when the dialog is closed.
1745 * @param calculationChooser
1747 public void setCalculationDialog(CalculationChooser calculationChooser)
1749 calculationDialog = calculationChooser;
1753 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1756 public CalculationChooser getCalculationDialog()
1758 return calculationDialog;
1762 * Constructs and sets the title for the Overview window (if there is one),
1763 * including the align frame's title, and view name (if applicable). Returns
1764 * the title, or null if this panel has no Overview window open.
1769 public String setOverviewTitle(AlignFrame alignFrame)
1771 if (this.overviewPanel == null)
1775 String overviewTitle = MessageManager
1776 .formatMessage("label.overview_params", new Object[]
1777 { alignFrame.getTitle() });
1778 String viewName = getViewName();
1779 if (viewName != null)
1781 overviewTitle += (" " + viewName);
1783 overviewPanel.setTitle(overviewTitle);
1784 return overviewTitle;
1788 * If this alignment panel has an Overview panel open, closes it
1790 public void closeOverviewPanel()
1792 if (overviewPanel != null)
1794 overviewPanel.close();
1795 overviewPanel = null;