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.Console;
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.print.PageFormat;
60 import java.awt.print.Printable;
61 import java.awt.print.PrinterException;
62 import java.beans.PropertyChangeEvent;
63 import java.beans.PropertyChangeListener;
65 import java.io.FileWriter;
66 import java.io.PrintWriter;
67 import java.util.List;
69 import javax.swing.SwingUtilities;
75 * @version $Revision: 1.161 $
77 @SuppressWarnings("serial")
78 public class AlignmentPanel extends GAlignmentPanel implements
79 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
82 * spare space in pixels between sequence id and alignment panel
84 private static final int ID_WIDTH_PADDING = 4;
86 public AlignViewport av;
88 OverviewPanel overviewPanel;
90 private SeqPanel seqPanel;
92 private IdPanel idPanel;
94 IdwidthAdjuster idwidthAdjuster;
96 public AlignFrame alignFrame;
98 private ScalePanel scalePanel;
100 private AnnotationPanel annotationPanel;
102 private AnnotationLabels alabels;
104 private int hextent = 0;
106 private int vextent = 0;
109 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110 * false, suppresses invoking the same method recursively.
112 private boolean scrollComplementaryPanel = true;
114 private PropertyChangeListener propertyChangeListener;
116 private CalculationChooser calculationDialog;
119 * Creates a new AlignmentPanel object.
124 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 // setBackground(Color.white); // BH 2019
129 setSeqPanel(new SeqPanel(av, this));
130 setIdPanel(new IdPanel(av, this));
132 setScalePanel(new ScalePanel(av, this));
134 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135 idwidthAdjuster = new IdwidthAdjuster(this);
136 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
138 setAnnotationPanel(new AnnotationPanel(this));
139 setAlabels(new AnnotationLabels(this));
141 annotationScroller.setViewportView(getAnnotationPanel());
142 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
144 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
147 setScrollValues(0, 0);
149 hscroll.addAdjustmentListener(this);
150 vscroll.addAdjustmentListener(this);
152 addComponentListener(new ComponentAdapter()
155 public void componentResized(ComponentEvent evt)
157 // reset the viewport ranges when the alignment panel is resized
158 // in particular, this initialises the end residue value when Jalview
160 ViewportRanges ranges = av.getRanges();
161 if (av.getWrapAlignment())
163 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
164 getSeqPanel().seqCanvas.getWidth());
165 ranges.setViewportWidth(widthInRes);
169 int widthInRes = getSeqPanel().seqCanvas.getWidth()
171 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
172 / av.getCharHeight();
174 ranges.setViewportWidth(widthInRes);
175 ranges.setViewportHeight(heightInSeq);
181 final AlignmentPanel ap = this;
182 propertyChangeListener = new PropertyChangeListener()
185 public void propertyChange(PropertyChangeEvent evt)
187 if (evt.getPropertyName().equals("alignment"))
189 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
194 av.addPropertyChangeListener(propertyChangeListener);
196 av.getRanges().addPropertyChangeListener(this);
198 adjustAnnotationHeight();
203 public AlignViewportI getAlignViewport()
208 public void alignmentChanged()
210 av.alignmentChanged(this);
212 if (getCalculationDialog() != null)
214 getCalculationDialog().validateCalcTypes();
217 alignFrame.updateEditMenuBar();
219 // no idea if we need to update structure
220 paintAlignment(true, true);
227 public void fontChanged()
229 // set idCanvas bufferedImage to null
230 // to prevent drawing old image
231 FontMetrics fm = getFontMetrics(av.getFont());
233 // update the flag controlling whether the grid is too small to render the font
234 av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
236 scalePanelHolder.setPreferredSize(
237 new Dimension(10, av.getCharHeight() + fm.getDescent()));
238 idSpaceFillerPanel1.setPreferredSize(
239 new Dimension(10, av.getCharHeight() + fm.getDescent()));
240 idwidthAdjuster.invalidate();
241 scalePanelHolder.invalidate();
242 // BH 2018 getIdPanel().getIdCanvas().gg = null;
243 getSeqPanel().seqCanvas.img = null;
244 getAnnotationPanel().adjustPanelHeight();
246 Dimension d = calculateIdWidth();
247 getIdPanel().getIdCanvas().setPreferredSize(d);
248 hscrollFillerPanel.setPreferredSize(d);
254 * Calculates the width of the alignment labels based on the displayed names
255 * and any bounds on label width set in preferences. The calculated width is
256 * also set as a property of the viewport.
258 * @return Dimension giving the maximum width of the alignment label panel
259 * that should be used.
261 public Dimension calculateIdWidth()
263 int oldWidth = av.getIdWidth();
265 // calculate sensible default width when no preference is available
267 if (av.getIdWidth() < 0)
269 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
270 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
271 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
272 r = calculateIdWidth(maxwidth);
273 av.setIdWidth(r.width);
278 r.width = av.getIdWidth();
283 * fudge: if desired width has changed, update layout
284 * (see also paintComponent - updates layout on a repaint)
286 if (r.width != oldWidth)
288 idPanelHolder.setPreferredSize(r);
295 * Calculate the width of the alignment labels based on the displayed names
296 * and any bounds on label width set in preferences.
299 * -1 or maximum width allowed for IdWidth
300 * @return Dimension giving the maximum width of the alignment label panel
301 * that should be used.
303 protected Dimension calculateIdWidth(int maxwidth)
305 Container c = new Container();
307 FontMetrics fm = c.getFontMetrics(
308 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
310 AlignmentI al = av.getAlignment();
314 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
316 SequenceI s = al.getSequenceAt(i);
317 String id = s.getDisplayId(av.getShowJVSuffix());
318 int stringWidth = fm.stringWidth(id);
319 idWidth = Math.max(idWidth, stringWidth);
323 // Also check annotation label widths
326 if (al.getAlignmentAnnotation() != null)
328 fm = c.getFontMetrics(getAlabels().getFont());
330 while (i < al.getAlignmentAnnotation().length)
332 String label = al.getAlignmentAnnotation()[i].label;
333 int stringWidth = fm.stringWidth(label);
334 idWidth = Math.max(idWidth, stringWidth);
339 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
340 w += ID_WIDTH_PADDING;
342 return new Dimension(w, 12);
346 * Highlight the given results on the alignment
349 public void highlightSearchResults(SearchResultsI results)
351 boolean scrolled = scrollToPosition(results, 0, false);
353 boolean fastPaint = !(scrolled && av.getWrapAlignment());
355 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
359 * Scroll the view to show the position of the highlighted region in results
362 * @param searchResults
365 public boolean scrollToPosition(SearchResultsI searchResults)
367 return scrollToPosition(searchResults, 0, false);
371 * Scrolls the view (if necessary) to show the position of the first
372 * highlighted region in results (if any). Answers true if the view was
373 * scrolled, or false if no matched region was found, or it is already
377 * @param verticalOffset
378 * if greater than zero, allows scrolling to a position below the
379 * first displayed sequence
381 * if true, try to centre the search results horizontally in the view
384 protected boolean scrollToPosition(SearchResultsI results,
385 int verticalOffset, boolean centre)
387 int startv, endv, starts, ends;
388 ViewportRanges ranges = av.getRanges();
390 if (results == null || results.isEmpty() || av == null
391 || av.getAlignment() == null)
395 int seqIndex = av.getAlignment().findIndex(results);
400 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
402 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
411 * To centre results, scroll to positions half the visible width
412 * left/right of the start/end positions
416 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
417 start = Math.max(start - offset, 0);
418 end = end + offset - 1;
424 if (end == seq.getEnd())
429 if (av.hasHiddenColumns())
431 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
432 start = hidden.absoluteToVisibleColumn(start);
433 end = hidden.absoluteToVisibleColumn(end);
436 if (!hidden.isVisible(r[0]))
438 // don't scroll - position isn't visible
445 * allow for offset of target sequence (actually scroll to one above it)
447 seqIndex = Math.max(0, seqIndex - verticalOffset);
448 boolean scrollNeeded = true;
450 if (!av.getWrapAlignment())
452 if ((startv = ranges.getStartRes()) >= start)
455 * Scroll left to make start of search results visible
457 setScrollValues(start, seqIndex);
459 else if ((endv = ranges.getEndRes()) <= end)
462 * Scroll right to make end of search results visible
464 setScrollValues(startv + end - endv, seqIndex);
466 else if ((starts = ranges.getStartSeq()) > seqIndex)
469 * Scroll up to make start of search results visible
471 setScrollValues(ranges.getStartRes(), seqIndex);
473 else if ((ends = ranges.getEndSeq()) <= seqIndex)
476 * Scroll down to make end of search results visible
478 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
481 * Else results are already visible - no need to scroll
483 scrollNeeded = false;
487 scrollNeeded = ranges.scrollToWrappedVisible(start);
490 paintAlignment(false, false);
498 * @return DOCUMENT ME!
500 public OverviewPanel getOverviewPanel()
502 return overviewPanel;
511 public void setOverviewPanel(OverviewPanel op)
519 * Hide or show annotation panel
522 public void setAnnotationVisible(boolean b)
524 if (!av.getWrapAlignment())
526 annotationSpaceFillerHolder.setVisible(b);
527 annotationScroller.setVisible(b);
533 * automatically adjust annotation panel height for new annotation whilst
534 * ensuring the alignment is still visible.
537 public void adjustAnnotationHeight()
539 // TODO: display vertical annotation scrollbar if necessary
540 // this is called after loading new annotation onto alignment
541 if (alignFrame.getHeight() == 0)
543 System.out.println("NEEDS FIXING");
545 validateAnnotationDimensions(true);
547 // TODO: many places call this method and also paintAlignment with various
548 // different settings. this means multiple redraws are triggered...
549 paintAlignment(true, av.needToUpdateStructureViews());
553 * calculate the annotation dimensions and refresh slider values accordingly.
554 * need to do repaints/notifys afterwards.
556 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
558 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
559 // are not changing ancestors, and keyboard action listeners do
560 // not need to be reset. addNotify() is a very expensive operation,
561 // requiring a full re-layout of all parents and children.
562 // Note in JComponent:
563 // This method is called by the toolkit internally and should
564 // not be called directly by programs.
565 // I note that addNotify() is called in several areas of Jalview.
567 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
568 annotationHeight = getAnnotationPanel()
569 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
572 annotationScroller.setPreferredSize(
573 new Dimension(annotationScroller.getWidth(), annotationHeight));
575 Dimension e = idPanel.getSize();
576 alabels.setSize(new Dimension(e.width, annotationHeight));
578 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
579 annotationSpaceFillerHolder.getWidth(), annotationHeight));
580 annotationScroller.validate();
581 annotationScroller.addNotify();
585 * update alignment layout for viewport settings
590 public void updateLayout()
593 setAnnotationVisible(av.isShowAnnotation());
594 boolean wrap = av.getWrapAlignment();
595 ViewportRanges ranges = av.getRanges();
596 ranges.setStartSeq(0);
597 scalePanelHolder.setVisible(!wrap);
598 hscroll.setVisible(!wrap);
599 idwidthAdjuster.setVisible(!wrap);
603 annotationScroller.setVisible(false);
604 annotationSpaceFillerHolder.setVisible(false);
606 else if (av.isShowAnnotation())
608 annotationScroller.setVisible(true);
609 annotationSpaceFillerHolder.setVisible(true);
610 validateAnnotationDimensions(false);
613 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
615 { // may not yet be laid out
618 int widthInRes = getSeqPanel().seqCanvas
619 .getWrappedCanvasWidth(canvasWidth);
620 ranges.setViewportWidth(widthInRes);
624 int widthInRes = (canvasWidth / av.getCharWidth());
625 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
626 / av.getCharHeight());
628 ranges.setViewportWidth(widthInRes);
629 ranges.setViewportHeight(heightInSeq);
633 idSpaceFillerPanel1.setVisible(!wrap);
639 * Adjust row/column scrollers to show a visible position in the alignment.
642 * visible column to scroll to
644 * visible row to scroll to
647 public void setScrollValues(int xpos, int ypos)
652 if (av == null || av.getAlignment() == null)
657 if (av.getWrapAlignment())
659 setScrollingForWrappedPanel(x);
663 int width = av.getAlignment().getVisibleWidth();
664 int height = av.getAlignment().getHeight();
666 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
667 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
674 if (vextent > height)
679 if ((hextent + x) > width)
684 if ((vextent + y) > height)
686 y = height - vextent;
699 // update the scroll values
700 hscroll.setValues(x, hextent, 0, width);
701 vscroll.setValues(y, vextent, 0, height);
706 * Respond to adjustment event when horizontal or vertical scrollbar is
710 * adjustment event encoding whether hscroll or vscroll changed
713 public void adjustmentValueChanged(AdjustmentEvent evt)
715 if (av.getWrapAlignment())
717 adjustScrollingWrapped(evt);
721 ViewportRanges ranges = av.getRanges();
723 if (evt.getSource() == hscroll)
725 int oldX = ranges.getStartRes();
726 int oldwidth = ranges.getViewportWidth();
727 int x = hscroll.getValue();
728 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
730 // if we're scrolling to the position we're already at, stop
731 // this prevents infinite recursion of events when the scroll/viewport
732 // ranges values are the same
733 if ((x == oldX) && (width == oldwidth))
737 ranges.setViewportStartAndWidth(x, width);
739 else if (evt.getSource() == vscroll)
741 int oldY = ranges.getStartSeq();
742 int oldheight = ranges.getViewportHeight();
743 int y = vscroll.getValue();
744 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
746 // if we're scrolling to the position we're already at, stop
747 // this prevents infinite recursion of events when the scroll/viewport
748 // ranges values are the same
749 if ((y == oldY) && (height == oldheight))
753 ranges.setViewportStartAndHeight(y, height);
759 * Responds to a scroll change by setting the start position of the viewport.
764 protected void adjustScrollingWrapped(AdjustmentEvent evt)
766 if (evt.getSource() == hscroll)
768 return; // no horizontal scroll when wrapped
770 final ViewportRanges ranges = av.getRanges();
772 if (evt.getSource() == vscroll)
774 int newY = vscroll.getValue();
777 * if we're scrolling to the position we're already at, stop
778 * this prevents infinite recursion of events when the scroll/viewport
779 * ranges values are the same
781 int oldX = ranges.getStartRes();
782 int oldY = ranges.getWrappedScrollPosition(oldX);
790 * limit page up/down to one width's worth of positions
792 int rowSize = ranges.getViewportWidth();
793 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
794 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
799 // This is only called if file loaded is a jar file that
800 // was wrapped when saved and user has wrap alignment true
801 // as preference setting
802 SwingUtilities.invokeLater(new Runnable()
807 // When updating scrolling to use ViewportChange events, this code
808 // could not be validated and it is not clear if it is now being
809 // called. Log warning here in case it is called and unforeseen
812 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
814 // scroll to start of panel
815 ranges.setStartRes(0);
816 ranges.setStartSeq(0);
824 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
827 public void paintAlignment(boolean updateOverview,
828 boolean updateStructures)
830 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
831 av.isShowAutocalculatedAbove());
832 sorter.sort(getAlignment().getAlignmentAnnotation(),
833 av.getSortAnnotationsBy());
836 if (updateStructures)
838 av.getStructureSelectionManager().sequenceColoursChanged(this);
843 if (overviewPanel != null)
845 overviewPanel.updateOverviewImage();
851 public void paintComponent(Graphics g)
853 invalidate(); // needed so that the id width adjuster works correctly
855 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
856 idPanelHolder.setPreferredSize(d);
857 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
859 validate(); // needed so that the id width adjuster works correctly
862 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
863 * though I still think this call should be elsewhere.
865 ViewportRanges ranges = av.getRanges();
866 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
867 super.paintComponent(g);
871 * Set vertical scroll bar position, and number of increments, for wrapped
874 * @param topLeftColumn
875 * the column position at top left (0..)
877 private void setScrollingForWrappedPanel(int topLeftColumn)
879 ViewportRanges ranges = av.getRanges();
880 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
881 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
884 * a scrollbar's value can be set to at most (maximum-extent)
885 * so we add extent (1) to the maxScroll value
887 vscroll.setUnitIncrement(1);
888 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
901 * @return DOCUMENT ME!
903 * @throws PrinterException
907 public int print(Graphics pg, PageFormat pf, int pi)
908 throws PrinterException
910 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
912 int pwidth = (int) pf.getImageableWidth();
913 int pheight = (int) pf.getImageableHeight();
915 if (av.getWrapAlignment())
917 return printWrappedAlignment(pwidth, pheight, pi, pg);
921 return printUnwrapped(pwidth, pheight, pi, pg, pg);
926 * Draws the alignment image, including sequence ids, sequences, and
927 * annotation labels and annotations if shown, on either one or two Graphics
937 * the graphics context for sequence ids and annotation labels
938 * @param alignmentGraphics
939 * the graphics context for sequences and annotations (may or may not
940 * be the same context as idGraphics)
942 * @throws PrinterException
944 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
945 Graphics idGraphics, Graphics alignmentGraphics)
946 throws PrinterException
948 final int idWidth = getVisibleIdWidth(false);
951 * Get the horizontal offset to where we draw the sequences.
952 * This is idWidth if using a single Graphics context, else zero.
954 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
957 FontMetrics fm = getFontMetrics(av.getFont());
958 final int charHeight = av.getCharHeight();
959 final int scaleHeight = charHeight + fm.getDescent();
961 idGraphics.setColor(Color.white);
962 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
963 idGraphics.setFont(av.getFont());
966 * How many sequences and residues can we fit on a printable page?
968 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
970 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
972 final int alignmentWidth = av.getAlignment().getVisibleWidth();
973 int pagesWide = (alignmentWidth / totalRes) + 1;
975 final int startRes = (pageIndex % pagesWide) * totalRes;
976 final int endRes = Math.min(startRes + totalRes - 1,
979 final int startSeq = (pageIndex / pagesWide) * totalSeq;
980 final int alignmentHeight = av.getAlignment().getHeight();
981 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
983 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
985 if (av.isShowAnnotation())
987 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
990 pagesHigh /= pageHeight;
992 if (pageIndex >= (pagesWide * pagesHigh))
994 return Printable.NO_SUCH_PAGE;
996 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
999 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1001 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1002 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1003 pageWidth - idWidth, scaleHeight);
1004 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1007 * Draw the sequence ids, offset for scale height,
1008 * then reset to top left (0, 0)
1010 idGraphics.translate(0, scaleHeight);
1011 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1012 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1013 : av.getSelectionGroup().getSequences(null);
1014 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1017 idGraphics.setFont(av.getFont());
1018 idGraphics.translate(0, -scaleHeight);
1021 * draw the sequences, offset for scale height, and id width (if using a
1022 * single graphics context), then reset to (0, scale height)
1024 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1025 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1026 startRes, endRes, startSeq, endSeq - 1);
1027 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1029 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1032 * draw annotation labels; drawComponent() translates by
1033 * getScrollOffset(), so compensate for that first;
1034 * then reset to (0, scale height)
1036 int offset = getAlabels().getScrollOffset();
1037 idGraphics.translate(0, -offset);
1038 idGraphics.translate(0, alignmentDrawnHeight);
1039 getAlabels().drawComponent(idGraphics, idWidth);
1040 idGraphics.translate(0, -alignmentDrawnHeight);
1043 * draw the annotations starting at
1044 * (idOffset, alignmentHeight) from (0, scaleHeight)
1046 alignmentGraphics.translate(alignmentGraphicsOffset,
1047 alignmentDrawnHeight);
1048 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1049 alignmentGraphics, -1, startRes, endRes + 1);
1052 return Printable.PAGE_EXISTS;
1056 * Prints one page of an alignment in wrapped mode. Returns
1057 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1058 * no page could be drawn (page number out of range).
1068 * @throws PrinterException
1070 public int printWrappedAlignment(int pageWidth, int pageHeight,
1071 int pageNumber, Graphics g) throws PrinterException
1073 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
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);
1096 av.getRanges().setViewportStartAndWidth(0, resWidth);
1098 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1100 g.setColor(Color.white);
1101 g.fillRect(0, 0, pageWidth, pageHeight);
1102 g.setFont(av.getFont());
1103 g.setColor(Color.black);
1106 * method: print the whole wrapped alignment, but with a clip region that
1107 * is restricted to the requested page; this supports selective print of
1108 * single pages or ranges, (at the cost of repeated processing in the
1109 * 'normal' case, when all pages are printed)
1111 g.translate(0, -pageNumber * pageHeight);
1113 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1116 * draw sequence ids and annotation labels (if shown)
1118 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1119 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1121 g.translate(idWidth, 0);
1123 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1124 pageWidth - idWidth, totalHeight, 0);
1126 if ((pageNumber * pageHeight) < totalHeight)
1128 return Printable.PAGE_EXISTS;
1132 return Printable.NO_SUCH_PAGE;
1137 * get current sequence ID panel width, or nominal value if panel were to be
1138 * displayed using default settings
1142 public int getVisibleIdWidth()
1144 return getVisibleIdWidth(true);
1148 * get current sequence ID panel width, or nominal value if panel were to be
1149 * displayed using default settings
1152 * indicate if the Id width for onscreen or offscreen display should
1156 protected int getVisibleIdWidth(boolean onscreen)
1158 // see if rendering offscreen - check preferences and calc width accordingly
1159 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1161 return calculateIdWidth(-1).width;
1163 Integer idwidth = onscreen ? null
1164 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1165 if (idwidth != null)
1167 return idwidth.intValue() + ID_WIDTH_PADDING;
1170 int w = getIdPanel().getWidth();
1171 return (w > 0 ? w : calculateIdWidth().width);
1175 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1176 * writes it to the specified file
1181 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1183 final int borderBottomOffset = 5;
1185 AlignmentDimension aDimension = getAlignmentDimension();
1186 // todo use a lambda function in place of callback here?
1187 ImageWriterI writer = new ImageWriterI()
1190 public void exportImage(Graphics graphics) throws Exception
1192 if (av.getWrapAlignment())
1194 printWrappedAlignment(aDimension.getWidth(),
1195 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1199 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1200 graphics, graphics);
1205 String fileTitle = alignFrame.getTitle();
1206 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1208 int imageWidth = aDimension.getWidth();
1209 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1210 String of = MessageManager.getString("label.alignment");
1211 exporter.doExport(file, this, imageWidth, imageHeight, of);
1215 * Calculates and returns a suitable width and height (in pixels) for an
1220 public AlignmentDimension getAlignmentDimension()
1222 int maxwidth = av.getAlignment().getVisibleWidth();
1224 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1225 + getScalePanel().getHeight();
1226 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1228 if (av.getWrapAlignment())
1230 height = getWrappedHeight();
1231 if (Jalview.isHeadlessMode())
1233 // need to obtain default alignment width and then add in any
1234 // additional allowance for id margin
1235 // this duplicates the calculation in getWrappedHeight but adjusts for
1237 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1238 - alignFrame.getInsets().left - alignFrame.getInsets().right
1239 - getVisibleIdWidth() + getVisibleIdWidth(false);
1243 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1247 else if (av.isShowAnnotation())
1249 height += getAnnotationPanel().adjustPanelHeight() + 3;
1251 return new AlignmentDimension(width, height);
1255 public void makePNGImageMap(File imgMapFile, String imageName)
1257 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1258 // ////////////////////////////////////////////
1259 int idWidth = getVisibleIdWidth(false);
1260 FontMetrics fm = getFontMetrics(av.getFont());
1261 int scaleHeight = av.getCharHeight() + fm.getDescent();
1264 // ////////////////////////////////
1265 if (imgMapFile != null)
1269 int sSize = av.getAlignment().getHeight();
1270 int alwidth = av.getAlignment().getWidth();
1271 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1272 out.println(HTMLOutput.getImageMapHTML());
1273 out.println("<img src=\"" + imageName
1274 + "\" border=\"0\" usemap=\"#Map\" >"
1275 + "<map name=\"Map\">");
1277 for (int s = 0; s < sSize; s++)
1279 int sy = s * av.getCharHeight() + scaleHeight;
1281 SequenceI seq = av.getAlignment().getSequenceAt(s);
1282 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1283 for (int column = 0; column < alwidth; column++)
1285 StringBuilder text = new StringBuilder(512);
1286 String triplet = null;
1287 if (av.getAlignment().isNucleotide())
1289 triplet = ResidueProperties.nucleotideName
1290 .get(seq.getCharAt(column) + "");
1294 triplet = ResidueProperties.aa2Triplet
1295 .get(seq.getCharAt(column) + "");
1298 if (triplet == null)
1303 int seqPos = seq.findPosition(column);
1304 int gSize = groups.length;
1305 for (int g = 0; g < gSize; g++)
1307 if (text.length() < 1)
1309 text.append("<area shape=\"rect\" coords=\"")
1310 .append((idWidth + column * av.getCharWidth()))
1311 .append(",").append(sy).append(",")
1313 + (column + 1) * av.getCharWidth()))
1314 .append(",").append((av.getCharHeight() + sy))
1315 .append("\"").append(" onMouseOver=\"toolTip('")
1316 .append(seqPos).append(" ").append(triplet);
1319 if (groups[g].getStartRes() < column
1320 && groups[g].getEndRes() > column)
1322 text.append("<br><em>").append(groups[g].getName())
1327 if (text.length() < 1)
1329 text.append("<area shape=\"rect\" coords=\"")
1330 .append((idWidth + column * av.getCharWidth()))
1331 .append(",").append(sy).append(",")
1332 .append((idWidth + (column + 1) * av.getCharWidth()))
1333 .append(",").append((av.getCharHeight() + sy))
1334 .append("\"").append(" onMouseOver=\"toolTip('")
1335 .append(seqPos).append(" ").append(triplet);
1337 if (!Comparison.isGap(seq.getCharAt(column)))
1339 List<SequenceFeature> features = seq.findFeatures(column,
1341 for (SequenceFeature sf : features)
1343 if (sf.isContactFeature())
1345 text.append("<br>").append(sf.getType()).append(" ")
1346 .append(sf.getBegin()).append(":")
1347 .append(sf.getEnd());
1351 text.append("<br>");
1352 text.append(sf.getType());
1353 String description = sf.getDescription();
1354 if (description != null
1355 && !sf.getType().equals(description))
1357 description = description.replace("\"", """);
1358 text.append(" ").append(description);
1361 String status = sf.getStatus();
1362 if (status != null && !"".equals(status))
1364 text.append(" (").append(status).append(")");
1367 if (text.length() > 1)
1369 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1370 out.println(text.toString());
1375 out.println("</map></body></html>");
1378 } catch (Exception ex)
1380 ex.printStackTrace();
1382 } // /////////END OF IMAGE MAP
1387 * Answers the height of the entire alignment in pixels, assuming it is in
1392 int getWrappedHeight()
1394 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1396 if (System.getProperty("java.awt.headless") != null
1397 && System.getProperty("java.awt.headless").equals("true"))
1399 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1400 - vscroll.getPreferredSize().width
1401 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1404 int chunkWidth = getSeqPanel().seqCanvas
1405 .getWrappedCanvasWidth(seqPanelWidth);
1407 int hgap = av.getCharHeight();
1408 if (av.getScaleAboveWrapped())
1410 hgap += av.getCharHeight();
1413 int annotationHeight = 0;
1414 if (av.isShowAnnotation())
1416 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1417 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1420 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1423 int maxwidth = av.getAlignment().getWidth();
1424 if (av.hasHiddenColumns())
1426 maxwidth = av.getAlignment().getHiddenColumns()
1427 .absoluteToVisibleColumn(maxwidth) - 1;
1430 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1436 * close the panel - deregisters all listeners and nulls any references to
1439 public void closePanel()
1441 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1442 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1443 PaintRefresher.RemoveComponent(this);
1448 * try to ensure references are nulled
1450 if (annotationPanel != null)
1452 annotationPanel.dispose();
1453 annotationPanel = null;
1458 av.removePropertyChangeListener(propertyChangeListener);
1459 propertyChangeListener = null;
1460 StructureSelectionManager ssm = av.getStructureSelectionManager();
1461 ssm.removeStructureViewerListener(getSeqPanel(), null);
1462 ssm.removeSelectionListener(getSeqPanel());
1463 ssm.removeCommandListener(av);
1464 ssm.removeStructureViewerListener(getSeqPanel(), null);
1465 ssm.removeSelectionListener(getSeqPanel());
1471 if (Console.isDebugEnabled())
1473 Console.warn("Closing alignment panel which is already closed.");
1479 * Close any open dialogs that would be orphaned when this one is closed
1481 protected void closeChildFrames()
1483 if (overviewPanel != null)
1485 overviewPanel.dispose();
1486 overviewPanel = null;
1488 if (calculationDialog != null)
1490 calculationDialog.closeFrame();
1491 calculationDialog = null;
1496 * hides or shows dynamic annotation rows based on groups and av state flags
1498 public void updateAnnotation()
1500 updateAnnotation(false, false);
1503 public void updateAnnotation(boolean applyGlobalSettings)
1505 updateAnnotation(applyGlobalSettings, false);
1508 public void updateAnnotation(boolean applyGlobalSettings,
1509 boolean preserveNewGroupSettings)
1511 av.updateGroupAnnotationSettings(applyGlobalSettings,
1512 preserveNewGroupSettings);
1513 adjustAnnotationHeight();
1517 public AlignmentI getAlignment()
1519 return av == null ? null : av.getAlignment();
1523 public String getViewName()
1525 return av.getViewName();
1529 * Make/Unmake this alignment panel the current input focus
1533 public void setSelected(boolean b)
1537 if (alignFrame.getSplitViewContainer() != null)
1540 * bring enclosing SplitFrame to front first if there is one
1542 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1544 alignFrame.setSelected(b);
1545 } catch (Exception ex)
1550 setAlignFrameView();
1554 public void setAlignFrameView()
1556 alignFrame.setDisplayedView(this);
1560 public StructureSelectionManager getStructureSelectionManager()
1562 return av.getStructureSelectionManager();
1566 public void raiseOOMWarning(String string, OutOfMemoryError error)
1568 new OOMWarning(string, error, this);
1572 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1575 return new FeatureRenderer(this);
1579 public jalview.api.FeatureRenderer getFeatureRenderer()
1581 return seqPanel.seqCanvas.getFeatureRenderer();
1584 public void updateFeatureRenderer(
1585 jalview.renderer.seqfeatures.FeatureRenderer fr)
1587 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1590 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1592 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1594 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1598 public ScalePanel getScalePanel()
1603 public void setScalePanel(ScalePanel scalePanel)
1605 this.scalePanel = scalePanel;
1608 public SeqPanel getSeqPanel()
1613 public void setSeqPanel(SeqPanel seqPanel)
1615 this.seqPanel = seqPanel;
1618 public AnnotationPanel getAnnotationPanel()
1620 return annotationPanel;
1623 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1625 this.annotationPanel = annotationPanel;
1628 public AnnotationLabels getAlabels()
1633 public void setAlabels(AnnotationLabels alabels)
1635 this.alabels = alabels;
1638 public IdPanel getIdPanel()
1643 public void setIdPanel(IdPanel idPanel)
1645 this.idPanel = idPanel;
1649 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1650 * The aim is to keep the two alignments 'lined up' on their centre columns.
1653 * holds mapped region(s) of this alignment that we are scrolling
1654 * 'to'; may be modified for sequence offset by this method
1655 * @param verticalOffset
1656 * the number of visible sequences to show above the mapped region
1658 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1660 scrollToPosition(sr, verticalOffset, true);
1664 * Set a flag to say do not scroll any (cDNA/protein) complement.
1668 protected void setToScrollComplementPanel(boolean b)
1670 this.scrollComplementaryPanel = b;
1674 * Get whether to scroll complement panel
1676 * @return true if cDNA/protein complement panels should be scrolled
1678 protected boolean isSetToScrollComplementPanel()
1680 return this.scrollComplementaryPanel;
1686 * @adjustHeight if true, try to recalculate panel height for visible
1689 protected void refresh(boolean adjustHeight)
1691 validateAnnotationDimensions(adjustHeight);
1695 // sort, repaint, update overview
1696 paintAlignment(true, false);
1700 // lightweight repaint
1707 * Property change event fired when a change is made to the viewport ranges
1708 * object associated with this alignment panel's viewport
1710 public void propertyChange(PropertyChangeEvent evt)
1712 // update this panel's scroll values based on the new viewport ranges values
1713 ViewportRanges ranges = av.getRanges();
1714 int x = ranges.getStartRes();
1715 int y = ranges.getStartSeq();
1716 setScrollValues(x, y);
1718 // now update any complementary alignment (its viewport ranges object
1719 // is different so does not get automatically updated)
1720 if (isSetToScrollComplementPanel())
1722 setToScrollComplementPanel(false);
1723 av.scrollComplementaryAlignment();
1724 setToScrollComplementPanel(true);
1729 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1730 * reference should be nulled when the dialog is closed.
1732 * @param calculationChooser
1734 public void setCalculationDialog(CalculationChooser calculationChooser)
1736 calculationDialog = calculationChooser;
1740 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1743 public CalculationChooser getCalculationDialog()
1745 return calculationDialog;
1749 * Constructs and sets the title for the Overview window (if there is one),
1750 * including the align frame's title, and view name (if applicable). Returns
1751 * the title, or null if this panel has no Overview window open.
1756 public String setOverviewTitle(AlignFrame alignFrame)
1758 if (this.overviewPanel == null)
1762 String overviewTitle = MessageManager
1763 .formatMessage("label.overview_params", new Object[]
1764 { alignFrame.getTitle() });
1765 String viewName = getViewName();
1766 if (viewName != null)
1768 overviewTitle += (" " + viewName);
1770 overviewPanel.setTitle(overviewTitle);
1771 return overviewTitle;
1775 * If this alignment panel has an Overview panel open, closes it
1777 public void closeOverviewPanel()
1779 if (overviewPanel != null)
1781 overviewPanel.close();
1782 overviewPanel = null;