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;
70 import javax.swing.SwingUtilities;
73 * The main panel of an AlignFrame, containing holders for the IdPanel,
74 * SeqPanel, AnnotationLabels (a JPanel), and AnnotationPanel.
76 * Additional holders contain an IdPanelWidthAdjuster space above the idPanel,
77 * AnnotationScroller (JScrollPane for AnnotationPanel), and vertical and
78 * horizontal scrollbars.
83 * @version $Revision: 1.161 $
85 @SuppressWarnings("serial")
86 public class AlignmentPanel extends GAlignmentPanel implements
87 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
89 public AlignViewport av;
91 OverviewPanel overviewPanel;
93 private SeqPanel seqPanel;
95 private IdPanel idPanel;
97 IdwidthAdjuster idwidthAdjuster;
99 public AlignFrame alignFrame;
101 private ScalePanel scalePanel;
103 private AnnotationPanel annotationPanel;
105 private AnnotationLabels alabels;
107 private int hextent = 0;
109 private int vextent = 0;
112 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
113 * false, suppresses invoking the same method recursively.
115 private boolean scrollComplementaryPanel = true;
117 private PropertyChangeListener propertyChangeListener;
119 private CalculationChooser calculationDialog;
122 * Creates a new AlignmentPanel object.
127 public AlignmentPanel(AlignFrame af, final AlignViewport av)
129 setBackground(Color.white); // BH 2019
133 setSeqPanel(new SeqPanel(av, this));
134 setIdPanel(new IdPanel(av, this));
136 setScalePanel(new ScalePanel(av, this));
138 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
139 idwidthAdjuster = new IdwidthAdjuster(this);
140 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
142 setAnnotationPanel(new AnnotationPanel(this));
143 setAlabels(new AnnotationLabels(this));
145 annotationScroller.setViewportView(getAnnotationPanel());
146 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
147 if (!av.isShowAnnotation())
149 annotationScroller.setVisible(false);
150 annotationSpaceFillerHolder.setVisible(false);
152 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
153 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
155 setScrollValues(0, 0);
157 hscroll.addAdjustmentListener(this);
158 vscroll.addAdjustmentListener(this);
160 addComponentListener(new ComponentAdapter()
163 public void componentResized(ComponentEvent evt)
165 // reset the viewport ranges when the alignment panel is resized
166 // in particular, this initialises the end residue value when Jalview
168 ViewportRanges ranges = av.getRanges();
169 if (av.getWrapAlignment())
171 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
172 getSeqPanel().seqCanvas.getWidth());
173 ranges.setViewportWidth(widthInRes);
177 int widthInRes = getSeqPanel().seqCanvas.getWidth()
179 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
180 / av.getCharHeight();
182 ranges.setViewportWidth(widthInRes);
183 ranges.setViewportHeight(heightInSeq);
189 final AlignmentPanel ap = this;
190 propertyChangeListener = new PropertyChangeListener()
193 public void propertyChange(PropertyChangeEvent evt)
195 if (evt.getPropertyName().equals("alignment"))
197 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
202 av.addPropertyChangeListener(propertyChangeListener);
204 av.getRanges().addPropertyChangeListener(this);
206 adjustAnnotationHeight();
211 public AlignViewportI getAlignViewport()
216 public void alignmentChanged()
218 av.alignmentChanged(this);
220 if (getCalculationDialog() != null)
222 getCalculationDialog().validateCalcTypes();
225 alignFrame.updateEditMenuBar();
227 // no idea if we need to update structure
228 paintAlignment(true, true);
235 public void fontChanged()
237 // set idCanvas bufferedImage to null
238 // to prevent drawing old image
239 FontMetrics fm = getFontMetrics(av.getFont());
241 scalePanelHolder.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idSpaceFillerPanel1.setPreferredSize(
244 new Dimension(10, av.getCharHeight() + fm.getDescent()));
245 idwidthAdjuster.invalidate();
246 scalePanelHolder.invalidate();
247 // BH 2018 getIdPanel().getIdCanvas().gg = null;
248 getSeqPanel().seqCanvas.img = null;
249 getAnnotationPanel().adjustPanelHeight();
251 Dimension d = calculateIdWidth();
253 d.setSize(d.width + 4, d.height);
254 getIdPanel().getIdCanvas().setPreferredSize(d);
255 hscrollFillerPanel.setPreferredSize(d);
261 * Calculate the width of the alignment labels based on the displayed names
262 * and any bounds on label width set in preferences.
264 * @return Dimension giving the maximum width of the alignment label panel
265 * that should be used.
267 public Dimension calculateIdWidth()
269 // calculate sensible default width when no preference is available
271 if (av.getIdWidth() < 0)
273 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
274 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
275 r = calculateIdWidth(maxwidth);
276 av.setIdWidth(r.width);
281 r.width = av.getIdWidth();
288 * Calculate the width of the alignment labels based on the displayed names
289 * and any bounds on label width set in preferences.
292 * -1 or maximum width allowed for IdWidth
293 * @return Dimension giving the maximum width of the alignment label panel
294 * that should be used.
296 public Dimension calculateIdWidth(int maxwidth)
298 Container c = new Container();
300 FontMetrics fm = c.getFontMetrics(
301 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
303 AlignmentI al = av.getAlignment();
308 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
310 SequenceI s = al.getSequenceAt(i);
312 id = s.getDisplayId(av.getShowJVSuffix());
314 if (fm.stringWidth(id) > idWidth)
316 idWidth = fm.stringWidth(id);
322 // Also check annotation label widths
325 if (al.getAlignmentAnnotation() != null)
327 fm = c.getFontMetrics(getAlabels().getFont());
329 while (i < al.getAlignmentAnnotation().length)
331 String label = al.getAlignmentAnnotation()[i].label;
333 if (fm.stringWidth(label) > idWidth)
335 idWidth = fm.stringWidth(label);
342 return new Dimension(
343 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
347 * Highlight the given results on the alignment
350 public void highlightSearchResults(SearchResultsI results)
352 boolean scrolled = scrollToPosition(results, 0, false);
354 boolean fastPaint = !(scrolled && av.getWrapAlignment());
356 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
360 * Scroll the view to show the position of the highlighted region in results
363 * @param searchResults
366 public boolean scrollToPosition(SearchResultsI searchResults)
368 return scrollToPosition(searchResults, 0, false);
372 * Scrolls the view (if necessary) to show the position of the first
373 * highlighted region in results (if any). Answers true if the view was
374 * scrolled, or false if no matched region was found, or it is already
378 * @param verticalOffset
379 * if greater than zero, allows scrolling to a position below the
380 * first displayed sequence
382 * if true, try to centre the search results horizontally in the view
385 protected boolean scrollToPosition(SearchResultsI results,
386 int verticalOffset, boolean centre)
388 int startv, endv, starts, ends;
389 ViewportRanges ranges = av.getRanges();
391 if (results == null || results.isEmpty() || av == null
392 || av.getAlignment() == null)
396 int seqIndex = av.getAlignment().findIndex(results);
401 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
403 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
412 * To centre results, scroll to positions half the visible width
413 * left/right of the start/end positions
417 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
418 start = Math.max(start - offset, 0);
419 end = end + offset - 1;
425 if (end == seq.getEnd())
430 if (av.hasHiddenColumns())
432 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
433 start = hidden.absoluteToVisibleColumn(start);
434 end = hidden.absoluteToVisibleColumn(end);
437 if (!hidden.isVisible(r[0]))
439 // don't scroll - position isn't visible
446 * allow for offset of target sequence (actually scroll to one above it)
448 seqIndex = Math.max(0, seqIndex - verticalOffset);
449 boolean scrollNeeded = true;
451 if (!av.getWrapAlignment())
453 if ((startv = ranges.getStartRes()) >= start)
456 * Scroll left to make start of search results visible
458 setScrollValues(start, seqIndex);
460 else if ((endv = ranges.getEndRes()) <= end)
463 * Scroll right to make end of search results visible
465 setScrollValues(startv + end - endv, seqIndex);
467 else if ((starts = ranges.getStartSeq()) > seqIndex)
470 * Scroll up to make start of search results visible
472 setScrollValues(ranges.getStartRes(), seqIndex);
474 else if ((ends = ranges.getEndSeq()) <= seqIndex)
477 * Scroll down to make end of search results visible
479 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
483 * Else results are already visible - no need to scroll
485 scrollNeeded = false;
489 scrollNeeded = ranges.scrollToWrappedVisible(start);
492 paintAlignment(false, false);
500 * @return DOCUMENT ME!
502 public OverviewPanel getOverviewPanel()
504 return overviewPanel;
513 public void setOverviewPanel(OverviewPanel op)
521 * Hide or show annotation panel
524 public void setAnnotationVisible(boolean b)
526 if (!av.getWrapAlignment())
528 annotationSpaceFillerHolder.setVisible(b);
529 annotationScroller.setVisible(b);
535 * automatically adjust annotation panel height for new annotation whilst
536 * ensuring the alignment is still visible.
539 public void adjustAnnotationHeight()
541 // TODO: display vertical annotation scrollbar if necessary
542 // this is called after loading new annotation onto alignment
543 if (alignFrame.getHeight() == 0)
545 System.out.println("NEEDS FIXING");
547 validateAnnotationDimensions(true);
549 // TODO: many places call this method and also paintAlignment with various
550 // different settings. this means multiple redraws are triggered...
551 paintAlignment(true, av.needToUpdateStructureViews());
555 * calculate the annotation dimensions and refresh slider values accordingly.
556 * need to do repaints/notifys afterwards.
558 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
560 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
561 // are not changing ancestors, and keyboard action listeners do
562 // not need to be reset. addNotify() is a very expensive operation,
563 // requiring a full re-layout of all parents and children.
564 // Note in JComponent:
565 // This method is called by the toolkit internally and should
566 // not be called directly by programs.
567 // I note that addNotify() is called in several areas of Jalview.
569 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
570 annotationHeight = getAnnotationPanel()
571 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
574 annotationScroller.setPreferredSize(
575 new Dimension(annotationScroller.getWidth(), annotationHeight));
577 Dimension e = idPanel.getSize();
578 alabels.setSize(new Dimension(e.width, annotationHeight));
581 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
582 annotationSpaceFillerHolder.getWidth(), annotationHeight));
583 annotationScroller.validate();
584 annotationScroller.addNotify();
588 * update alignment layout for viewport settings
593 public void updateLayout()
595 fontChanged(); // fires repaint
596 setAnnotationVisible(av.isShowAnnotation());
597 boolean wrap = av.getWrapAlignment();
598 ViewportRanges ranges = av.getRanges();
599 ranges.setStartSeq(0);
600 scalePanelHolder.setVisible(!wrap);
601 hscroll.setVisible(!wrap);
602 idwidthAdjuster.setVisible(!wrap);
606 annotationScroller.setVisible(false);
607 annotationSpaceFillerHolder.setVisible(false);
609 else if (av.isShowAnnotation())
611 annotationScroller.setVisible(true);
612 annotationSpaceFillerHolder.setVisible(true);
613 validateAnnotationDimensions(false);
616 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
618 { // may not yet be laid out
621 int widthInRes = getSeqPanel().seqCanvas
622 .getWrappedCanvasWidth(canvasWidth);
623 ranges.setViewportWidth(widthInRes);
627 int widthInRes = (canvasWidth / av.getCharWidth());
628 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
629 / av.getCharHeight());
631 ranges.setViewportWidth(widthInRes);
632 ranges.setViewportHeight(heightInSeq);
636 idSpaceFillerPanel1.setVisible(!wrap);
642 * Adjust row/column scrollers to show a visible position in the alignment.
645 * visible column to scroll to
647 * visible row to scroll to
650 public void setScrollValues(int xpos, int ypos)
655 if (av == null || av.getAlignment() == null)
660 if (av.getWrapAlignment())
662 setScrollingForWrappedPanel(x);
666 int width = av.getAlignment().getVisibleWidth();
667 int height = av.getAlignment().getHeight();
669 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
670 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
677 if (vextent > height)
682 if ((hextent + x) > width)
687 if ((vextent + y) > height)
689 y = height - vextent;
702 // update the scroll values
703 hscroll.setValues(x, hextent, 0, width);
704 vscroll.setValues(y, vextent, 0, height);
709 * Respond to adjustment event when horizontal or vertical scrollbar is
713 * adjustment event encoding whether hscroll or vscroll changed
716 public void adjustmentValueChanged(AdjustmentEvent evt)
718 if (av.getWrapAlignment())
720 adjustScrollingWrapped(evt);
724 ViewportRanges ranges = av.getRanges();
726 if (evt.getSource() == hscroll)
728 int oldX = ranges.getStartRes();
729 int oldwidth = ranges.getViewportWidth();
730 int x = hscroll.getValue();
731 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
733 // if we're scrolling to the position we're already at, stop
734 // this prevents infinite recursion of events when the scroll/viewport
735 // ranges values are the same
736 if ((x == oldX) && (width == oldwidth))
740 ranges.setViewportStartAndWidth(x, width);
742 else if (evt.getSource() == vscroll)
744 int oldY = ranges.getStartSeq();
745 int oldheight = ranges.getViewportHeight();
746 int y = vscroll.getValue();
747 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
749 // if we're scrolling to the position we're already at, stop
750 // this prevents infinite recursion of events when the scroll/viewport
751 // ranges values are the same
752 if ((y == oldY) && (height == oldheight))
756 ranges.setViewportStartAndHeight(y, height);
762 * Responds to a scroll change by setting the start position of the viewport.
767 protected void adjustScrollingWrapped(AdjustmentEvent evt)
769 if (evt.getSource() == hscroll)
771 return; // no horizontal scroll when wrapped
773 final ViewportRanges ranges = av.getRanges();
775 if (evt.getSource() == vscroll)
777 int newY = vscroll.getValue();
780 * if we're scrolling to the position we're already at, stop
781 * this prevents infinite recursion of events when the scroll/viewport
782 * ranges values are the same
784 int oldX = ranges.getStartRes();
785 int oldY = ranges.getWrappedScrollPosition(oldX);
793 * limit page up/down to one width's worth of positions
795 int rowSize = ranges.getViewportWidth();
796 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
797 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
802 // This is only called if file loaded is a jar file that
803 // was wrapped when saved and user has wrap alignment true
804 // as preference setting
805 SwingUtilities.invokeLater(new Runnable()
810 // When updating scrolling to use ViewportChange events, this code
811 // could not be validated and it is not clear if it is now being
812 // called. Log warning here in case it is called and unforeseen
815 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
817 // scroll to start of panel
818 ranges.setStartRes(0);
819 ranges.setStartSeq(0);
827 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
830 public void paintAlignment(boolean updateOverview,
831 boolean updateStructures)
833 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
834 av.isShowAutocalculatedAbove());
835 sorter.sort(getAlignment().getAlignmentAnnotation(),
836 av.getSortAnnotationsBy());
839 if (updateStructures)
841 av.getStructureSelectionManager().sequenceColoursChanged(this);
845 if (overviewPanel != null)
847 overviewPanel.updateOverviewImage();
859 public void paintComponent(Graphics g)
862 invalidate(); // needed so that the id width adjuster works correctly
864 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
865 idPanelHolder.setPreferredSize(d);
866 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
868 validate(); // needed so that the id width adjuster works correctly
871 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
872 * though I still think this call should be elsewhere.
874 ViewportRanges ranges = av.getRanges();
875 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
876 super.paintComponent(g);
880 * Set vertical scroll bar position, and number of increments, for wrapped
883 * @param topLeftColumn
884 * the column position at top left (0..)
886 private void setScrollingForWrappedPanel(int topLeftColumn)
888 ViewportRanges ranges = av.getRanges();
889 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
890 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
893 * a scrollbar's value can be set to at most (maximum-extent)
894 * so we add extent (1) to the maxScroll value
896 vscroll.setUnitIncrement(1);
897 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
910 * @return DOCUMENT ME!
912 * @throws PrinterException
916 public int print(Graphics pg, PageFormat pf, int pi)
917 throws PrinterException
919 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
921 int pwidth = (int) pf.getImageableWidth();
922 int pheight = (int) pf.getImageableHeight();
924 if (av.getWrapAlignment())
926 return printWrappedAlignment(pwidth, pheight, pi, pg);
930 return printUnwrapped(pwidth, pheight, pi, pg, pg);
935 * Draws the alignment image, including sequence ids, sequences, and
936 * annotation labels and annotations if shown, on either one or two Graphics
946 * the graphics context for sequence ids and annotation labels
947 * @param alignmentGraphics
948 * the graphics context for sequences and annotations (may or may not
949 * be the same context as idGraphics)
951 * @throws PrinterException
953 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
954 Graphics idGraphics, Graphics alignmentGraphics)
955 throws PrinterException
957 final int idWidth = getVisibleIdWidth(false);
960 * Get the horizontal offset to where we draw the sequences.
961 * This is idWidth if using a single Graphics context, else zero.
963 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
966 FontMetrics fm = getFontMetrics(av.getFont());
967 final int charHeight = av.getCharHeight();
968 final int scaleHeight = charHeight + fm.getDescent();
970 idGraphics.setColor(Color.white);
971 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
972 idGraphics.setFont(av.getFont());
975 * How many sequences and residues can we fit on a printable page?
977 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
979 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
981 final int alignmentWidth = av.getAlignment().getVisibleWidth();
982 int pagesWide = (alignmentWidth / totalRes) + 1;
984 final int startRes = (pageIndex % pagesWide) * totalRes;
985 final int endRes = Math.min(startRes + totalRes - 1,
988 final int startSeq = (pageIndex / pagesWide) * totalSeq;
989 final int alignmentHeight = av.getAlignment().getHeight();
990 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
992 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
994 if (av.isShowAnnotation())
996 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
999 pagesHigh /= pageHeight;
1001 if (pageIndex >= (pagesWide * pagesHigh))
1003 return Printable.NO_SUCH_PAGE;
1005 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1008 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1010 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1011 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1012 pageWidth - idWidth, scaleHeight);
1013 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1016 * Draw the sequence ids, offset for scale height,
1017 * then reset to top left (0, 0)
1019 idGraphics.translate(0, scaleHeight);
1020 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1021 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1022 : av.getSelectionGroup().getSequences(null);
1023 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1026 idGraphics.setFont(av.getFont());
1027 idGraphics.translate(0, -scaleHeight);
1030 * draw the sequences, offset for scale height, and id width (if using a
1031 * single graphics context), then reset to (0, scale height)
1033 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1034 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1035 endRes, startSeq, endSeq - 1);
1036 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1038 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1041 * draw annotation labels; drawComponent() translates by
1042 * getScrollOffset(), so compensate for that first;
1043 * then reset to (0, scale height)
1045 int offset = getAlabels().getScrollOffset();
1046 idGraphics.translate(0, -offset);
1047 idGraphics.translate(0, alignmentDrawnHeight);
1048 getAlabels().drawComponent(idGraphics, idWidth);
1049 idGraphics.translate(0, -alignmentDrawnHeight);
1052 * draw the annotations starting at
1053 * (idOffset, alignmentHeight) from (0, scaleHeight)
1055 alignmentGraphics.translate(alignmentGraphicsOffset,
1056 alignmentDrawnHeight);
1057 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1058 alignmentGraphics, -1, startRes, endRes + 1);
1061 return Printable.PAGE_EXISTS;
1065 * Prints one page of an alignment in wrapped mode. Returns
1066 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1067 * no page could be drawn (page number out of range).
1077 * @throws PrinterException
1079 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1080 Graphics g) throws PrinterException
1082 int annotationHeight = 0;
1083 if (av.isShowAnnotation())
1085 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1088 int hgap = av.getCharHeight();
1089 if (av.getScaleAboveWrapped())
1091 hgap += av.getCharHeight();
1094 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1097 int idWidth = getVisibleIdWidth(false);
1099 int maxwidth = av.getAlignment().getVisibleWidth();
1101 int resWidth = getSeqPanel().seqCanvas
1102 .getWrappedCanvasWidth(pageWidth - idWidth);
1104 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1106 g.setColor(Color.white);
1107 g.fillRect(0, 0, pageWidth, pageHeight);
1108 g.setFont(av.getFont());
1109 g.setColor(Color.black);
1112 * method: print the whole wrapped alignment, but with a clip region that
1113 * is restricted to the requested page; this supports selective print of
1114 * single pages or ranges, (at the cost of some repeated processing in
1115 * the 'normal' case, when all pages are printed)
1117 g.translate(0, -pageNumber * pageHeight);
1119 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1122 * draw sequence ids and annotation labels (if shown)
1124 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1125 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1127 g.translate(idWidth, 0);
1129 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1132 if ((pageNumber * pageHeight) < totalHeight)
1134 return Printable.PAGE_EXISTS;
1138 return Printable.NO_SUCH_PAGE;
1143 * get current sequence ID panel width, or nominal value if panel were to be
1144 * displayed using default settings
1148 public int getVisibleIdWidth()
1150 return getVisibleIdWidth(true);
1154 * get current sequence ID panel width, or nominal value if panel were to be
1155 * displayed using default settings
1158 * indicate if the Id width for onscreen or offscreen display should
1162 public int getVisibleIdWidth(boolean onscreen)
1164 // see if rendering offscreen - check preferences and calc width accordingly
1165 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1167 return calculateIdWidth(-1).width + 4;
1169 Integer idwidth = null;
1170 if (onscreen || (idwidth = Cache
1171 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1173 int w = getIdPanel().getWidth();
1174 return (w > 0 ? w : calculateIdWidth().width + 4);
1176 return idwidth.intValue() + 4;
1180 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1181 * writes it to the specified file
1186 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1188 final int borderBottomOffset = 5;
1190 AlignmentDimension aDimension = getAlignmentDimension();
1191 // todo use a lambda function in place of callback here?
1192 ImageWriterI writer = new ImageWriterI()
1195 public void exportImage(Graphics graphics) throws Exception
1197 if (av.getWrapAlignment())
1199 printWrappedAlignment(aDimension.getWidth(),
1200 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1204 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1205 graphics, graphics);
1210 String fileTitle = alignFrame.getTitle();
1211 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1213 int imageWidth = aDimension.getWidth();
1214 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1215 String of = MessageManager.getString("label.alignment");
1216 exporter.doExport(file, this, imageWidth, imageHeight, of);
1220 * Calculates and returns a suitable width and height (in pixels) for an
1225 public AlignmentDimension getAlignmentDimension()
1227 int maxwidth = av.getAlignment().getVisibleWidth();
1229 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1230 + getScalePanel().getHeight();
1231 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1233 if (av.getWrapAlignment())
1235 height = getWrappedHeight();
1236 if (Jalview.isHeadlessMode())
1238 // need to obtain default alignment width and then add in any
1239 // additional allowance for id margin
1240 // this duplicates the calculation in getWrappedHeight but adjusts for
1242 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1243 - alignFrame.getInsets().left - alignFrame.getInsets().right
1244 - getVisibleIdWidth() + getVisibleIdWidth(false);
1248 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1252 else if (av.isShowAnnotation())
1254 height += getAnnotationPanel().adjustPanelHeight() + 3;
1256 return new AlignmentDimension(width, height);
1260 public void makePNGImageMap(File imgMapFile, String imageName)
1262 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1263 // ////////////////////////////////////////////
1264 int idWidth = getVisibleIdWidth(false);
1265 FontMetrics fm = getFontMetrics(av.getFont());
1266 int scaleHeight = av.getCharHeight() + fm.getDescent();
1269 // ////////////////////////////////
1270 if (imgMapFile != null)
1274 int sSize = av.getAlignment().getHeight();
1275 int alwidth = av.getAlignment().getWidth();
1276 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1277 out.println(HTMLOutput.getImageMapHTML());
1278 out.println("<img src=\"" + imageName
1279 + "\" border=\"0\" usemap=\"#Map\" >"
1280 + "<map name=\"Map\">");
1282 for (int s = 0; s < sSize; s++)
1284 int sy = s * av.getCharHeight() + scaleHeight;
1286 SequenceI seq = av.getAlignment().getSequenceAt(s);
1287 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1288 for (int column = 0; column < alwidth; column++)
1290 StringBuilder text = new StringBuilder(512);
1291 String triplet = null;
1292 if (av.getAlignment().isNucleotide())
1294 triplet = ResidueProperties.nucleotideName.get(seq
1295 .getCharAt(column) + "");
1299 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1303 if (triplet == null)
1308 int seqPos = seq.findPosition(column);
1309 int gSize = groups.length;
1310 for (int g = 0; g < gSize; g++)
1312 if (text.length() < 1)
1314 text.append("<area shape=\"rect\" coords=\"")
1315 .append((idWidth + column * av.getCharWidth()))
1316 .append(",").append(sy).append(",")
1317 .append((idWidth + (column + 1) * av.getCharWidth()))
1318 .append(",").append((av.getCharHeight() + sy))
1319 .append("\"").append(" onMouseOver=\"toolTip('")
1320 .append(seqPos).append(" ").append(triplet);
1323 if (groups[g].getStartRes() < column
1324 && groups[g].getEndRes() > column)
1326 text.append("<br><em>").append(groups[g].getName())
1331 if (text.length() < 1)
1333 text.append("<area shape=\"rect\" coords=\"")
1334 .append((idWidth + column * av.getCharWidth()))
1335 .append(",").append(sy).append(",")
1336 .append((idWidth + (column + 1) * av.getCharWidth()))
1337 .append(",").append((av.getCharHeight() + sy))
1338 .append("\"").append(" onMouseOver=\"toolTip('")
1339 .append(seqPos).append(" ").append(triplet);
1341 if (!Comparison.isGap(seq.getCharAt(column)))
1343 List<SequenceFeature> features = seq.findFeatures(column, column);
1344 for (SequenceFeature sf : features)
1346 if (sf.isContactFeature())
1348 text.append("<br>").append(sf.getType()).append(" ")
1349 .append(sf.getBegin()).append(":")
1350 .append(sf.getEnd());
1354 text.append("<br>");
1355 text.append(sf.getType());
1356 String description = sf.getDescription();
1357 if (description != null
1358 && !sf.getType().equals(description))
1360 description = description.replace("\"", """);
1361 text.append(" ").append(description);
1364 String status = sf.getStatus();
1365 if (status != null && !"".equals(status))
1367 text.append(" (").append(status).append(")");
1370 if (text.length() > 1)
1372 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1373 out.println(text.toString());
1378 out.println("</map></body></html>");
1381 } catch (Exception ex)
1383 ex.printStackTrace();
1385 } // /////////END OF IMAGE MAP
1389 int getWrappedHeight()
1391 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1393 if (Jalview.isHeadlessMode())
1395 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1396 - vscroll.getPreferredSize().width
1397 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1400 int chunkWidth = getSeqPanel().seqCanvas
1401 .getWrappedCanvasWidth(seqPanelWidth);
1403 int hgap = av.getCharHeight();
1404 if (av.getScaleAboveWrapped())
1406 hgap += av.getCharHeight();
1409 int annotationHeight = 0;
1410 if (av.isShowAnnotation())
1412 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1415 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1418 int maxwidth = av.getAlignment().getWidth();
1419 if (av.hasHiddenColumns())
1421 maxwidth = av.getAlignment().getHiddenColumns()
1422 .absoluteToVisibleColumn(maxwidth) - 1;
1425 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1431 * close the panel - deregisters all listeners and nulls any references to
1434 public void closePanel()
1436 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1437 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1438 PaintRefresher.RemoveComponent(this);
1443 * try to ensure references are nulled
1445 if (annotationPanel != null)
1447 annotationPanel.dispose();
1448 annotationPanel = null;
1453 av.removePropertyChangeListener(propertyChangeListener);
1454 propertyChangeListener = null;
1455 StructureSelectionManager ssm = av.getStructureSelectionManager();
1456 ssm.removeStructureViewerListener(getSeqPanel(), null);
1457 ssm.removeSelectionListener(getSeqPanel());
1458 ssm.removeCommandListener(av);
1459 ssm.removeStructureViewerListener(getSeqPanel(), null);
1460 ssm.removeSelectionListener(getSeqPanel());
1466 if (Cache.log.isDebugEnabled())
1468 Cache.log.warn("Closing alignment panel which is already closed.");
1474 * Close any open dialogs that would be orphaned when this one is closed
1476 protected void closeChildFrames()
1478 if (overviewPanel != null)
1480 overviewPanel.dispose();
1481 overviewPanel = null;
1483 if (calculationDialog != null)
1485 calculationDialog.closeFrame();
1486 calculationDialog = null;
1491 * hides or shows dynamic annotation rows based on groups and av state flags
1493 public void updateAnnotation()
1495 updateAnnotation(false, false);
1498 public void updateAnnotation(boolean applyGlobalSettings)
1500 updateAnnotation(applyGlobalSettings, false);
1503 public void updateAnnotation(boolean applyGlobalSettings,
1504 boolean preserveNewGroupSettings)
1506 av.updateGroupAnnotationSettings(applyGlobalSettings,
1507 preserveNewGroupSettings);
1508 adjustAnnotationHeight();
1512 public AlignmentI getAlignment()
1514 return av == null ? null : av.getAlignment();
1518 public String getViewName()
1520 return av.getViewName();
1524 * Make/Unmake this alignment panel the current input focus
1528 public void setSelected(boolean b)
1532 if (alignFrame.getSplitViewContainer() != null)
1535 * bring enclosing SplitFrame to front first if there is one
1537 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1539 alignFrame.setSelected(b);
1540 } catch (Exception ex)
1546 alignFrame.setDisplayedView(this);
1551 public StructureSelectionManager getStructureSelectionManager()
1553 return av.getStructureSelectionManager();
1557 public void raiseOOMWarning(String string, OutOfMemoryError error)
1559 new OOMWarning(string, error, this);
1563 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1566 return new FeatureRenderer(this);
1570 public jalview.api.FeatureRenderer getFeatureRenderer()
1572 return seqPanel.seqCanvas.getFeatureRenderer();
1575 public void updateFeatureRenderer(
1576 jalview.renderer.seqfeatures.FeatureRenderer fr)
1578 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1581 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1583 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1585 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1589 public ScalePanel getScalePanel()
1594 public void setScalePanel(ScalePanel scalePanel)
1596 this.scalePanel = scalePanel;
1599 public SeqPanel getSeqPanel()
1604 public void setSeqPanel(SeqPanel seqPanel)
1606 this.seqPanel = seqPanel;
1609 public AnnotationPanel getAnnotationPanel()
1611 return annotationPanel;
1614 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1616 this.annotationPanel = annotationPanel;
1619 public AnnotationLabels getAlabels()
1624 public void setAlabels(AnnotationLabels alabels)
1626 this.alabels = alabels;
1629 public IdPanel getIdPanel()
1634 public void setIdPanel(IdPanel idPanel)
1636 this.idPanel = idPanel;
1640 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1641 * The aim is to keep the two alignments 'lined up' on their centre columns.
1644 * holds mapped region(s) of this alignment that we are scrolling
1645 * 'to'; may be modified for sequence offset by this method
1646 * @param verticalOffset
1647 * the number of visible sequences to show above the mapped region
1649 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1651 scrollToPosition(sr, verticalOffset, true);
1655 * Set a flag to say do not scroll any (cDNA/protein) complement.
1659 protected void setToScrollComplementPanel(boolean b)
1661 this.scrollComplementaryPanel = b;
1665 * Get whether to scroll complement panel
1667 * @return true if cDNA/protein complement panels should be scrolled
1669 protected boolean isSetToScrollComplementPanel()
1671 return this.scrollComplementaryPanel;
1677 * @adjustHeight if true, try to recalculate panel height for visible
1680 protected void refresh(boolean adjustHeight)
1682 validateAnnotationDimensions(adjustHeight);
1686 // sort, repaint, update overview
1687 paintAlignment(true, false);
1691 // lightweight repaint
1698 * Property change event fired when a change is made to the viewport ranges
1699 * object associated with this alignment panel's viewport
1701 public void propertyChange(PropertyChangeEvent evt)
1703 // update this panel's scroll values based on the new viewport ranges values
1704 ViewportRanges ranges = av.getRanges();
1705 int x = ranges.getStartRes();
1706 int y = ranges.getStartSeq();
1707 setScrollValues(x, y);
1709 // now update any complementary alignment (its viewport ranges object
1710 // is different so does not get automatically updated)
1711 if (isSetToScrollComplementPanel())
1713 setToScrollComplementPanel(false);
1714 av.scrollComplementaryAlignment();
1715 setToScrollComplementPanel(true);
1720 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1721 * reference should be nulled when the dialog is closed.
1723 * @param calculationChooser
1725 public void setCalculationDialog(CalculationChooser calculationChooser)
1727 calculationDialog = calculationChooser;
1731 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1734 public CalculationChooser getCalculationDialog()
1736 return calculationDialog;
1740 public SequenceRenderer getSequenceRenderer()
1742 return seqPanel.seqCanvas.getSequenceRenderer();
1745 public boolean scrollTo(int ostart, int end, int seqIndex,
1746 boolean scrollToNearest, boolean redrawOverview)
1748 int startv, endv, starts, ends;// , width;
1751 if (av.hasHiddenColumns())
1753 AlignmentI al = av.getAlignment();
1754 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1755 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1758 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1760 // don't scroll - position isn't visible
1770 ViewportRanges ranges = av.getRanges();
1771 if (!av.getWrapAlignment())
1774 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1775 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1776 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1777 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1778 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1779 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1780 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1781 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1784 // below is scrolling logic up to Jalview 2.8.2
1785 // if ((av.getStartRes() > end)
1786 // || (av.getEndRes() < start)
1787 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1789 // if (start > av.getAlignment().getWidth() - hextent)
1791 // start = av.getAlignment().getWidth() - hextent;
1798 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1800 // seqIndex = av.getAlignment().getHeight() - vextent;
1801 // if (seqIndex < 0)
1806 // setScrollValues(start, seqIndex);
1808 // logic copied from jalview.gui.AlignmentPanel:
1809 if ((startv = ranges.getStartRes()) >= start)
1812 * Scroll left to make start of search results visible
1814 setScrollValues(start - 1, seqIndex);
1816 else if ((endv = ranges.getEndRes()) <= end)
1819 * Scroll right to make end of search results visible
1821 setScrollValues(startv + 1 + end - endv, seqIndex);
1823 else if ((starts = ranges.getStartSeq()) > seqIndex)
1826 * Scroll up to make start of search results visible
1828 setScrollValues(ranges.getStartRes(), seqIndex);
1830 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1833 * Scroll down to make end of search results visible
1835 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1838 * Else results are already visible - no need to scroll
1843 ranges.scrollToWrappedVisible(start);
1846 paintAlignment(redrawOverview, false);
1851 public void overviewDone(BufferedImage miniMe)
1853 overviewPanel.canvas.finalizeDraw(miniMe);
1857 private boolean holdRepaint = false;
1859 public boolean getHoldRepaint()
1864 public void setHoldRepaint(boolean b)
1866 if (holdRepaint == b)
1878 public void repaint()
1882 // System.out.println("AP repaint holding");
1883 // Platform.stackTrace();