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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
45 import javax.swing.SwingUtilities;
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.HiddenColumns;
55 import jalview.datamodel.SearchResultsI;
56 import jalview.datamodel.SequenceFeature;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ImageExporter.ImageWriterI;
60 import jalview.io.HTMLOutput;
61 import jalview.io.exceptions.ImageOutputException;
62 import jalview.jbgui.GAlignmentPanel;
63 import jalview.math.AlignmentDimension;
64 import jalview.schemes.ResidueProperties;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.Comparison;
67 import jalview.util.ImageMaker;
68 import jalview.util.MessageManager;
69 import jalview.util.imagemaker.BitmapImageSizing;
70 import jalview.viewmodel.ViewportListenerI;
71 import jalview.viewmodel.ViewportRanges;
77 * @version $Revision: 1.161 $
79 @SuppressWarnings("serial")
80 public class AlignmentPanel extends GAlignmentPanel implements
81 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
84 * spare space in pixels between sequence id and alignment panel
86 private static final int ID_WIDTH_PADDING = 4;
88 public AlignViewport av;
90 OverviewPanel overviewPanel;
92 private SeqPanel seqPanel;
94 private IdPanel idPanel;
96 IdwidthAdjuster idwidthAdjuster;
98 public AlignFrame alignFrame;
100 private ScalePanel scalePanel;
102 private AnnotationPanel annotationPanel;
104 private AnnotationLabels alabels;
106 private int hextent = 0;
108 private int vextent = 0;
111 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
112 * false, suppresses invoking the same method recursively.
114 private boolean scrollComplementaryPanel = true;
116 private PropertyChangeListener propertyChangeListener;
118 private CalculationChooser calculationDialog;
121 * Creates a new AlignmentPanel object.
126 public AlignmentPanel(AlignFrame af, final AlignViewport av)
128 // setBackground(Color.white); // BH 2019
131 setSeqPanel(new SeqPanel(av, this));
132 setIdPanel(new IdPanel(av, this));
134 setScalePanel(new ScalePanel(av, this));
136 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
137 idwidthAdjuster = new IdwidthAdjuster(this);
138 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
140 setAnnotationPanel(new AnnotationPanel(this));
141 setAlabels(new AnnotationLabels(this));
143 annotationScroller.setViewportView(getAnnotationPanel());
144 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
146 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
147 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
149 setScrollValues(0, 0);
151 hscroll.addAdjustmentListener(this);
152 vscroll.addAdjustmentListener(this);
154 addComponentListener(new ComponentAdapter()
157 public void componentResized(ComponentEvent evt)
159 // reset the viewport ranges when the alignment panel is resized
160 // in particular, this initialises the end residue value when Jalview
162 ViewportRanges ranges = av.getRanges();
163 if (av.getWrapAlignment())
165 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
166 getSeqPanel().seqCanvas.getWidth());
167 ranges.setViewportWidth(widthInRes);
171 int widthInRes = getSeqPanel().seqCanvas.getWidth()
173 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
174 / av.getCharHeight();
176 ranges.setViewportWidth(widthInRes);
177 ranges.setViewportHeight(heightInSeq);
183 final AlignmentPanel ap = this;
184 propertyChangeListener = new PropertyChangeListener()
187 public void propertyChange(PropertyChangeEvent evt)
189 if (evt.getPropertyName().equals("alignment"))
191 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
196 av.addPropertyChangeListener(propertyChangeListener);
198 av.getRanges().addPropertyChangeListener(this);
200 adjustAnnotationHeight();
205 public AlignViewportI getAlignViewport()
210 public void alignmentChanged()
212 av.alignmentChanged(this);
214 if (getCalculationDialog() != null)
216 getCalculationDialog().validateCalcTypes();
219 alignFrame.updateEditMenuBar();
221 // no idea if we need to update structure
222 paintAlignment(true, true);
229 public void fontChanged()
231 // set idCanvas bufferedImage to null
232 // to prevent drawing old image
233 FontMetrics fm = getFontMetrics(av.getFont());
235 // update the flag controlling whether the grid is too small to render the
237 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
239 scalePanelHolder.setPreferredSize(
240 new Dimension(10, av.getCharHeight() + fm.getDescent()));
241 idSpaceFillerPanel1.setPreferredSize(
242 new Dimension(10, av.getCharHeight() + fm.getDescent()));
243 idwidthAdjuster.invalidate();
244 scalePanelHolder.invalidate();
245 // BH 2018 getIdPanel().getIdCanvas().gg = null;
246 getSeqPanel().seqCanvas.img = null;
247 getAnnotationPanel().adjustPanelHeight();
249 Dimension d = calculateIdWidth();
250 getIdPanel().getIdCanvas().setPreferredSize(d);
251 hscrollFillerPanel.setPreferredSize(d);
257 * Calculates the width of the alignment labels based on the displayed names
258 * and any bounds on label width set in preferences. The calculated width is
259 * also set as a property of the viewport.
261 * @return Dimension giving the maximum width of the alignment label panel
262 * that should be used.
264 public Dimension calculateIdWidth()
266 int oldWidth = av.getIdWidth();
268 // calculate sensible default width when no preference is available
270 if (av.getIdWidth() < 0)
272 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
273 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
274 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
275 r = calculateIdWidth(maxwidth);
276 av.setIdWidth(r.width);
281 r.width = av.getIdWidth();
286 * fudge: if desired width has changed, update layout
287 * (see also paintComponent - updates layout on a repaint)
289 if (r.width != oldWidth)
291 idPanelHolder.setPreferredSize(r);
298 * Calculate the width of the alignment labels based on the displayed names
299 * and any bounds on label width set in preferences.
302 * -1 or maximum width allowed for IdWidth
303 * @return Dimension giving the maximum width of the alignment label panel
304 * that should be used.
306 protected Dimension calculateIdWidth(int maxwidth)
308 Container c = new Container();
310 FontMetrics fm = c.getFontMetrics(
311 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
313 AlignmentI al = av.getAlignment();
317 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
319 SequenceI s = al.getSequenceAt(i);
320 String id = s.getDisplayId(av.getShowJVSuffix());
321 int stringWidth = fm.stringWidth(id);
322 idWidth = Math.max(idWidth, stringWidth);
326 // Also check annotation label widths
329 if (al.getAlignmentAnnotation() != null)
331 fm = c.getFontMetrics(getAlabels().getFont());
333 while (i < al.getAlignmentAnnotation().length)
335 String label = al.getAlignmentAnnotation()[i].label;
336 int stringWidth = fm.stringWidth(label);
337 idWidth = Math.max(idWidth, stringWidth);
342 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
343 w += ID_WIDTH_PADDING;
345 return new Dimension(w, 12);
349 * Highlight the given results on the alignment
352 public void highlightSearchResults(SearchResultsI results)
354 boolean scrolled = scrollToPosition(results, 0, false);
356 boolean fastPaint = !(scrolled && av.getWrapAlignment());
358 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
362 * Scroll the view to show the position of the highlighted region in results
365 * @param searchResults
368 public boolean scrollToPosition(SearchResultsI searchResults)
370 return scrollToPosition(searchResults, 0, false);
374 * Scrolls the view (if necessary) to show the position of the first
375 * highlighted region in results (if any). Answers true if the view was
376 * scrolled, or false if no matched region was found, or it is already
380 * @param verticalOffset
381 * if greater than zero, allows scrolling to a position below the
382 * first displayed sequence
384 * if true, try to centre the search results horizontally in the view
387 protected boolean scrollToPosition(SearchResultsI results,
388 int verticalOffset, boolean centre)
390 int startv, endv, starts, ends;
391 ViewportRanges ranges = av.getRanges();
393 if (results == null || results.isEmpty() || av == null
394 || av.getAlignment() == null)
398 int seqIndex = av.getAlignment().findIndex(results);
403 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
405 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
414 * To centre results, scroll to positions half the visible width
415 * left/right of the start/end positions
419 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
420 start = Math.max(start - offset, 0);
421 end = end + offset - 1;
427 if (end == seq.getEnd())
432 if (av.hasHiddenColumns())
434 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
435 start = hidden.absoluteToVisibleColumn(start);
436 end = hidden.absoluteToVisibleColumn(end);
439 if (!hidden.isVisible(r[0]))
441 // don't scroll - position isn't visible
448 * allow for offset of target sequence (actually scroll to one above it)
450 seqIndex = Math.max(0, seqIndex - verticalOffset);
451 boolean scrollNeeded = true;
453 if (!av.getWrapAlignment())
455 if ((startv = ranges.getStartRes()) >= start)
458 * Scroll left to make start of search results visible
460 setScrollValues(start, seqIndex);
462 else if ((endv = ranges.getEndRes()) <= end)
465 * Scroll right to make end of search results visible
467 setScrollValues(startv + end - endv, seqIndex);
469 else if ((starts = ranges.getStartSeq()) > seqIndex)
472 * Scroll up to make start of search results visible
474 setScrollValues(ranges.getStartRes(), seqIndex);
476 else if ((ends = ranges.getEndSeq()) <= seqIndex)
479 * Scroll down to make end of search results visible
481 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
484 * Else results are already visible - no need to scroll
486 scrollNeeded = false;
490 scrollNeeded = ranges.scrollToWrappedVisible(start);
493 paintAlignment(false, false);
501 * @return DOCUMENT ME!
503 public OverviewPanel getOverviewPanel()
505 return overviewPanel;
514 public void setOverviewPanel(OverviewPanel op)
522 * Hide or show annotation panel
525 public void setAnnotationVisible(boolean b)
527 if (!av.getWrapAlignment())
529 annotationSpaceFillerHolder.setVisible(b);
530 annotationScroller.setVisible(b);
536 * automatically adjust annotation panel height for new annotation whilst
537 * ensuring the alignment is still visible.
540 public void adjustAnnotationHeight()
542 // TODO: display vertical annotation scrollbar if necessary
543 // this is called after loading new annotation onto alignment
544 if (alignFrame.getHeight() == 0)
546 System.out.println("NEEDS FIXING");
548 validateAnnotationDimensions(true);
550 // TODO: many places call this method and also paintAlignment with various
551 // different settings. this means multiple redraws are triggered...
552 paintAlignment(true, av.needToUpdateStructureViews());
556 * calculate the annotation dimensions and refresh slider values accordingly.
557 * need to do repaints/notifys afterwards.
559 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
561 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
562 // are not changing ancestors, and keyboard action listeners do
563 // not need to be reset. addNotify() is a very expensive operation,
564 // requiring a full re-layout of all parents and children.
565 // Note in JComponent:
566 // This method is called by the toolkit internally and should
567 // not be called directly by programs.
568 // I note that addNotify() is called in several areas of Jalview.
570 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
571 annotationHeight = getAnnotationPanel()
572 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
575 annotationScroller.setPreferredSize(
576 new Dimension(annotationScroller.getWidth(), annotationHeight));
578 Dimension e = idPanel.getSize();
579 alabels.setSize(new Dimension(e.width, annotationHeight));
581 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
582 annotationSpaceFillerHolder.getWidth(), annotationHeight));
583 annotationScroller.validate();
584 annotationScroller.addNotify();
588 * update alignment layout for viewport settings
593 public void updateLayout()
596 setAnnotationVisible(av.isShowAnnotation());
597 boolean wrap = av.getWrapAlignment();
598 ViewportRanges ranges = av.getRanges();
599 ranges.setStartSeq(0);
600 scalePanelHolder.setVisible(!wrap);
601 hscroll.setVisible(!wrap);
602 idwidthAdjuster.setVisible(!wrap);
606 annotationScroller.setVisible(false);
607 annotationSpaceFillerHolder.setVisible(false);
609 else if (av.isShowAnnotation())
611 annotationScroller.setVisible(true);
612 annotationSpaceFillerHolder.setVisible(true);
613 validateAnnotationDimensions(false);
616 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
618 { // may not yet be laid out
621 int widthInRes = getSeqPanel().seqCanvas
622 .getWrappedCanvasWidth(canvasWidth);
623 ranges.setViewportWidth(widthInRes);
627 int widthInRes = (canvasWidth / av.getCharWidth());
628 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
629 / av.getCharHeight());
631 ranges.setViewportWidth(widthInRes);
632 ranges.setViewportHeight(heightInSeq);
636 idSpaceFillerPanel1.setVisible(!wrap);
642 * Adjust row/column scrollers to show a visible position in the alignment.
645 * visible column to scroll to
647 * visible row to scroll to
650 public void setScrollValues(int xpos, int ypos)
655 if (av == null || av.getAlignment() == null)
660 if (av.getWrapAlignment())
662 setScrollingForWrappedPanel(x);
666 int width = av.getAlignment().getVisibleWidth();
667 int height = av.getAlignment().getHeight();
669 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
670 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
677 if (vextent > height)
682 if ((hextent + x) > width)
687 if ((vextent + y) > height)
689 y = height - vextent;
702 // update the scroll values
703 hscroll.setValues(x, hextent, 0, width);
704 vscroll.setValues(y, vextent, 0, height);
709 * Respond to adjustment event when horizontal or vertical scrollbar is
713 * adjustment event encoding whether hscroll or vscroll changed
716 public void adjustmentValueChanged(AdjustmentEvent evt)
718 if (av.getWrapAlignment())
720 adjustScrollingWrapped(evt);
724 ViewportRanges ranges = av.getRanges();
726 if (evt.getSource() == hscroll)
728 int oldX = ranges.getStartRes();
729 int oldwidth = ranges.getViewportWidth();
730 int x = hscroll.getValue();
731 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
733 // if we're scrolling to the position we're already at, stop
734 // this prevents infinite recursion of events when the scroll/viewport
735 // ranges values are the same
736 if ((x == oldX) && (width == oldwidth))
740 ranges.setViewportStartAndWidth(x, width);
742 else if (evt.getSource() == vscroll)
744 int oldY = ranges.getStartSeq();
745 int oldheight = ranges.getViewportHeight();
746 int y = vscroll.getValue();
747 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
749 // if we're scrolling to the position we're already at, stop
750 // this prevents infinite recursion of events when the scroll/viewport
751 // ranges values are the same
752 if ((y == oldY) && (height == oldheight))
756 ranges.setViewportStartAndHeight(y, height);
762 * Responds to a scroll change by setting the start position of the viewport.
767 protected void adjustScrollingWrapped(AdjustmentEvent evt)
769 if (evt.getSource() == hscroll)
771 return; // no horizontal scroll when wrapped
773 final ViewportRanges ranges = av.getRanges();
775 if (evt.getSource() == vscroll)
777 int newY = vscroll.getValue();
780 * if we're scrolling to the position we're already at, stop
781 * this prevents infinite recursion of events when the scroll/viewport
782 * ranges values are the same
784 int oldX = ranges.getStartRes();
785 int oldY = ranges.getWrappedScrollPosition(oldX);
793 * limit page up/down to one width's worth of positions
795 int rowSize = ranges.getViewportWidth();
796 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
797 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
802 // This is only called if file loaded is a jar file that
803 // was wrapped when saved and user has wrap alignment true
804 // as preference setting
805 SwingUtilities.invokeLater(new Runnable()
810 // When updating scrolling to use ViewportChange events, this code
811 // could not be validated and it is not clear if it is now being
812 // called. Log warning here in case it is called and unforeseen
815 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
817 // scroll to start of panel
818 ranges.setStartRes(0);
819 ranges.setStartSeq(0);
827 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
830 public void paintAlignment(boolean updateOverview,
831 boolean updateStructures)
833 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
834 av.isShowAutocalculatedAbove());
835 sorter.sort(getAlignment().getAlignmentAnnotation(),
836 av.getSortAnnotationsBy());
839 if (updateStructures)
841 av.getStructureSelectionManager().sequenceColoursChanged(this);
846 if (overviewPanel != null)
848 overviewPanel.updateOverviewImage();
854 public void paintComponent(Graphics g)
856 invalidate(); // needed so that the id width adjuster works correctly
858 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
859 idPanelHolder.setPreferredSize(d);
860 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
862 validate(); // needed so that the id width adjuster works correctly
865 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
866 * though I still think this call should be elsewhere.
868 ViewportRanges ranges = av.getRanges();
869 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
870 super.paintComponent(g);
874 * Set vertical scroll bar position, and number of increments, for wrapped
877 * @param topLeftColumn
878 * the column position at top left (0..)
880 private void setScrollingForWrappedPanel(int topLeftColumn)
882 ViewportRanges ranges = av.getRanges();
883 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
884 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
887 * a scrollbar's value can be set to at most (maximum-extent)
888 * so we add extent (1) to the maxScroll value
890 vscroll.setUnitIncrement(1);
891 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
904 * @return DOCUMENT ME!
906 * @throws PrinterException
910 public int print(Graphics pg, PageFormat pf, int pi)
911 throws PrinterException
913 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
915 int pwidth = (int) pf.getImageableWidth();
916 int pheight = (int) pf.getImageableHeight();
918 if (av.getWrapAlignment())
920 return printWrappedAlignment(pwidth, pheight, pi, pg);
924 return printUnwrapped(pwidth, pheight, pi, pg, pg);
929 * Draws the alignment image, including sequence ids, sequences, and
930 * annotation labels and annotations if shown, on either one or two Graphics
940 * the graphics context for sequence ids and annotation labels
941 * @param alignmentGraphics
942 * the graphics context for sequences and annotations (may or may not
943 * be the same context as idGraphics)
945 * @throws PrinterException
947 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
948 Graphics idGraphics, Graphics alignmentGraphics)
949 throws PrinterException
951 final int idWidth = getVisibleIdWidth(false);
954 * Get the horizontal offset to where we draw the sequences.
955 * This is idWidth if using a single Graphics context, else zero.
957 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
960 FontMetrics fm = getFontMetrics(av.getFont());
961 final int charHeight = av.getCharHeight();
962 final int scaleHeight = charHeight + fm.getDescent();
964 idGraphics.setColor(Color.white);
965 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
966 idGraphics.setFont(av.getFont());
969 * How many sequences and residues can we fit on a printable page?
971 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
973 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
975 final int alignmentWidth = av.getAlignment().getVisibleWidth();
976 int pagesWide = (alignmentWidth / totalRes) + 1;
978 final int startRes = (pageIndex % pagesWide) * totalRes;
979 final int endRes = Math.min(startRes + totalRes - 1,
982 final int startSeq = (pageIndex / pagesWide) * totalSeq;
983 final int alignmentHeight = av.getAlignment().getHeight();
984 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
986 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
988 if (av.isShowAnnotation())
990 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
993 pagesHigh /= pageHeight;
995 if (pageIndex >= (pagesWide * pagesHigh))
997 return Printable.NO_SUCH_PAGE;
999 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1002 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1004 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1005 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1006 pageWidth - idWidth, scaleHeight);
1007 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1010 * Draw the sequence ids, offset for scale height,
1011 * then reset to top left (0, 0)
1013 idGraphics.translate(0, scaleHeight);
1014 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1015 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1016 : av.getSelectionGroup().getSequences(null);
1017 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1020 idGraphics.setFont(av.getFont());
1021 idGraphics.translate(0, -scaleHeight);
1024 * draw the sequences, offset for scale height, and id width (if using a
1025 * single graphics context), then reset to (0, scale height)
1027 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1028 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1029 startRes, endRes, startSeq, endSeq - 1);
1030 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1032 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1035 * draw annotation labels; drawComponent() translates by
1036 * getScrollOffset(), so compensate for that first;
1037 * then reset to (0, scale height)
1039 int offset = getAlabels().getScrollOffset();
1040 idGraphics.translate(0, -offset);
1041 idGraphics.translate(0, alignmentDrawnHeight);
1042 getAlabels().drawComponent(idGraphics, idWidth);
1043 idGraphics.translate(0, -alignmentDrawnHeight);
1046 * draw the annotations starting at
1047 * (idOffset, alignmentHeight) from (0, scaleHeight)
1049 alignmentGraphics.translate(alignmentGraphicsOffset,
1050 alignmentDrawnHeight);
1052 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1053 alignmentGraphics, -1, startRes, endRes + 1);
1056 return Printable.PAGE_EXISTS;
1060 * Prints one page of an alignment in wrapped mode. Returns
1061 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1062 * no page could be drawn (page number out of range).
1072 * @throws PrinterException
1074 public int printWrappedAlignment(int pageWidth, int pageHeight,
1075 int pageNumber, Graphics g) throws PrinterException
1077 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1079 int annotationHeight = 0;
1080 if (av.isShowAnnotation())
1082 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1085 int hgap = av.getCharHeight();
1086 if (av.getScaleAboveWrapped())
1088 hgap += av.getCharHeight();
1091 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1094 int idWidth = getVisibleIdWidth(false);
1096 int maxwidth = av.getAlignment().getVisibleWidth();
1098 int resWidth = getSeqPanel().seqCanvas
1099 .getWrappedCanvasWidth(pageWidth - idWidth);
1100 av.getRanges().setViewportStartAndWidth(0, resWidth);
1102 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1104 g.setColor(Color.white);
1105 g.fillRect(0, 0, pageWidth, pageHeight);
1106 g.setFont(av.getFont());
1107 g.setColor(Color.black);
1110 * method: print the whole wrapped alignment, but with a clip region that
1111 * is restricted to the requested page; this supports selective print of
1112 * single pages or ranges, (at the cost of repeated processing in the
1113 * 'normal' case, when all pages are printed)
1115 g.translate(0, -pageNumber * pageHeight);
1117 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1120 * draw sequence ids and annotation labels (if shown)
1122 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1123 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1125 g.translate(idWidth, 0);
1127 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1128 pageWidth - idWidth, totalHeight, 0);
1130 if ((pageNumber * pageHeight) < totalHeight)
1132 return Printable.PAGE_EXISTS;
1136 return Printable.NO_SUCH_PAGE;
1141 * get current sequence ID panel width, or nominal value if panel were to be
1142 * displayed using default settings
1146 public int getVisibleIdWidth()
1148 return getVisibleIdWidth(true);
1152 * get current sequence ID panel width, or nominal value if panel were to be
1153 * displayed using default settings
1156 * indicate if the Id width for onscreen or offscreen display should
1160 protected int getVisibleIdWidth(boolean onscreen)
1162 // see if rendering offscreen - check preferences and calc width accordingly
1163 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1165 return calculateIdWidth(-1).width;
1167 Integer idwidth = onscreen ? null
1168 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1169 if (idwidth != null)
1171 return idwidth.intValue() + ID_WIDTH_PADDING;
1174 int w = getIdPanel().getWidth();
1175 return (w > 0 ? w : calculateIdWidth().width);
1178 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer) throws ImageOutputException
1180 makeAlignmentImage(type, file, renderer,
1181 BitmapImageSizing.nullBitmapImageSizing());
1185 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1186 * writes it to the specified file
1190 * @param textrenderer
1191 * @param bitmapscale
1193 void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1194 BitmapImageSizing userBis) throws ImageOutputException
1196 final int borderBottomOffset = 5;
1198 AlignmentDimension aDimension = getAlignmentDimension();
1199 // todo use a lambda function in place of callback here?
1200 ImageWriterI writer = new ImageWriterI()
1203 public void exportImage(Graphics graphics) throws Exception
1205 if (av.getWrapAlignment())
1207 printWrappedAlignment(aDimension.getWidth(),
1208 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1212 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1213 graphics, graphics);
1218 String fileTitle = alignFrame.getTitle();
1219 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1221 int imageWidth = aDimension.getWidth();
1222 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1223 String of = MessageManager.getString("label.alignment");
1224 exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1229 * Calculates and returns a suitable width and height (in pixels) for an
1234 public AlignmentDimension getAlignmentDimension()
1236 int maxwidth = av.getAlignment().getVisibleWidth();
1238 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1239 + getScalePanel().getHeight();
1240 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1242 if (av.getWrapAlignment())
1244 height = getWrappedHeight();
1245 if (Jalview.isHeadlessMode())
1247 // need to obtain default alignment width and then add in any
1248 // additional allowance for id margin
1249 // this duplicates the calculation in getWrappedHeight but adjusts for
1251 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1252 - alignFrame.getInsets().left - alignFrame.getInsets().right
1253 - getVisibleIdWidth() + getVisibleIdWidth(false);
1257 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1261 else if (av.isShowAnnotation())
1263 height += getAnnotationPanel().adjustPanelHeight() + 3;
1265 return new AlignmentDimension(width, height);
1269 public void makePNGImageMap(File imgMapFile, String imageName) throws ImageOutputException
1271 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1272 // ////////////////////////////////////////////
1273 int idWidth = getVisibleIdWidth(false);
1274 FontMetrics fm = getFontMetrics(av.getFont());
1275 int scaleHeight = av.getCharHeight() + fm.getDescent();
1278 // ////////////////////////////////
1279 if (imgMapFile != null)
1283 int sSize = av.getAlignment().getHeight();
1284 int alwidth = av.getAlignment().getWidth();
1285 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1286 out.println(HTMLOutput.getImageMapHTML());
1287 out.println("<img src=\"" + imageName
1288 + "\" border=\"0\" usemap=\"#Map\" >"
1289 + "<map name=\"Map\">");
1291 for (int s = 0; s < sSize; s++)
1293 int sy = s * av.getCharHeight() + scaleHeight;
1295 SequenceI seq = av.getAlignment().getSequenceAt(s);
1296 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1297 for (int column = 0; column < alwidth; column++)
1299 StringBuilder text = new StringBuilder(512);
1300 String triplet = null;
1301 if (av.getAlignment().isNucleotide())
1303 triplet = ResidueProperties.nucleotideName
1304 .get(seq.getCharAt(column) + "");
1308 triplet = ResidueProperties.aa2Triplet
1309 .get(seq.getCharAt(column) + "");
1312 if (triplet == null)
1317 int seqPos = seq.findPosition(column);
1318 int gSize = groups.length;
1319 for (int g = 0; g < gSize; g++)
1321 if (text.length() < 1)
1323 text.append("<area shape=\"rect\" coords=\"")
1324 .append((idWidth + column * av.getCharWidth()))
1325 .append(",").append(sy).append(",")
1327 + (column + 1) * av.getCharWidth()))
1328 .append(",").append((av.getCharHeight() + sy))
1329 .append("\"").append(" onMouseOver=\"toolTip('")
1330 .append(seqPos).append(" ").append(triplet);
1333 if (groups[g].getStartRes() < column
1334 && groups[g].getEndRes() > column)
1336 text.append("<br><em>").append(groups[g].getName())
1341 if (text.length() < 1)
1343 text.append("<area shape=\"rect\" coords=\"")
1344 .append((idWidth + column * av.getCharWidth()))
1345 .append(",").append(sy).append(",")
1346 .append((idWidth + (column + 1) * av.getCharWidth()))
1347 .append(",").append((av.getCharHeight() + sy))
1348 .append("\"").append(" onMouseOver=\"toolTip('")
1349 .append(seqPos).append(" ").append(triplet);
1351 if (!Comparison.isGap(seq.getCharAt(column)))
1353 List<SequenceFeature> features = seq.findFeatures(column,
1355 for (SequenceFeature sf : features)
1357 if (sf.isContactFeature())
1359 text.append("<br>").append(sf.getType()).append(" ")
1360 .append(sf.getBegin()).append(":")
1361 .append(sf.getEnd());
1365 text.append("<br>");
1366 text.append(sf.getType());
1367 String description = sf.getDescription();
1368 if (description != null
1369 && !sf.getType().equals(description))
1371 description = description.replace("\"", """);
1372 text.append(" ").append(description);
1375 String status = sf.getStatus();
1376 if (status != null && !"".equals(status))
1378 text.append(" (").append(status).append(")");
1381 if (text.length() > 1)
1383 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1384 out.println(text.toString());
1389 out.println("</map></body></html>");
1392 } catch (Exception ex)
1394 throw new ImageOutputException("couldn't write ImageMap due to unexpected error",ex);
1396 } // /////////END OF IMAGE MAP
1401 * Answers the height of the entire alignment in pixels, assuming it is in
1406 int getWrappedHeight()
1408 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1410 if (System.getProperty("java.awt.headless") != null
1411 && System.getProperty("java.awt.headless").equals("true"))
1413 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1414 - vscroll.getPreferredSize().width
1415 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1418 int chunkWidth = getSeqPanel().seqCanvas
1419 .getWrappedCanvasWidth(seqPanelWidth);
1421 int hgap = av.getCharHeight();
1422 if (av.getScaleAboveWrapped())
1424 hgap += av.getCharHeight();
1427 int annotationHeight = 0;
1428 if (av.isShowAnnotation())
1430 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1431 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1434 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1437 int maxwidth = av.getAlignment().getWidth();
1438 if (av.hasHiddenColumns())
1440 maxwidth = av.getAlignment().getHiddenColumns()
1441 .absoluteToVisibleColumn(maxwidth) - 1;
1444 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1450 * close the panel - deregisters all listeners and nulls any references to
1453 public void closePanel()
1455 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1456 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1457 PaintRefresher.RemoveComponent(this);
1462 * try to ensure references are nulled
1464 if (annotationPanel != null)
1466 annotationPanel.dispose();
1467 annotationPanel = null;
1472 av.removePropertyChangeListener(propertyChangeListener);
1473 propertyChangeListener = null;
1474 StructureSelectionManager ssm = av.getStructureSelectionManager();
1475 ssm.removeStructureViewerListener(getSeqPanel(), null);
1476 ssm.removeSelectionListener(getSeqPanel());
1477 ssm.removeCommandListener(av);
1478 ssm.removeStructureViewerListener(getSeqPanel(), null);
1479 ssm.removeSelectionListener(getSeqPanel());
1485 if (Console.isDebugEnabled())
1487 Console.warn("Closing alignment panel which is already closed.");
1493 * Close any open dialogs that would be orphaned when this one is closed
1495 protected void closeChildFrames()
1497 if (overviewPanel != null)
1499 overviewPanel.dispose();
1500 overviewPanel = null;
1502 if (calculationDialog != null)
1504 calculationDialog.closeFrame();
1505 calculationDialog = null;
1510 * hides or shows dynamic annotation rows based on groups and av state flags
1512 public void updateAnnotation()
1514 updateAnnotation(false, false);
1517 public void updateAnnotation(boolean applyGlobalSettings)
1519 updateAnnotation(applyGlobalSettings, false);
1522 public void updateAnnotation(boolean applyGlobalSettings,
1523 boolean preserveNewGroupSettings)
1525 av.updateGroupAnnotationSettings(applyGlobalSettings,
1526 preserveNewGroupSettings);
1527 adjustAnnotationHeight();
1531 public AlignmentI getAlignment()
1533 return av == null ? null : av.getAlignment();
1537 public String getViewName()
1539 return av.getViewName();
1543 * Make/Unmake this alignment panel the current input focus
1547 public void setSelected(boolean b)
1551 if (alignFrame.getSplitViewContainer() != null)
1554 * bring enclosing SplitFrame to front first if there is one
1556 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1558 alignFrame.setSelected(b);
1559 } catch (Exception ex)
1564 setAlignFrameView();
1568 public void setAlignFrameView()
1570 alignFrame.setDisplayedView(this);
1574 public StructureSelectionManager getStructureSelectionManager()
1576 return av.getStructureSelectionManager();
1580 public void raiseOOMWarning(String string, OutOfMemoryError error)
1582 new OOMWarning(string, error, this);
1586 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1589 return new FeatureRenderer(this);
1593 public jalview.api.FeatureRenderer getFeatureRenderer()
1595 return seqPanel.seqCanvas.getFeatureRenderer();
1598 public void updateFeatureRenderer(
1599 jalview.renderer.seqfeatures.FeatureRenderer fr)
1601 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1604 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1606 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1608 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1612 public ScalePanel getScalePanel()
1617 public void setScalePanel(ScalePanel scalePanel)
1619 this.scalePanel = scalePanel;
1622 public SeqPanel getSeqPanel()
1627 public void setSeqPanel(SeqPanel seqPanel)
1629 this.seqPanel = seqPanel;
1632 public AnnotationPanel getAnnotationPanel()
1634 return annotationPanel;
1637 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1639 this.annotationPanel = annotationPanel;
1642 public AnnotationLabels getAlabels()
1647 public void setAlabels(AnnotationLabels alabels)
1649 this.alabels = alabels;
1652 public IdPanel getIdPanel()
1657 public void setIdPanel(IdPanel idPanel)
1659 this.idPanel = idPanel;
1663 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1664 * The aim is to keep the two alignments 'lined up' on their centre columns.
1667 * holds mapped region(s) of this alignment that we are scrolling
1668 * 'to'; may be modified for sequence offset by this method
1669 * @param verticalOffset
1670 * the number of visible sequences to show above the mapped region
1672 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1674 scrollToPosition(sr, verticalOffset, true);
1678 * Set a flag to say do not scroll any (cDNA/protein) complement.
1682 protected void setToScrollComplementPanel(boolean b)
1684 this.scrollComplementaryPanel = b;
1688 * Get whether to scroll complement panel
1690 * @return true if cDNA/protein complement panels should be scrolled
1692 protected boolean isSetToScrollComplementPanel()
1694 return this.scrollComplementaryPanel;
1700 * @adjustHeight if true, try to recalculate panel height for visible
1703 protected void refresh(boolean adjustHeight)
1705 validateAnnotationDimensions(adjustHeight);
1709 // sort, repaint, update overview
1710 paintAlignment(true, false);
1714 // lightweight repaint
1721 * Property change event fired when a change is made to the viewport ranges
1722 * object associated with this alignment panel's viewport
1724 public void propertyChange(PropertyChangeEvent evt)
1726 // update this panel's scroll values based on the new viewport ranges values
1727 ViewportRanges ranges = av.getRanges();
1728 int x = ranges.getStartRes();
1729 int y = ranges.getStartSeq();
1730 setScrollValues(x, y);
1732 // now update any complementary alignment (its viewport ranges object
1733 // is different so does not get automatically updated)
1734 if (isSetToScrollComplementPanel())
1736 setToScrollComplementPanel(false);
1737 av.scrollComplementaryAlignment();
1738 setToScrollComplementPanel(true);
1743 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1744 * reference should be nulled when the dialog is closed.
1746 * @param calculationChooser
1748 public void setCalculationDialog(CalculationChooser calculationChooser)
1750 calculationDialog = calculationChooser;
1754 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1757 public CalculationChooser getCalculationDialog()
1759 return calculationDialog;
1763 * Constructs and sets the title for the Overview window (if there is one),
1764 * including the align frame's title, and view name (if applicable). Returns
1765 * the title, or null if this panel has no Overview window open.
1770 public String setOverviewTitle(AlignFrame alignFrame)
1772 if (this.overviewPanel == null)
1776 String overviewTitle = MessageManager
1777 .formatMessage("label.overview_params", new Object[]
1778 { alignFrame.getTitle() });
1779 String viewName = getViewName();
1780 if (viewName != null)
1782 overviewTitle += (" " + viewName);
1784 overviewPanel.setTitle(overviewTitle);
1785 return overviewTitle;
1789 * If this alignment panel has an Overview panel open, closes it
1791 public void closeOverviewPanel()
1793 if (overviewPanel != null)
1795 overviewPanel.close();
1796 overviewPanel = null;