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.image.BufferedImage;
60 import java.awt.print.PageFormat;
61 import java.awt.print.Printable;
62 import java.awt.print.PrinterException;
63 import java.beans.PropertyChangeEvent;
64 import java.beans.PropertyChangeListener;
66 import java.io.FileWriter;
67 import java.io.PrintWriter;
68 import java.util.List;
71 * The main panel of an AlignFrame, containing holders for the IdPanel,
72 * SeqPanel, AnnotationLabels (a JPanel), and AnnotationPanel.
74 * Additional holders contain an IdPanelWidthAdjuster space above the idPanel,
75 * AnnotationScroller (JScrollPane for AnnotationPanel), and vertical and
76 * horizontal scrollbars.
81 * @version $Revision: 1.161 $
83 @SuppressWarnings("serial")
84 public class AlignmentPanel extends GAlignmentPanel implements
85 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
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
131 setSeqPanel(new SeqPanel(av, this));
132 setIdPanel(new IdPanel(av, this));
134 setScalePanel(new ScalePanel(av, this));
136 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
137 idwidthAdjuster = new IdwidthAdjuster(this);
138 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
140 setAnnotationPanel(new AnnotationPanel(this));
141 setAlabels(new AnnotationLabels(this));
143 annotationScroller.setViewportView(getAnnotationPanel());
144 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
145 if (!av.isShowAnnotation())
147 annotationScroller.setVisible(false);
148 annotationSpaceFillerHolder.setVisible(false);
150 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
151 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
153 setScrollValues(0, 0);
155 hscroll.addAdjustmentListener(this);
156 vscroll.addAdjustmentListener(this);
158 addComponentListener(new ComponentAdapter()
161 public void componentResized(ComponentEvent evt)
163 // reset the viewport ranges when the alignment panel is resized
164 // in particular, this initialises the end residue value when Jalview
166 ViewportRanges ranges = av.getRanges();
167 if (av.getWrapAlignment())
169 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
170 getSeqPanel().seqCanvas.getWidth());
171 ranges.setViewportWidth(widthInRes);
175 int widthInRes = getSeqPanel().seqCanvas.getWidth()
177 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
178 / av.getCharHeight();
180 ranges.setViewportWidth(widthInRes);
181 ranges.setViewportHeight(heightInSeq);
182 ViewportRanges.sTest += "AP.resize chht=" + av.getCharHeight()
183 + "canvHt=" + getSeqPanel().seqCanvas.getHeight() + " "
184 + heightInSeq + "\n";
190 final AlignmentPanel ap = this;
191 propertyChangeListener = new PropertyChangeListener()
194 public void propertyChange(PropertyChangeEvent evt)
196 if (evt.getPropertyName().equals("alignment"))
198 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
203 av.addPropertyChangeListener(propertyChangeListener);
205 av.getRanges().addPropertyChangeListener(this);
207 adjustAnnotationHeight();
212 public AlignViewportI getAlignViewport()
217 public void alignmentChanged()
219 av.alignmentChanged(this);
221 if (getCalculationDialog() != null)
223 getCalculationDialog().validateCalcTypes();
226 alignFrame.updateEditMenuBar();
228 // no idea if we need to update structure
229 paintAlignment(true, true);
236 public void fontChanged()
238 // set idCanvas bufferedImage to null
239 // to prevent drawing old image
240 FontMetrics fm = getFontMetrics(av.getFont());
242 scalePanelHolder.setPreferredSize(
243 new Dimension(10, av.getCharHeight() + fm.getDescent()));
244 idSpaceFillerPanel1.setPreferredSize(
245 new Dimension(10, av.getCharHeight() + fm.getDescent()));
246 idwidthAdjuster.invalidate();
247 scalePanelHolder.invalidate();
248 // BH 2018 getIdPanel().getIdCanvas().gg = null;
249 getSeqPanel().seqCanvas.img = null;
250 getAnnotationPanel().adjustPanelHeight();
252 Dimension d = calculateIdWidth();
254 d.setSize(d.width + 4, d.height);
255 getIdPanel().getIdCanvas().setPreferredSize(d);
256 hscrollFillerPanel.setPreferredSize(d);
262 * Calculate the width of the alignment labels based on the displayed names
263 * and any bounds on label width set in preferences.
265 * @return Dimension giving the maximum width of the alignment label panel
266 * that should be used.
268 public Dimension calculateIdWidth()
270 // calculate sensible default width when no preference is available
272 if (av.getIdWidth() < 0)
274 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
275 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
276 r = calculateIdWidth(maxwidth);
277 av.setIdWidth(r.width);
282 r.width = av.getIdWidth();
289 * Calculate the width of the alignment labels based on the displayed names
290 * and any bounds on label width set in preferences.
293 * -1 or maximum width allowed for IdWidth
294 * @return Dimension giving the maximum width of the alignment label panel
295 * that should be used.
297 public Dimension calculateIdWidth(int maxwidth)
299 Container c = new Container();
301 FontMetrics fm = c.getFontMetrics(
302 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
304 AlignmentI al = av.getAlignment();
309 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
311 SequenceI s = al.getSequenceAt(i);
313 id = s.getDisplayId(av.getShowJVSuffix());
315 if (fm.stringWidth(id) > idWidth)
317 idWidth = fm.stringWidth(id);
323 // Also check annotation label widths
326 if (al.getAlignmentAnnotation() != null)
328 fm = c.getFontMetrics(getAlabels().getFont());
330 while (i < al.getAlignmentAnnotation().length)
332 String label = al.getAlignmentAnnotation()[i].label;
334 if (fm.stringWidth(label) > idWidth)
336 idWidth = fm.stringWidth(label);
343 return new Dimension(
344 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 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
484 * Else results are already visible - no need to scroll
486 scrollNeeded = false;
490 scrollNeeded = ranges.scrollToWrappedVisible(start);
493 paintAlignment(false, false);
501 * @return DOCUMENT ME!
503 public OverviewPanel getOverviewPanel()
505 return overviewPanel;
514 public void setOverviewPanel(OverviewPanel op)
522 * Hide or show annotation panel
525 public void setAnnotationVisible(boolean b)
527 if (!av.getWrapAlignment())
529 annotationSpaceFillerHolder.setVisible(b);
530 annotationScroller.setVisible(b);
536 * automatically adjust annotation panel height for new annotation whilst
537 * ensuring the alignment is still visible.
540 public void adjustAnnotationHeight()
542 // TODO: display vertical annotation scrollbar if necessary
543 // this is called after loading new annotation onto alignment
544 if (alignFrame.getHeight() == 0)
546 System.out.println("NEEDS FIXING");
548 validateAnnotationDimensions(true);
550 // TODO: many places call this method and also paintAlignment with various
551 // different settings. this means multiple redraws are triggered...
552 paintAlignment(true, av.needToUpdateStructureViews());
556 * calculate the annotation dimensions and refresh slider values accordingly.
557 * need to do repaints/notifys afterwards.
559 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
561 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
562 // are not changing ancestors, and keyboard action listeners do
563 // not need to be reset. addNotify() is a very expensive operation,
564 // requiring a full re-layout of all parents and children.
565 // Note in JComponent:
566 // This method is called by the toolkit internally and should
567 // not be called directly by programs.
568 // I note that addNotify() is called in several areas of Jalview.
570 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
571 annotationHeight = getAnnotationPanel()
572 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
575 annotationScroller.setPreferredSize(
576 new Dimension(annotationScroller.getWidth(), annotationHeight));
578 Dimension e = idPanel.getSize();
579 alabels.setSize(new Dimension(e.width, annotationHeight));
582 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
583 annotationSpaceFillerHolder.getWidth(), annotationHeight));
584 annotationScroller.validate();
585 annotationScroller.addNotify();
589 * update alignment layout for viewport settings
594 public void updateLayout()
596 fontChanged(); // fires repaint
597 setAnnotationVisible(av.isShowAnnotation());
598 boolean wrap = av.getWrapAlignment();
599 ViewportRanges ranges = av.getRanges();
600 ranges.setStartSeq(0);
601 scalePanelHolder.setVisible(!wrap);
602 hscroll.setVisible(!wrap);
603 idwidthAdjuster.setVisible(!wrap);
607 annotationScroller.setVisible(false);
608 annotationSpaceFillerHolder.setVisible(false);
610 else if (av.isShowAnnotation())
612 annotationScroller.setVisible(true);
613 annotationSpaceFillerHolder.setVisible(true);
614 validateAnnotationDimensions(false);
617 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
619 { // may not yet be laid out
622 int widthInRes = getSeqPanel().seqCanvas
623 .getWrappedCanvasWidth(canvasWidth);
624 ranges.setViewportWidth(widthInRes);
628 int widthInRes = (canvasWidth / av.getCharWidth());
629 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
630 / av.getCharHeight());
632 ranges.setViewportWidth(widthInRes);
633 ranges.setViewportHeight(heightInSeq);
637 idSpaceFillerPanel1.setVisible(!wrap);
643 * Adjust row/column scrollers to show a visible position in the alignment.
646 * visible column to scroll to
648 * visible row to scroll to
651 public void setScrollValues(int xpos, int ypos)
656 if (av == null || av.getAlignment() == null)
661 if (av.getWrapAlignment())
663 setScrollingForWrappedPanel(x);
667 int width = av.getAlignment().getVisibleWidth();
668 int height = av.getAlignment().getHeight();
670 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
671 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
678 if (vextent > height)
683 if ((hextent + x) > width)
688 if ((vextent + y) > height)
690 y = height - vextent;
703 // update the scroll values
704 hscroll.setValues(x, hextent, 0, width);
705 vscroll.setValues(y, vextent, 0, height);
710 * Respond to adjustment event when horizontal or vertical scrollbar is
714 * adjustment event encoding whether hscroll or vscroll changed
717 public void adjustmentValueChanged(AdjustmentEvent evt)
719 if (av.getWrapAlignment())
721 adjustScrollingWrapped(evt);
725 ViewportRanges ranges = av.getRanges();
727 if (evt.getSource() == hscroll)
729 int oldX = ranges.getStartRes();
730 int oldwidth = ranges.getViewportWidth();
731 int x = hscroll.getValue();
732 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
734 // if we're scrolling to the position we're already at, stop
735 // this prevents infinite recursion of events when the scroll/viewport
736 // ranges values are the same
737 if ((x == oldX) && (width == oldwidth))
741 ranges.setViewportStartAndWidth(x, width);
743 else if (evt.getSource() == vscroll)
745 int oldY = ranges.getStartSeq();
746 int oldheight = ranges.getViewportHeight();
747 int y = vscroll.getValue();
748 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
751 // if we're scrolling to the position we're already at, stop
752 // this prevents infinite recursion of events when the scroll/viewport
753 // ranges values are the same
754 if ((y == oldY) && (height == oldheight))
759 ViewportRanges.sTest += "AP.valChanged chht=" + av.getCharHeight()
760 + "canvHt=" + getSeqPanel().seqCanvas.getHeight() + " "
763 ranges.setViewportStartAndHeight(y, height);
769 * Responds to a scroll change by setting the start position of the viewport.
774 protected void adjustScrollingWrapped(AdjustmentEvent evt)
776 if (evt.getSource() == hscroll)
778 return; // no horizontal scroll when wrapped
780 final ViewportRanges ranges = av.getRanges();
782 if (evt.getSource() == vscroll)
784 int newY = vscroll.getValue();
787 * if we're scrolling to the position we're already at, stop
788 * this prevents infinite recursion of events when the scroll/viewport
789 * ranges values are the same
791 int oldX = ranges.getStartRes();
792 int oldY = ranges.getWrappedScrollPosition(oldX);
800 * limit page up/down to one width's worth of positions
802 int rowSize = ranges.getViewportWidth();
803 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
804 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
809 // This is only called if file loaded is a jar file that
810 // was wrapped when saved and user has wrap alignment true
811 // as preference setting
812 Jalview.execRunnable(new Runnable()
817 // When updating scrolling to use ViewportChange events, this code
818 // could not be validated and it is not clear if it is now being
819 // called. Log warning here in case it is called and unforeseen
822 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
824 // scroll to start of panel
825 ranges.setStartRes(0);
826 ranges.setStartSeq(0);
834 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
837 public void paintAlignment(boolean updateOverview,
838 boolean updateStructures)
840 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
841 av.isShowAutocalculatedAbove());
842 sorter.sort(getAlignment().getAlignmentAnnotation(),
843 av.getSortAnnotationsBy());
846 if (updateStructures)
848 av.getStructureSelectionManager().sequenceColoursChanged(this);
852 if (overviewPanel != null)
854 overviewPanel.updateOverviewImage();
866 public void paintComponent(Graphics g)
869 invalidate(); // needed so that the id width adjuster works correctly
871 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
872 idPanelHolder.setPreferredSize(d);
873 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
875 validate(); // needed so that the id width adjuster works correctly
878 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
879 * though I still think this call should be elsewhere.
881 ViewportRanges ranges = av.getRanges();
882 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
883 super.paintComponent(g);
887 * Set vertical scroll bar position, and number of increments, for wrapped
890 * @param topLeftColumn
891 * the column position at top left (0..)
893 private void setScrollingForWrappedPanel(int topLeftColumn)
895 ViewportRanges ranges = av.getRanges();
896 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
897 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
900 * a scrollbar's value can be set to at most (maximum-extent)
901 * so we add extent (1) to the maxScroll value
903 vscroll.setUnitIncrement(1);
904 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
917 * @return DOCUMENT ME!
919 * @throws PrinterException
923 public int print(Graphics pg, PageFormat pf, int pi)
924 throws PrinterException
926 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
928 int pwidth = (int) pf.getImageableWidth();
929 int pheight = (int) pf.getImageableHeight();
931 if (av.getWrapAlignment())
933 return printWrappedAlignment(pwidth, pheight, pi, pg);
937 return printUnwrapped(pwidth, pheight, pi, pg, pg);
942 * Draws the alignment image, including sequence ids, sequences, and
943 * annotation labels and annotations if shown, on either one or two Graphics
953 * the graphics context for sequence ids and annotation labels
954 * @param alignmentGraphics
955 * the graphics context for sequences and annotations (may or may not
956 * be the same context as idGraphics)
958 * @throws PrinterException
960 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
961 Graphics idGraphics, Graphics alignmentGraphics)
962 throws PrinterException
964 final int idWidth = getVisibleIdWidth(false);
967 * Get the horizontal offset to where we draw the sequences.
968 * This is idWidth if using a single Graphics context, else zero.
970 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
973 FontMetrics fm = getFontMetrics(av.getFont());
974 final int charHeight = av.getCharHeight();
975 final int scaleHeight = charHeight + fm.getDescent();
977 idGraphics.setColor(Color.white);
978 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
979 idGraphics.setFont(av.getFont());
982 * How many sequences and residues can we fit on a printable page?
984 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
986 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
988 final int alignmentWidth = av.getAlignment().getVisibleWidth();
989 int pagesWide = (alignmentWidth / totalRes) + 1;
991 final int startRes = (pageIndex % pagesWide) * totalRes;
992 final int endRes = Math.min(startRes + totalRes - 1,
995 final int startSeq = (pageIndex / pagesWide) * totalSeq;
996 final int alignmentHeight = av.getAlignment().getHeight();
997 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
999 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1001 if (av.isShowAnnotation())
1003 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1006 pagesHigh /= pageHeight;
1008 if (pageIndex >= (pagesWide * pagesHigh))
1010 return Printable.NO_SUCH_PAGE;
1012 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1015 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1017 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1018 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1019 pageWidth - idWidth, scaleHeight);
1020 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1023 * Draw the sequence ids, offset for scale height,
1024 * then reset to top left (0, 0)
1026 idGraphics.translate(0, scaleHeight);
1027 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1028 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1029 : av.getSelectionGroup().getSequences(null);
1030 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1033 idGraphics.setFont(av.getFont());
1034 idGraphics.translate(0, -scaleHeight);
1037 * draw the sequences, offset for scale height, and id width (if using a
1038 * single graphics context), then reset to (0, scale height)
1040 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1041 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1042 endRes, startSeq, endSeq - 1);
1043 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1045 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1048 * draw annotation labels; drawComponent() translates by
1049 * getScrollOffset(), so compensate for that first;
1050 * then reset to (0, scale height)
1052 int offset = getAlabels().getScrollOffset();
1053 idGraphics.translate(0, -offset);
1054 idGraphics.translate(0, alignmentDrawnHeight);
1055 getAlabels().drawComponent(idGraphics, idWidth);
1056 idGraphics.translate(0, -alignmentDrawnHeight);
1059 * draw the annotations starting at
1060 * (idOffset, alignmentHeight) from (0, scaleHeight)
1062 alignmentGraphics.translate(alignmentGraphicsOffset,
1063 alignmentDrawnHeight);
1064 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1065 alignmentGraphics, -1, startRes, endRes + 1);
1068 return Printable.PAGE_EXISTS;
1072 * Prints one page of an alignment in wrapped mode. Returns
1073 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1074 * no page could be drawn (page number out of range).
1084 * @throws PrinterException
1086 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1087 Graphics g) throws PrinterException
1090 int annotationHeight = 0;
1091 if (av.isShowAnnotation())
1093 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1096 int hgap = av.getCharHeight();
1097 if (av.getScaleAboveWrapped())
1099 hgap += av.getCharHeight();
1102 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1105 int idWidth = getVisibleIdWidth(false);
1107 int maxwidth = av.getAlignment().getVisibleWidth();
1109 int resWidth = getSeqPanel().seqCanvas
1110 .getWrappedCanvasWidth(pageWidth - idWidth);
1112 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1116 g.setColor(Color.white);
1117 g.fillRect(0, 0, pageWidth, pageHeight);
1118 g.setFont(av.getFont());
1119 g.setColor(Color.black);
1122 * method: print the whole wrapped alignment, but with a clip region that
1123 * is restricted to the requested page; this supports selective print of
1124 * single pages or ranges, (at the cost of some repeated processing in
1125 * the 'normal' case, when all pages are printed)
1127 g.translate(0, -pageNumber * pageHeight);
1129 // BH 2020.03.19 avoiding g.setClip
1130 g.clipRect(0, pageNumber * pageHeight, pageWidth, pageHeight);
1133 * draw sequence ids and annotation labels (if shown)
1135 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1136 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1138 g.translate(idWidth, 0);
1140 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1144 if ((pageNumber * pageHeight) < totalHeight)
1146 return Printable.PAGE_EXISTS;
1150 return Printable.NO_SUCH_PAGE;
1155 * get current sequence ID panel width, or nominal value if panel were to be
1156 * displayed using default settings
1160 public int getVisibleIdWidth()
1162 return getVisibleIdWidth(true);
1166 * get current sequence ID panel width, or nominal value if panel were to be
1167 * displayed using default settings
1170 * indicate if the Id width for onscreen or offscreen display should
1174 public int getVisibleIdWidth(boolean onscreen)
1176 // see if rendering offscreen - check preferences and calc width accordingly
1177 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1179 return calculateIdWidth(-1).width + 4;
1181 Integer idwidth = null;
1182 if (onscreen || (idwidth = Cache
1183 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1185 int w = getIdPanel().getWidth();
1186 return (w > 0 ? w : calculateIdWidth().width + 4);
1188 return idwidth.intValue() + 4;
1192 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1193 * writes it to the specified file
1198 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1200 final int borderBottomOffset = 5;
1202 AlignmentDimension aDimension = getAlignmentDimension();
1203 // todo use a lambda function in place of callback here?
1204 ImageWriterI writer = new ImageWriterI()
1207 public void exportImage(Graphics graphics) throws Exception
1209 if (av.getWrapAlignment())
1211 printWrappedAlignment(aDimension.getWidth(),
1212 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1216 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1217 graphics, graphics);
1222 String fileTitle = alignFrame.getTitle();
1223 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1225 int imageWidth = aDimension.getWidth();
1226 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1227 String of = MessageManager.getString("label.alignment");
1228 exporter.doExport(file, this, imageWidth, imageHeight, of);
1232 * Calculates and returns a suitable width and height (in pixels) for an
1237 public AlignmentDimension getAlignmentDimension()
1239 int maxwidth = av.getAlignment().getVisibleWidth();
1241 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1242 + getScalePanel().getHeight();
1243 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1245 if (av.getWrapAlignment())
1247 height = getWrappedHeight();
1248 if (Jalview.isHeadlessMode())
1250 // need to obtain default alignment width and then add in any
1251 // additional allowance for id margin
1252 // this duplicates the calculation in getWrappedHeight but adjusts for
1254 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1255 - alignFrame.getInsets().left - alignFrame.getInsets().right
1256 - getVisibleIdWidth() + getVisibleIdWidth(false);
1260 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1264 else if (av.isShowAnnotation())
1266 height += getAnnotationPanel().adjustPanelHeight() + 3;
1268 return new AlignmentDimension(width, height);
1272 public void makePNGImageMap(File imgMapFile, String imageName)
1274 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1275 // ////////////////////////////////////////////
1276 int idWidth = getVisibleIdWidth(false);
1277 FontMetrics fm = getFontMetrics(av.getFont());
1278 int scaleHeight = av.getCharHeight() + fm.getDescent();
1281 // ////////////////////////////////
1282 if (imgMapFile != null)
1286 int sSize = av.getAlignment().getHeight();
1287 int alwidth = av.getAlignment().getWidth();
1288 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1289 out.println(HTMLOutput.getImageMapHTML());
1290 out.println("<img src=\"" + imageName
1291 + "\" border=\"0\" usemap=\"#Map\" >"
1292 + "<map name=\"Map\">");
1294 for (int s = 0; s < sSize; s++)
1296 int sy = s * av.getCharHeight() + scaleHeight;
1298 SequenceI seq = av.getAlignment().getSequenceAt(s);
1299 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1300 for (int column = 0; column < alwidth; column++)
1302 StringBuilder text = new StringBuilder(512);
1303 String triplet = null;
1304 if (av.getAlignment().isNucleotide())
1306 triplet = ResidueProperties.nucleotideName.get(seq
1307 .getCharAt(column) + "");
1311 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1315 if (triplet == null)
1320 int seqPos = seq.findPosition(column);
1321 int gSize = groups.length;
1322 for (int g = 0; g < gSize; g++)
1324 if (text.length() < 1)
1326 text.append("<area shape=\"rect\" coords=\"")
1327 .append((idWidth + column * av.getCharWidth()))
1328 .append(",").append(sy).append(",")
1329 .append((idWidth + (column + 1) * av.getCharWidth()))
1330 .append(",").append((av.getCharHeight() + sy))
1331 .append("\"").append(" onMouseOver=\"toolTip('")
1332 .append(seqPos).append(" ").append(triplet);
1335 if (groups[g].getStartRes() < column
1336 && groups[g].getEndRes() > column)
1338 text.append("<br><em>").append(groups[g].getName())
1343 if (text.length() < 1)
1345 text.append("<area shape=\"rect\" coords=\"")
1346 .append((idWidth + column * av.getCharWidth()))
1347 .append(",").append(sy).append(",")
1348 .append((idWidth + (column + 1) * av.getCharWidth()))
1349 .append(",").append((av.getCharHeight() + sy))
1350 .append("\"").append(" onMouseOver=\"toolTip('")
1351 .append(seqPos).append(" ").append(triplet);
1353 if (!Comparison.isGap(seq.getCharAt(column)))
1355 List<SequenceFeature> features = seq.findFeatures(column, column);
1356 for (SequenceFeature sf : features)
1358 if (sf.isContactFeature())
1360 text.append("<br>").append(sf.getType()).append(" ")
1361 .append(sf.getBegin()).append(":")
1362 .append(sf.getEnd());
1366 text.append("<br>");
1367 text.append(sf.getType());
1368 String description = sf.getDescription();
1369 if (description != null
1370 && !sf.getType().equals(description))
1372 description = description.replace("\"", """);
1373 text.append(" ").append(description);
1376 String status = sf.getStatus();
1377 if (status != null && !"".equals(status))
1379 text.append(" (").append(status).append(")");
1382 if (text.length() > 1)
1384 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1385 out.println(text.toString());
1390 out.println("</map></body></html>");
1393 } catch (Exception ex)
1395 ex.printStackTrace();
1397 } // /////////END OF IMAGE MAP
1401 int getWrappedHeight()
1403 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1405 if (Jalview.isHeadlessMode())
1407 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1408 - vscroll.getPreferredSize().width
1409 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1412 int chunkWidth = getSeqPanel().seqCanvas
1413 .getWrappedCanvasWidth(seqPanelWidth);
1415 int hgap = av.getCharHeight();
1416 if (av.getScaleAboveWrapped())
1418 hgap += av.getCharHeight();
1421 int annotationHeight = 0;
1422 if (av.isShowAnnotation())
1424 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1427 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1430 int maxwidth = av.getAlignment().getWidth();
1431 if (av.hasHiddenColumns())
1433 maxwidth = av.getAlignment().getHiddenColumns()
1434 .absoluteToVisibleColumn(maxwidth) - 1;
1437 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1443 * close the panel - deregisters all listeners and nulls any references to
1446 public void closePanel()
1448 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1449 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1450 PaintRefresher.RemoveComponent(this);
1455 * try to ensure references are nulled
1457 if (annotationPanel != null)
1459 annotationPanel.dispose();
1460 annotationPanel = null;
1465 av.removePropertyChangeListener(propertyChangeListener);
1466 propertyChangeListener = null;
1467 StructureSelectionManager ssm = av.getStructureSelectionManager();
1468 ssm.removeStructureViewerListener(getSeqPanel(), null);
1469 ssm.removeSelectionListener(getSeqPanel());
1470 ssm.removeCommandListener(av);
1471 ssm.removeStructureViewerListener(getSeqPanel(), null);
1472 ssm.removeSelectionListener(getSeqPanel());
1478 if (Cache.log.isDebugEnabled())
1480 Cache.log.warn("Closing alignment panel which is already closed.");
1486 * Close any open dialogs that would be orphaned when this one is closed
1488 protected void closeChildFrames()
1490 if (overviewPanel != null)
1492 overviewPanel.dispose();
1493 overviewPanel = null;
1495 if (calculationDialog != null)
1497 calculationDialog.closeFrame();
1498 calculationDialog = null;
1503 * hides or shows dynamic annotation rows based on groups and av state flags
1505 public void updateAnnotation()
1507 updateAnnotation(false, false);
1510 public void updateAnnotation(boolean applyGlobalSettings)
1512 updateAnnotation(applyGlobalSettings, false);
1515 public void updateAnnotation(boolean applyGlobalSettings,
1516 boolean preserveNewGroupSettings)
1518 av.updateGroupAnnotationSettings(applyGlobalSettings,
1519 preserveNewGroupSettings);
1520 adjustAnnotationHeight();
1524 public AlignmentI getAlignment()
1526 return av == null ? null : av.getAlignment();
1530 public String getViewName()
1532 return av.getViewName();
1536 * Make/Unmake this alignment panel the current input focus
1540 public void setSelected(boolean b)
1544 if (alignFrame.getSplitViewContainer() != null)
1547 * bring enclosing SplitFrame to front first if there is one
1549 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1551 alignFrame.setSelected(b);
1552 } catch (Exception ex)
1558 alignFrame.setDisplayedView(this);
1563 public StructureSelectionManager getStructureSelectionManager()
1565 return av.getStructureSelectionManager();
1569 public void raiseOOMWarning(String string, OutOfMemoryError error)
1571 new OOMWarning(string, error, this);
1575 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1578 return new FeatureRenderer(this);
1582 public jalview.api.FeatureRenderer getFeatureRenderer()
1584 return seqPanel.seqCanvas.getFeatureRenderer();
1587 public void updateFeatureRenderer(
1588 jalview.renderer.seqfeatures.FeatureRenderer fr)
1590 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1593 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1595 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1597 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1601 public ScalePanel getScalePanel()
1606 public void setScalePanel(ScalePanel scalePanel)
1608 this.scalePanel = scalePanel;
1611 public SeqPanel getSeqPanel()
1616 public void setSeqPanel(SeqPanel seqPanel)
1618 this.seqPanel = seqPanel;
1621 public AnnotationPanel getAnnotationPanel()
1623 return annotationPanel;
1626 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1628 this.annotationPanel = annotationPanel;
1631 public AnnotationLabels getAlabels()
1636 public void setAlabels(AnnotationLabels alabels)
1638 this.alabels = alabels;
1641 public IdPanel getIdPanel()
1646 public void setIdPanel(IdPanel idPanel)
1648 this.idPanel = idPanel;
1652 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1653 * The aim is to keep the two alignments 'lined up' on their centre columns.
1656 * holds mapped region(s) of this alignment that we are scrolling
1657 * 'to'; may be modified for sequence offset by this method
1658 * @param verticalOffset
1659 * the number of visible sequences to show above the mapped region
1661 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1663 scrollToPosition(sr, verticalOffset, true);
1667 * Set a flag to say do not scroll any (cDNA/protein) complement.
1671 protected void setToScrollComplementPanel(boolean b)
1673 this.scrollComplementaryPanel = b;
1677 * Get whether to scroll complement panel
1679 * @return true if cDNA/protein complement panels should be scrolled
1681 protected boolean isSetToScrollComplementPanel()
1683 return this.scrollComplementaryPanel;
1689 * @adjustHeight if true, try to recalculate panel height for visible
1692 protected void refresh(boolean adjustHeight)
1694 validateAnnotationDimensions(adjustHeight);
1698 // sort, repaint, update overview
1699 paintAlignment(true, false);
1703 // lightweight repaint
1710 * Property change event fired when a change is made to the viewport ranges
1711 * object associated with this alignment panel's viewport
1713 public void propertyChange(PropertyChangeEvent evt)
1715 // update this panel's scroll values based on the new viewport ranges values
1716 ViewportRanges ranges = av.getRanges();
1717 int x = ranges.getStartRes();
1718 int y = ranges.getStartSeq();
1719 setScrollValues(x, y);
1721 // now update any complementary alignment (its viewport ranges object
1722 // is different so does not get automatically updated)
1723 if (isSetToScrollComplementPanel())
1725 setToScrollComplementPanel(false);
1726 av.scrollComplementaryAlignment();
1727 setToScrollComplementPanel(true);
1732 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1733 * reference should be nulled when the dialog is closed.
1735 * @param calculationChooser
1737 public void setCalculationDialog(CalculationChooser calculationChooser)
1739 calculationDialog = calculationChooser;
1743 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1746 public CalculationChooser getCalculationDialog()
1748 return calculationDialog;
1752 public SequenceRenderer getSequenceRenderer()
1754 return seqPanel.seqCanvas.getSequenceRenderer();
1757 public boolean scrollTo(int ostart, int end, int seqIndex,
1758 boolean scrollToNearest, boolean redrawOverview)
1760 int startv, endv, starts, ends;// , width;
1763 if (av.hasHiddenColumns())
1765 AlignmentI al = av.getAlignment();
1766 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1767 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1770 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1772 // don't scroll - position isn't visible
1782 ViewportRanges ranges = av.getRanges();
1783 if (!av.getWrapAlignment())
1786 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1787 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1788 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1789 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1790 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1791 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1792 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1793 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1796 // below is scrolling logic up to Jalview 2.8.2
1797 // if ((av.getStartRes() > end)
1798 // || (av.getEndRes() < start)
1799 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1801 // if (start > av.getAlignment().getWidth() - hextent)
1803 // start = av.getAlignment().getWidth() - hextent;
1810 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1812 // seqIndex = av.getAlignment().getHeight() - vextent;
1813 // if (seqIndex < 0)
1818 // setScrollValues(start, seqIndex);
1820 // logic copied from jalview.gui.AlignmentPanel:
1821 if ((startv = ranges.getStartRes()) >= start)
1824 * Scroll left to make start of search results visible
1826 setScrollValues(start - 1, seqIndex);
1828 else if ((endv = ranges.getEndRes()) <= end)
1831 * Scroll right to make end of search results visible
1833 setScrollValues(startv + 1 + end - endv, seqIndex);
1835 else if ((starts = ranges.getStartSeq()) > seqIndex)
1838 * Scroll up to make start of search results visible
1840 setScrollValues(ranges.getStartRes(), seqIndex);
1842 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1845 * Scroll down to make end of search results visible
1847 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1850 * Else results are already visible - no need to scroll
1855 ranges.scrollToWrappedVisible(start);
1858 paintAlignment(redrawOverview, false);
1863 public void overviewDone(BufferedImage miniMe)
1865 overviewPanel.canvas.finalizeDraw(miniMe);
1869 private boolean holdRepaint = false;
1871 public boolean getHoldRepaint()
1876 public void setHoldRepaint(boolean b)
1878 if (holdRepaint == b)
1890 public void repaint()
1894 // System.out.println("AP repaint holding");
1895 // Platform.stackTrace();