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 jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.api.SequenceRenderer;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.ImageExporter.ImageWriterI;
36 import jalview.io.HTMLOutput;
37 import jalview.jbgui.GAlignmentPanel;
38 import jalview.math.AlignmentDimension;
39 import jalview.schemes.ResidueProperties;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.Comparison;
42 import jalview.util.ImageMaker;
43 import jalview.util.MessageManager;
44 import jalview.viewmodel.ViewportListenerI;
45 import jalview.viewmodel.ViewportRanges;
47 import java.awt.BorderLayout;
48 import java.awt.Color;
49 import java.awt.Container;
50 import java.awt.Dimension;
52 import java.awt.FontMetrics;
53 import java.awt.Graphics;
54 import java.awt.Graphics2D;
55 import java.awt.event.AdjustmentEvent;
56 import java.awt.event.AdjustmentListener;
57 import java.awt.event.ComponentAdapter;
58 import java.awt.event.ComponentEvent;
59 import java.awt.print.PageFormat;
60 import java.awt.print.Printable;
61 import java.awt.print.PrinterException;
62 import java.beans.PropertyChangeEvent;
63 import java.beans.PropertyChangeListener;
65 import java.io.FileWriter;
66 import java.io.PrintWriter;
67 import java.util.List;
69 import javax.swing.SwingUtilities;
75 * @version $Revision: 1.161 $
77 @SuppressWarnings("serial")
78 public class AlignmentPanel extends GAlignmentPanel implements
79 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
81 public AlignViewport av;
83 OverviewPanel overviewPanel;
85 private SeqPanel seqPanel;
87 private IdPanel idPanel;
89 IdwidthAdjuster idwidthAdjuster;
91 public AlignFrame alignFrame;
93 private ScalePanel scalePanel;
95 private AnnotationPanel annotationPanel;
97 private AnnotationLabels alabels;
99 private int hextent = 0;
101 private int vextent = 0;
104 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
105 * false, suppresses invoking the same method recursively.
107 private boolean scrollComplementaryPanel = true;
109 private PropertyChangeListener propertyChangeListener;
111 private CalculationChooser calculationDialog;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 setBackground(Color.white); // BH 2019
125 setSeqPanel(new SeqPanel(av, this));
126 setIdPanel(new IdPanel(av, this));
128 setScalePanel(new ScalePanel(av, this));
130 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
131 idwidthAdjuster = new IdwidthAdjuster(this);
132 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
134 setAnnotationPanel(new AnnotationPanel(this));
135 setAlabels(new AnnotationLabels(this));
137 annotationScroller.setViewportView(getAnnotationPanel());
138 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
140 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
141 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
143 setScrollValues(0, 0);
145 hscroll.addAdjustmentListener(this);
146 vscroll.addAdjustmentListener(this);
148 addComponentListener(new ComponentAdapter()
151 public void componentResized(ComponentEvent evt)
153 // reset the viewport ranges when the alignment panel is resized
154 // in particular, this initialises the end residue value when Jalview
156 ViewportRanges ranges = av.getRanges();
157 if (av.getWrapAlignment())
159 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
160 getSeqPanel().seqCanvas.getWidth());
161 ranges.setViewportWidth(widthInRes);
165 int widthInRes = getSeqPanel().seqCanvas.getWidth()
167 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
168 / av.getCharHeight();
170 ranges.setViewportWidth(widthInRes);
171 ranges.setViewportHeight(heightInSeq);
177 final AlignmentPanel ap = this;
178 propertyChangeListener = new PropertyChangeListener()
181 public void propertyChange(PropertyChangeEvent evt)
183 if (evt.getPropertyName().equals("alignment"))
185 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
190 av.addPropertyChangeListener(propertyChangeListener);
192 av.getRanges().addPropertyChangeListener(this);
194 adjustAnnotationHeight();
199 public AlignViewportI getAlignViewport()
204 public void alignmentChanged()
206 av.alignmentChanged(this);
208 if (getCalculationDialog() != null)
210 getCalculationDialog().validateCalcTypes();
213 alignFrame.updateEditMenuBar();
215 // no idea if we need to update structure
216 paintAlignment(true, true);
223 public void fontChanged()
225 // set idCanvas bufferedImage to null
226 // to prevent drawing old image
227 FontMetrics fm = getFontMetrics(av.getFont());
229 scalePanelHolder.setPreferredSize(
230 new Dimension(10, av.getCharHeight() + fm.getDescent()));
231 idSpaceFillerPanel1.setPreferredSize(
232 new Dimension(10, av.getCharHeight() + fm.getDescent()));
233 idwidthAdjuster.invalidate();
234 scalePanelHolder.invalidate();
235 // BH 2018 getIdPanel().getIdCanvas().gg = null;
236 getSeqPanel().seqCanvas.img = null;
237 getAnnotationPanel().adjustPanelHeight();
239 Dimension d = calculateIdWidth();
241 d.setSize(d.width + 4, d.height);
242 getIdPanel().getIdCanvas().setPreferredSize(d);
243 hscrollFillerPanel.setPreferredSize(d);
249 * Calculate the width of the alignment labels based on the displayed names
250 * and any bounds on label width set in preferences.
252 * @return Dimension giving the maximum width of the alignment label panel
253 * that should be used.
255 public Dimension calculateIdWidth()
257 // calculate sensible default width when no preference is available
259 if (av.getIdWidth() < 0)
261 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
262 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
263 r = calculateIdWidth(maxwidth);
264 av.setIdWidth(r.width);
269 r.width = av.getIdWidth();
276 * Calculate the width of the alignment labels based on the displayed names
277 * and any bounds on label width set in preferences.
280 * -1 or maximum width allowed for IdWidth
281 * @return Dimension giving the maximum width of the alignment label panel
282 * that should be used.
284 public Dimension calculateIdWidth(int maxwidth)
286 Container c = new Container();
288 FontMetrics fm = c.getFontMetrics(
289 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
291 AlignmentI al = av.getAlignment();
296 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
298 SequenceI s = al.getSequenceAt(i);
300 id = s.getDisplayId(av.getShowJVSuffix());
302 if (fm.stringWidth(id) > idWidth)
304 idWidth = fm.stringWidth(id);
310 // Also check annotation label widths
313 if (al.getAlignmentAnnotation() != null)
315 fm = c.getFontMetrics(getAlabels().getFont());
317 while (i < al.getAlignmentAnnotation().length)
319 String label = al.getAlignmentAnnotation()[i].label;
321 if (fm.stringWidth(label) > idWidth)
323 idWidth = fm.stringWidth(label);
330 return new Dimension(
331 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
335 * Highlight the given results on the alignment
338 public void highlightSearchResults(SearchResultsI results)
340 boolean scrolled = scrollToPosition(results, 0, false);
342 boolean fastPaint = !(scrolled && av.getWrapAlignment());
344 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
348 * Scroll the view to show the position of the highlighted region in results
351 * @param searchResults
354 public boolean scrollToPosition(SearchResultsI searchResults)
356 return scrollToPosition(searchResults, 0, false);
360 * Scrolls the view (if necessary) to show the position of the first
361 * highlighted region in results (if any). Answers true if the view was
362 * scrolled, or false if no matched region was found, or it is already
366 * @param verticalOffset
367 * if greater than zero, allows scrolling to a position below the
368 * first displayed sequence
370 * if true, try to centre the search results horizontally in the view
373 protected boolean scrollToPosition(SearchResultsI results,
374 int verticalOffset, boolean centre)
376 int startv, endv, starts, ends;
377 ViewportRanges ranges = av.getRanges();
379 if (results == null || results.isEmpty() || av == null
380 || av.getAlignment() == null)
384 int seqIndex = av.getAlignment().findIndex(results);
389 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
391 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
400 * To centre results, scroll to positions half the visible width
401 * left/right of the start/end positions
405 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
406 start = Math.max(start - offset, 0);
407 end = end + offset - 1;
413 if (end == seq.getEnd())
418 if (av.hasHiddenColumns())
420 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
421 start = hidden.absoluteToVisibleColumn(start);
422 end = hidden.absoluteToVisibleColumn(end);
425 if (!hidden.isVisible(r[0]))
427 // don't scroll - position isn't visible
434 * allow for offset of target sequence (actually scroll to one above it)
436 seqIndex = Math.max(0, seqIndex - verticalOffset);
437 boolean scrollNeeded = true;
439 if (!av.getWrapAlignment())
441 if ((startv = ranges.getStartRes()) >= start)
444 * Scroll left to make start of search results visible
446 setScrollValues(start, seqIndex);
448 else if ((endv = ranges.getEndRes()) <= end)
451 * Scroll right to make end of search results visible
453 setScrollValues(startv + end - endv, seqIndex);
455 else if ((starts = ranges.getStartSeq()) > seqIndex)
458 * Scroll up to make start of search results visible
460 setScrollValues(ranges.getStartRes(), seqIndex);
462 else if ((ends = ranges.getEndSeq()) <= seqIndex)
465 * Scroll down to make end of search results visible
467 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
471 * Else results are already visible - no need to scroll
473 scrollNeeded = false;
477 scrollNeeded = ranges.scrollToWrappedVisible(start);
480 paintAlignment(false, false);
488 * @return DOCUMENT ME!
490 public OverviewPanel getOverviewPanel()
492 return overviewPanel;
501 public void setOverviewPanel(OverviewPanel op)
509 * Hide or show annotation panel
512 public void setAnnotationVisible(boolean b)
514 if (!av.getWrapAlignment())
516 annotationSpaceFillerHolder.setVisible(b);
517 annotationScroller.setVisible(b);
523 * automatically adjust annotation panel height for new annotation whilst
524 * ensuring the alignment is still visible.
527 public void adjustAnnotationHeight()
529 // TODO: display vertical annotation scrollbar if necessary
530 // this is called after loading new annotation onto alignment
531 if (alignFrame.getHeight() == 0)
533 System.out.println("NEEDS FIXING");
535 validateAnnotationDimensions(true);
537 // TODO: many places call this method and also paintAlignment with various
538 // different settings. this means multiple redraws are triggered...
539 paintAlignment(true, av.needToUpdateStructureViews());
543 * calculate the annotation dimensions and refresh slider values accordingly.
544 * need to do repaints/notifys afterwards.
546 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
548 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
549 // are not changing ancestors, and keyboard action listeners do
550 // not need to be reset. addNotify() is a very expensive operation,
551 // requiring a full re-layout of all parents and children.
552 // Note in JComponent:
553 // This method is called by the toolkit internally and should
554 // not be called directly by programs.
555 // I note that addNotify() is called in several areas of Jalview.
557 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
558 annotationHeight = getAnnotationPanel()
559 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
562 annotationScroller.setPreferredSize(
563 new Dimension(annotationScroller.getWidth(), annotationHeight));
565 Dimension e = idPanel.getSize();
566 alabels.setSize(new Dimension(e.width, annotationHeight));
569 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
570 annotationSpaceFillerHolder.getWidth(), annotationHeight));
571 annotationScroller.validate();
572 annotationScroller.addNotify();
576 * update alignment layout for viewport settings
581 public void updateLayout()
584 setAnnotationVisible(av.isShowAnnotation());
585 boolean wrap = av.getWrapAlignment();
586 ViewportRanges ranges = av.getRanges();
587 ranges.setStartSeq(0);
588 scalePanelHolder.setVisible(!wrap);
589 hscroll.setVisible(!wrap);
590 idwidthAdjuster.setVisible(!wrap);
594 annotationScroller.setVisible(false);
595 annotationSpaceFillerHolder.setVisible(false);
597 else if (av.isShowAnnotation())
599 annotationScroller.setVisible(true);
600 annotationSpaceFillerHolder.setVisible(true);
601 validateAnnotationDimensions(false);
604 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
606 { // may not yet be laid out
609 int widthInRes = getSeqPanel().seqCanvas
610 .getWrappedCanvasWidth(canvasWidth);
611 ranges.setViewportWidth(widthInRes);
615 int widthInRes = (canvasWidth / av.getCharWidth());
616 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
617 / av.getCharHeight());
619 ranges.setViewportWidth(widthInRes);
620 ranges.setViewportHeight(heightInSeq);
624 idSpaceFillerPanel1.setVisible(!wrap);
630 * Adjust row/column scrollers to show a visible position in the alignment.
633 * visible column to scroll to
635 * visible row to scroll to
638 public void setScrollValues(int xpos, int ypos)
643 if (av == null || av.getAlignment() == null)
648 if (av.getWrapAlignment())
650 setScrollingForWrappedPanel(x);
654 int width = av.getAlignment().getVisibleWidth();
655 int height = av.getAlignment().getHeight();
657 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
658 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
665 if (vextent > height)
670 if ((hextent + x) > width)
675 if ((vextent + y) > height)
677 y = height - vextent;
690 // update the scroll values
691 hscroll.setValues(x, hextent, 0, width);
692 vscroll.setValues(y, vextent, 0, height);
697 * Respond to adjustment event when horizontal or vertical scrollbar is
701 * adjustment event encoding whether hscroll or vscroll changed
704 public void adjustmentValueChanged(AdjustmentEvent evt)
706 if (av.getWrapAlignment())
708 adjustScrollingWrapped(evt);
712 ViewportRanges ranges = av.getRanges();
714 if (evt.getSource() == hscroll)
716 int oldX = ranges.getStartRes();
717 int oldwidth = ranges.getViewportWidth();
718 int x = hscroll.getValue();
719 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
721 // if we're scrolling to the position we're already at, stop
722 // this prevents infinite recursion of events when the scroll/viewport
723 // ranges values are the same
724 if ((x == oldX) && (width == oldwidth))
728 ranges.setViewportStartAndWidth(x, width);
730 else if (evt.getSource() == vscroll)
732 int oldY = ranges.getStartSeq();
733 int oldheight = ranges.getViewportHeight();
734 int y = vscroll.getValue();
735 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
737 // if we're scrolling to the position we're already at, stop
738 // this prevents infinite recursion of events when the scroll/viewport
739 // ranges values are the same
740 if ((y == oldY) && (height == oldheight))
744 ranges.setViewportStartAndHeight(y, height);
750 * Responds to a scroll change by setting the start position of the viewport.
755 protected void adjustScrollingWrapped(AdjustmentEvent evt)
757 if (evt.getSource() == hscroll)
759 return; // no horizontal scroll when wrapped
761 final ViewportRanges ranges = av.getRanges();
763 if (evt.getSource() == vscroll)
765 int newY = vscroll.getValue();
768 * if we're scrolling to the position we're already at, stop
769 * this prevents infinite recursion of events when the scroll/viewport
770 * ranges values are the same
772 int oldX = ranges.getStartRes();
773 int oldY = ranges.getWrappedScrollPosition(oldX);
781 * limit page up/down to one width's worth of positions
783 int rowSize = ranges.getViewportWidth();
784 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
785 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
790 // This is only called if file loaded is a jar file that
791 // was wrapped when saved and user has wrap alignment true
792 // as preference setting
793 SwingUtilities.invokeLater(new Runnable()
798 // When updating scrolling to use ViewportChange events, this code
799 // could not be validated and it is not clear if it is now being
800 // called. Log warning here in case it is called and unforeseen
803 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
805 // scroll to start of panel
806 ranges.setStartRes(0);
807 ranges.setStartSeq(0);
815 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
818 public void paintAlignment(boolean updateOverview,
819 boolean updateStructures)
821 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
822 av.isShowAutocalculatedAbove());
823 sorter.sort(getAlignment().getAlignmentAnnotation(),
824 av.getSortAnnotationsBy());
827 if (updateStructures)
829 av.getStructureSelectionManager().sequenceColoursChanged(this);
834 if (overviewPanel != null)
836 overviewPanel.updateOverviewImage();
848 public void paintComponent(Graphics g)
850 invalidate(); // needed so that the id width adjuster works correctly
852 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
853 idPanelHolder.setPreferredSize(d);
854 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
856 validate(); // needed so that the id width adjuster works correctly
859 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
860 * though I still think this call should be elsewhere.
862 ViewportRanges ranges = av.getRanges();
863 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
864 super.paintComponent(g);
868 * Set vertical scroll bar position, and number of increments, for wrapped
871 * @param topLeftColumn
872 * the column position at top left (0..)
874 private void setScrollingForWrappedPanel(int topLeftColumn)
876 ViewportRanges ranges = av.getRanges();
877 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
878 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
881 * a scrollbar's value can be set to at most (maximum-extent)
882 * so we add extent (1) to the maxScroll value
884 vscroll.setUnitIncrement(1);
885 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
898 * @return DOCUMENT ME!
900 * @throws PrinterException
904 public int print(Graphics pg, PageFormat pf, int pi)
905 throws PrinterException
907 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
909 int pwidth = (int) pf.getImageableWidth();
910 int pheight = (int) pf.getImageableHeight();
912 if (av.getWrapAlignment())
914 return printWrappedAlignment(pwidth, pheight, pi, pg);
918 return printUnwrapped(pwidth, pheight, pi, pg, pg);
923 * Draws the alignment image, including sequence ids, sequences, and
924 * annotation labels and annotations if shown, on either one or two Graphics
934 * the graphics context for sequence ids and annotation labels
935 * @param alignmentGraphics
936 * the graphics context for sequences and annotations (may or may not
937 * be the same context as idGraphics)
939 * @throws PrinterException
941 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
942 Graphics idGraphics, Graphics alignmentGraphics)
943 throws PrinterException
945 final int idWidth = getVisibleIdWidth(false);
948 * Get the horizontal offset to where we draw the sequences.
949 * This is idWidth if using a single Graphics context, else zero.
951 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
954 FontMetrics fm = getFontMetrics(av.getFont());
955 final int charHeight = av.getCharHeight();
956 final int scaleHeight = charHeight + fm.getDescent();
958 idGraphics.setColor(Color.white);
959 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
960 idGraphics.setFont(av.getFont());
963 * How many sequences and residues can we fit on a printable page?
965 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
967 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
969 final int alignmentWidth = av.getAlignment().getVisibleWidth();
970 int pagesWide = (alignmentWidth / totalRes) + 1;
972 final int startRes = (pageIndex % pagesWide) * totalRes;
973 final int endRes = Math.min(startRes + totalRes - 1,
976 final int startSeq = (pageIndex / pagesWide) * totalSeq;
977 final int alignmentHeight = av.getAlignment().getHeight();
978 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
980 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
982 if (av.isShowAnnotation())
984 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
987 pagesHigh /= pageHeight;
989 if (pageIndex >= (pagesWide * pagesHigh))
991 return Printable.NO_SUCH_PAGE;
993 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
996 * draw the Scale at horizontal offset, then reset to top left (0, 0)
998 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
999 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1000 pageWidth - idWidth, scaleHeight);
1001 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1004 * Draw the sequence ids, offset for scale height,
1005 * then reset to top left (0, 0)
1007 idGraphics.translate(0, scaleHeight);
1008 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1009 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1010 : av.getSelectionGroup().getSequences(null);
1011 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1014 idGraphics.setFont(av.getFont());
1015 idGraphics.translate(0, -scaleHeight);
1018 * draw the sequences, offset for scale height, and id width (if using a
1019 * single graphics context), then reset to (0, scale height)
1021 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1022 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1023 endRes, startSeq, endSeq - 1);
1024 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1026 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1029 * draw annotation labels; drawComponent() translates by
1030 * getScrollOffset(), so compensate for that first;
1031 * then reset to (0, scale height)
1033 int offset = getAlabels().getScrollOffset();
1034 idGraphics.translate(0, -offset);
1035 idGraphics.translate(0, alignmentDrawnHeight);
1036 getAlabels().drawComponent(idGraphics, idWidth);
1037 idGraphics.translate(0, -alignmentDrawnHeight);
1040 * draw the annotations starting at
1041 * (idOffset, alignmentHeight) from (0, scaleHeight)
1043 alignmentGraphics.translate(alignmentGraphicsOffset,
1044 alignmentDrawnHeight);
1045 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1046 alignmentGraphics, -1, startRes, endRes + 1);
1049 return Printable.PAGE_EXISTS;
1053 * Prints one page of an alignment in wrapped mode. Returns
1054 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1055 * no page could be drawn (page number out of range).
1065 * @throws PrinterException
1067 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1068 Graphics g) throws PrinterException
1070 int annotationHeight = 0;
1071 if (av.isShowAnnotation())
1073 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1076 int hgap = av.getCharHeight();
1077 if (av.getScaleAboveWrapped())
1079 hgap += av.getCharHeight();
1082 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1085 int idWidth = getVisibleIdWidth(false);
1087 int maxwidth = av.getAlignment().getVisibleWidth();
1089 int resWidth = getSeqPanel().seqCanvas
1090 .getWrappedCanvasWidth(pageWidth - idWidth);
1092 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1094 g.setColor(Color.white);
1095 g.fillRect(0, 0, pageWidth, pageHeight);
1096 g.setFont(av.getFont());
1097 g.setColor(Color.black);
1100 * method: print the whole wrapped alignment, but with a clip region that
1101 * is restricted to the requested page; this supports selective print of
1102 * single pages or ranges, (at the cost of some repeated processing in
1103 * the 'normal' case, when all pages are printed)
1105 g.translate(0, -pageNumber * pageHeight);
1107 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1110 * draw sequence ids and annotation labels (if shown)
1112 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1113 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1115 g.translate(idWidth, 0);
1117 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1120 if ((pageNumber * pageHeight) < totalHeight)
1122 return Printable.PAGE_EXISTS;
1126 return Printable.NO_SUCH_PAGE;
1131 * get current sequence ID panel width, or nominal value if panel were to be
1132 * displayed using default settings
1136 public int getVisibleIdWidth()
1138 return getVisibleIdWidth(true);
1142 * get current sequence ID panel width, or nominal value if panel were to be
1143 * displayed using default settings
1146 * indicate if the Id width for onscreen or offscreen display should
1150 public int getVisibleIdWidth(boolean onscreen)
1152 // see if rendering offscreen - check preferences and calc width accordingly
1153 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1155 return calculateIdWidth(-1).width + 4;
1157 Integer idwidth = null;
1158 if (onscreen || (idwidth = Cache
1159 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1161 int w = getIdPanel().getWidth();
1162 return (w > 0 ? w : calculateIdWidth().width + 4);
1164 return idwidth.intValue() + 4;
1168 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1169 * writes it to the specified file
1174 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1176 final int borderBottomOffset = 5;
1178 AlignmentDimension aDimension = getAlignmentDimension();
1179 // todo use a lambda function in place of callback here?
1180 ImageWriterI writer = new ImageWriterI()
1183 public void exportImage(Graphics graphics) throws Exception
1185 if (av.getWrapAlignment())
1187 printWrappedAlignment(aDimension.getWidth(),
1188 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1192 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1193 graphics, graphics);
1198 String fileTitle = alignFrame.getTitle();
1199 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1201 int imageWidth = aDimension.getWidth();
1202 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1203 String of = MessageManager.getString("label.alignment");
1204 exporter.doExport(file, this, imageWidth, imageHeight, of);
1208 * Calculates and returns a suitable width and height (in pixels) for an
1213 public AlignmentDimension getAlignmentDimension()
1215 int maxwidth = av.getAlignment().getVisibleWidth();
1217 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1218 + getScalePanel().getHeight();
1219 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1221 if (av.getWrapAlignment())
1223 height = getWrappedHeight();
1224 if (Jalview.isHeadlessMode())
1226 // need to obtain default alignment width and then add in any
1227 // additional allowance for id margin
1228 // this duplicates the calculation in getWrappedHeight but adjusts for
1230 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1231 - alignFrame.getInsets().left - alignFrame.getInsets().right
1232 - getVisibleIdWidth() + getVisibleIdWidth(false);
1236 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1240 else if (av.isShowAnnotation())
1242 height += getAnnotationPanel().adjustPanelHeight() + 3;
1244 return new AlignmentDimension(width, height);
1248 public void makePNGImageMap(File imgMapFile, String imageName)
1250 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1251 // ////////////////////////////////////////////
1252 int idWidth = getVisibleIdWidth(false);
1253 FontMetrics fm = getFontMetrics(av.getFont());
1254 int scaleHeight = av.getCharHeight() + fm.getDescent();
1257 // ////////////////////////////////
1258 if (imgMapFile != null)
1262 int sSize = av.getAlignment().getHeight();
1263 int alwidth = av.getAlignment().getWidth();
1264 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1265 out.println(HTMLOutput.getImageMapHTML());
1266 out.println("<img src=\"" + imageName
1267 + "\" border=\"0\" usemap=\"#Map\" >"
1268 + "<map name=\"Map\">");
1270 for (int s = 0; s < sSize; s++)
1272 int sy = s * av.getCharHeight() + scaleHeight;
1274 SequenceI seq = av.getAlignment().getSequenceAt(s);
1275 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1276 for (int column = 0; column < alwidth; column++)
1278 StringBuilder text = new StringBuilder(512);
1279 String triplet = null;
1280 if (av.getAlignment().isNucleotide())
1282 triplet = ResidueProperties.nucleotideName.get(seq
1283 .getCharAt(column) + "");
1287 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1291 if (triplet == null)
1296 int seqPos = seq.findPosition(column);
1297 int gSize = groups.length;
1298 for (int g = 0; g < gSize; g++)
1300 if (text.length() < 1)
1302 text.append("<area shape=\"rect\" coords=\"")
1303 .append((idWidth + column * av.getCharWidth()))
1304 .append(",").append(sy).append(",")
1305 .append((idWidth + (column + 1) * av.getCharWidth()))
1306 .append(",").append((av.getCharHeight() + sy))
1307 .append("\"").append(" onMouseOver=\"toolTip('")
1308 .append(seqPos).append(" ").append(triplet);
1311 if (groups[g].getStartRes() < column
1312 && groups[g].getEndRes() > column)
1314 text.append("<br><em>").append(groups[g].getName())
1319 if (text.length() < 1)
1321 text.append("<area shape=\"rect\" coords=\"")
1322 .append((idWidth + column * av.getCharWidth()))
1323 .append(",").append(sy).append(",")
1324 .append((idWidth + (column + 1) * av.getCharWidth()))
1325 .append(",").append((av.getCharHeight() + sy))
1326 .append("\"").append(" onMouseOver=\"toolTip('")
1327 .append(seqPos).append(" ").append(triplet);
1329 if (!Comparison.isGap(seq.getCharAt(column)))
1331 List<SequenceFeature> features = seq.findFeatures(column, column);
1332 for (SequenceFeature sf : features)
1334 if (sf.isContactFeature())
1336 text.append("<br>").append(sf.getType()).append(" ")
1337 .append(sf.getBegin()).append(":")
1338 .append(sf.getEnd());
1342 text.append("<br>");
1343 text.append(sf.getType());
1344 String description = sf.getDescription();
1345 if (description != null
1346 && !sf.getType().equals(description))
1348 description = description.replace("\"", """);
1349 text.append(" ").append(description);
1352 String status = sf.getStatus();
1353 if (status != null && !"".equals(status))
1355 text.append(" (").append(status).append(")");
1358 if (text.length() > 1)
1360 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1361 out.println(text.toString());
1366 out.println("</map></body></html>");
1369 } catch (Exception ex)
1371 ex.printStackTrace();
1373 } // /////////END OF IMAGE MAP
1377 int getWrappedHeight()
1379 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1381 if (Jalview.isHeadlessMode())
1383 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1384 - vscroll.getPreferredSize().width
1385 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1388 int chunkWidth = getSeqPanel().seqCanvas
1389 .getWrappedCanvasWidth(seqPanelWidth);
1391 int hgap = av.getCharHeight();
1392 if (av.getScaleAboveWrapped())
1394 hgap += av.getCharHeight();
1397 int annotationHeight = 0;
1398 if (av.isShowAnnotation())
1400 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1403 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1406 int maxwidth = av.getAlignment().getWidth();
1407 if (av.hasHiddenColumns())
1409 maxwidth = av.getAlignment().getHiddenColumns()
1410 .absoluteToVisibleColumn(maxwidth) - 1;
1413 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1419 * close the panel - deregisters all listeners and nulls any references to
1422 public void closePanel()
1424 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1425 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1426 PaintRefresher.RemoveComponent(this);
1431 * try to ensure references are nulled
1433 if (annotationPanel != null)
1435 annotationPanel.dispose();
1436 annotationPanel = null;
1441 av.removePropertyChangeListener(propertyChangeListener);
1442 propertyChangeListener = null;
1443 StructureSelectionManager ssm = av.getStructureSelectionManager();
1444 ssm.removeStructureViewerListener(getSeqPanel(), null);
1445 ssm.removeSelectionListener(getSeqPanel());
1446 ssm.removeCommandListener(av);
1447 ssm.removeStructureViewerListener(getSeqPanel(), null);
1448 ssm.removeSelectionListener(getSeqPanel());
1454 if (Cache.log.isDebugEnabled())
1456 Cache.log.warn("Closing alignment panel which is already closed.");
1462 * Close any open dialogs that would be orphaned when this one is closed
1464 protected void closeChildFrames()
1466 if (overviewPanel != null)
1468 overviewPanel.dispose();
1469 overviewPanel = null;
1471 if (calculationDialog != null)
1473 calculationDialog.closeFrame();
1474 calculationDialog = null;
1479 * hides or shows dynamic annotation rows based on groups and av state flags
1481 public void updateAnnotation()
1483 updateAnnotation(false, false);
1486 public void updateAnnotation(boolean applyGlobalSettings)
1488 updateAnnotation(applyGlobalSettings, false);
1491 public void updateAnnotation(boolean applyGlobalSettings,
1492 boolean preserveNewGroupSettings)
1494 av.updateGroupAnnotationSettings(applyGlobalSettings,
1495 preserveNewGroupSettings);
1496 adjustAnnotationHeight();
1500 public AlignmentI getAlignment()
1502 return av == null ? null : av.getAlignment();
1506 public String getViewName()
1508 return av.getViewName();
1512 * Make/Unmake this alignment panel the current input focus
1516 public void setSelected(boolean b)
1520 if (alignFrame.getSplitViewContainer() != null)
1523 * bring enclosing SplitFrame to front first if there is one
1525 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1527 alignFrame.setSelected(b);
1528 } catch (Exception ex)
1534 alignFrame.setDisplayedView(this);
1539 public StructureSelectionManager getStructureSelectionManager()
1541 return av.getStructureSelectionManager();
1545 public void raiseOOMWarning(String string, OutOfMemoryError error)
1547 new OOMWarning(string, error, this);
1551 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1554 return new FeatureRenderer(this);
1558 public jalview.api.FeatureRenderer getFeatureRenderer()
1560 return seqPanel.seqCanvas.getFeatureRenderer();
1563 public void updateFeatureRenderer(
1564 jalview.renderer.seqfeatures.FeatureRenderer fr)
1566 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1569 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1571 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1573 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1577 public ScalePanel getScalePanel()
1582 public void setScalePanel(ScalePanel scalePanel)
1584 this.scalePanel = scalePanel;
1587 public SeqPanel getSeqPanel()
1592 public void setSeqPanel(SeqPanel seqPanel)
1594 this.seqPanel = seqPanel;
1597 public AnnotationPanel getAnnotationPanel()
1599 return annotationPanel;
1602 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1604 this.annotationPanel = annotationPanel;
1607 public AnnotationLabels getAlabels()
1612 public void setAlabels(AnnotationLabels alabels)
1614 this.alabels = alabels;
1617 public IdPanel getIdPanel()
1622 public void setIdPanel(IdPanel idPanel)
1624 this.idPanel = idPanel;
1628 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1629 * The aim is to keep the two alignments 'lined up' on their centre columns.
1632 * holds mapped region(s) of this alignment that we are scrolling
1633 * 'to'; may be modified for sequence offset by this method
1634 * @param verticalOffset
1635 * the number of visible sequences to show above the mapped region
1637 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1639 scrollToPosition(sr, verticalOffset, true);
1643 * Set a flag to say do not scroll any (cDNA/protein) complement.
1647 protected void setToScrollComplementPanel(boolean b)
1649 this.scrollComplementaryPanel = b;
1653 * Get whether to scroll complement panel
1655 * @return true if cDNA/protein complement panels should be scrolled
1657 protected boolean isSetToScrollComplementPanel()
1659 return this.scrollComplementaryPanel;
1665 * @adjustHeight if true, try to recalculate panel height for visible
1668 protected void refresh(boolean adjustHeight)
1670 validateAnnotationDimensions(adjustHeight);
1674 // sort, repaint, update overview
1675 paintAlignment(true, false);
1679 // lightweight repaint
1686 * Property change event fired when a change is made to the viewport ranges
1687 * object associated with this alignment panel's viewport
1689 public void propertyChange(PropertyChangeEvent evt)
1691 // update this panel's scroll values based on the new viewport ranges values
1692 ViewportRanges ranges = av.getRanges();
1693 int x = ranges.getStartRes();
1694 int y = ranges.getStartSeq();
1695 setScrollValues(x, y);
1697 // now update any complementary alignment (its viewport ranges object
1698 // is different so does not get automatically updated)
1699 if (isSetToScrollComplementPanel())
1701 setToScrollComplementPanel(false);
1702 av.scrollComplementaryAlignment();
1703 setToScrollComplementPanel(true);
1708 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1709 * reference should be nulled when the dialog is closed.
1711 * @param calculationChooser
1713 public void setCalculationDialog(CalculationChooser calculationChooser)
1715 calculationDialog = calculationChooser;
1719 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1722 public CalculationChooser getCalculationDialog()
1724 return calculationDialog;
1728 public SequenceRenderer getSequenceRenderer()
1730 return seqPanel.seqCanvas.getSequenceRenderer();
1733 public boolean scrollTo(int ostart, int end, int seqIndex,
1734 boolean scrollToNearest, boolean redrawOverview)
1736 int startv, endv, starts, ends;// , width;
1739 if (av.hasHiddenColumns())
1741 AlignmentI al = av.getAlignment();
1742 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1743 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1746 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1748 // don't scroll - position isn't visible
1758 ViewportRanges ranges = av.getRanges();
1759 if (!av.getWrapAlignment())
1762 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1763 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1764 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1765 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1766 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1767 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1768 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1769 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1772 // below is scrolling logic up to Jalview 2.8.2
1773 // if ((av.getStartRes() > end)
1774 // || (av.getEndRes() < start)
1775 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1777 // if (start > av.getAlignment().getWidth() - hextent)
1779 // start = av.getAlignment().getWidth() - hextent;
1786 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1788 // seqIndex = av.getAlignment().getHeight() - vextent;
1789 // if (seqIndex < 0)
1794 // setScrollValues(start, seqIndex);
1796 // logic copied from jalview.gui.AlignmentPanel:
1797 if ((startv = ranges.getStartRes()) >= start)
1800 * Scroll left to make start of search results visible
1802 setScrollValues(start - 1, seqIndex);
1804 else if ((endv = ranges.getEndRes()) <= end)
1807 * Scroll right to make end of search results visible
1809 setScrollValues(startv + 1 + end - endv, seqIndex);
1811 else if ((starts = ranges.getStartSeq()) > seqIndex)
1814 * Scroll up to make start of search results visible
1816 setScrollValues(ranges.getStartRes(), seqIndex);
1818 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1821 * Scroll down to make end of search results visible
1823 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1826 * Else results are already visible - no need to scroll
1831 ranges.scrollToWrappedVisible(start);
1834 paintAlignment(redrawOverview, false);