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)
130 System.out.println("AP 1");
131 setBackground(Color.white); // BH 2019
136 System.out.println("AP 2");
137 setSeqPanel(new SeqPanel(av, this));
139 System.out.println("AP 3");
140 setIdPanel(new IdPanel(av, this));
142 System.out.println("AP 4");
144 setScalePanel(new ScalePanel(av, this));
146 System.out.println("AP 5");
147 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
148 idwidthAdjuster = new IdwidthAdjuster(this);
149 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
151 setAnnotationPanel(new AnnotationPanel(this));
152 setAlabels(new AnnotationLabels(this));
154 annotationScroller.setViewportView(getAnnotationPanel());
155 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
156 if (!av.isShowAnnotation())
158 annotationScroller.setVisible(false);
159 annotationSpaceFillerHolder.setVisible(false);
161 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
162 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
164 setScrollValues(0, 0);
166 hscroll.addAdjustmentListener(this);
167 vscroll.addAdjustmentListener(this);
169 addComponentListener(new ComponentAdapter()
172 public void componentResized(ComponentEvent evt)
174 // reset the viewport ranges when the alignment panel is resized
175 // in particular, this initialises the end residue value when Jalview
177 ViewportRanges ranges = av.getRanges();
178 if (av.getWrapAlignment())
180 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
181 getSeqPanel().seqCanvas.getWidth());
182 ranges.setViewportWidth(widthInRes);
186 int widthInRes = getSeqPanel().seqCanvas.getWidth()
188 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
189 / av.getCharHeight();
191 ranges.setViewportWidth(widthInRes);
192 ranges.setViewportHeight(heightInSeq);
198 final AlignmentPanel ap = this;
199 propertyChangeListener = new PropertyChangeListener()
202 public void propertyChange(PropertyChangeEvent evt)
204 if (evt.getPropertyName().equals("alignment"))
206 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
211 av.addPropertyChangeListener(propertyChangeListener);
213 av.getRanges().addPropertyChangeListener(this);
215 adjustAnnotationHeight();
220 public AlignViewportI getAlignViewport()
225 public void alignmentChanged()
227 av.alignmentChanged(this);
229 if (getCalculationDialog() != null)
231 getCalculationDialog().validateCalcTypes();
234 alignFrame.updateEditMenuBar();
236 // no idea if we need to update structure
237 paintAlignment(true, true);
244 public void fontChanged()
246 // set idCanvas bufferedImage to null
247 // to prevent drawing old image
248 FontMetrics fm = getFontMetrics(av.getFont());
250 scalePanelHolder.setPreferredSize(
251 new Dimension(10, av.getCharHeight() + fm.getDescent()));
252 idSpaceFillerPanel1.setPreferredSize(
253 new Dimension(10, av.getCharHeight() + fm.getDescent()));
254 idwidthAdjuster.invalidate();
255 scalePanelHolder.invalidate();
256 // BH 2018 getIdPanel().getIdCanvas().gg = null;
257 getSeqPanel().seqCanvas.img = null;
258 getAnnotationPanel().adjustPanelHeight();
260 Dimension d = calculateIdWidth();
262 d.setSize(d.width + 4, d.height);
263 getIdPanel().getIdCanvas().setPreferredSize(d);
264 hscrollFillerPanel.setPreferredSize(d);
266 System.out.println("AP 99");
269 System.out.println("AP 100");
273 * Calculate the width of the alignment labels based on the displayed names
274 * and any bounds on label width set in preferences.
276 * @return Dimension giving the maximum width of the alignment label panel
277 * that should be used.
279 public Dimension calculateIdWidth()
281 // calculate sensible default width when no preference is available
283 if (av.getIdWidth() < 0)
285 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
286 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
287 r = calculateIdWidth(maxwidth);
288 av.setIdWidth(r.width);
293 r.width = av.getIdWidth();
300 * Calculate the width of the alignment labels based on the displayed names
301 * and any bounds on label width set in preferences.
304 * -1 or maximum width allowed for IdWidth
305 * @return Dimension giving the maximum width of the alignment label panel
306 * that should be used.
308 public Dimension calculateIdWidth(int maxwidth)
310 Container c = new Container();
312 FontMetrics fm = c.getFontMetrics(
313 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
315 AlignmentI al = av.getAlignment();
320 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
322 SequenceI s = al.getSequenceAt(i);
324 id = s.getDisplayId(av.getShowJVSuffix());
326 if (fm.stringWidth(id) > idWidth)
328 idWidth = fm.stringWidth(id);
334 // Also check annotation label widths
337 if (al.getAlignmentAnnotation() != null)
339 fm = c.getFontMetrics(getAlabels().getFont());
341 while (i < al.getAlignmentAnnotation().length)
343 String label = al.getAlignmentAnnotation()[i].label;
345 if (fm.stringWidth(label) > idWidth)
347 idWidth = fm.stringWidth(label);
354 return new Dimension(
355 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
359 * Highlight the given results on the alignment
362 public void highlightSearchResults(SearchResultsI results)
364 boolean scrolled = scrollToPosition(results, 0, false);
366 boolean fastPaint = !(scrolled && av.getWrapAlignment());
368 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
372 * Scroll the view to show the position of the highlighted region in results
375 * @param searchResults
378 public boolean scrollToPosition(SearchResultsI searchResults)
380 return scrollToPosition(searchResults, 0, false);
384 * Scrolls the view (if necessary) to show the position of the first
385 * highlighted region in results (if any). Answers true if the view was
386 * scrolled, or false if no matched region was found, or it is already
390 * @param verticalOffset
391 * if greater than zero, allows scrolling to a position below the
392 * first displayed sequence
394 * if true, try to centre the search results horizontally in the view
397 protected boolean scrollToPosition(SearchResultsI results,
398 int verticalOffset, boolean centre)
400 int startv, endv, starts, ends;
401 ViewportRanges ranges = av.getRanges();
403 if (results == null || results.isEmpty() || av == null
404 || av.getAlignment() == null)
408 int seqIndex = av.getAlignment().findIndex(results);
413 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
415 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
424 * To centre results, scroll to positions half the visible width
425 * left/right of the start/end positions
429 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
430 start = Math.max(start - offset, 0);
431 end = end + offset - 1;
437 if (end == seq.getEnd())
442 if (av.hasHiddenColumns())
444 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
445 start = hidden.absoluteToVisibleColumn(start);
446 end = hidden.absoluteToVisibleColumn(end);
449 if (!hidden.isVisible(r[0]))
451 // don't scroll - position isn't visible
458 * allow for offset of target sequence (actually scroll to one above it)
460 seqIndex = Math.max(0, seqIndex - verticalOffset);
461 boolean scrollNeeded = true;
463 if (!av.getWrapAlignment())
465 if ((startv = ranges.getStartRes()) >= start)
468 * Scroll left to make start of search results visible
470 setScrollValues(start, seqIndex);
472 else if ((endv = ranges.getEndRes()) <= end)
475 * Scroll right to make end of search results visible
477 setScrollValues(startv + end - endv, seqIndex);
479 else if ((starts = ranges.getStartSeq()) > seqIndex)
482 * Scroll up to make start of search results visible
484 setScrollValues(ranges.getStartRes(), seqIndex);
486 else if ((ends = ranges.getEndSeq()) <= seqIndex)
489 * Scroll down to make end of search results visible
491 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
495 * Else results are already visible - no need to scroll
497 scrollNeeded = false;
501 scrollNeeded = ranges.scrollToWrappedVisible(start);
504 paintAlignment(false, false);
512 * @return DOCUMENT ME!
514 public OverviewPanel getOverviewPanel()
516 return overviewPanel;
525 public void setOverviewPanel(OverviewPanel op)
533 * Hide or show annotation panel
536 public void setAnnotationVisible(boolean b)
538 if (!av.getWrapAlignment())
540 annotationSpaceFillerHolder.setVisible(b);
541 annotationScroller.setVisible(b);
547 * automatically adjust annotation panel height for new annotation whilst
548 * ensuring the alignment is still visible.
551 public void adjustAnnotationHeight()
553 // TODO: display vertical annotation scrollbar if necessary
554 // this is called after loading new annotation onto alignment
555 if (alignFrame.getHeight() == 0)
557 System.out.println("NEEDS FIXING");
559 validateAnnotationDimensions(true);
561 // TODO: many places call this method and also paintAlignment with various
562 // different settings. this means multiple redraws are triggered...
563 paintAlignment(true, av.needToUpdateStructureViews());
567 * calculate the annotation dimensions and refresh slider values accordingly.
568 * need to do repaints/notifys afterwards.
570 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
572 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
573 // are not changing ancestors, and keyboard action listeners do
574 // not need to be reset. addNotify() is a very expensive operation,
575 // requiring a full re-layout of all parents and children.
576 // Note in JComponent:
577 // This method is called by the toolkit internally and should
578 // not be called directly by programs.
579 // I note that addNotify() is called in several areas of Jalview.
581 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
582 annotationHeight = getAnnotationPanel()
583 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
586 annotationScroller.setPreferredSize(
587 new Dimension(annotationScroller.getWidth(), annotationHeight));
589 Dimension e = idPanel.getSize();
590 alabels.setSize(new Dimension(e.width, annotationHeight));
593 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
594 annotationSpaceFillerHolder.getWidth(), annotationHeight));
595 annotationScroller.validate();
596 annotationScroller.addNotify();
600 * update alignment layout for viewport settings
605 public void updateLayout()
607 fontChanged(); // fires repaint
608 setAnnotationVisible(av.isShowAnnotation());
609 boolean wrap = av.getWrapAlignment();
610 ViewportRanges ranges = av.getRanges();
611 ranges.setStartSeq(0);
612 scalePanelHolder.setVisible(!wrap);
613 hscroll.setVisible(!wrap);
614 idwidthAdjuster.setVisible(!wrap);
618 annotationScroller.setVisible(false);
619 annotationSpaceFillerHolder.setVisible(false);
621 else if (av.isShowAnnotation())
623 annotationScroller.setVisible(true);
624 annotationSpaceFillerHolder.setVisible(true);
625 validateAnnotationDimensions(false);
628 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
630 { // may not yet be laid out
633 int widthInRes = getSeqPanel().seqCanvas
634 .getWrappedCanvasWidth(canvasWidth);
635 ranges.setViewportWidth(widthInRes);
639 int widthInRes = (canvasWidth / av.getCharWidth());
640 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
641 / av.getCharHeight());
643 ranges.setViewportWidth(widthInRes);
644 ranges.setViewportHeight(heightInSeq);
648 idSpaceFillerPanel1.setVisible(!wrap);
654 * Adjust row/column scrollers to show a visible position in the alignment.
657 * visible column to scroll to
659 * visible row to scroll to
662 public void setScrollValues(int xpos, int ypos)
667 if (av == null || av.getAlignment() == null)
672 if (av.getWrapAlignment())
674 setScrollingForWrappedPanel(x);
678 int width = av.getAlignment().getVisibleWidth();
679 int height = av.getAlignment().getHeight();
681 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
682 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
689 if (vextent > height)
694 if ((hextent + x) > width)
699 if ((vextent + y) > height)
701 y = height - vextent;
714 // update the scroll values
715 hscroll.setValues(x, hextent, 0, width);
716 vscroll.setValues(y, vextent, 0, height);
721 * Respond to adjustment event when horizontal or vertical scrollbar is
725 * adjustment event encoding whether hscroll or vscroll changed
728 public void adjustmentValueChanged(AdjustmentEvent evt)
730 if (av.getWrapAlignment())
732 adjustScrollingWrapped(evt);
736 ViewportRanges ranges = av.getRanges();
738 if (evt.getSource() == hscroll)
740 int oldX = ranges.getStartRes();
741 int oldwidth = ranges.getViewportWidth();
742 int x = hscroll.getValue();
743 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
745 // if we're scrolling to the position we're already at, stop
746 // this prevents infinite recursion of events when the scroll/viewport
747 // ranges values are the same
748 if ((x == oldX) && (width == oldwidth))
752 ranges.setViewportStartAndWidth(x, width);
754 else if (evt.getSource() == vscroll)
756 int oldY = ranges.getStartSeq();
757 int oldheight = ranges.getViewportHeight();
758 int y = vscroll.getValue();
759 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
761 // if we're scrolling to the position we're already at, stop
762 // this prevents infinite recursion of events when the scroll/viewport
763 // ranges values are the same
764 if ((y == oldY) && (height == oldheight))
768 ranges.setViewportStartAndHeight(y, height);
774 * Responds to a scroll change by setting the start position of the viewport.
779 protected void adjustScrollingWrapped(AdjustmentEvent evt)
781 if (evt.getSource() == hscroll)
783 return; // no horizontal scroll when wrapped
785 final ViewportRanges ranges = av.getRanges();
787 if (evt.getSource() == vscroll)
789 int newY = vscroll.getValue();
792 * if we're scrolling to the position we're already at, stop
793 * this prevents infinite recursion of events when the scroll/viewport
794 * ranges values are the same
796 int oldX = ranges.getStartRes();
797 int oldY = ranges.getWrappedScrollPosition(oldX);
805 * limit page up/down to one width's worth of positions
807 int rowSize = ranges.getViewportWidth();
808 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
809 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
814 // This is only called if file loaded is a jar file that
815 // was wrapped when saved and user has wrap alignment true
816 // as preference setting
817 SwingUtilities.invokeLater(new Runnable()
822 // When updating scrolling to use ViewportChange events, this code
823 // could not be validated and it is not clear if it is now being
824 // called. Log warning here in case it is called and unforeseen
827 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
829 // scroll to start of panel
830 ranges.setStartRes(0);
831 ranges.setStartSeq(0);
839 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
842 public void paintAlignment(boolean updateOverview,
843 boolean updateStructures)
845 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
846 av.isShowAutocalculatedAbove());
847 sorter.sort(getAlignment().getAlignmentAnnotation(),
848 av.getSortAnnotationsBy());
851 if (updateStructures)
853 av.getStructureSelectionManager().sequenceColoursChanged(this);
858 if (overviewPanel != null)
860 getAlignment().resetColors();
861 overviewPanel.updateOverviewImage();
873 public void paintComponent(Graphics g)
876 invalidate(); // needed so that the id width adjuster works correctly
878 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
879 idPanelHolder.setPreferredSize(d);
880 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
882 validate(); // needed so that the id width adjuster works correctly
885 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
886 * though I still think this call should be elsewhere.
888 ViewportRanges ranges = av.getRanges();
889 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
890 super.paintComponent(g);
894 * Set vertical scroll bar position, and number of increments, for wrapped
897 * @param topLeftColumn
898 * the column position at top left (0..)
900 private void setScrollingForWrappedPanel(int topLeftColumn)
902 ViewportRanges ranges = av.getRanges();
903 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
904 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
907 * a scrollbar's value can be set to at most (maximum-extent)
908 * so we add extent (1) to the maxScroll value
910 vscroll.setUnitIncrement(1);
911 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
924 * @return DOCUMENT ME!
926 * @throws PrinterException
930 public int print(Graphics pg, PageFormat pf, int pi)
931 throws PrinterException
933 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
935 int pwidth = (int) pf.getImageableWidth();
936 int pheight = (int) pf.getImageableHeight();
938 if (av.getWrapAlignment())
940 return printWrappedAlignment(pwidth, pheight, pi, pg);
944 return printUnwrapped(pwidth, pheight, pi, pg, pg);
949 * Draws the alignment image, including sequence ids, sequences, and
950 * annotation labels and annotations if shown, on either one or two Graphics
960 * the graphics context for sequence ids and annotation labels
961 * @param alignmentGraphics
962 * the graphics context for sequences and annotations (may or may not
963 * be the same context as idGraphics)
965 * @throws PrinterException
967 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
968 Graphics idGraphics, Graphics alignmentGraphics)
969 throws PrinterException
971 final int idWidth = getVisibleIdWidth(false);
974 * Get the horizontal offset to where we draw the sequences.
975 * This is idWidth if using a single Graphics context, else zero.
977 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
980 FontMetrics fm = getFontMetrics(av.getFont());
981 final int charHeight = av.getCharHeight();
982 final int scaleHeight = charHeight + fm.getDescent();
984 idGraphics.setColor(Color.white);
985 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
986 idGraphics.setFont(av.getFont());
989 * How many sequences and residues can we fit on a printable page?
991 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
993 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
995 final int alignmentWidth = av.getAlignment().getVisibleWidth();
996 int pagesWide = (alignmentWidth / totalRes) + 1;
998 final int startRes = (pageIndex % pagesWide) * totalRes;
999 final int endRes = Math.min(startRes + totalRes - 1,
1000 alignmentWidth - 1);
1002 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1003 final int alignmentHeight = av.getAlignment().getHeight();
1004 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1006 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1008 if (av.isShowAnnotation())
1010 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1013 pagesHigh /= pageHeight;
1015 if (pageIndex >= (pagesWide * pagesHigh))
1017 return Printable.NO_SUCH_PAGE;
1019 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1022 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1024 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1025 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1026 pageWidth - idWidth, scaleHeight);
1027 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1030 * Draw the sequence ids, offset for scale height,
1031 * then reset to top left (0, 0)
1033 idGraphics.translate(0, scaleHeight);
1034 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1035 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1036 : av.getSelectionGroup().getSequences(null);
1037 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1040 idGraphics.setFont(av.getFont());
1041 idGraphics.translate(0, -scaleHeight);
1044 * draw the sequences, offset for scale height, and id width (if using a
1045 * single graphics context), then reset to (0, scale height)
1047 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1048 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1049 endRes, startSeq, endSeq - 1);
1050 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1052 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1055 * draw annotation labels; drawComponent() translates by
1056 * getScrollOffset(), so compensate for that first;
1057 * then reset to (0, scale height)
1059 int offset = getAlabels().getScrollOffset();
1060 idGraphics.translate(0, -offset);
1061 idGraphics.translate(0, alignmentDrawnHeight);
1062 getAlabels().drawComponent(idGraphics, idWidth);
1063 idGraphics.translate(0, -alignmentDrawnHeight);
1066 * draw the annotations starting at
1067 * (idOffset, alignmentHeight) from (0, scaleHeight)
1069 alignmentGraphics.translate(alignmentGraphicsOffset,
1070 alignmentDrawnHeight);
1071 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1072 alignmentGraphics, -1, startRes, endRes + 1);
1075 return Printable.PAGE_EXISTS;
1079 * Prints one page of an alignment in wrapped mode. Returns
1080 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1081 * no page could be drawn (page number out of range).
1091 * @throws PrinterException
1093 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1094 Graphics g) throws PrinterException
1096 int annotationHeight = 0;
1097 if (av.isShowAnnotation())
1099 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1102 int hgap = av.getCharHeight();
1103 if (av.getScaleAboveWrapped())
1105 hgap += av.getCharHeight();
1108 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1111 int idWidth = getVisibleIdWidth(false);
1113 int maxwidth = av.getAlignment().getVisibleWidth();
1115 int resWidth = getSeqPanel().seqCanvas
1116 .getWrappedCanvasWidth(pageWidth - idWidth);
1118 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1120 g.setColor(Color.white);
1121 g.fillRect(0, 0, pageWidth, pageHeight);
1122 g.setFont(av.getFont());
1123 g.setColor(Color.black);
1126 * method: print the whole wrapped alignment, but with a clip region that
1127 * is restricted to the requested page; this supports selective print of
1128 * single pages or ranges, (at the cost of some repeated processing in
1129 * the 'normal' case, when all pages are printed)
1131 g.translate(0, -pageNumber * pageHeight);
1133 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1136 * draw sequence ids and annotation labels (if shown)
1138 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1139 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1141 g.translate(idWidth, 0);
1143 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1146 if ((pageNumber * pageHeight) < totalHeight)
1148 return Printable.PAGE_EXISTS;
1152 return Printable.NO_SUCH_PAGE;
1157 * get current sequence ID panel width, or nominal value if panel were to be
1158 * displayed using default settings
1162 public int getVisibleIdWidth()
1164 return getVisibleIdWidth(true);
1168 * get current sequence ID panel width, or nominal value if panel were to be
1169 * displayed using default settings
1172 * indicate if the Id width for onscreen or offscreen display should
1176 public int getVisibleIdWidth(boolean onscreen)
1178 // see if rendering offscreen - check preferences and calc width accordingly
1179 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1181 return calculateIdWidth(-1).width + 4;
1183 Integer idwidth = null;
1184 if (onscreen || (idwidth = Cache
1185 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1187 int w = getIdPanel().getWidth();
1188 return (w > 0 ? w : calculateIdWidth().width + 4);
1190 return idwidth.intValue() + 4;
1194 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1195 * writes it to the specified file
1200 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1202 final int borderBottomOffset = 5;
1204 AlignmentDimension aDimension = getAlignmentDimension();
1205 // todo use a lambda function in place of callback here?
1206 ImageWriterI writer = new ImageWriterI()
1209 public void exportImage(Graphics graphics) throws Exception
1211 if (av.getWrapAlignment())
1213 printWrappedAlignment(aDimension.getWidth(),
1214 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1218 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1219 graphics, graphics);
1224 String fileTitle = alignFrame.getTitle();
1225 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1227 int imageWidth = aDimension.getWidth();
1228 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1229 String of = MessageManager.getString("label.alignment");
1230 exporter.doExport(file, this, imageWidth, imageHeight, of);
1234 * Calculates and returns a suitable width and height (in pixels) for an
1239 public AlignmentDimension getAlignmentDimension()
1241 int maxwidth = av.getAlignment().getVisibleWidth();
1243 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1244 + getScalePanel().getHeight();
1245 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1247 if (av.getWrapAlignment())
1249 height = getWrappedHeight();
1250 if (Jalview.isHeadlessMode())
1252 // need to obtain default alignment width and then add in any
1253 // additional allowance for id margin
1254 // this duplicates the calculation in getWrappedHeight but adjusts for
1256 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1257 - alignFrame.getInsets().left - alignFrame.getInsets().right
1258 - getVisibleIdWidth() + getVisibleIdWidth(false);
1262 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1266 else if (av.isShowAnnotation())
1268 height += getAnnotationPanel().adjustPanelHeight() + 3;
1270 return new AlignmentDimension(width, height);
1274 public void makePNGImageMap(File imgMapFile, String imageName)
1276 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1277 // ////////////////////////////////////////////
1278 int idWidth = getVisibleIdWidth(false);
1279 FontMetrics fm = getFontMetrics(av.getFont());
1280 int scaleHeight = av.getCharHeight() + fm.getDescent();
1283 // ////////////////////////////////
1284 if (imgMapFile != null)
1288 int sSize = av.getAlignment().getHeight();
1289 int alwidth = av.getAlignment().getWidth();
1290 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1291 out.println(HTMLOutput.getImageMapHTML());
1292 out.println("<img src=\"" + imageName
1293 + "\" border=\"0\" usemap=\"#Map\" >"
1294 + "<map name=\"Map\">");
1296 for (int s = 0; s < sSize; s++)
1298 int sy = s * av.getCharHeight() + scaleHeight;
1300 SequenceI seq = av.getAlignment().getSequenceAt(s);
1301 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1302 for (int column = 0; column < alwidth; column++)
1304 StringBuilder text = new StringBuilder(512);
1305 String triplet = null;
1306 if (av.getAlignment().isNucleotide())
1308 triplet = ResidueProperties.nucleotideName.get(seq
1309 .getCharAt(column) + "");
1313 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1317 if (triplet == null)
1322 int seqPos = seq.findPosition(column);
1323 int gSize = groups.length;
1324 for (int g = 0; g < gSize; g++)
1326 if (text.length() < 1)
1328 text.append("<area shape=\"rect\" coords=\"")
1329 .append((idWidth + column * av.getCharWidth()))
1330 .append(",").append(sy).append(",")
1331 .append((idWidth + (column + 1) * av.getCharWidth()))
1332 .append(",").append((av.getCharHeight() + sy))
1333 .append("\"").append(" onMouseOver=\"toolTip('")
1334 .append(seqPos).append(" ").append(triplet);
1337 if (groups[g].getStartRes() < column
1338 && groups[g].getEndRes() > column)
1340 text.append("<br><em>").append(groups[g].getName())
1345 if (text.length() < 1)
1347 text.append("<area shape=\"rect\" coords=\"")
1348 .append((idWidth + column * av.getCharWidth()))
1349 .append(",").append(sy).append(",")
1350 .append((idWidth + (column + 1) * av.getCharWidth()))
1351 .append(",").append((av.getCharHeight() + sy))
1352 .append("\"").append(" onMouseOver=\"toolTip('")
1353 .append(seqPos).append(" ").append(triplet);
1355 if (!Comparison.isGap(seq.getCharAt(column)))
1357 List<SequenceFeature> features = seq.findFeatures(column, column);
1358 for (SequenceFeature sf : features)
1360 if (sf.isContactFeature())
1362 text.append("<br>").append(sf.getType()).append(" ")
1363 .append(sf.getBegin()).append(":")
1364 .append(sf.getEnd());
1368 text.append("<br>");
1369 text.append(sf.getType());
1370 String description = sf.getDescription();
1371 if (description != null
1372 && !sf.getType().equals(description))
1374 description = description.replace("\"", """);
1375 text.append(" ").append(description);
1378 String status = sf.getStatus();
1379 if (status != null && !"".equals(status))
1381 text.append(" (").append(status).append(")");
1384 if (text.length() > 1)
1386 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1387 out.println(text.toString());
1392 out.println("</map></body></html>");
1395 } catch (Exception ex)
1397 ex.printStackTrace();
1399 } // /////////END OF IMAGE MAP
1403 int getWrappedHeight()
1405 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1407 if (Jalview.isHeadlessMode())
1409 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1410 - vscroll.getPreferredSize().width
1411 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1414 int chunkWidth = getSeqPanel().seqCanvas
1415 .getWrappedCanvasWidth(seqPanelWidth);
1417 int hgap = av.getCharHeight();
1418 if (av.getScaleAboveWrapped())
1420 hgap += av.getCharHeight();
1423 int annotationHeight = 0;
1424 if (av.isShowAnnotation())
1426 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1429 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1432 int maxwidth = av.getAlignment().getWidth();
1433 if (av.hasHiddenColumns())
1435 maxwidth = av.getAlignment().getHiddenColumns()
1436 .absoluteToVisibleColumn(maxwidth) - 1;
1439 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1445 * close the panel - deregisters all listeners and nulls any references to
1448 public void closePanel()
1450 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1451 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1452 PaintRefresher.RemoveComponent(this);
1457 * try to ensure references are nulled
1459 if (annotationPanel != null)
1461 annotationPanel.dispose();
1462 annotationPanel = null;
1467 av.removePropertyChangeListener(propertyChangeListener);
1468 propertyChangeListener = null;
1469 StructureSelectionManager ssm = av.getStructureSelectionManager();
1470 ssm.removeStructureViewerListener(getSeqPanel(), null);
1471 ssm.removeSelectionListener(getSeqPanel());
1472 ssm.removeCommandListener(av);
1473 ssm.removeStructureViewerListener(getSeqPanel(), null);
1474 ssm.removeSelectionListener(getSeqPanel());
1480 if (Cache.log.isDebugEnabled())
1482 Cache.log.warn("Closing alignment panel which is already closed.");
1488 * Close any open dialogs that would be orphaned when this one is closed
1490 protected void closeChildFrames()
1492 if (overviewPanel != null)
1494 overviewPanel.dispose();
1495 overviewPanel = null;
1497 if (calculationDialog != null)
1499 calculationDialog.closeFrame();
1500 calculationDialog = null;
1505 * hides or shows dynamic annotation rows based on groups and av state flags
1507 public void updateAnnotation()
1509 updateAnnotation(false, false);
1512 public void updateAnnotation(boolean applyGlobalSettings)
1514 updateAnnotation(applyGlobalSettings, false);
1517 public void updateAnnotation(boolean applyGlobalSettings,
1518 boolean preserveNewGroupSettings)
1520 av.updateGroupAnnotationSettings(applyGlobalSettings,
1521 preserveNewGroupSettings);
1522 adjustAnnotationHeight();
1526 public AlignmentI getAlignment()
1528 return av == null ? null : av.getAlignment();
1532 public String getViewName()
1534 return av.getViewName();
1538 * Make/Unmake this alignment panel the current input focus
1542 public void setSelected(boolean b)
1546 if (alignFrame.getSplitViewContainer() != null)
1549 * bring enclosing SplitFrame to front first if there is one
1551 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1553 alignFrame.setSelected(b);
1554 } catch (Exception ex)
1560 alignFrame.setDisplayedView(this);
1565 public StructureSelectionManager getStructureSelectionManager()
1567 return av.getStructureSelectionManager();
1571 public void raiseOOMWarning(String string, OutOfMemoryError error)
1573 new OOMWarning(string, error, this);
1577 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1580 return new FeatureRenderer(this);
1584 public jalview.api.FeatureRenderer getFeatureRenderer()
1586 return seqPanel.seqCanvas.getFeatureRenderer();
1589 public void updateFeatureRenderer(
1590 jalview.renderer.seqfeatures.FeatureRenderer fr)
1592 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1595 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1597 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1599 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1603 public ScalePanel getScalePanel()
1608 public void setScalePanel(ScalePanel scalePanel)
1610 this.scalePanel = scalePanel;
1613 public SeqPanel getSeqPanel()
1618 public void setSeqPanel(SeqPanel seqPanel)
1620 this.seqPanel = seqPanel;
1623 public AnnotationPanel getAnnotationPanel()
1625 return annotationPanel;
1628 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1630 this.annotationPanel = annotationPanel;
1633 public AnnotationLabels getAlabels()
1638 public void setAlabels(AnnotationLabels alabels)
1640 this.alabels = alabels;
1643 public IdPanel getIdPanel()
1648 public void setIdPanel(IdPanel idPanel)
1650 this.idPanel = idPanel;
1654 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1655 * The aim is to keep the two alignments 'lined up' on their centre columns.
1658 * holds mapped region(s) of this alignment that we are scrolling
1659 * 'to'; may be modified for sequence offset by this method
1660 * @param verticalOffset
1661 * the number of visible sequences to show above the mapped region
1663 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1665 scrollToPosition(sr, verticalOffset, true);
1669 * Set a flag to say do not scroll any (cDNA/protein) complement.
1673 protected void setToScrollComplementPanel(boolean b)
1675 this.scrollComplementaryPanel = b;
1679 * Get whether to scroll complement panel
1681 * @return true if cDNA/protein complement panels should be scrolled
1683 protected boolean isSetToScrollComplementPanel()
1685 return this.scrollComplementaryPanel;
1691 * @adjustHeight if true, try to recalculate panel height for visible
1694 protected void refresh(boolean adjustHeight)
1696 validateAnnotationDimensions(adjustHeight);
1700 // sort, repaint, update overview
1701 paintAlignment(true, false);
1705 // lightweight repaint
1712 * Property change event fired when a change is made to the viewport ranges
1713 * object associated with this alignment panel's viewport
1715 public void propertyChange(PropertyChangeEvent evt)
1717 // update this panel's scroll values based on the new viewport ranges values
1718 ViewportRanges ranges = av.getRanges();
1719 int x = ranges.getStartRes();
1720 int y = ranges.getStartSeq();
1721 setScrollValues(x, y);
1723 // now update any complementary alignment (its viewport ranges object
1724 // is different so does not get automatically updated)
1725 if (isSetToScrollComplementPanel())
1727 setToScrollComplementPanel(false);
1728 av.scrollComplementaryAlignment();
1729 setToScrollComplementPanel(true);
1734 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1735 * reference should be nulled when the dialog is closed.
1737 * @param calculationChooser
1739 public void setCalculationDialog(CalculationChooser calculationChooser)
1741 calculationDialog = calculationChooser;
1745 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1748 public CalculationChooser getCalculationDialog()
1750 return calculationDialog;
1754 public SequenceRenderer getSequenceRenderer()
1756 return seqPanel.seqCanvas.getSequenceRenderer();
1759 public boolean scrollTo(int ostart, int end, int seqIndex,
1760 boolean scrollToNearest, boolean redrawOverview)
1762 int startv, endv, starts, ends;// , width;
1765 if (av.hasHiddenColumns())
1767 AlignmentI al = av.getAlignment();
1768 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1769 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1772 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1774 // don't scroll - position isn't visible
1784 ViewportRanges ranges = av.getRanges();
1785 if (!av.getWrapAlignment())
1788 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1789 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1790 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1791 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1792 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1793 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1794 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1795 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1798 // below is scrolling logic up to Jalview 2.8.2
1799 // if ((av.getStartRes() > end)
1800 // || (av.getEndRes() < start)
1801 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1803 // if (start > av.getAlignment().getWidth() - hextent)
1805 // start = av.getAlignment().getWidth() - hextent;
1812 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1814 // seqIndex = av.getAlignment().getHeight() - vextent;
1815 // if (seqIndex < 0)
1820 // setScrollValues(start, seqIndex);
1822 // logic copied from jalview.gui.AlignmentPanel:
1823 if ((startv = ranges.getStartRes()) >= start)
1826 * Scroll left to make start of search results visible
1828 setScrollValues(start - 1, seqIndex);
1830 else if ((endv = ranges.getEndRes()) <= end)
1833 * Scroll right to make end of search results visible
1835 setScrollValues(startv + 1 + end - endv, seqIndex);
1837 else if ((starts = ranges.getStartSeq()) > seqIndex)
1840 * Scroll up to make start of search results visible
1842 setScrollValues(ranges.getStartRes(), seqIndex);
1844 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1847 * Scroll down to make end of search results visible
1849 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1852 * Else results are already visible - no need to scroll
1857 ranges.scrollToWrappedVisible(start);
1860 paintAlignment(redrawOverview, false);
1865 public void overviewDone(BufferedImage miniMe)
1867 overviewPanel.canvas.finalizeDraw(miniMe);
1871 private boolean holdRepaint = false;
1873 public boolean getHoldRepaint()
1878 public void setHoldRepaint(boolean b)
1880 if (holdRepaint == b)
1892 public void repaint()
1896 // System.out.println("AP repaint holding");
1897 // Platform.stackTrace();