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.bin.Cache;
27 import jalview.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.ImageExporter.ImageWriterI;
35 import jalview.io.HTMLOutput;
36 import jalview.jbgui.GAlignmentPanel;
37 import jalview.math.AlignmentDimension;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.ImageMaker;
42 import jalview.util.MessageManager;
43 import jalview.viewmodel.ViewportListenerI;
44 import jalview.viewmodel.ViewportRanges;
46 import java.awt.BorderLayout;
47 import java.awt.Color;
48 import java.awt.Container;
49 import java.awt.Dimension;
51 import java.awt.FontMetrics;
52 import java.awt.Graphics;
53 import java.awt.Graphics2D;
54 import java.awt.event.AdjustmentEvent;
55 import java.awt.event.AdjustmentListener;
56 import java.awt.event.ComponentAdapter;
57 import java.awt.event.ComponentEvent;
58 import java.awt.print.PageFormat;
59 import java.awt.print.Printable;
60 import java.awt.print.PrinterException;
61 import java.beans.PropertyChangeEvent;
62 import java.beans.PropertyChangeListener;
64 import java.io.FileWriter;
65 import java.io.PrintWriter;
66 import java.util.List;
68 import javax.swing.SwingUtilities;
74 * @version $Revision: 1.161 $
76 @SuppressWarnings("serial")
77 public class AlignmentPanel extends GAlignmentPanel implements
78 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
80 public AlignViewport av;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * false, suppresses invoking the same method recursively.
106 private boolean scrollComplementaryPanel = true;
108 private PropertyChangeListener propertyChangeListener;
110 private CalculationChooser calculationDialog;
113 * Creates a new AlignmentPanel object.
118 public AlignmentPanel(AlignFrame af, final AlignViewport av)
120 // setBackground(Color.white); // BH 2019
123 setSeqPanel(new SeqPanel(av, this));
124 setIdPanel(new IdPanel(av, this));
126 setScalePanel(new ScalePanel(av, this));
128 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
129 idwidthAdjuster = new IdwidthAdjuster(this);
130 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
132 setAnnotationPanel(new AnnotationPanel(this));
133 setAlabels(new AnnotationLabels(this));
135 annotationScroller.setViewportView(getAnnotationPanel());
136 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
138 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
139 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
141 setScrollValues(0, 0);
143 hscroll.addAdjustmentListener(this);
144 vscroll.addAdjustmentListener(this);
146 addComponentListener(new ComponentAdapter()
149 public void componentResized(ComponentEvent evt)
151 // reset the viewport ranges when the alignment panel is resized
152 // in particular, this initialises the end residue value when Jalview
154 ViewportRanges ranges = av.getRanges();
155 if (av.getWrapAlignment())
157 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
158 getSeqPanel().seqCanvas.getWidth());
159 ranges.setViewportWidth(widthInRes);
163 int widthInRes = getSeqPanel().seqCanvas.getWidth()
165 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
166 / av.getCharHeight();
168 ranges.setViewportWidth(widthInRes);
169 ranges.setViewportHeight(heightInSeq);
175 final AlignmentPanel ap = this;
176 propertyChangeListener = new PropertyChangeListener()
179 public void propertyChange(PropertyChangeEvent evt)
181 if (evt.getPropertyName().equals("alignment"))
183 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
188 av.addPropertyChangeListener(propertyChangeListener);
190 av.getRanges().addPropertyChangeListener(this);
192 adjustAnnotationHeight();
197 public AlignViewportI getAlignViewport()
202 public void alignmentChanged()
204 av.alignmentChanged(this);
206 if (getCalculationDialog() != null)
208 getCalculationDialog().validateCalcTypes();
211 alignFrame.updateEditMenuBar();
213 // no idea if we need to update structure
214 paintAlignment(true, true);
221 public void fontChanged()
223 // set idCanvas bufferedImage to null
224 // to prevent drawing old image
225 FontMetrics fm = getFontMetrics(av.getFont());
227 scalePanelHolder.setPreferredSize(
228 new Dimension(10, av.getCharHeight() + fm.getDescent()));
229 idSpaceFillerPanel1.setPreferredSize(
230 new Dimension(10, av.getCharHeight() + fm.getDescent()));
231 idwidthAdjuster.invalidate();
232 scalePanelHolder.invalidate();
233 // BH 2018 getIdPanel().getIdCanvas().gg = null;
234 getSeqPanel().seqCanvas.img = null;
235 getAnnotationPanel().adjustPanelHeight();
237 Dimension d = calculateIdWidth();
239 d.setSize(d.width + 4, d.height);
240 getIdPanel().getIdCanvas().setPreferredSize(d);
241 hscrollFillerPanel.setPreferredSize(d);
247 * Calculate the width of the alignment labels based on the displayed names
248 * and any bounds on label width set in preferences.
250 * @return Dimension giving the maximum width of the alignment label panel
251 * that should be used.
253 public Dimension calculateIdWidth()
255 // calculate sensible default width when no preference is available
257 if (av.getIdWidth() < 0)
259 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
260 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
261 r = calculateIdWidth(maxwidth);
262 av.setIdWidth(r.width);
267 r.width = av.getIdWidth();
274 * Calculate the width of the alignment labels based on the displayed names
275 * and any bounds on label width set in preferences.
278 * -1 or maximum width allowed for IdWidth
279 * @return Dimension giving the maximum width of the alignment label panel
280 * that should be used.
282 public Dimension calculateIdWidth(int maxwidth)
284 Container c = new Container();
286 FontMetrics fm = c.getFontMetrics(
287 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
289 AlignmentI al = av.getAlignment();
294 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
296 SequenceI s = al.getSequenceAt(i);
298 id = s.getDisplayId(av.getShowJVSuffix());
300 if (fm.stringWidth(id) > idWidth)
302 idWidth = fm.stringWidth(id);
308 // Also check annotation label widths
311 if (al.getAlignmentAnnotation() != null)
313 fm = c.getFontMetrics(getAlabels().getFont());
315 while (i < al.getAlignmentAnnotation().length)
317 String label = al.getAlignmentAnnotation()[i].label;
319 if (fm.stringWidth(label) > idWidth)
321 idWidth = fm.stringWidth(label);
328 return new Dimension(
329 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
333 * Highlight the given results on the alignment
336 public void highlightSearchResults(SearchResultsI results)
338 boolean scrolled = scrollToPosition(results, 0, false);
340 boolean fastPaint = !(scrolled && av.getWrapAlignment());
342 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
346 * Scroll the view to show the position of the highlighted region in results
349 * @param searchResults
352 public boolean scrollToPosition(SearchResultsI searchResults)
354 return scrollToPosition(searchResults, 0, false);
358 * Scrolls the view (if necessary) to show the position of the first
359 * highlighted region in results (if any). Answers true if the view was
360 * scrolled, or false if no matched region was found, or it is already
364 * @param verticalOffset
365 * if greater than zero, allows scrolling to a position below the
366 * first displayed sequence
368 * if true, try to centre the search results horizontally in the view
371 protected boolean scrollToPosition(SearchResultsI results,
372 int verticalOffset, boolean centre)
374 int startv, endv, starts, ends;
375 ViewportRanges ranges = av.getRanges();
377 if (results == null || results.isEmpty() || av == null
378 || av.getAlignment() == null)
382 int seqIndex = av.getAlignment().findIndex(results);
387 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
389 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
398 * To centre results, scroll to positions half the visible width
399 * left/right of the start/end positions
403 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
404 start = Math.max(start - offset, 0);
405 end = end + offset - 1;
411 if (end == seq.getEnd())
416 if (av.hasHiddenColumns())
418 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
419 start = hidden.absoluteToVisibleColumn(start);
420 end = hidden.absoluteToVisibleColumn(end);
423 if (!hidden.isVisible(r[0]))
425 // don't scroll - position isn't visible
432 * allow for offset of target sequence (actually scroll to one above it)
434 seqIndex = Math.max(0, seqIndex - verticalOffset);
435 boolean scrollNeeded = true;
437 if (!av.getWrapAlignment())
439 if ((startv = ranges.getStartRes()) >= start)
442 * Scroll left to make start of search results visible
444 setScrollValues(start, seqIndex);
446 else if ((endv = ranges.getEndRes()) <= end)
449 * Scroll right to make end of search results visible
451 setScrollValues(startv + end - endv, seqIndex);
453 else if ((starts = ranges.getStartSeq()) > seqIndex)
456 * Scroll up to make start of search results visible
458 setScrollValues(ranges.getStartRes(), seqIndex);
460 else if ((ends = ranges.getEndSeq()) <= seqIndex)
463 * Scroll down to make end of search results visible
465 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
469 * Else results are already visible - no need to scroll
471 scrollNeeded = false;
475 scrollNeeded = ranges.scrollToWrappedVisible(start);
478 paintAlignment(false, false);
486 * @return DOCUMENT ME!
488 public OverviewPanel getOverviewPanel()
490 return overviewPanel;
499 public void setOverviewPanel(OverviewPanel op)
507 * Hide or show annotation panel
510 public void setAnnotationVisible(boolean b)
512 if (!av.getWrapAlignment())
514 annotationSpaceFillerHolder.setVisible(b);
515 annotationScroller.setVisible(b);
521 * automatically adjust annotation panel height for new annotation whilst
522 * ensuring the alignment is still visible.
525 public void adjustAnnotationHeight()
527 // TODO: display vertical annotation scrollbar if necessary
528 // this is called after loading new annotation onto alignment
529 if (alignFrame.getHeight() == 0)
531 System.out.println("NEEDS FIXING");
533 validateAnnotationDimensions(true);
535 // TODO: many places call this method and also paintAlignment with various
536 // different settings. this means multiple redraws are triggered...
537 paintAlignment(true, av.needToUpdateStructureViews());
541 * calculate the annotation dimensions and refresh slider values accordingly.
542 * need to do repaints/notifys afterwards.
544 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
546 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
547 annotationHeight = getAnnotationPanel()
548 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
551 annotationScroller.setPreferredSize(
552 new Dimension(annotationScroller.getWidth(), annotationHeight));
554 Dimension e = idPanel.getSize();
555 alabels.setSize(new Dimension(e.width, annotationHeight));
557 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
558 annotationSpaceFillerHolder.getWidth(), annotationHeight));
559 annotationScroller.validate();
560 annotationScroller.addNotify();
564 * update alignment layout for viewport settings
569 public void updateLayout()
572 setAnnotationVisible(av.isShowAnnotation());
573 boolean wrap = av.getWrapAlignment();
574 ViewportRanges ranges = av.getRanges();
575 ranges.setStartSeq(0);
576 scalePanelHolder.setVisible(!wrap);
577 hscroll.setVisible(!wrap);
578 idwidthAdjuster.setVisible(!wrap);
582 annotationScroller.setVisible(false);
583 annotationSpaceFillerHolder.setVisible(false);
585 else if (av.isShowAnnotation())
587 annotationScroller.setVisible(true);
588 annotationSpaceFillerHolder.setVisible(true);
589 validateAnnotationDimensions(false);
592 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
594 { // may not yet be laid out
597 int widthInRes = getSeqPanel().seqCanvas
598 .getWrappedCanvasWidth(canvasWidth);
599 ranges.setViewportWidth(widthInRes);
603 int widthInRes = (canvasWidth / av.getCharWidth());
604 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
605 / av.getCharHeight());
607 ranges.setViewportWidth(widthInRes);
608 ranges.setViewportHeight(heightInSeq);
612 idSpaceFillerPanel1.setVisible(!wrap);
618 * Adjust row/column scrollers to show a visible position in the alignment.
621 * visible column to scroll to
623 * visible row to scroll to
626 public void setScrollValues(int xpos, int ypos)
631 if (av == null || av.getAlignment() == null)
636 if (av.getWrapAlignment())
638 setScrollingForWrappedPanel(x);
642 int width = av.getAlignment().getVisibleWidth();
643 int height = av.getAlignment().getHeight();
645 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
646 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
653 if (vextent > height)
658 if ((hextent + x) > width)
663 if ((vextent + y) > height)
665 y = height - vextent;
678 // update the scroll values
679 hscroll.setValues(x, hextent, 0, width);
680 vscroll.setValues(y, vextent, 0, height);
685 * Respond to adjustment event when horizontal or vertical scrollbar is
689 * adjustment event encoding whether hscroll or vscroll changed
692 public void adjustmentValueChanged(AdjustmentEvent evt)
694 if (av.getWrapAlignment())
696 adjustScrollingWrapped(evt);
700 ViewportRanges ranges = av.getRanges();
702 if (evt.getSource() == hscroll)
704 int oldX = ranges.getStartRes();
705 int oldwidth = ranges.getViewportWidth();
706 int x = hscroll.getValue();
707 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
709 // if we're scrolling to the position we're already at, stop
710 // this prevents infinite recursion of events when the scroll/viewport
711 // ranges values are the same
712 if ((x == oldX) && (width == oldwidth))
716 ranges.setViewportStartAndWidth(x, width);
718 else if (evt.getSource() == vscroll)
720 int oldY = ranges.getStartSeq();
721 int oldheight = ranges.getViewportHeight();
722 int y = vscroll.getValue();
723 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
725 // if we're scrolling to the position we're already at, stop
726 // this prevents infinite recursion of events when the scroll/viewport
727 // ranges values are the same
728 if ((y == oldY) && (height == oldheight))
732 ranges.setViewportStartAndHeight(y, height);
738 * Responds to a scroll change by setting the start position of the viewport.
743 protected void adjustScrollingWrapped(AdjustmentEvent evt)
745 if (evt.getSource() == hscroll)
747 return; // no horizontal scroll when wrapped
749 final ViewportRanges ranges = av.getRanges();
751 if (evt.getSource() == vscroll)
753 int newY = vscroll.getValue();
756 * if we're scrolling to the position we're already at, stop
757 * this prevents infinite recursion of events when the scroll/viewport
758 * ranges values are the same
760 int oldX = ranges.getStartRes();
761 int oldY = ranges.getWrappedScrollPosition(oldX);
769 * limit page up/down to one width's worth of positions
771 int rowSize = ranges.getViewportWidth();
772 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
773 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
778 // This is only called if file loaded is a jar file that
779 // was wrapped when saved and user has wrap alignment true
780 // as preference setting
781 SwingUtilities.invokeLater(new Runnable()
786 // When updating scrolling to use ViewportChange events, this code
787 // could not be validated and it is not clear if it is now being
788 // called. Log warning here in case it is called and unforeseen
791 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
793 // scroll to start of panel
794 ranges.setStartRes(0);
795 ranges.setStartSeq(0);
803 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
806 public void paintAlignment(boolean updateOverview,
807 boolean updateStructures)
809 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
810 av.isShowAutocalculatedAbove());
811 sorter.sort(getAlignment().getAlignmentAnnotation(),
812 av.getSortAnnotationsBy());
813 // BH 2019.04.18 this should not be necessary, but
814 // there is something wrong with the fast painting
815 // in that there is a -1 shift that should not be there.
816 // It is being covered in Java by the Consensus and Conservation
817 // threads forcing a full repaint after pasting.
818 seqPanel.seqCanvas.clearFastPaint();
821 if (updateStructures)
823 av.getStructureSelectionManager().sequenceColoursChanged(this);
828 if (overviewPanel != null)
830 overviewPanel.updateOverviewImage();
842 public void paintComponent(Graphics g)
844 invalidate(); // needed so that the id width adjuster works correctly
846 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
847 idPanelHolder.setPreferredSize(d);
848 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
850 validate(); // needed so that the id width adjuster works correctly
853 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
854 * though I still think this call should be elsewhere.
856 ViewportRanges ranges = av.getRanges();
857 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
858 super.paintComponent(g);
862 * Set vertical scroll bar position, and number of increments, for wrapped
865 * @param topLeftColumn
866 * the column position at top left (0..)
868 private void setScrollingForWrappedPanel(int topLeftColumn)
870 ViewportRanges ranges = av.getRanges();
871 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
872 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
875 * a scrollbar's value can be set to at most (maximum-extent)
876 * so we add extent (1) to the maxScroll value
878 vscroll.setUnitIncrement(1);
879 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
892 * @return DOCUMENT ME!
894 * @throws PrinterException
898 public int print(Graphics pg, PageFormat pf, int pi)
899 throws PrinterException
901 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
903 int pwidth = (int) pf.getImageableWidth();
904 int pheight = (int) pf.getImageableHeight();
906 if (av.getWrapAlignment())
908 return printWrappedAlignment(pwidth, pheight, pi, pg);
912 return printUnwrapped(pwidth, pheight, pi, pg, pg);
917 * Draws the alignment image, including sequence ids, sequences, and
918 * annotation labels and annotations if shown, on either one or two Graphics
928 * the graphics context for sequence ids and annotation labels
929 * @param alignmentGraphics
930 * the graphics context for sequences and annotations (may or may not
931 * be the same context as idGraphics)
933 * @throws PrinterException
935 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
936 Graphics idGraphics, Graphics alignmentGraphics)
937 throws PrinterException
939 final int idWidth = getVisibleIdWidth(false);
942 * Get the horizontal offset to where we draw the sequences.
943 * This is idWidth if using a single Graphics context, else zero.
945 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
948 FontMetrics fm = getFontMetrics(av.getFont());
949 final int charHeight = av.getCharHeight();
950 final int scaleHeight = charHeight + fm.getDescent();
952 idGraphics.setColor(Color.white);
953 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
954 idGraphics.setFont(av.getFont());
957 * How many sequences and residues can we fit on a printable page?
959 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
961 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
963 final int alignmentWidth = av.getAlignment().getVisibleWidth();
964 int pagesWide = (alignmentWidth / totalRes) + 1;
966 final int startRes = (pageIndex % pagesWide) * totalRes;
967 final int endRes = Math.min(startRes + totalRes - 1,
970 final int startSeq = (pageIndex / pagesWide) * totalSeq;
971 final int alignmentHeight = av.getAlignment().getHeight();
972 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
974 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
976 if (av.isShowAnnotation())
978 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
981 pagesHigh /= pageHeight;
983 if (pageIndex >= (pagesWide * pagesHigh))
985 return Printable.NO_SUCH_PAGE;
987 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
990 * draw the Scale at horizontal offset, then reset to top left (0, 0)
992 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
993 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
994 pageWidth - idWidth, scaleHeight);
995 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
998 * Draw the sequence ids, offset for scale height,
999 * then reset to top left (0, 0)
1001 idGraphics.translate(0, scaleHeight);
1002 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1003 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1004 : av.getSelectionGroup().getSequences(null);
1005 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1008 idGraphics.setFont(av.getFont());
1009 idGraphics.translate(0, -scaleHeight);
1012 * draw the sequences, offset for scale height, and id width (if using a
1013 * single graphics context), then reset to (0, scale height)
1015 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1016 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1017 endRes, startSeq, endSeq - 1);
1018 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1020 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1023 * draw annotation labels; drawComponent() translates by
1024 * getScrollOffset(), so compensate for that first;
1025 * then reset to (0, scale height)
1027 int offset = getAlabels().getScrollOffset();
1028 idGraphics.translate(0, -offset);
1029 idGraphics.translate(0, alignmentDrawnHeight);
1030 getAlabels().drawComponent(idGraphics, idWidth);
1031 idGraphics.translate(0, -alignmentDrawnHeight);
1034 * draw the annotations starting at
1035 * (idOffset, alignmentHeight) from (0, scaleHeight)
1037 alignmentGraphics.translate(alignmentGraphicsOffset,
1038 alignmentDrawnHeight);
1039 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1040 alignmentGraphics, -1, startRes, endRes + 1);
1043 return Printable.PAGE_EXISTS;
1047 * Prints one page of an alignment in wrapped mode. Returns
1048 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1049 * no page could be drawn (page number out of range).
1059 * @throws PrinterException
1061 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1062 Graphics g) throws PrinterException
1064 int annotationHeight = 0;
1065 if (av.isShowAnnotation())
1067 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1070 int hgap = av.getCharHeight();
1071 if (av.getScaleAboveWrapped())
1073 hgap += av.getCharHeight();
1076 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1079 int idWidth = getVisibleIdWidth(false);
1081 int maxwidth = av.getAlignment().getVisibleWidth();
1083 int resWidth = getSeqPanel().seqCanvas
1084 .getWrappedCanvasWidth(pageWidth - idWidth);
1086 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1088 g.setColor(Color.white);
1089 g.fillRect(0, 0, pageWidth, pageHeight);
1090 g.setFont(av.getFont());
1091 g.setColor(Color.black);
1094 * method: print the whole wrapped alignment, but with a clip region that
1095 * is restricted to the requested page; this supports selective print of
1096 * single pages or ranges, (at the cost of some repeated processing in
1097 * the 'normal' case, when all pages are printed)
1099 g.translate(0, -pageNumber * pageHeight);
1101 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1104 * draw sequence ids and annotation labels (if shown)
1106 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1107 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1109 g.translate(idWidth, 0);
1111 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1114 if ((pageNumber * pageHeight) < totalHeight)
1116 return Printable.PAGE_EXISTS;
1120 return Printable.NO_SUCH_PAGE;
1125 * get current sequence ID panel width, or nominal value if panel were to be
1126 * displayed using default settings
1130 public int getVisibleIdWidth()
1132 return getVisibleIdWidth(true);
1136 * get current sequence ID panel width, or nominal value if panel were to be
1137 * displayed using default settings
1140 * indicate if the Id width for onscreen or offscreen display should
1144 public int getVisibleIdWidth(boolean onscreen)
1146 // see if rendering offscreen - check preferences and calc width accordingly
1147 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1149 return calculateIdWidth(-1).width + 4;
1151 Integer idwidth = null;
1152 if (onscreen || (idwidth = Cache
1153 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1155 int w = getIdPanel().getWidth();
1156 return (w > 0 ? w : calculateIdWidth().width + 4);
1158 return idwidth.intValue() + 4;
1162 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1163 * writes it to the specified file
1168 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1170 final int borderBottomOffset = 5;
1172 AlignmentDimension aDimension = getAlignmentDimension();
1173 // todo use a lambda function in place of callback here?
1174 ImageWriterI writer = new ImageWriterI()
1177 public void exportImage(Graphics graphics) throws Exception
1179 if (av.getWrapAlignment())
1181 printWrappedAlignment(aDimension.getWidth(),
1182 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1186 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1187 graphics, graphics);
1192 String fileTitle = alignFrame.getTitle();
1193 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1195 int imageWidth = aDimension.getWidth();
1196 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1197 String of = MessageManager.getString("label.alignment");
1198 exporter.doExport(file, this, imageWidth, imageHeight, of);
1202 * Calculates and returns a suitable width and height (in pixels) for an
1207 public AlignmentDimension getAlignmentDimension()
1209 int maxwidth = av.getAlignment().getVisibleWidth();
1211 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1212 + getScalePanel().getHeight();
1213 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1215 if (av.getWrapAlignment())
1217 height = getWrappedHeight();
1218 if (Jalview.isHeadlessMode())
1220 // need to obtain default alignment width and then add in any
1221 // additional allowance for id margin
1222 // this duplicates the calculation in getWrappedHeight but adjusts for
1224 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1225 - alignFrame.getInsets().left - alignFrame.getInsets().right
1226 - getVisibleIdWidth() + getVisibleIdWidth(false);
1230 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1234 else if (av.isShowAnnotation())
1236 height += getAnnotationPanel().adjustPanelHeight() + 3;
1238 return new AlignmentDimension(width, height);
1242 public void makePNGImageMap(File imgMapFile, String imageName)
1244 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1245 // ////////////////////////////////////////////
1246 int idWidth = getVisibleIdWidth(false);
1247 FontMetrics fm = getFontMetrics(av.getFont());
1248 int scaleHeight = av.getCharHeight() + fm.getDescent();
1251 // ////////////////////////////////
1252 if (imgMapFile != null)
1256 int sSize = av.getAlignment().getHeight();
1257 int alwidth = av.getAlignment().getWidth();
1258 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1259 out.println(HTMLOutput.getImageMapHTML());
1260 out.println("<img src=\"" + imageName
1261 + "\" border=\"0\" usemap=\"#Map\" >"
1262 + "<map name=\"Map\">");
1264 for (int s = 0; s < sSize; s++)
1266 int sy = s * av.getCharHeight() + scaleHeight;
1268 SequenceI seq = av.getAlignment().getSequenceAt(s);
1269 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1270 for (int column = 0; column < alwidth; column++)
1272 StringBuilder text = new StringBuilder(512);
1273 String triplet = null;
1274 if (av.getAlignment().isNucleotide())
1276 triplet = ResidueProperties.nucleotideName.get(seq
1277 .getCharAt(column) + "");
1281 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1285 if (triplet == null)
1290 int seqPos = seq.findPosition(column);
1291 int gSize = groups.length;
1292 for (int g = 0; g < gSize; g++)
1294 if (text.length() < 1)
1296 text.append("<area shape=\"rect\" coords=\"")
1297 .append((idWidth + column * av.getCharWidth()))
1298 .append(",").append(sy).append(",")
1299 .append((idWidth + (column + 1) * av.getCharWidth()))
1300 .append(",").append((av.getCharHeight() + sy))
1301 .append("\"").append(" onMouseOver=\"toolTip('")
1302 .append(seqPos).append(" ").append(triplet);
1305 if (groups[g].getStartRes() < column
1306 && groups[g].getEndRes() > column)
1308 text.append("<br><em>").append(groups[g].getName())
1313 if (text.length() < 1)
1315 text.append("<area shape=\"rect\" coords=\"")
1316 .append((idWidth + column * av.getCharWidth()))
1317 .append(",").append(sy).append(",")
1318 .append((idWidth + (column + 1) * av.getCharWidth()))
1319 .append(",").append((av.getCharHeight() + sy))
1320 .append("\"").append(" onMouseOver=\"toolTip('")
1321 .append(seqPos).append(" ").append(triplet);
1323 if (!Comparison.isGap(seq.getCharAt(column)))
1325 List<SequenceFeature> features = seq.findFeatures(column, column);
1326 for (SequenceFeature sf : features)
1328 if (sf.isContactFeature())
1330 text.append("<br>").append(sf.getType()).append(" ")
1331 .append(sf.getBegin()).append(":")
1332 .append(sf.getEnd());
1336 text.append("<br>");
1337 text.append(sf.getType());
1338 String description = sf.getDescription();
1339 if (description != null
1340 && !sf.getType().equals(description))
1342 description = description.replace("\"", """);
1343 text.append(" ").append(description);
1346 String status = sf.getStatus();
1347 if (status != null && !"".equals(status))
1349 text.append(" (").append(status).append(")");
1352 if (text.length() > 1)
1354 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1355 out.println(text.toString());
1360 out.println("</map></body></html>");
1363 } catch (Exception ex)
1365 ex.printStackTrace();
1367 } // /////////END OF IMAGE MAP
1371 int getWrappedHeight()
1373 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1375 if (System.getProperty("java.awt.headless") != null
1376 && System.getProperty("java.awt.headless").equals("true"))
1378 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1379 - vscroll.getPreferredSize().width
1380 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1383 int chunkWidth = getSeqPanel().seqCanvas
1384 .getWrappedCanvasWidth(seqPanelWidth);
1386 int hgap = av.getCharHeight();
1387 if (av.getScaleAboveWrapped())
1389 hgap += av.getCharHeight();
1392 int annotationHeight = 0;
1393 if (av.isShowAnnotation())
1395 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1398 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1401 int maxwidth = av.getAlignment().getWidth();
1402 if (av.hasHiddenColumns())
1404 maxwidth = av.getAlignment().getHiddenColumns()
1405 .absoluteToVisibleColumn(maxwidth) - 1;
1408 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1414 * close the panel - deregisters all listeners and nulls any references to
1417 public void closePanel()
1419 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1420 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1421 PaintRefresher.RemoveComponent(this);
1426 * try to ensure references are nulled
1428 if (annotationPanel != null)
1430 annotationPanel.dispose();
1431 annotationPanel = null;
1436 av.removePropertyChangeListener(propertyChangeListener);
1437 propertyChangeListener = null;
1438 StructureSelectionManager ssm = av.getStructureSelectionManager();
1439 ssm.removeStructureViewerListener(getSeqPanel(), null);
1440 ssm.removeSelectionListener(getSeqPanel());
1441 ssm.removeCommandListener(av);
1442 ssm.removeStructureViewerListener(getSeqPanel(), null);
1443 ssm.removeSelectionListener(getSeqPanel());
1449 if (Cache.log.isDebugEnabled())
1451 Cache.log.warn("Closing alignment panel which is already closed.");
1457 * Close any open dialogs that would be orphaned when this one is closed
1459 protected void closeChildFrames()
1461 if (overviewPanel != null)
1463 overviewPanel.dispose();
1464 overviewPanel = null;
1466 if (calculationDialog != null)
1468 calculationDialog.closeFrame();
1469 calculationDialog = null;
1474 * hides or shows dynamic annotation rows based on groups and av state flags
1476 public void updateAnnotation()
1478 updateAnnotation(false, false);
1481 public void updateAnnotation(boolean applyGlobalSettings)
1483 updateAnnotation(applyGlobalSettings, false);
1486 public void updateAnnotation(boolean applyGlobalSettings,
1487 boolean preserveNewGroupSettings)
1489 av.updateGroupAnnotationSettings(applyGlobalSettings,
1490 preserveNewGroupSettings);
1491 adjustAnnotationHeight();
1495 public AlignmentI getAlignment()
1497 return av == null ? null : av.getAlignment();
1501 public String getViewName()
1503 return av.getViewName();
1507 * Make/Unmake this alignment panel the current input focus
1511 public void setSelected(boolean b)
1515 if (alignFrame.getSplitViewContainer() != null)
1518 * bring enclosing SplitFrame to front first if there is one
1520 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1522 alignFrame.setSelected(b);
1523 } catch (Exception ex)
1529 alignFrame.setDisplayedView(this);
1534 public StructureSelectionManager getStructureSelectionManager()
1536 return av.getStructureSelectionManager();
1540 public void raiseOOMWarning(String string, OutOfMemoryError error)
1542 new OOMWarning(string, error, this);
1546 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1549 return new FeatureRenderer(this);
1553 public jalview.api.FeatureRenderer getFeatureRenderer()
1555 return seqPanel.seqCanvas.getFeatureRenderer();
1558 public void updateFeatureRenderer(
1559 jalview.renderer.seqfeatures.FeatureRenderer fr)
1561 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1564 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1566 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1568 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1572 public ScalePanel getScalePanel()
1577 public void setScalePanel(ScalePanel scalePanel)
1579 this.scalePanel = scalePanel;
1582 public SeqPanel getSeqPanel()
1587 public void setSeqPanel(SeqPanel seqPanel)
1589 this.seqPanel = seqPanel;
1592 public AnnotationPanel getAnnotationPanel()
1594 return annotationPanel;
1597 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1599 this.annotationPanel = annotationPanel;
1602 public AnnotationLabels getAlabels()
1607 public void setAlabels(AnnotationLabels alabels)
1609 this.alabels = alabels;
1612 public IdPanel getIdPanel()
1617 public void setIdPanel(IdPanel idPanel)
1619 this.idPanel = idPanel;
1623 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1624 * The aim is to keep the two alignments 'lined up' on their centre columns.
1627 * holds mapped region(s) of this alignment that we are scrolling
1628 * 'to'; may be modified for sequence offset by this method
1629 * @param verticalOffset
1630 * the number of visible sequences to show above the mapped region
1632 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1634 scrollToPosition(sr, verticalOffset, true);
1638 * Set a flag to say do not scroll any (cDNA/protein) complement.
1642 protected void setToScrollComplementPanel(boolean b)
1644 this.scrollComplementaryPanel = b;
1648 * Get whether to scroll complement panel
1650 * @return true if cDNA/protein complement panels should be scrolled
1652 protected boolean isSetToScrollComplementPanel()
1654 return this.scrollComplementaryPanel;
1660 * @adjustHeight if true, try to recalculate panel height for visible
1663 protected void refresh(boolean adjustHeight)
1665 validateAnnotationDimensions(adjustHeight);
1669 // sort, repaint, update overview
1670 paintAlignment(true, false);
1674 // lightweight repaint
1681 * Property change event fired when a change is made to the viewport ranges
1682 * object associated with this alignment panel's viewport
1684 public void propertyChange(PropertyChangeEvent evt)
1686 // update this panel's scroll values based on the new viewport ranges values
1687 ViewportRanges ranges = av.getRanges();
1688 int x = ranges.getStartRes();
1689 int y = ranges.getStartSeq();
1690 setScrollValues(x, y);
1692 // now update any complementary alignment (its viewport ranges object
1693 // is different so does not get automatically updated)
1694 if (isSetToScrollComplementPanel())
1696 setToScrollComplementPanel(false);
1697 av.scrollComplementaryAlignment();
1698 setToScrollComplementPanel(true);
1703 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1704 * reference should be nulled when the dialog is closed.
1706 * @param calculationChooser
1708 public void setCalculationDialog(CalculationChooser calculationChooser)
1710 calculationDialog = calculationChooser;
1714 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1717 public CalculationChooser getCalculationDialog()
1719 return calculationDialog;