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.bin.Cache;
27 import jalview.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.ImageExporter.ImageWriterI;
35 import jalview.io.HTMLOutput;
36 import jalview.jbgui.GAlignmentPanel;
37 import jalview.math.AlignmentDimension;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.ImageMaker;
42 import jalview.util.MessageManager;
43 import jalview.viewmodel.ViewportListenerI;
44 import jalview.viewmodel.ViewportRanges;
46 import java.awt.BorderLayout;
47 import java.awt.Color;
48 import java.awt.Container;
49 import java.awt.Dimension;
51 import java.awt.FontMetrics;
52 import java.awt.Graphics;
53 import java.awt.Graphics2D;
54 import java.awt.event.AdjustmentEvent;
55 import java.awt.event.AdjustmentListener;
56 import java.awt.event.ComponentAdapter;
57 import java.awt.event.ComponentEvent;
58 import java.awt.print.PageFormat;
59 import java.awt.print.Printable;
60 import java.awt.print.PrinterException;
61 import java.beans.PropertyChangeEvent;
62 import java.beans.PropertyChangeListener;
64 import java.io.FileWriter;
65 import java.io.PrintWriter;
66 import java.util.List;
68 import javax.swing.SwingUtilities;
74 * @version $Revision: 1.161 $
76 @SuppressWarnings("serial")
77 public class AlignmentPanel extends GAlignmentPanel implements
78 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
80 public AlignViewport av;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * false, suppresses invoking the same method recursively.
106 private boolean scrollComplementaryPanel = true;
108 private PropertyChangeListener propertyChangeListener;
110 private CalculationChooser calculationDialog;
113 * Creates a new AlignmentPanel object.
118 public AlignmentPanel(AlignFrame af, final AlignViewport av)
120 // setBackground(Color.white); // BH 2019
123 setSeqPanel(new SeqPanel(av, this));
124 setIdPanel(new IdPanel(av, this));
126 setScalePanel(new ScalePanel(av, this));
128 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
129 idwidthAdjuster = new IdwidthAdjuster(this);
130 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
132 setAnnotationPanel(new AnnotationPanel(this));
133 setAlabels(new AnnotationLabels(this));
135 annotationScroller.setViewportView(getAnnotationPanel());
136 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
138 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
139 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
141 setScrollValues(0, 0);
143 hscroll.addAdjustmentListener(this);
144 vscroll.addAdjustmentListener(this);
146 addComponentListener(new ComponentAdapter()
149 public void componentResized(ComponentEvent evt)
151 // reset the viewport ranges when the alignment panel is resized
152 // in particular, this initialises the end residue value when Jalview
154 ViewportRanges ranges = av.getRanges();
155 if (av.getWrapAlignment())
157 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
158 getSeqPanel().seqCanvas.getWidth());
159 ranges.setViewportWidth(widthInRes);
163 int widthInRes = getSeqPanel().seqCanvas.getWidth()
165 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
166 / av.getCharHeight();
168 ranges.setViewportWidth(widthInRes);
169 ranges.setViewportHeight(heightInSeq);
175 final AlignmentPanel ap = this;
176 propertyChangeListener = new PropertyChangeListener()
179 public void propertyChange(PropertyChangeEvent evt)
181 if (evt.getPropertyName().equals("alignment"))
183 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
188 av.addPropertyChangeListener(propertyChangeListener);
190 av.getRanges().addPropertyChangeListener(this);
192 adjustAnnotationHeight();
197 public AlignViewportI getAlignViewport()
202 public void alignmentChanged()
204 av.alignmentChanged(this);
206 if (getCalculationDialog() != null)
208 getCalculationDialog().validateCalcTypes();
211 alignFrame.updateEditMenuBar();
213 // no idea if we need to update structure
214 paintAlignment(true, true);
221 public void fontChanged()
223 // set idCanvas bufferedImage to null
224 // to prevent drawing old image
225 FontMetrics fm = getFontMetrics(av.getFont());
227 scalePanelHolder.setPreferredSize(
228 new Dimension(10, av.getCharHeight() + fm.getDescent()));
229 idSpaceFillerPanel1.setPreferredSize(
230 new Dimension(10, av.getCharHeight() + fm.getDescent()));
231 idwidthAdjuster.invalidate();
232 scalePanelHolder.invalidate();
233 // BH 2018 getIdPanel().getIdCanvas().gg = null;
234 getSeqPanel().seqCanvas.img = null;
235 getAnnotationPanel().adjustPanelHeight();
237 Dimension d = calculateIdWidth();
239 d.setSize(d.width + 4, d.height);
240 getIdPanel().getIdCanvas().setPreferredSize(d);
241 hscrollFillerPanel.setPreferredSize(d);
247 * Calculate the width of the alignment labels based on the displayed names
248 * and any bounds on label width set in preferences.
250 * @return Dimension giving the maximum width of the alignment label panel
251 * that should be used.
253 public Dimension calculateIdWidth()
255 // calculate sensible default width when no preference is available
257 if (av.getIdWidth() < 0)
259 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
260 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
261 r = calculateIdWidth(maxwidth);
262 av.setIdWidth(r.width);
267 r.width = av.getIdWidth();
274 * Calculate the width of the alignment labels based on the displayed names
275 * and any bounds on label width set in preferences.
278 * -1 or maximum width allowed for IdWidth
279 * @return Dimension giving the maximum width of the alignment label panel
280 * that should be used.
282 public Dimension calculateIdWidth(int maxwidth)
284 Container c = new Container();
286 FontMetrics fm = c.getFontMetrics(
287 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
289 AlignmentI al = av.getAlignment();
294 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
296 SequenceI s = al.getSequenceAt(i);
298 id = s.getDisplayId(av.getShowJVSuffix());
300 if (fm.stringWidth(id) > idWidth)
302 idWidth = fm.stringWidth(id);
308 // Also check annotation label widths
311 if (al.getAlignmentAnnotation() != null)
313 fm = c.getFontMetrics(getAlabels().getFont());
315 while (i < al.getAlignmentAnnotation().length)
317 String label = al.getAlignmentAnnotation()[i].label;
319 if (fm.stringWidth(label) > idWidth)
321 idWidth = fm.stringWidth(label);
328 return new Dimension(
329 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
333 * Highlight the given results on the alignment
336 public void highlightSearchResults(SearchResultsI results)
338 boolean scrolled = scrollToPosition(results, 0, false);
340 boolean fastPaint = !(scrolled && av.getWrapAlignment());
342 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
346 * Scroll the view to show the position of the highlighted region in results
349 * @param searchResults
352 public boolean scrollToPosition(SearchResultsI searchResults)
354 return scrollToPosition(searchResults, 0, false);
358 * Scrolls the view (if necessary) to show the position of the first
359 * highlighted region in results (if any). Answers true if the view was
360 * scrolled, or false if no matched region was found, or it is already
364 * @param verticalOffset
365 * if greater than zero, allows scrolling to a position below the
366 * first displayed sequence
368 * if true, try to centre the search results horizontally in the view
371 protected boolean scrollToPosition(SearchResultsI results,
372 int verticalOffset, boolean centre)
374 int startv, endv, starts, ends;
375 ViewportRanges ranges = av.getRanges();
377 if (results == null || results.isEmpty() || av == null
378 || av.getAlignment() == null)
382 int seqIndex = av.getAlignment().findIndex(results);
387 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
389 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
398 * To centre results, scroll to positions half the visible width
399 * left/right of the start/end positions
403 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
404 start = Math.max(start - offset, 0);
405 end = end + offset - 1;
411 if (end == seq.getEnd())
416 if (av.hasHiddenColumns())
418 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
419 start = hidden.absoluteToVisibleColumn(start);
420 end = hidden.absoluteToVisibleColumn(end);
423 if (!hidden.isVisible(r[0]))
425 // don't scroll - position isn't visible
432 * allow for offset of target sequence (actually scroll to one above it)
434 seqIndex = Math.max(0, seqIndex - verticalOffset);
435 boolean scrollNeeded = true;
437 if (!av.getWrapAlignment())
439 if ((startv = ranges.getStartRes()) >= start)
442 * Scroll left to make start of search results visible
444 setScrollValues(start, seqIndex);
446 else if ((endv = ranges.getEndRes()) <= end)
449 * Scroll right to make end of search results visible
451 setScrollValues(startv + end - endv, seqIndex);
453 else if ((starts = ranges.getStartSeq()) > seqIndex)
456 * Scroll up to make start of search results visible
458 setScrollValues(ranges.getStartRes(), seqIndex);
460 else if ((ends = ranges.getEndSeq()) <= seqIndex)
463 * Scroll down to make end of search results visible
465 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
469 * Else results are already visible - no need to scroll
471 scrollNeeded = false;
475 scrollNeeded = ranges.scrollToWrappedVisible(start);
478 paintAlignment(false, false);
486 * @return DOCUMENT ME!
488 public OverviewPanel getOverviewPanel()
490 return overviewPanel;
499 public void setOverviewPanel(OverviewPanel op)
507 * Hide or show annotation panel
510 public void setAnnotationVisible(boolean b)
512 if (!av.getWrapAlignment())
514 annotationSpaceFillerHolder.setVisible(b);
515 annotationScroller.setVisible(b);
521 * automatically adjust annotation panel height for new annotation whilst
522 * ensuring the alignment is still visible.
525 public void adjustAnnotationHeight()
527 // TODO: display vertical annotation scrollbar if necessary
528 // this is called after loading new annotation onto alignment
529 if (alignFrame.getHeight() == 0)
531 System.out.println("NEEDS FIXING");
533 validateAnnotationDimensions(true);
535 // TODO: many places call this method and also paintAlignment with various
536 // different settings. this means multiple redraws are triggered...
537 paintAlignment(true, av.needToUpdateStructureViews());
541 * calculate the annotation dimensions and refresh slider values accordingly.
542 * need to do repaints/notifys afterwards.
544 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
546 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
547 // are not changing ancestors, and keyboard action listeners do
548 // not need to be reset. addNotify() is a very expensive operation,
549 // requiring a full re-layout of all parents and children.
550 // Note in JComponent:
551 // This method is called by the toolkit internally and should
552 // not be called directly by programs.
553 // I note that addNotify() is called in several areas of Jalview.
555 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
556 annotationHeight = getAnnotationPanel()
557 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
560 annotationScroller.setPreferredSize(
561 new Dimension(annotationScroller.getWidth(), annotationHeight));
563 Dimension e = idPanel.getSize();
564 alabels.setSize(new Dimension(e.width, annotationHeight));
567 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
568 annotationSpaceFillerHolder.getWidth(), annotationHeight));
569 annotationScroller.validate();
570 annotationScroller.addNotify();
574 * update alignment layout for viewport settings
579 public void updateLayout()
582 setAnnotationVisible(av.isShowAnnotation());
583 boolean wrap = av.getWrapAlignment();
584 ViewportRanges ranges = av.getRanges();
585 ranges.setStartSeq(0);
586 scalePanelHolder.setVisible(!wrap);
587 hscroll.setVisible(!wrap);
588 idwidthAdjuster.setVisible(!wrap);
592 annotationScroller.setVisible(false);
593 annotationSpaceFillerHolder.setVisible(false);
595 else if (av.isShowAnnotation())
597 annotationScroller.setVisible(true);
598 annotationSpaceFillerHolder.setVisible(true);
599 validateAnnotationDimensions(false);
602 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
604 { // may not yet be laid out
607 int widthInRes = getSeqPanel().seqCanvas
608 .getWrappedCanvasWidth(canvasWidth);
609 ranges.setViewportWidth(widthInRes);
613 int widthInRes = (canvasWidth / av.getCharWidth());
614 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
615 / av.getCharHeight());
617 ranges.setViewportWidth(widthInRes);
618 ranges.setViewportHeight(heightInSeq);
622 idSpaceFillerPanel1.setVisible(!wrap);
628 * Adjust row/column scrollers to show a visible position in the alignment.
631 * visible column to scroll to
633 * visible row to scroll to
636 public void setScrollValues(int xpos, int ypos)
641 if (av == null || av.getAlignment() == null)
646 if (av.getWrapAlignment())
648 setScrollingForWrappedPanel(x);
652 int width = av.getAlignment().getVisibleWidth();
653 int height = av.getAlignment().getHeight();
655 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
656 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
663 if (vextent > height)
668 if ((hextent + x) > width)
673 if ((vextent + y) > height)
675 y = height - vextent;
688 // update the scroll values
689 hscroll.setValues(x, hextent, 0, width);
690 vscroll.setValues(y, vextent, 0, height);
695 * Respond to adjustment event when horizontal or vertical scrollbar is
699 * adjustment event encoding whether hscroll or vscroll changed
702 public void adjustmentValueChanged(AdjustmentEvent evt)
704 if (av.getWrapAlignment())
706 adjustScrollingWrapped(evt);
710 ViewportRanges ranges = av.getRanges();
712 if (evt.getSource() == hscroll)
714 int oldX = ranges.getStartRes();
715 int oldwidth = ranges.getViewportWidth();
716 int x = hscroll.getValue();
717 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
719 // if we're scrolling to the position we're already at, stop
720 // this prevents infinite recursion of events when the scroll/viewport
721 // ranges values are the same
722 if ((x == oldX) && (width == oldwidth))
726 ranges.setViewportStartAndWidth(x, width);
728 else if (evt.getSource() == vscroll)
730 int oldY = ranges.getStartSeq();
731 int oldheight = ranges.getViewportHeight();
732 int y = vscroll.getValue();
733 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
735 // if we're scrolling to the position we're already at, stop
736 // this prevents infinite recursion of events when the scroll/viewport
737 // ranges values are the same
738 if ((y == oldY) && (height == oldheight))
742 ranges.setViewportStartAndHeight(y, height);
748 * Responds to a scroll change by setting the start position of the viewport.
753 protected void adjustScrollingWrapped(AdjustmentEvent evt)
755 if (evt.getSource() == hscroll)
757 return; // no horizontal scroll when wrapped
759 final ViewportRanges ranges = av.getRanges();
761 if (evt.getSource() == vscroll)
763 int newY = vscroll.getValue();
766 * if we're scrolling to the position we're already at, stop
767 * this prevents infinite recursion of events when the scroll/viewport
768 * ranges values are the same
770 int oldX = ranges.getStartRes();
771 int oldY = ranges.getWrappedScrollPosition(oldX);
779 * limit page up/down to one width's worth of positions
781 int rowSize = ranges.getViewportWidth();
782 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
783 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
788 // This is only called if file loaded is a jar file that
789 // was wrapped when saved and user has wrap alignment true
790 // as preference setting
791 SwingUtilities.invokeLater(new Runnable()
796 // When updating scrolling to use ViewportChange events, this code
797 // could not be validated and it is not clear if it is now being
798 // called. Log warning here in case it is called and unforeseen
801 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
803 // scroll to start of panel
804 ranges.setStartRes(0);
805 ranges.setStartSeq(0);
813 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
816 public void paintAlignment(boolean updateOverview,
817 boolean updateStructures)
819 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
820 av.isShowAutocalculatedAbove());
821 sorter.sort(getAlignment().getAlignmentAnnotation(),
822 av.getSortAnnotationsBy());
825 if (updateStructures)
827 av.getStructureSelectionManager().sequenceColoursChanged(this);
832 if (overviewPanel != null)
834 overviewPanel.updateOverviewImage();
846 public void paintComponent(Graphics g)
848 invalidate(); // needed so that the id width adjuster works correctly
850 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
851 idPanelHolder.setPreferredSize(d);
852 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
854 validate(); // needed so that the id width adjuster works correctly
857 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
858 * though I still think this call should be elsewhere.
860 ViewportRanges ranges = av.getRanges();
861 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
862 super.paintComponent(g);
866 * Set vertical scroll bar position, and number of increments, for wrapped
869 * @param topLeftColumn
870 * the column position at top left (0..)
872 private void setScrollingForWrappedPanel(int topLeftColumn)
874 ViewportRanges ranges = av.getRanges();
875 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
876 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
879 * a scrollbar's value can be set to at most (maximum-extent)
880 * so we add extent (1) to the maxScroll value
882 vscroll.setUnitIncrement(1);
883 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
896 * @return DOCUMENT ME!
898 * @throws PrinterException
902 public int print(Graphics pg, PageFormat pf, int pi)
903 throws PrinterException
905 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
907 int pwidth = (int) pf.getImageableWidth();
908 int pheight = (int) pf.getImageableHeight();
910 if (av.getWrapAlignment())
912 return printWrappedAlignment(pwidth, pheight, pi, pg);
916 return printUnwrapped(pwidth, pheight, pi, pg, pg);
921 * Draws the alignment image, including sequence ids, sequences, and
922 * annotation labels and annotations if shown, on either one or two Graphics
932 * the graphics context for sequence ids and annotation labels
933 * @param alignmentGraphics
934 * the graphics context for sequences and annotations (may or may not
935 * be the same context as idGraphics)
937 * @throws PrinterException
939 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
940 Graphics idGraphics, Graphics alignmentGraphics)
941 throws PrinterException
943 final int idWidth = getVisibleIdWidth(false);
946 * Get the horizontal offset to where we draw the sequences.
947 * This is idWidth if using a single Graphics context, else zero.
949 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
952 FontMetrics fm = getFontMetrics(av.getFont());
953 final int charHeight = av.getCharHeight();
954 final int scaleHeight = charHeight + fm.getDescent();
956 idGraphics.setColor(Color.white);
957 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
958 idGraphics.setFont(av.getFont());
961 * How many sequences and residues can we fit on a printable page?
963 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
965 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
967 final int alignmentWidth = av.getAlignment().getVisibleWidth();
968 int pagesWide = (alignmentWidth / totalRes) + 1;
970 final int startRes = (pageIndex % pagesWide) * totalRes;
971 final int endRes = Math.min(startRes + totalRes - 1,
974 final int startSeq = (pageIndex / pagesWide) * totalSeq;
975 final int alignmentHeight = av.getAlignment().getHeight();
976 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
978 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
980 if (av.isShowAnnotation())
982 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
985 pagesHigh /= pageHeight;
987 if (pageIndex >= (pagesWide * pagesHigh))
989 return Printable.NO_SUCH_PAGE;
991 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
994 * draw the Scale at horizontal offset, then reset to top left (0, 0)
996 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
997 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
998 pageWidth - idWidth, scaleHeight);
999 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1002 * Draw the sequence ids, offset for scale height,
1003 * then reset to top left (0, 0)
1005 idGraphics.translate(0, scaleHeight);
1006 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1007 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1008 : av.getSelectionGroup().getSequences(null);
1009 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1012 idGraphics.setFont(av.getFont());
1013 idGraphics.translate(0, -scaleHeight);
1016 * draw the sequences, offset for scale height, and id width (if using a
1017 * single graphics context), then reset to (0, scale height)
1019 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1020 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1021 endRes, startSeq, endSeq - 1);
1022 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1024 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1027 * draw annotation labels; drawComponent() translates by
1028 * getScrollOffset(), so compensate for that first;
1029 * then reset to (0, scale height)
1031 int offset = getAlabels().getScrollOffset();
1032 idGraphics.translate(0, -offset);
1033 idGraphics.translate(0, alignmentDrawnHeight);
1034 getAlabels().drawComponent(idGraphics, idWidth);
1035 idGraphics.translate(0, -alignmentDrawnHeight);
1038 * draw the annotations starting at
1039 * (idOffset, alignmentHeight) from (0, scaleHeight)
1041 alignmentGraphics.translate(alignmentGraphicsOffset,
1042 alignmentDrawnHeight);
1043 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1044 alignmentGraphics, -1, startRes, endRes + 1);
1047 return Printable.PAGE_EXISTS;
1051 * Prints one page of an alignment in wrapped mode. Returns
1052 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1053 * no page could be drawn (page number out of range).
1063 * @throws PrinterException
1065 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1066 Graphics g) throws PrinterException
1068 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
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);
1091 av.getRanges().setViewportStartAndWidth(0, resWidth);
1093 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1095 g.setColor(Color.white);
1096 g.fillRect(0, 0, pageWidth, pageHeight);
1097 g.setFont(av.getFont());
1098 g.setColor(Color.black);
1101 * method: print the whole wrapped alignment, but with a clip region that
1102 * is restricted to the requested page; this supports selective print of
1103 * single pages or ranges, (at the cost of repeated processing in the
1104 * 'normal' case, when all pages are printed)
1106 g.translate(0, -pageNumber * pageHeight);
1108 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1111 * draw sequence ids and annotation labels (if shown)
1113 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1114 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1116 g.translate(idWidth, 0);
1118 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1121 if ((pageNumber * pageHeight) < totalHeight)
1123 return Printable.PAGE_EXISTS;
1127 return Printable.NO_SUCH_PAGE;
1132 * get current sequence ID panel width, or nominal value if panel were to be
1133 * displayed using default settings
1137 public int getVisibleIdWidth()
1139 return getVisibleIdWidth(true);
1143 * get current sequence ID panel width, or nominal value if panel were to be
1144 * displayed using default settings
1147 * indicate if the Id width for onscreen or offscreen display should
1151 public int getVisibleIdWidth(boolean onscreen)
1153 // see if rendering offscreen - check preferences and calc width accordingly
1154 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1156 return calculateIdWidth(-1).width + 4;
1158 Integer idwidth = null;
1159 if (onscreen || (idwidth = Cache
1160 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1162 int w = getIdPanel().getWidth();
1163 return (w > 0 ? w : calculateIdWidth().width + 4);
1165 return idwidth.intValue() + 4;
1169 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1170 * writes it to the specified file
1175 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1177 final int borderBottomOffset = 5;
1179 AlignmentDimension aDimension = getAlignmentDimension();
1180 // todo use a lambda function in place of callback here?
1181 ImageWriterI writer = new ImageWriterI()
1184 public void exportImage(Graphics graphics) throws Exception
1186 if (av.getWrapAlignment())
1188 printWrappedAlignment(aDimension.getWidth(),
1189 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1193 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1194 graphics, graphics);
1199 String fileTitle = alignFrame.getTitle();
1200 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1202 int imageWidth = aDimension.getWidth();
1203 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1204 String of = MessageManager.getString("label.alignment");
1205 exporter.doExport(file, this, imageWidth, imageHeight, of);
1209 * Calculates and returns a suitable width and height (in pixels) for an
1214 public AlignmentDimension getAlignmentDimension()
1216 int maxwidth = av.getAlignment().getVisibleWidth();
1218 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1219 + getScalePanel().getHeight();
1220 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1222 if (av.getWrapAlignment())
1224 height = getWrappedHeight();
1225 if (Jalview.isHeadlessMode())
1227 // need to obtain default alignment width and then add in any
1228 // additional allowance for id margin
1229 // this duplicates the calculation in getWrappedHeight but adjusts for
1231 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1232 - alignFrame.getInsets().left - alignFrame.getInsets().right
1233 - getVisibleIdWidth() + getVisibleIdWidth(false);
1237 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1241 else if (av.isShowAnnotation())
1243 height += getAnnotationPanel().adjustPanelHeight() + 3;
1245 return new AlignmentDimension(width, height);
1249 public void makePNGImageMap(File imgMapFile, String imageName)
1251 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1252 // ////////////////////////////////////////////
1253 int idWidth = getVisibleIdWidth(false);
1254 FontMetrics fm = getFontMetrics(av.getFont());
1255 int scaleHeight = av.getCharHeight() + fm.getDescent();
1258 // ////////////////////////////////
1259 if (imgMapFile != null)
1263 int sSize = av.getAlignment().getHeight();
1264 int alwidth = av.getAlignment().getWidth();
1265 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1266 out.println(HTMLOutput.getImageMapHTML());
1267 out.println("<img src=\"" + imageName
1268 + "\" border=\"0\" usemap=\"#Map\" >"
1269 + "<map name=\"Map\">");
1271 for (int s = 0; s < sSize; s++)
1273 int sy = s * av.getCharHeight() + scaleHeight;
1275 SequenceI seq = av.getAlignment().getSequenceAt(s);
1276 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1277 for (int column = 0; column < alwidth; column++)
1279 StringBuilder text = new StringBuilder(512);
1280 String triplet = null;
1281 if (av.getAlignment().isNucleotide())
1283 triplet = ResidueProperties.nucleotideName.get(seq
1284 .getCharAt(column) + "");
1288 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1292 if (triplet == null)
1297 int seqPos = seq.findPosition(column);
1298 int gSize = groups.length;
1299 for (int g = 0; g < gSize; g++)
1301 if (text.length() < 1)
1303 text.append("<area shape=\"rect\" coords=\"")
1304 .append((idWidth + column * av.getCharWidth()))
1305 .append(",").append(sy).append(",")
1306 .append((idWidth + (column + 1) * av.getCharWidth()))
1307 .append(",").append((av.getCharHeight() + sy))
1308 .append("\"").append(" onMouseOver=\"toolTip('")
1309 .append(seqPos).append(" ").append(triplet);
1312 if (groups[g].getStartRes() < column
1313 && groups[g].getEndRes() > column)
1315 text.append("<br><em>").append(groups[g].getName())
1320 if (text.length() < 1)
1322 text.append("<area shape=\"rect\" coords=\"")
1323 .append((idWidth + column * av.getCharWidth()))
1324 .append(",").append(sy).append(",")
1325 .append((idWidth + (column + 1) * av.getCharWidth()))
1326 .append(",").append((av.getCharHeight() + sy))
1327 .append("\"").append(" onMouseOver=\"toolTip('")
1328 .append(seqPos).append(" ").append(triplet);
1330 if (!Comparison.isGap(seq.getCharAt(column)))
1332 List<SequenceFeature> features = seq.findFeatures(column, column);
1333 for (SequenceFeature sf : features)
1335 if (sf.isContactFeature())
1337 text.append("<br>").append(sf.getType()).append(" ")
1338 .append(sf.getBegin()).append(":")
1339 .append(sf.getEnd());
1343 text.append("<br>");
1344 text.append(sf.getType());
1345 String description = sf.getDescription();
1346 if (description != null
1347 && !sf.getType().equals(description))
1349 description = description.replace("\"", """);
1350 text.append(" ").append(description);
1353 String status = sf.getStatus();
1354 if (status != null && !"".equals(status))
1356 text.append(" (").append(status).append(")");
1359 if (text.length() > 1)
1361 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1362 out.println(text.toString());
1367 out.println("</map></body></html>");
1370 } catch (Exception ex)
1372 ex.printStackTrace();
1374 } // /////////END OF IMAGE MAP
1379 * Answers the height of the entire alignment in pixels, assuming it is in
1384 int getWrappedHeight()
1386 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1388 if (System.getProperty("java.awt.headless") != null
1389 && System.getProperty("java.awt.headless").equals("true"))
1391 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1392 - vscroll.getPreferredSize().width
1393 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1396 int chunkWidth = getSeqPanel().seqCanvas
1397 .getWrappedCanvasWidth(seqPanelWidth);
1399 int hgap = av.getCharHeight();
1400 if (av.getScaleAboveWrapped())
1402 hgap += av.getCharHeight();
1405 int annotationHeight = 0;
1406 if (av.isShowAnnotation())
1408 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1409 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1412 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1415 int maxwidth = av.getAlignment().getWidth();
1416 if (av.hasHiddenColumns())
1418 maxwidth = av.getAlignment().getHiddenColumns()
1419 .absoluteToVisibleColumn(maxwidth) - 1;
1422 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1428 * close the panel - deregisters all listeners and nulls any references to
1431 public void closePanel()
1433 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1434 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1435 PaintRefresher.RemoveComponent(this);
1440 * try to ensure references are nulled
1442 if (annotationPanel != null)
1444 annotationPanel.dispose();
1445 annotationPanel = null;
1450 av.removePropertyChangeListener(propertyChangeListener);
1451 propertyChangeListener = null;
1452 StructureSelectionManager ssm = av.getStructureSelectionManager();
1453 ssm.removeStructureViewerListener(getSeqPanel(), null);
1454 ssm.removeSelectionListener(getSeqPanel());
1455 ssm.removeCommandListener(av);
1456 ssm.removeStructureViewerListener(getSeqPanel(), null);
1457 ssm.removeSelectionListener(getSeqPanel());
1463 if (Cache.log.isDebugEnabled())
1465 Cache.log.warn("Closing alignment panel which is already closed.");
1471 * Close any open dialogs that would be orphaned when this one is closed
1473 protected void closeChildFrames()
1475 if (overviewPanel != null)
1477 overviewPanel.dispose();
1478 overviewPanel = null;
1480 if (calculationDialog != null)
1482 calculationDialog.closeFrame();
1483 calculationDialog = null;
1488 * hides or shows dynamic annotation rows based on groups and av state flags
1490 public void updateAnnotation()
1492 updateAnnotation(false, false);
1495 public void updateAnnotation(boolean applyGlobalSettings)
1497 updateAnnotation(applyGlobalSettings, false);
1500 public void updateAnnotation(boolean applyGlobalSettings,
1501 boolean preserveNewGroupSettings)
1503 av.updateGroupAnnotationSettings(applyGlobalSettings,
1504 preserveNewGroupSettings);
1505 adjustAnnotationHeight();
1509 public AlignmentI getAlignment()
1511 return av == null ? null : av.getAlignment();
1515 public String getViewName()
1517 return av.getViewName();
1521 * Make/Unmake this alignment panel the current input focus
1525 public void setSelected(boolean b)
1529 if (alignFrame.getSplitViewContainer() != null)
1532 * bring enclosing SplitFrame to front first if there is one
1534 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1536 alignFrame.setSelected(b);
1537 } catch (Exception ex)
1543 alignFrame.setDisplayedView(this);
1548 public StructureSelectionManager getStructureSelectionManager()
1550 return av.getStructureSelectionManager();
1554 public void raiseOOMWarning(String string, OutOfMemoryError error)
1556 new OOMWarning(string, error, this);
1560 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1563 return new FeatureRenderer(this);
1567 public jalview.api.FeatureRenderer getFeatureRenderer()
1569 return seqPanel.seqCanvas.getFeatureRenderer();
1572 public void updateFeatureRenderer(
1573 jalview.renderer.seqfeatures.FeatureRenderer fr)
1575 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1578 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1580 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1582 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1586 public ScalePanel getScalePanel()
1591 public void setScalePanel(ScalePanel scalePanel)
1593 this.scalePanel = scalePanel;
1596 public SeqPanel getSeqPanel()
1601 public void setSeqPanel(SeqPanel seqPanel)
1603 this.seqPanel = seqPanel;
1606 public AnnotationPanel getAnnotationPanel()
1608 return annotationPanel;
1611 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1613 this.annotationPanel = annotationPanel;
1616 public AnnotationLabels getAlabels()
1621 public void setAlabels(AnnotationLabels alabels)
1623 this.alabels = alabels;
1626 public IdPanel getIdPanel()
1631 public void setIdPanel(IdPanel idPanel)
1633 this.idPanel = idPanel;
1637 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1638 * The aim is to keep the two alignments 'lined up' on their centre columns.
1641 * holds mapped region(s) of this alignment that we are scrolling
1642 * 'to'; may be modified for sequence offset by this method
1643 * @param verticalOffset
1644 * the number of visible sequences to show above the mapped region
1646 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1648 scrollToPosition(sr, verticalOffset, true);
1652 * Set a flag to say do not scroll any (cDNA/protein) complement.
1656 protected void setToScrollComplementPanel(boolean b)
1658 this.scrollComplementaryPanel = b;
1662 * Get whether to scroll complement panel
1664 * @return true if cDNA/protein complement panels should be scrolled
1666 protected boolean isSetToScrollComplementPanel()
1668 return this.scrollComplementaryPanel;
1674 * @adjustHeight if true, try to recalculate panel height for visible
1677 protected void refresh(boolean adjustHeight)
1679 validateAnnotationDimensions(adjustHeight);
1683 // sort, repaint, update overview
1684 paintAlignment(true, false);
1688 // lightweight repaint
1695 * Property change event fired when a change is made to the viewport ranges
1696 * object associated with this alignment panel's viewport
1698 public void propertyChange(PropertyChangeEvent evt)
1700 // update this panel's scroll values based on the new viewport ranges values
1701 ViewportRanges ranges = av.getRanges();
1702 int x = ranges.getStartRes();
1703 int y = ranges.getStartSeq();
1704 setScrollValues(x, y);
1706 // now update any complementary alignment (its viewport ranges object
1707 // is different so does not get automatically updated)
1708 if (isSetToScrollComplementPanel())
1710 setToScrollComplementPanel(false);
1711 av.scrollComplementaryAlignment();
1712 setToScrollComplementPanel(true);
1717 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1718 * reference should be nulled when the dialog is closed.
1720 * @param calculationChooser
1722 public void setCalculationDialog(CalculationChooser calculationChooser)
1724 calculationDialog = calculationChooser;
1728 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1731 public CalculationChooser getCalculationDialog()
1733 return calculationDialog;