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);
846 if (overviewPanel != null)
848 getAlignment().resetColors();
849 overviewPanel.updateOverviewImage();
861 public void paintComponent(Graphics g)
864 invalidate(); // needed so that the id width adjuster works correctly
866 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
867 idPanelHolder.setPreferredSize(d);
868 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
870 validate(); // needed so that the id width adjuster works correctly
873 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
874 * though I still think this call should be elsewhere.
876 ViewportRanges ranges = av.getRanges();
877 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
878 super.paintComponent(g);
882 * Set vertical scroll bar position, and number of increments, for wrapped
885 * @param topLeftColumn
886 * the column position at top left (0..)
888 private void setScrollingForWrappedPanel(int topLeftColumn)
890 ViewportRanges ranges = av.getRanges();
891 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
892 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
895 * a scrollbar's value can be set to at most (maximum-extent)
896 * so we add extent (1) to the maxScroll value
898 vscroll.setUnitIncrement(1);
899 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
912 * @return DOCUMENT ME!
914 * @throws PrinterException
918 public int print(Graphics pg, PageFormat pf, int pi)
919 throws PrinterException
921 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
923 int pwidth = (int) pf.getImageableWidth();
924 int pheight = (int) pf.getImageableHeight();
926 if (av.getWrapAlignment())
928 return printWrappedAlignment(pwidth, pheight, pi, pg);
932 return printUnwrapped(pwidth, pheight, pi, pg, pg);
937 * Draws the alignment image, including sequence ids, sequences, and
938 * annotation labels and annotations if shown, on either one or two Graphics
948 * the graphics context for sequence ids and annotation labels
949 * @param alignmentGraphics
950 * the graphics context for sequences and annotations (may or may not
951 * be the same context as idGraphics)
953 * @throws PrinterException
955 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
956 Graphics idGraphics, Graphics alignmentGraphics)
957 throws PrinterException
959 final int idWidth = getVisibleIdWidth(false);
962 * Get the horizontal offset to where we draw the sequences.
963 * This is idWidth if using a single Graphics context, else zero.
965 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
968 FontMetrics fm = getFontMetrics(av.getFont());
969 final int charHeight = av.getCharHeight();
970 final int scaleHeight = charHeight + fm.getDescent();
972 idGraphics.setColor(Color.white);
973 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
974 idGraphics.setFont(av.getFont());
977 * How many sequences and residues can we fit on a printable page?
979 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
981 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
983 final int alignmentWidth = av.getAlignment().getVisibleWidth();
984 int pagesWide = (alignmentWidth / totalRes) + 1;
986 final int startRes = (pageIndex % pagesWide) * totalRes;
987 final int endRes = Math.min(startRes + totalRes - 1,
990 final int startSeq = (pageIndex / pagesWide) * totalSeq;
991 final int alignmentHeight = av.getAlignment().getHeight();
992 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
994 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
996 if (av.isShowAnnotation())
998 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1001 pagesHigh /= pageHeight;
1003 if (pageIndex >= (pagesWide * pagesHigh))
1005 return Printable.NO_SUCH_PAGE;
1007 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1010 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1012 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1013 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1014 pageWidth - idWidth, scaleHeight);
1015 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1018 * Draw the sequence ids, offset for scale height,
1019 * then reset to top left (0, 0)
1021 idGraphics.translate(0, scaleHeight);
1022 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1023 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1024 : av.getSelectionGroup().getSequences(null);
1025 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1028 idGraphics.setFont(av.getFont());
1029 idGraphics.translate(0, -scaleHeight);
1032 * draw the sequences, offset for scale height, and id width (if using a
1033 * single graphics context), then reset to (0, scale height)
1035 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1036 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1037 endRes, startSeq, endSeq - 1);
1038 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1040 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1043 * draw annotation labels; drawComponent() translates by
1044 * getScrollOffset(), so compensate for that first;
1045 * then reset to (0, scale height)
1047 int offset = getAlabels().getScrollOffset();
1048 idGraphics.translate(0, -offset);
1049 idGraphics.translate(0, alignmentDrawnHeight);
1050 getAlabels().drawComponent(idGraphics, idWidth);
1051 idGraphics.translate(0, -alignmentDrawnHeight);
1054 * draw the annotations starting at
1055 * (idOffset, alignmentHeight) from (0, scaleHeight)
1057 alignmentGraphics.translate(alignmentGraphicsOffset,
1058 alignmentDrawnHeight);
1059 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1060 alignmentGraphics, -1, startRes, endRes + 1);
1063 return Printable.PAGE_EXISTS;
1067 * Prints one page of an alignment in wrapped mode. Returns
1068 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1069 * no page could be drawn (page number out of range).
1079 * @throws PrinterException
1081 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1082 Graphics g) throws PrinterException
1084 int annotationHeight = 0;
1085 if (av.isShowAnnotation())
1087 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1090 int hgap = av.getCharHeight();
1091 if (av.getScaleAboveWrapped())
1093 hgap += av.getCharHeight();
1096 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1099 int idWidth = getVisibleIdWidth(false);
1101 int maxwidth = av.getAlignment().getVisibleWidth();
1103 int resWidth = getSeqPanel().seqCanvas
1104 .getWrappedCanvasWidth(pageWidth - idWidth);
1106 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1108 g.setColor(Color.white);
1109 g.fillRect(0, 0, pageWidth, pageHeight);
1110 g.setFont(av.getFont());
1111 g.setColor(Color.black);
1114 * method: print the whole wrapped alignment, but with a clip region that
1115 * is restricted to the requested page; this supports selective print of
1116 * single pages or ranges, (at the cost of some repeated processing in
1117 * the 'normal' case, when all pages are printed)
1119 g.translate(0, -pageNumber * pageHeight);
1121 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1124 * draw sequence ids and annotation labels (if shown)
1126 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1127 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1129 g.translate(idWidth, 0);
1131 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1134 if ((pageNumber * pageHeight) < totalHeight)
1136 return Printable.PAGE_EXISTS;
1140 return Printable.NO_SUCH_PAGE;
1145 * get current sequence ID panel width, or nominal value if panel were to be
1146 * displayed using default settings
1150 public int getVisibleIdWidth()
1152 return getVisibleIdWidth(true);
1156 * get current sequence ID panel width, or nominal value if panel were to be
1157 * displayed using default settings
1160 * indicate if the Id width for onscreen or offscreen display should
1164 public int getVisibleIdWidth(boolean onscreen)
1166 // see if rendering offscreen - check preferences and calc width accordingly
1167 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1169 return calculateIdWidth(-1).width + 4;
1171 Integer idwidth = null;
1172 if (onscreen || (idwidth = Cache
1173 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1175 int w = getIdPanel().getWidth();
1176 return (w > 0 ? w : calculateIdWidth().width + 4);
1178 return idwidth.intValue() + 4;
1182 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1183 * writes it to the specified file
1188 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1190 final int borderBottomOffset = 5;
1192 AlignmentDimension aDimension = getAlignmentDimension();
1193 // todo use a lambda function in place of callback here?
1194 ImageWriterI writer = new ImageWriterI()
1197 public void exportImage(Graphics graphics) throws Exception
1199 if (av.getWrapAlignment())
1201 printWrappedAlignment(aDimension.getWidth(),
1202 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1206 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1207 graphics, graphics);
1212 String fileTitle = alignFrame.getTitle();
1213 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1215 int imageWidth = aDimension.getWidth();
1216 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1217 String of = MessageManager.getString("label.alignment");
1218 exporter.doExport(file, this, imageWidth, imageHeight, of);
1222 * Calculates and returns a suitable width and height (in pixels) for an
1227 public AlignmentDimension getAlignmentDimension()
1229 int maxwidth = av.getAlignment().getVisibleWidth();
1231 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1232 + getScalePanel().getHeight();
1233 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1235 if (av.getWrapAlignment())
1237 height = getWrappedHeight();
1238 if (Jalview.isHeadlessMode())
1240 // need to obtain default alignment width and then add in any
1241 // additional allowance for id margin
1242 // this duplicates the calculation in getWrappedHeight but adjusts for
1244 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1245 - alignFrame.getInsets().left - alignFrame.getInsets().right
1246 - getVisibleIdWidth() + getVisibleIdWidth(false);
1250 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1254 else if (av.isShowAnnotation())
1256 height += getAnnotationPanel().adjustPanelHeight() + 3;
1258 return new AlignmentDimension(width, height);
1262 public void makePNGImageMap(File imgMapFile, String imageName)
1264 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1265 // ////////////////////////////////////////////
1266 int idWidth = getVisibleIdWidth(false);
1267 FontMetrics fm = getFontMetrics(av.getFont());
1268 int scaleHeight = av.getCharHeight() + fm.getDescent();
1271 // ////////////////////////////////
1272 if (imgMapFile != null)
1276 int sSize = av.getAlignment().getHeight();
1277 int alwidth = av.getAlignment().getWidth();
1278 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1279 out.println(HTMLOutput.getImageMapHTML());
1280 out.println("<img src=\"" + imageName
1281 + "\" border=\"0\" usemap=\"#Map\" >"
1282 + "<map name=\"Map\">");
1284 for (int s = 0; s < sSize; s++)
1286 int sy = s * av.getCharHeight() + scaleHeight;
1288 SequenceI seq = av.getAlignment().getSequenceAt(s);
1289 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1290 for (int column = 0; column < alwidth; column++)
1292 StringBuilder text = new StringBuilder(512);
1293 String triplet = null;
1294 if (av.getAlignment().isNucleotide())
1296 triplet = ResidueProperties.nucleotideName.get(seq
1297 .getCharAt(column) + "");
1301 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1305 if (triplet == null)
1310 int seqPos = seq.findPosition(column);
1311 int gSize = groups.length;
1312 for (int g = 0; g < gSize; g++)
1314 if (text.length() < 1)
1316 text.append("<area shape=\"rect\" coords=\"")
1317 .append((idWidth + column * av.getCharWidth()))
1318 .append(",").append(sy).append(",")
1319 .append((idWidth + (column + 1) * av.getCharWidth()))
1320 .append(",").append((av.getCharHeight() + sy))
1321 .append("\"").append(" onMouseOver=\"toolTip('")
1322 .append(seqPos).append(" ").append(triplet);
1325 if (groups[g].getStartRes() < column
1326 && groups[g].getEndRes() > column)
1328 text.append("<br><em>").append(groups[g].getName())
1333 if (text.length() < 1)
1335 text.append("<area shape=\"rect\" coords=\"")
1336 .append((idWidth + column * av.getCharWidth()))
1337 .append(",").append(sy).append(",")
1338 .append((idWidth + (column + 1) * av.getCharWidth()))
1339 .append(",").append((av.getCharHeight() + sy))
1340 .append("\"").append(" onMouseOver=\"toolTip('")
1341 .append(seqPos).append(" ").append(triplet);
1343 if (!Comparison.isGap(seq.getCharAt(column)))
1345 List<SequenceFeature> features = seq.findFeatures(column, column);
1346 for (SequenceFeature sf : features)
1348 if (sf.isContactFeature())
1350 text.append("<br>").append(sf.getType()).append(" ")
1351 .append(sf.getBegin()).append(":")
1352 .append(sf.getEnd());
1356 text.append("<br>");
1357 text.append(sf.getType());
1358 String description = sf.getDescription();
1359 if (description != null
1360 && !sf.getType().equals(description))
1362 description = description.replace("\"", """);
1363 text.append(" ").append(description);
1366 String status = sf.getStatus();
1367 if (status != null && !"".equals(status))
1369 text.append(" (").append(status).append(")");
1372 if (text.length() > 1)
1374 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1375 out.println(text.toString());
1380 out.println("</map></body></html>");
1383 } catch (Exception ex)
1385 ex.printStackTrace();
1387 } // /////////END OF IMAGE MAP
1391 int getWrappedHeight()
1393 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1395 if (Jalview.isHeadlessMode())
1397 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1398 - vscroll.getPreferredSize().width
1399 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1402 int chunkWidth = getSeqPanel().seqCanvas
1403 .getWrappedCanvasWidth(seqPanelWidth);
1405 int hgap = av.getCharHeight();
1406 if (av.getScaleAboveWrapped())
1408 hgap += av.getCharHeight();
1411 int annotationHeight = 0;
1412 if (av.isShowAnnotation())
1414 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1417 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1420 int maxwidth = av.getAlignment().getWidth();
1421 if (av.hasHiddenColumns())
1423 maxwidth = av.getAlignment().getHiddenColumns()
1424 .absoluteToVisibleColumn(maxwidth) - 1;
1427 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1433 * close the panel - deregisters all listeners and nulls any references to
1436 public void closePanel()
1438 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1439 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1440 PaintRefresher.RemoveComponent(this);
1445 * try to ensure references are nulled
1447 if (annotationPanel != null)
1449 annotationPanel.dispose();
1450 annotationPanel = null;
1455 av.removePropertyChangeListener(propertyChangeListener);
1456 propertyChangeListener = null;
1457 StructureSelectionManager ssm = av.getStructureSelectionManager();
1458 ssm.removeStructureViewerListener(getSeqPanel(), null);
1459 ssm.removeSelectionListener(getSeqPanel());
1460 ssm.removeCommandListener(av);
1461 ssm.removeStructureViewerListener(getSeqPanel(), null);
1462 ssm.removeSelectionListener(getSeqPanel());
1468 if (Cache.log.isDebugEnabled())
1470 Cache.log.warn("Closing alignment panel which is already closed.");
1476 * Close any open dialogs that would be orphaned when this one is closed
1478 protected void closeChildFrames()
1480 if (overviewPanel != null)
1482 overviewPanel.dispose();
1483 overviewPanel = null;
1485 if (calculationDialog != null)
1487 calculationDialog.closeFrame();
1488 calculationDialog = null;
1493 * hides or shows dynamic annotation rows based on groups and av state flags
1495 public void updateAnnotation()
1497 updateAnnotation(false, false);
1500 public void updateAnnotation(boolean applyGlobalSettings)
1502 updateAnnotation(applyGlobalSettings, false);
1505 public void updateAnnotation(boolean applyGlobalSettings,
1506 boolean preserveNewGroupSettings)
1508 av.updateGroupAnnotationSettings(applyGlobalSettings,
1509 preserveNewGroupSettings);
1510 adjustAnnotationHeight();
1514 public AlignmentI getAlignment()
1516 return av == null ? null : av.getAlignment();
1520 public String getViewName()
1522 return av.getViewName();
1526 * Make/Unmake this alignment panel the current input focus
1530 public void setSelected(boolean b)
1534 if (alignFrame.getSplitViewContainer() != null)
1537 * bring enclosing SplitFrame to front first if there is one
1539 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1541 alignFrame.setSelected(b);
1542 } catch (Exception ex)
1548 alignFrame.setDisplayedView(this);
1553 public StructureSelectionManager getStructureSelectionManager()
1555 return av.getStructureSelectionManager();
1559 public void raiseOOMWarning(String string, OutOfMemoryError error)
1561 new OOMWarning(string, error, this);
1565 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1568 return new FeatureRenderer(this);
1572 public jalview.api.FeatureRenderer getFeatureRenderer()
1574 return seqPanel.seqCanvas.getFeatureRenderer();
1577 public void updateFeatureRenderer(
1578 jalview.renderer.seqfeatures.FeatureRenderer fr)
1580 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1583 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1585 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1587 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1591 public ScalePanel getScalePanel()
1596 public void setScalePanel(ScalePanel scalePanel)
1598 this.scalePanel = scalePanel;
1601 public SeqPanel getSeqPanel()
1606 public void setSeqPanel(SeqPanel seqPanel)
1608 this.seqPanel = seqPanel;
1611 public AnnotationPanel getAnnotationPanel()
1613 return annotationPanel;
1616 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1618 this.annotationPanel = annotationPanel;
1621 public AnnotationLabels getAlabels()
1626 public void setAlabels(AnnotationLabels alabels)
1628 this.alabels = alabels;
1631 public IdPanel getIdPanel()
1636 public void setIdPanel(IdPanel idPanel)
1638 this.idPanel = idPanel;
1642 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1643 * The aim is to keep the two alignments 'lined up' on their centre columns.
1646 * holds mapped region(s) of this alignment that we are scrolling
1647 * 'to'; may be modified for sequence offset by this method
1648 * @param verticalOffset
1649 * the number of visible sequences to show above the mapped region
1651 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1653 scrollToPosition(sr, verticalOffset, true);
1657 * Set a flag to say do not scroll any (cDNA/protein) complement.
1661 protected void setToScrollComplementPanel(boolean b)
1663 this.scrollComplementaryPanel = b;
1667 * Get whether to scroll complement panel
1669 * @return true if cDNA/protein complement panels should be scrolled
1671 protected boolean isSetToScrollComplementPanel()
1673 return this.scrollComplementaryPanel;
1679 * @adjustHeight if true, try to recalculate panel height for visible
1682 protected void refresh(boolean adjustHeight)
1684 validateAnnotationDimensions(adjustHeight);
1688 // sort, repaint, update overview
1689 paintAlignment(true, false);
1693 // lightweight repaint
1700 * Property change event fired when a change is made to the viewport ranges
1701 * object associated with this alignment panel's viewport
1703 public void propertyChange(PropertyChangeEvent evt)
1705 // update this panel's scroll values based on the new viewport ranges values
1706 ViewportRanges ranges = av.getRanges();
1707 int x = ranges.getStartRes();
1708 int y = ranges.getStartSeq();
1709 setScrollValues(x, y);
1711 // now update any complementary alignment (its viewport ranges object
1712 // is different so does not get automatically updated)
1713 if (isSetToScrollComplementPanel())
1715 setToScrollComplementPanel(false);
1716 av.scrollComplementaryAlignment();
1717 setToScrollComplementPanel(true);
1722 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1723 * reference should be nulled when the dialog is closed.
1725 * @param calculationChooser
1727 public void setCalculationDialog(CalculationChooser calculationChooser)
1729 calculationDialog = calculationChooser;
1733 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1736 public CalculationChooser getCalculationDialog()
1738 return calculationDialog;
1742 public SequenceRenderer getSequenceRenderer()
1744 return seqPanel.seqCanvas.getSequenceRenderer();
1747 public boolean scrollTo(int ostart, int end, int seqIndex,
1748 boolean scrollToNearest, boolean redrawOverview)
1750 int startv, endv, starts, ends;// , width;
1753 if (av.hasHiddenColumns())
1755 AlignmentI al = av.getAlignment();
1756 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1757 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1760 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1762 // don't scroll - position isn't visible
1772 ViewportRanges ranges = av.getRanges();
1773 if (!av.getWrapAlignment())
1776 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1777 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1778 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1779 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1780 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1781 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1782 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1783 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1786 // below is scrolling logic up to Jalview 2.8.2
1787 // if ((av.getStartRes() > end)
1788 // || (av.getEndRes() < start)
1789 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1791 // if (start > av.getAlignment().getWidth() - hextent)
1793 // start = av.getAlignment().getWidth() - hextent;
1800 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1802 // seqIndex = av.getAlignment().getHeight() - vextent;
1803 // if (seqIndex < 0)
1808 // setScrollValues(start, seqIndex);
1810 // logic copied from jalview.gui.AlignmentPanel:
1811 if ((startv = ranges.getStartRes()) >= start)
1814 * Scroll left to make start of search results visible
1816 setScrollValues(start - 1, seqIndex);
1818 else if ((endv = ranges.getEndRes()) <= end)
1821 * Scroll right to make end of search results visible
1823 setScrollValues(startv + 1 + end - endv, seqIndex);
1825 else if ((starts = ranges.getStartSeq()) > seqIndex)
1828 * Scroll up to make start of search results visible
1830 setScrollValues(ranges.getStartRes(), seqIndex);
1832 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1835 * Scroll down to make end of search results visible
1837 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1840 * Else results are already visible - no need to scroll
1845 ranges.scrollToWrappedVisible(start);
1848 paintAlignment(redrawOverview, false);
1853 public void overviewDone(BufferedImage miniMe)
1855 overviewPanel.canvas.finalizeDraw(miniMe);
1859 private boolean holdRepaint = false;
1861 public boolean getHoldRepaint()
1866 public void setHoldRepaint(boolean b)
1868 if (holdRepaint == b)
1880 public void repaint()
1884 // System.out.println("AP repaint holding");
1885 // Platform.stackTrace();