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;
76 * @version $Revision: 1.161 $
78 @SuppressWarnings("serial")
79 public class AlignmentPanel extends GAlignmentPanel implements
80 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
82 public AlignViewport av;
84 OverviewPanel overviewPanel;
86 private SeqPanel seqPanel;
88 private IdPanel idPanel;
90 IdwidthAdjuster idwidthAdjuster;
92 public AlignFrame alignFrame;
94 private ScalePanel scalePanel;
96 private AnnotationPanel annotationPanel;
98 private AnnotationLabels alabels;
100 private int hextent = 0;
102 private int vextent = 0;
105 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
106 * false, suppresses invoking the same method recursively.
108 private boolean scrollComplementaryPanel = true;
110 private PropertyChangeListener propertyChangeListener;
112 private CalculationChooser calculationDialog;
115 * Creates a new AlignmentPanel object.
120 public AlignmentPanel(AlignFrame af, final AlignViewport av)
122 setBackground(Color.white); // BH 2019
126 setSeqPanel(new SeqPanel(av, this));
127 setIdPanel(new IdPanel(av, this));
129 setScalePanel(new ScalePanel(av, this));
131 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
132 idwidthAdjuster = new IdwidthAdjuster(this);
133 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
135 setAnnotationPanel(new AnnotationPanel(this));
136 setAlabels(new AnnotationLabels(this));
138 annotationScroller.setViewportView(getAnnotationPanel());
139 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
140 if (!av.isShowAnnotation())
142 annotationScroller.setVisible(false);
143 annotationSpaceFillerHolder.setVisible(false);
145 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
146 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
148 setScrollValues(0, 0);
150 hscroll.addAdjustmentListener(this);
151 vscroll.addAdjustmentListener(this);
153 addComponentListener(new ComponentAdapter()
156 public void componentResized(ComponentEvent evt)
158 // reset the viewport ranges when the alignment panel is resized
159 // in particular, this initialises the end residue value when Jalview
161 ViewportRanges ranges = av.getRanges();
162 if (av.getWrapAlignment())
164 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
165 getSeqPanel().seqCanvas.getWidth());
166 ranges.setViewportWidth(widthInRes);
170 int widthInRes = getSeqPanel().seqCanvas.getWidth()
172 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
173 / av.getCharHeight();
175 ranges.setViewportWidth(widthInRes);
176 ranges.setViewportHeight(heightInSeq);
182 final AlignmentPanel ap = this;
183 propertyChangeListener = new PropertyChangeListener()
186 public void propertyChange(PropertyChangeEvent evt)
188 if (evt.getPropertyName().equals("alignment"))
190 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
195 av.addPropertyChangeListener(propertyChangeListener);
197 av.getRanges().addPropertyChangeListener(this);
199 adjustAnnotationHeight();
204 public AlignViewportI getAlignViewport()
209 public void alignmentChanged()
211 av.alignmentChanged(this);
213 if (getCalculationDialog() != null)
215 getCalculationDialog().validateCalcTypes();
218 alignFrame.updateEditMenuBar();
220 // no idea if we need to update structure
221 paintAlignment(true, true);
228 public void fontChanged()
230 // set idCanvas bufferedImage to null
231 // to prevent drawing old image
232 FontMetrics fm = getFontMetrics(av.getFont());
234 scalePanelHolder.setPreferredSize(
235 new Dimension(10, av.getCharHeight() + fm.getDescent()));
236 idSpaceFillerPanel1.setPreferredSize(
237 new Dimension(10, av.getCharHeight() + fm.getDescent()));
238 idwidthAdjuster.invalidate();
239 scalePanelHolder.invalidate();
240 // BH 2018 getIdPanel().getIdCanvas().gg = null;
241 getSeqPanel().seqCanvas.img = null;
242 getAnnotationPanel().adjustPanelHeight();
244 Dimension d = calculateIdWidth();
246 d.setSize(d.width + 4, d.height);
247 getIdPanel().getIdCanvas().setPreferredSize(d);
248 hscrollFillerPanel.setPreferredSize(d);
254 * Calculate the width of the alignment labels based on the displayed names
255 * and any bounds on label width set in preferences.
257 * @return Dimension giving the maximum width of the alignment label panel
258 * that should be used.
260 public Dimension calculateIdWidth()
262 // calculate sensible default width when no preference is available
264 if (av.getIdWidth() < 0)
266 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
267 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
268 r = calculateIdWidth(maxwidth);
269 av.setIdWidth(r.width);
274 r.width = av.getIdWidth();
281 * Calculate the width of the alignment labels based on the displayed names
282 * and any bounds on label width set in preferences.
285 * -1 or maximum width allowed for IdWidth
286 * @return Dimension giving the maximum width of the alignment label panel
287 * that should be used.
289 public Dimension calculateIdWidth(int maxwidth)
291 Container c = new Container();
293 FontMetrics fm = c.getFontMetrics(
294 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
296 AlignmentI al = av.getAlignment();
301 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
303 SequenceI s = al.getSequenceAt(i);
305 id = s.getDisplayId(av.getShowJVSuffix());
307 if (fm.stringWidth(id) > idWidth)
309 idWidth = fm.stringWidth(id);
315 // Also check annotation label widths
318 if (al.getAlignmentAnnotation() != null)
320 fm = c.getFontMetrics(getAlabels().getFont());
322 while (i < al.getAlignmentAnnotation().length)
324 String label = al.getAlignmentAnnotation()[i].label;
326 if (fm.stringWidth(label) > idWidth)
328 idWidth = fm.stringWidth(label);
335 return new Dimension(
336 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
340 * Highlight the given results on the alignment
343 public void highlightSearchResults(SearchResultsI results)
345 boolean scrolled = scrollToPosition(results, 0, false);
347 boolean fastPaint = !(scrolled && av.getWrapAlignment());
349 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
353 * Scroll the view to show the position of the highlighted region in results
356 * @param searchResults
359 public boolean scrollToPosition(SearchResultsI searchResults)
361 return scrollToPosition(searchResults, 0, false);
365 * Scrolls the view (if necessary) to show the position of the first
366 * highlighted region in results (if any). Answers true if the view was
367 * scrolled, or false if no matched region was found, or it is already
371 * @param verticalOffset
372 * if greater than zero, allows scrolling to a position below the
373 * first displayed sequence
375 * if true, try to centre the search results horizontally in the view
378 protected boolean scrollToPosition(SearchResultsI results,
379 int verticalOffset, boolean centre)
381 int startv, endv, starts, ends;
382 ViewportRanges ranges = av.getRanges();
384 if (results == null || results.isEmpty() || av == null
385 || av.getAlignment() == null)
389 int seqIndex = av.getAlignment().findIndex(results);
394 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
396 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
405 * To centre results, scroll to positions half the visible width
406 * left/right of the start/end positions
410 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
411 start = Math.max(start - offset, 0);
412 end = end + offset - 1;
418 if (end == seq.getEnd())
423 if (av.hasHiddenColumns())
425 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
426 start = hidden.absoluteToVisibleColumn(start);
427 end = hidden.absoluteToVisibleColumn(end);
430 if (!hidden.isVisible(r[0]))
432 // don't scroll - position isn't visible
439 * allow for offset of target sequence (actually scroll to one above it)
441 seqIndex = Math.max(0, seqIndex - verticalOffset);
442 boolean scrollNeeded = true;
444 if (!av.getWrapAlignment())
446 if ((startv = ranges.getStartRes()) >= start)
449 * Scroll left to make start of search results visible
451 setScrollValues(start, seqIndex);
453 else if ((endv = ranges.getEndRes()) <= end)
456 * Scroll right to make end of search results visible
458 setScrollValues(startv + end - endv, seqIndex);
460 else if ((starts = ranges.getStartSeq()) > seqIndex)
463 * Scroll up to make start of search results visible
465 setScrollValues(ranges.getStartRes(), seqIndex);
467 else if ((ends = ranges.getEndSeq()) <= seqIndex)
470 * Scroll down to make end of search results visible
472 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
476 * Else results are already visible - no need to scroll
478 scrollNeeded = false;
482 scrollNeeded = ranges.scrollToWrappedVisible(start);
485 paintAlignment(false, false);
493 * @return DOCUMENT ME!
495 public OverviewPanel getOverviewPanel()
497 return overviewPanel;
506 public void setOverviewPanel(OverviewPanel op)
514 * Hide or show annotation panel
517 public void setAnnotationVisible(boolean b)
519 if (!av.getWrapAlignment())
521 annotationSpaceFillerHolder.setVisible(b);
522 annotationScroller.setVisible(b);
528 * automatically adjust annotation panel height for new annotation whilst
529 * ensuring the alignment is still visible.
532 public void adjustAnnotationHeight()
534 // TODO: display vertical annotation scrollbar if necessary
535 // this is called after loading new annotation onto alignment
536 if (alignFrame.getHeight() == 0)
538 System.out.println("NEEDS FIXING");
540 validateAnnotationDimensions(true);
542 // TODO: many places call this method and also paintAlignment with various
543 // different settings. this means multiple redraws are triggered...
544 paintAlignment(true, av.needToUpdateStructureViews());
548 * calculate the annotation dimensions and refresh slider values accordingly.
549 * need to do repaints/notifys afterwards.
551 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
553 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
554 // are not changing ancestors, and keyboard action listeners do
555 // not need to be reset. addNotify() is a very expensive operation,
556 // requiring a full re-layout of all parents and children.
557 // Note in JComponent:
558 // This method is called by the toolkit internally and should
559 // not be called directly by programs.
560 // I note that addNotify() is called in several areas of Jalview.
562 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
563 annotationHeight = getAnnotationPanel()
564 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
567 annotationScroller.setPreferredSize(
568 new Dimension(annotationScroller.getWidth(), annotationHeight));
570 Dimension e = idPanel.getSize();
571 alabels.setSize(new Dimension(e.width, annotationHeight));
574 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
575 annotationSpaceFillerHolder.getWidth(), annotationHeight));
576 annotationScroller.validate();
577 annotationScroller.addNotify();
581 * update alignment layout for viewport settings
586 public void updateLayout()
589 setAnnotationVisible(av.isShowAnnotation());
590 boolean wrap = av.getWrapAlignment();
591 ViewportRanges ranges = av.getRanges();
592 ranges.setStartSeq(0);
593 scalePanelHolder.setVisible(!wrap);
594 hscroll.setVisible(!wrap);
595 idwidthAdjuster.setVisible(!wrap);
599 annotationScroller.setVisible(false);
600 annotationSpaceFillerHolder.setVisible(false);
602 else if (av.isShowAnnotation())
604 annotationScroller.setVisible(true);
605 annotationSpaceFillerHolder.setVisible(true);
606 validateAnnotationDimensions(false);
609 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
611 { // may not yet be laid out
614 int widthInRes = getSeqPanel().seqCanvas
615 .getWrappedCanvasWidth(canvasWidth);
616 ranges.setViewportWidth(widthInRes);
620 int widthInRes = (canvasWidth / av.getCharWidth());
621 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
622 / av.getCharHeight());
624 ranges.setViewportWidth(widthInRes);
625 ranges.setViewportHeight(heightInSeq);
629 idSpaceFillerPanel1.setVisible(!wrap);
635 * Adjust row/column scrollers to show a visible position in the alignment.
638 * visible column to scroll to
640 * visible row to scroll to
643 public void setScrollValues(int xpos, int ypos)
648 if (av == null || av.getAlignment() == null)
653 if (av.getWrapAlignment())
655 setScrollingForWrappedPanel(x);
659 int width = av.getAlignment().getVisibleWidth();
660 int height = av.getAlignment().getHeight();
662 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
663 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
670 if (vextent > height)
675 if ((hextent + x) > width)
680 if ((vextent + y) > height)
682 y = height - vextent;
695 // update the scroll values
696 hscroll.setValues(x, hextent, 0, width);
697 vscroll.setValues(y, vextent, 0, height);
702 * Respond to adjustment event when horizontal or vertical scrollbar is
706 * adjustment event encoding whether hscroll or vscroll changed
709 public void adjustmentValueChanged(AdjustmentEvent evt)
711 if (av.getWrapAlignment())
713 adjustScrollingWrapped(evt);
717 ViewportRanges ranges = av.getRanges();
719 if (evt.getSource() == hscroll)
721 int oldX = ranges.getStartRes();
722 int oldwidth = ranges.getViewportWidth();
723 int x = hscroll.getValue();
724 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
726 // if we're scrolling to the position we're already at, stop
727 // this prevents infinite recursion of events when the scroll/viewport
728 // ranges values are the same
729 if ((x == oldX) && (width == oldwidth))
733 ranges.setViewportStartAndWidth(x, width);
735 else if (evt.getSource() == vscroll)
737 int oldY = ranges.getStartSeq();
738 int oldheight = ranges.getViewportHeight();
739 int y = vscroll.getValue();
740 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
742 // if we're scrolling to the position we're already at, stop
743 // this prevents infinite recursion of events when the scroll/viewport
744 // ranges values are the same
745 if ((y == oldY) && (height == oldheight))
749 ranges.setViewportStartAndHeight(y, height);
755 * Responds to a scroll change by setting the start position of the viewport.
760 protected void adjustScrollingWrapped(AdjustmentEvent evt)
762 if (evt.getSource() == hscroll)
764 return; // no horizontal scroll when wrapped
766 final ViewportRanges ranges = av.getRanges();
768 if (evt.getSource() == vscroll)
770 int newY = vscroll.getValue();
773 * if we're scrolling to the position we're already at, stop
774 * this prevents infinite recursion of events when the scroll/viewport
775 * ranges values are the same
777 int oldX = ranges.getStartRes();
778 int oldY = ranges.getWrappedScrollPosition(oldX);
786 * limit page up/down to one width's worth of positions
788 int rowSize = ranges.getViewportWidth();
789 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
790 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
795 // This is only called if file loaded is a jar file that
796 // was wrapped when saved and user has wrap alignment true
797 // as preference setting
798 SwingUtilities.invokeLater(new Runnable()
803 // When updating scrolling to use ViewportChange events, this code
804 // could not be validated and it is not clear if it is now being
805 // called. Log warning here in case it is called and unforeseen
808 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
810 // scroll to start of panel
811 ranges.setStartRes(0);
812 ranges.setStartSeq(0);
820 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
823 public void paintAlignment(boolean updateOverview,
824 boolean updateStructures)
826 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
827 av.isShowAutocalculatedAbove());
828 sorter.sort(getAlignment().getAlignmentAnnotation(),
829 av.getSortAnnotationsBy());
832 if (updateStructures)
834 av.getStructureSelectionManager().sequenceColoursChanged(this);
839 if (overviewPanel != null)
841 overviewPanel.updateOverviewImage();
853 public void paintComponent(Graphics g)
855 invalidate(); // needed so that the id width adjuster works correctly
857 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
858 idPanelHolder.setPreferredSize(d);
859 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
861 validate(); // needed so that the id width adjuster works correctly
864 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
865 * though I still think this call should be elsewhere.
867 ViewportRanges ranges = av.getRanges();
868 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
869 super.paintComponent(g);
873 * Set vertical scroll bar position, and number of increments, for wrapped
876 * @param topLeftColumn
877 * the column position at top left (0..)
879 private void setScrollingForWrappedPanel(int topLeftColumn)
881 ViewportRanges ranges = av.getRanges();
882 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
883 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
886 * a scrollbar's value can be set to at most (maximum-extent)
887 * so we add extent (1) to the maxScroll value
889 vscroll.setUnitIncrement(1);
890 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
903 * @return DOCUMENT ME!
905 * @throws PrinterException
909 public int print(Graphics pg, PageFormat pf, int pi)
910 throws PrinterException
912 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
914 int pwidth = (int) pf.getImageableWidth();
915 int pheight = (int) pf.getImageableHeight();
917 if (av.getWrapAlignment())
919 return printWrappedAlignment(pwidth, pheight, pi, pg);
923 return printUnwrapped(pwidth, pheight, pi, pg, pg);
928 * Draws the alignment image, including sequence ids, sequences, and
929 * annotation labels and annotations if shown, on either one or two Graphics
939 * the graphics context for sequence ids and annotation labels
940 * @param alignmentGraphics
941 * the graphics context for sequences and annotations (may or may not
942 * be the same context as idGraphics)
944 * @throws PrinterException
946 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
947 Graphics idGraphics, Graphics alignmentGraphics)
948 throws PrinterException
950 final int idWidth = getVisibleIdWidth(false);
953 * Get the horizontal offset to where we draw the sequences.
954 * This is idWidth if using a single Graphics context, else zero.
956 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
959 FontMetrics fm = getFontMetrics(av.getFont());
960 final int charHeight = av.getCharHeight();
961 final int scaleHeight = charHeight + fm.getDescent();
963 idGraphics.setColor(Color.white);
964 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
965 idGraphics.setFont(av.getFont());
968 * How many sequences and residues can we fit on a printable page?
970 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
972 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
974 final int alignmentWidth = av.getAlignment().getVisibleWidth();
975 int pagesWide = (alignmentWidth / totalRes) + 1;
977 final int startRes = (pageIndex % pagesWide) * totalRes;
978 final int endRes = Math.min(startRes + totalRes - 1,
981 final int startSeq = (pageIndex / pagesWide) * totalSeq;
982 final int alignmentHeight = av.getAlignment().getHeight();
983 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
985 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
987 if (av.isShowAnnotation())
989 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
992 pagesHigh /= pageHeight;
994 if (pageIndex >= (pagesWide * pagesHigh))
996 return Printable.NO_SUCH_PAGE;
998 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1001 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1003 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1004 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1005 pageWidth - idWidth, scaleHeight);
1006 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1009 * Draw the sequence ids, offset for scale height,
1010 * then reset to top left (0, 0)
1012 idGraphics.translate(0, scaleHeight);
1013 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1014 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1015 : av.getSelectionGroup().getSequences(null);
1016 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1019 idGraphics.setFont(av.getFont());
1020 idGraphics.translate(0, -scaleHeight);
1023 * draw the sequences, offset for scale height, and id width (if using a
1024 * single graphics context), then reset to (0, scale height)
1026 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1027 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1028 endRes, startSeq, endSeq - 1);
1029 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1031 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1034 * draw annotation labels; drawComponent() translates by
1035 * getScrollOffset(), so compensate for that first;
1036 * then reset to (0, scale height)
1038 int offset = getAlabels().getScrollOffset();
1039 idGraphics.translate(0, -offset);
1040 idGraphics.translate(0, alignmentDrawnHeight);
1041 getAlabels().drawComponent(idGraphics, idWidth);
1042 idGraphics.translate(0, -alignmentDrawnHeight);
1045 * draw the annotations starting at
1046 * (idOffset, alignmentHeight) from (0, scaleHeight)
1048 alignmentGraphics.translate(alignmentGraphicsOffset,
1049 alignmentDrawnHeight);
1050 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1051 alignmentGraphics, -1, startRes, endRes + 1);
1054 return Printable.PAGE_EXISTS;
1058 * Prints one page of an alignment in wrapped mode. Returns
1059 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1060 * no page could be drawn (page number out of range).
1070 * @throws PrinterException
1072 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1073 Graphics g) throws PrinterException
1075 int annotationHeight = 0;
1076 if (av.isShowAnnotation())
1078 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1081 int hgap = av.getCharHeight();
1082 if (av.getScaleAboveWrapped())
1084 hgap += av.getCharHeight();
1087 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1090 int idWidth = getVisibleIdWidth(false);
1092 int maxwidth = av.getAlignment().getVisibleWidth();
1094 int resWidth = getSeqPanel().seqCanvas
1095 .getWrappedCanvasWidth(pageWidth - idWidth);
1097 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1099 g.setColor(Color.white);
1100 g.fillRect(0, 0, pageWidth, pageHeight);
1101 g.setFont(av.getFont());
1102 g.setColor(Color.black);
1105 * method: print the whole wrapped alignment, but with a clip region that
1106 * is restricted to the requested page; this supports selective print of
1107 * single pages or ranges, (at the cost of some repeated processing in
1108 * the 'normal' case, when all pages are printed)
1110 g.translate(0, -pageNumber * pageHeight);
1112 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1115 * draw sequence ids and annotation labels (if shown)
1117 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1118 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1120 g.translate(idWidth, 0);
1122 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1125 if ((pageNumber * pageHeight) < totalHeight)
1127 return Printable.PAGE_EXISTS;
1131 return Printable.NO_SUCH_PAGE;
1136 * get current sequence ID panel width, or nominal value if panel were to be
1137 * displayed using default settings
1141 public int getVisibleIdWidth()
1143 return getVisibleIdWidth(true);
1147 * get current sequence ID panel width, or nominal value if panel were to be
1148 * displayed using default settings
1151 * indicate if the Id width for onscreen or offscreen display should
1155 public int getVisibleIdWidth(boolean onscreen)
1157 // see if rendering offscreen - check preferences and calc width accordingly
1158 if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1160 return calculateIdWidth(-1).width + 4;
1162 Integer idwidth = null;
1163 if (onscreen || (idwidth = Cache
1164 .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1166 int w = getIdPanel().getWidth();
1167 return (w > 0 ? w : calculateIdWidth().width + 4);
1169 return idwidth.intValue() + 4;
1173 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1174 * writes it to the specified file
1179 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1181 final int borderBottomOffset = 5;
1183 AlignmentDimension aDimension = getAlignmentDimension();
1184 // todo use a lambda function in place of callback here?
1185 ImageWriterI writer = new ImageWriterI()
1188 public void exportImage(Graphics graphics) throws Exception
1190 if (av.getWrapAlignment())
1192 printWrappedAlignment(aDimension.getWidth(),
1193 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1197 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1198 graphics, graphics);
1203 String fileTitle = alignFrame.getTitle();
1204 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1206 int imageWidth = aDimension.getWidth();
1207 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1208 String of = MessageManager.getString("label.alignment");
1209 exporter.doExport(file, this, imageWidth, imageHeight, of);
1213 * Calculates and returns a suitable width and height (in pixels) for an
1218 public AlignmentDimension getAlignmentDimension()
1220 int maxwidth = av.getAlignment().getVisibleWidth();
1222 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1223 + getScalePanel().getHeight();
1224 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1226 if (av.getWrapAlignment())
1228 height = getWrappedHeight();
1229 if (Jalview.isHeadlessMode())
1231 // need to obtain default alignment width and then add in any
1232 // additional allowance for id margin
1233 // this duplicates the calculation in getWrappedHeight but adjusts for
1235 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1236 - alignFrame.getInsets().left - alignFrame.getInsets().right
1237 - getVisibleIdWidth() + getVisibleIdWidth(false);
1241 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1245 else if (av.isShowAnnotation())
1247 height += getAnnotationPanel().adjustPanelHeight() + 3;
1249 return new AlignmentDimension(width, height);
1253 public void makePNGImageMap(File imgMapFile, String imageName)
1255 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1256 // ////////////////////////////////////////////
1257 int idWidth = getVisibleIdWidth(false);
1258 FontMetrics fm = getFontMetrics(av.getFont());
1259 int scaleHeight = av.getCharHeight() + fm.getDescent();
1262 // ////////////////////////////////
1263 if (imgMapFile != null)
1267 int sSize = av.getAlignment().getHeight();
1268 int alwidth = av.getAlignment().getWidth();
1269 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1270 out.println(HTMLOutput.getImageMapHTML());
1271 out.println("<img src=\"" + imageName
1272 + "\" border=\"0\" usemap=\"#Map\" >"
1273 + "<map name=\"Map\">");
1275 for (int s = 0; s < sSize; s++)
1277 int sy = s * av.getCharHeight() + scaleHeight;
1279 SequenceI seq = av.getAlignment().getSequenceAt(s);
1280 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1281 for (int column = 0; column < alwidth; column++)
1283 StringBuilder text = new StringBuilder(512);
1284 String triplet = null;
1285 if (av.getAlignment().isNucleotide())
1287 triplet = ResidueProperties.nucleotideName.get(seq
1288 .getCharAt(column) + "");
1292 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1296 if (triplet == null)
1301 int seqPos = seq.findPosition(column);
1302 int gSize = groups.length;
1303 for (int g = 0; g < gSize; g++)
1305 if (text.length() < 1)
1307 text.append("<area shape=\"rect\" coords=\"")
1308 .append((idWidth + column * av.getCharWidth()))
1309 .append(",").append(sy).append(",")
1310 .append((idWidth + (column + 1) * av.getCharWidth()))
1311 .append(",").append((av.getCharHeight() + sy))
1312 .append("\"").append(" onMouseOver=\"toolTip('")
1313 .append(seqPos).append(" ").append(triplet);
1316 if (groups[g].getStartRes() < column
1317 && groups[g].getEndRes() > column)
1319 text.append("<br><em>").append(groups[g].getName())
1324 if (text.length() < 1)
1326 text.append("<area shape=\"rect\" coords=\"")
1327 .append((idWidth + column * av.getCharWidth()))
1328 .append(",").append(sy).append(",")
1329 .append((idWidth + (column + 1) * av.getCharWidth()))
1330 .append(",").append((av.getCharHeight() + sy))
1331 .append("\"").append(" onMouseOver=\"toolTip('")
1332 .append(seqPos).append(" ").append(triplet);
1334 if (!Comparison.isGap(seq.getCharAt(column)))
1336 List<SequenceFeature> features = seq.findFeatures(column, column);
1337 for (SequenceFeature sf : features)
1339 if (sf.isContactFeature())
1341 text.append("<br>").append(sf.getType()).append(" ")
1342 .append(sf.getBegin()).append(":")
1343 .append(sf.getEnd());
1347 text.append("<br>");
1348 text.append(sf.getType());
1349 String description = sf.getDescription();
1350 if (description != null
1351 && !sf.getType().equals(description))
1353 description = description.replace("\"", """);
1354 text.append(" ").append(description);
1357 String status = sf.getStatus();
1358 if (status != null && !"".equals(status))
1360 text.append(" (").append(status).append(")");
1363 if (text.length() > 1)
1365 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1366 out.println(text.toString());
1371 out.println("</map></body></html>");
1374 } catch (Exception ex)
1376 ex.printStackTrace();
1378 } // /////////END OF IMAGE MAP
1382 int getWrappedHeight()
1384 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1386 if (Jalview.isHeadlessMode())
1388 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1389 - vscroll.getPreferredSize().width
1390 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1393 int chunkWidth = getSeqPanel().seqCanvas
1394 .getWrappedCanvasWidth(seqPanelWidth);
1396 int hgap = av.getCharHeight();
1397 if (av.getScaleAboveWrapped())
1399 hgap += av.getCharHeight();
1402 int annotationHeight = 0;
1403 if (av.isShowAnnotation())
1405 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1408 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1411 int maxwidth = av.getAlignment().getWidth();
1412 if (av.hasHiddenColumns())
1414 maxwidth = av.getAlignment().getHiddenColumns()
1415 .absoluteToVisibleColumn(maxwidth) - 1;
1418 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1424 * close the panel - deregisters all listeners and nulls any references to
1427 public void closePanel()
1429 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1430 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1431 PaintRefresher.RemoveComponent(this);
1436 * try to ensure references are nulled
1438 if (annotationPanel != null)
1440 annotationPanel.dispose();
1441 annotationPanel = null;
1446 av.removePropertyChangeListener(propertyChangeListener);
1447 propertyChangeListener = null;
1448 StructureSelectionManager ssm = av.getStructureSelectionManager();
1449 ssm.removeStructureViewerListener(getSeqPanel(), null);
1450 ssm.removeSelectionListener(getSeqPanel());
1451 ssm.removeCommandListener(av);
1452 ssm.removeStructureViewerListener(getSeqPanel(), null);
1453 ssm.removeSelectionListener(getSeqPanel());
1459 if (Cache.log.isDebugEnabled())
1461 Cache.log.warn("Closing alignment panel which is already closed.");
1467 * Close any open dialogs that would be orphaned when this one is closed
1469 protected void closeChildFrames()
1471 if (overviewPanel != null)
1473 overviewPanel.dispose();
1474 overviewPanel = null;
1476 if (calculationDialog != null)
1478 calculationDialog.closeFrame();
1479 calculationDialog = null;
1484 * hides or shows dynamic annotation rows based on groups and av state flags
1486 public void updateAnnotation()
1488 updateAnnotation(false, false);
1491 public void updateAnnotation(boolean applyGlobalSettings)
1493 updateAnnotation(applyGlobalSettings, false);
1496 public void updateAnnotation(boolean applyGlobalSettings,
1497 boolean preserveNewGroupSettings)
1499 av.updateGroupAnnotationSettings(applyGlobalSettings,
1500 preserveNewGroupSettings);
1501 adjustAnnotationHeight();
1505 public AlignmentI getAlignment()
1507 return av == null ? null : av.getAlignment();
1511 public String getViewName()
1513 return av.getViewName();
1517 * Make/Unmake this alignment panel the current input focus
1521 public void setSelected(boolean b)
1525 if (alignFrame.getSplitViewContainer() != null)
1528 * bring enclosing SplitFrame to front first if there is one
1530 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1532 alignFrame.setSelected(b);
1533 } catch (Exception ex)
1539 alignFrame.setDisplayedView(this);
1544 public StructureSelectionManager getStructureSelectionManager()
1546 return av.getStructureSelectionManager();
1550 public void raiseOOMWarning(String string, OutOfMemoryError error)
1552 new OOMWarning(string, error, this);
1556 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1559 return new FeatureRenderer(this);
1563 public jalview.api.FeatureRenderer getFeatureRenderer()
1565 return seqPanel.seqCanvas.getFeatureRenderer();
1568 public void updateFeatureRenderer(
1569 jalview.renderer.seqfeatures.FeatureRenderer fr)
1571 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1574 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1576 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1578 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1582 public ScalePanel getScalePanel()
1587 public void setScalePanel(ScalePanel scalePanel)
1589 this.scalePanel = scalePanel;
1592 public SeqPanel getSeqPanel()
1597 public void setSeqPanel(SeqPanel seqPanel)
1599 this.seqPanel = seqPanel;
1602 public AnnotationPanel getAnnotationPanel()
1604 return annotationPanel;
1607 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1609 this.annotationPanel = annotationPanel;
1612 public AnnotationLabels getAlabels()
1617 public void setAlabels(AnnotationLabels alabels)
1619 this.alabels = alabels;
1622 public IdPanel getIdPanel()
1627 public void setIdPanel(IdPanel idPanel)
1629 this.idPanel = idPanel;
1633 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1634 * The aim is to keep the two alignments 'lined up' on their centre columns.
1637 * holds mapped region(s) of this alignment that we are scrolling
1638 * 'to'; may be modified for sequence offset by this method
1639 * @param verticalOffset
1640 * the number of visible sequences to show above the mapped region
1642 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1644 scrollToPosition(sr, verticalOffset, true);
1648 * Set a flag to say do not scroll any (cDNA/protein) complement.
1652 protected void setToScrollComplementPanel(boolean b)
1654 this.scrollComplementaryPanel = b;
1658 * Get whether to scroll complement panel
1660 * @return true if cDNA/protein complement panels should be scrolled
1662 protected boolean isSetToScrollComplementPanel()
1664 return this.scrollComplementaryPanel;
1670 * @adjustHeight if true, try to recalculate panel height for visible
1673 protected void refresh(boolean adjustHeight)
1675 validateAnnotationDimensions(adjustHeight);
1679 // sort, repaint, update overview
1680 paintAlignment(true, false);
1684 // lightweight repaint
1691 * Property change event fired when a change is made to the viewport ranges
1692 * object associated with this alignment panel's viewport
1694 public void propertyChange(PropertyChangeEvent evt)
1696 // update this panel's scroll values based on the new viewport ranges values
1697 ViewportRanges ranges = av.getRanges();
1698 int x = ranges.getStartRes();
1699 int y = ranges.getStartSeq();
1700 setScrollValues(x, y);
1702 // now update any complementary alignment (its viewport ranges object
1703 // is different so does not get automatically updated)
1704 if (isSetToScrollComplementPanel())
1706 setToScrollComplementPanel(false);
1707 av.scrollComplementaryAlignment();
1708 setToScrollComplementPanel(true);
1713 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1714 * reference should be nulled when the dialog is closed.
1716 * @param calculationChooser
1718 public void setCalculationDialog(CalculationChooser calculationChooser)
1720 calculationDialog = calculationChooser;
1724 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1727 public CalculationChooser getCalculationDialog()
1729 return calculationDialog;
1733 public SequenceRenderer getSequenceRenderer()
1735 return seqPanel.seqCanvas.getSequenceRenderer();
1738 public boolean scrollTo(int ostart, int end, int seqIndex,
1739 boolean scrollToNearest, boolean redrawOverview)
1741 int startv, endv, starts, ends;// , width;
1744 if (av.hasHiddenColumns())
1746 AlignmentI al = av.getAlignment();
1747 start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1748 end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1751 if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1753 // don't scroll - position isn't visible
1763 ViewportRanges ranges = av.getRanges();
1764 if (!av.getWrapAlignment())
1767 * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1768 * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1769 * setScrollValues(start - 1, seqIndex); } else if ((endv =
1770 * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1771 * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1772 * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1773 * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1774 * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1777 // below is scrolling logic up to Jalview 2.8.2
1778 // if ((av.getStartRes() > end)
1779 // || (av.getEndRes() < start)
1780 // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1782 // if (start > av.getAlignment().getWidth() - hextent)
1784 // start = av.getAlignment().getWidth() - hextent;
1791 // if (seqIndex > av.getAlignment().getHeight() - vextent)
1793 // seqIndex = av.getAlignment().getHeight() - vextent;
1794 // if (seqIndex < 0)
1799 // setScrollValues(start, seqIndex);
1801 // logic copied from jalview.gui.AlignmentPanel:
1802 if ((startv = ranges.getStartRes()) >= start)
1805 * Scroll left to make start of search results visible
1807 setScrollValues(start - 1, seqIndex);
1809 else if ((endv = ranges.getEndRes()) <= end)
1812 * Scroll right to make end of search results visible
1814 setScrollValues(startv + 1 + end - endv, seqIndex);
1816 else if ((starts = ranges.getStartSeq()) > seqIndex)
1819 * Scroll up to make start of search results visible
1821 setScrollValues(ranges.getStartRes(), seqIndex);
1823 else if ((ends = ranges.getEndSeq()) <= seqIndex)
1826 * Scroll down to make end of search results visible
1828 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1831 * Else results are already visible - no need to scroll
1836 ranges.scrollToWrappedVisible(start);
1839 paintAlignment(redrawOverview, false);