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 scalePanelHolder.setPreferredSize(
234 new Dimension(10, av.getCharHeight() + fm.getDescent()));
235 idSpaceFillerPanel1.setPreferredSize(
236 new Dimension(10, av.getCharHeight() + fm.getDescent()));
237 idwidthAdjuster.invalidate();
238 scalePanelHolder.invalidate();
239 // BH 2018 getIdPanel().getIdCanvas().gg = null;
240 getSeqPanel().seqCanvas.img = null;
241 getAnnotationPanel().adjustPanelHeight();
243 Dimension d = calculateIdWidth();
244 getIdPanel().getIdCanvas().setPreferredSize(d);
245 hscrollFillerPanel.setPreferredSize(d);
251 * Calculates the width of the alignment labels based on the displayed names
252 * and any bounds on label width set in preferences. The calculated width is
253 * also set as a property of the viewport.
255 * @return Dimension giving the maximum width of the alignment label panel
256 * that should be used.
258 public Dimension calculateIdWidth()
260 int oldWidth = av.getIdWidth();
262 // calculate sensible default width when no preference is available
264 if (av.getIdWidth() < 0)
266 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
267 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
268 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
269 r = calculateIdWidth(maxwidth);
270 av.setIdWidth(r.width);
275 r.width = av.getIdWidth();
280 * fudge: if desired width has changed, update layout
281 * (see also paintComponent - updates layout on a repaint)
283 if (r.width != oldWidth)
285 idPanelHolder.setPreferredSize(r);
292 * Calculate the width of the alignment labels based on the displayed names
293 * and any bounds on label width set in preferences.
296 * -1 or maximum width allowed for IdWidth
297 * @return Dimension giving the maximum width of the alignment label panel
298 * that should be used.
300 protected Dimension calculateIdWidth(int maxwidth)
302 Container c = new Container();
304 FontMetrics fm = c.getFontMetrics(
305 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
307 AlignmentI al = av.getAlignment();
311 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
313 SequenceI s = al.getSequenceAt(i);
314 String id = s.getDisplayId(av.getShowJVSuffix());
315 int stringWidth = fm.stringWidth(id);
316 idWidth = Math.max(idWidth, stringWidth);
320 // Also check annotation label widths
323 if (al.getAlignmentAnnotation() != null)
325 fm = c.getFontMetrics(getAlabels().getFont());
327 while (i < al.getAlignmentAnnotation().length)
329 String label = al.getAlignmentAnnotation()[i].label;
330 int stringWidth = fm.stringWidth(label);
331 idWidth = Math.max(idWidth, stringWidth);
336 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
337 w += ID_WIDTH_PADDING;
339 return new Dimension(w, 12);
343 * Highlight the given results on the alignment
346 public void highlightSearchResults(SearchResultsI results)
348 boolean scrolled = scrollToPosition(results, 0, false);
350 boolean fastPaint = !(scrolled && av.getWrapAlignment());
352 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
356 * Scroll the view to show the position of the highlighted region in results
359 * @param searchResults
362 public boolean scrollToPosition(SearchResultsI searchResults)
364 return scrollToPosition(searchResults, 0, false);
368 * Scrolls the view (if necessary) to show the position of the first
369 * highlighted region in results (if any). Answers true if the view was
370 * scrolled, or false if no matched region was found, or it is already
374 * @param verticalOffset
375 * if greater than zero, allows scrolling to a position below the
376 * first displayed sequence
378 * if true, try to centre the search results horizontally in the view
381 protected boolean scrollToPosition(SearchResultsI results,
382 int verticalOffset, boolean centre)
384 int startv, endv, starts, ends;
385 ViewportRanges ranges = av.getRanges();
387 if (results == null || results.isEmpty() || av == null
388 || av.getAlignment() == null)
392 int seqIndex = av.getAlignment().findIndex(results);
397 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
399 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
408 * To centre results, scroll to positions half the visible width
409 * left/right of the start/end positions
413 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
414 start = Math.max(start - offset, 0);
415 end = end + offset - 1;
421 if (end == seq.getEnd())
426 if (av.hasHiddenColumns())
428 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
429 start = hidden.absoluteToVisibleColumn(start);
430 end = hidden.absoluteToVisibleColumn(end);
433 if (!hidden.isVisible(r[0]))
435 // don't scroll - position isn't visible
442 * allow for offset of target sequence (actually scroll to one above it)
444 seqIndex = Math.max(0, seqIndex - verticalOffset);
445 boolean scrollNeeded = true;
447 if (!av.getWrapAlignment())
449 if ((startv = ranges.getStartRes()) >= start)
452 * Scroll left to make start of search results visible
454 setScrollValues(start, seqIndex);
456 else if ((endv = ranges.getEndRes()) <= end)
459 * Scroll right to make end of search results visible
461 setScrollValues(startv + end - endv, seqIndex);
463 else if ((starts = ranges.getStartSeq()) > seqIndex)
466 * Scroll up to make start of search results visible
468 setScrollValues(ranges.getStartRes(), seqIndex);
470 else if ((ends = ranges.getEndSeq()) <= seqIndex)
473 * Scroll down to make end of search results visible
475 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
479 * Else results are already visible - no need to scroll
481 scrollNeeded = false;
485 scrollNeeded = ranges.scrollToWrappedVisible(start);
488 paintAlignment(false, false);
496 * @return DOCUMENT ME!
498 public OverviewPanel getOverviewPanel()
500 return overviewPanel;
509 public void setOverviewPanel(OverviewPanel op)
517 * Hide or show annotation panel
520 public void setAnnotationVisible(boolean b)
522 if (!av.getWrapAlignment())
524 annotationSpaceFillerHolder.setVisible(b);
525 annotationScroller.setVisible(b);
531 * automatically adjust annotation panel height for new annotation whilst
532 * ensuring the alignment is still visible.
535 public void adjustAnnotationHeight()
537 // TODO: display vertical annotation scrollbar if necessary
538 // this is called after loading new annotation onto alignment
539 if (alignFrame.getHeight() == 0)
541 System.out.println("NEEDS FIXING");
543 validateAnnotationDimensions(true);
545 // TODO: many places call this method and also paintAlignment with various
546 // different settings. this means multiple redraws are triggered...
547 paintAlignment(true, av.needToUpdateStructureViews());
551 * calculate the annotation dimensions and refresh slider values accordingly.
552 * need to do repaints/notifys afterwards.
554 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
556 // BH 2018.04.18 comment: addNotify() is not appropriate here. We
557 // are not changing ancestors, and keyboard action listeners do
558 // not need to be reset. addNotify() is a very expensive operation,
559 // requiring a full re-layout of all parents and children.
560 // Note in JComponent:
561 // This method is called by the toolkit internally and should
562 // not be called directly by programs.
563 // I note that addNotify() is called in several areas of Jalview.
565 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
566 annotationHeight = getAnnotationPanel()
567 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
570 annotationScroller.setPreferredSize(
571 new Dimension(annotationScroller.getWidth(), annotationHeight));
573 Dimension e = idPanel.getSize();
574 alabels.setSize(new Dimension(e.width, annotationHeight));
577 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
578 annotationSpaceFillerHolder.getWidth(), annotationHeight));
579 annotationScroller.validate();
580 annotationScroller.addNotify();
584 * update alignment layout for viewport settings
589 public void updateLayout()
592 setAnnotationVisible(av.isShowAnnotation());
593 boolean wrap = av.getWrapAlignment();
594 ViewportRanges ranges = av.getRanges();
595 ranges.setStartSeq(0);
596 scalePanelHolder.setVisible(!wrap);
597 hscroll.setVisible(!wrap);
598 idwidthAdjuster.setVisible(!wrap);
602 annotationScroller.setVisible(false);
603 annotationSpaceFillerHolder.setVisible(false);
605 else if (av.isShowAnnotation())
607 annotationScroller.setVisible(true);
608 annotationSpaceFillerHolder.setVisible(true);
609 validateAnnotationDimensions(false);
612 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
614 { // may not yet be laid out
617 int widthInRes = getSeqPanel().seqCanvas
618 .getWrappedCanvasWidth(canvasWidth);
619 ranges.setViewportWidth(widthInRes);
623 int widthInRes = (canvasWidth / av.getCharWidth());
624 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
625 / av.getCharHeight());
627 ranges.setViewportWidth(widthInRes);
628 ranges.setViewportHeight(heightInSeq);
632 idSpaceFillerPanel1.setVisible(!wrap);
638 * Adjust row/column scrollers to show a visible position in the alignment.
641 * visible column to scroll to
643 * visible row to scroll to
646 public void setScrollValues(int xpos, int ypos)
651 if (av == null || av.getAlignment() == null)
656 if (av.getWrapAlignment())
658 setScrollingForWrappedPanel(x);
662 int width = av.getAlignment().getVisibleWidth();
663 int height = av.getAlignment().getHeight();
665 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
666 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
673 if (vextent > height)
678 if ((hextent + x) > width)
683 if ((vextent + y) > height)
685 y = height - vextent;
698 // update the scroll values
699 hscroll.setValues(x, hextent, 0, width);
700 vscroll.setValues(y, vextent, 0, height);
705 * Respond to adjustment event when horizontal or vertical scrollbar is
709 * adjustment event encoding whether hscroll or vscroll changed
712 public void adjustmentValueChanged(AdjustmentEvent evt)
714 if (av.getWrapAlignment())
716 adjustScrollingWrapped(evt);
720 ViewportRanges ranges = av.getRanges();
722 if (evt.getSource() == hscroll)
724 int oldX = ranges.getStartRes();
725 int oldwidth = ranges.getViewportWidth();
726 int x = hscroll.getValue();
727 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
729 // if we're scrolling to the position we're already at, stop
730 // this prevents infinite recursion of events when the scroll/viewport
731 // ranges values are the same
732 if ((x == oldX) && (width == oldwidth))
736 ranges.setViewportStartAndWidth(x, width);
738 else if (evt.getSource() == vscroll)
740 int oldY = ranges.getStartSeq();
741 int oldheight = ranges.getViewportHeight();
742 int y = vscroll.getValue();
743 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
745 // if we're scrolling to the position we're already at, stop
746 // this prevents infinite recursion of events when the scroll/viewport
747 // ranges values are the same
748 if ((y == oldY) && (height == oldheight))
752 ranges.setViewportStartAndHeight(y, height);
758 * Responds to a scroll change by setting the start position of the viewport.
763 protected void adjustScrollingWrapped(AdjustmentEvent evt)
765 if (evt.getSource() == hscroll)
767 return; // no horizontal scroll when wrapped
769 final ViewportRanges ranges = av.getRanges();
771 if (evt.getSource() == vscroll)
773 int newY = vscroll.getValue();
776 * if we're scrolling to the position we're already at, stop
777 * this prevents infinite recursion of events when the scroll/viewport
778 * ranges values are the same
780 int oldX = ranges.getStartRes();
781 int oldY = ranges.getWrappedScrollPosition(oldX);
789 * limit page up/down to one width's worth of positions
791 int rowSize = ranges.getViewportWidth();
792 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
793 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
798 // This is only called if file loaded is a jar file that
799 // was wrapped when saved and user has wrap alignment true
800 // as preference setting
801 SwingUtilities.invokeLater(new Runnable()
806 // When updating scrolling to use ViewportChange events, this code
807 // could not be validated and it is not clear if it is now being
808 // called. Log warning here in case it is called and unforeseen
811 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
813 // scroll to start of panel
814 ranges.setStartRes(0);
815 ranges.setStartSeq(0);
823 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
826 public void paintAlignment(boolean updateOverview,
827 boolean updateStructures)
829 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
830 av.isShowAutocalculatedAbove());
831 sorter.sort(getAlignment().getAlignmentAnnotation(),
832 av.getSortAnnotationsBy());
835 if (updateStructures)
837 av.getStructureSelectionManager().sequenceColoursChanged(this);
842 if (overviewPanel != null)
844 overviewPanel.updateOverviewImage();
850 public void paintComponent(Graphics g)
852 invalidate(); // needed so that the id width adjuster works correctly
854 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
855 idPanelHolder.setPreferredSize(d);
856 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
858 validate(); // needed so that the id width adjuster works correctly
861 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
862 * though I still think this call should be elsewhere.
864 ViewportRanges ranges = av.getRanges();
865 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
866 super.paintComponent(g);
870 * Set vertical scroll bar position, and number of increments, for wrapped
873 * @param topLeftColumn
874 * the column position at top left (0..)
876 private void setScrollingForWrappedPanel(int topLeftColumn)
878 ViewportRanges ranges = av.getRanges();
879 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
880 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
883 * a scrollbar's value can be set to at most (maximum-extent)
884 * so we add extent (1) to the maxScroll value
886 vscroll.setUnitIncrement(1);
887 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
900 * @return DOCUMENT ME!
902 * @throws PrinterException
906 public int print(Graphics pg, PageFormat pf, int pi)
907 throws PrinterException
909 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
911 int pwidth = (int) pf.getImageableWidth();
912 int pheight = (int) pf.getImageableHeight();
914 if (av.getWrapAlignment())
916 return printWrappedAlignment(pwidth, pheight, pi, pg);
920 return printUnwrapped(pwidth, pheight, pi, pg, pg);
925 * Draws the alignment image, including sequence ids, sequences, and
926 * annotation labels and annotations if shown, on either one or two Graphics
936 * the graphics context for sequence ids and annotation labels
937 * @param alignmentGraphics
938 * the graphics context for sequences and annotations (may or may not
939 * be the same context as idGraphics)
941 * @throws PrinterException
943 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
944 Graphics idGraphics, Graphics alignmentGraphics)
945 throws PrinterException
947 final int idWidth = getVisibleIdWidth(false);
950 * Get the horizontal offset to where we draw the sequences.
951 * This is idWidth if using a single Graphics context, else zero.
953 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
956 FontMetrics fm = getFontMetrics(av.getFont());
957 final int charHeight = av.getCharHeight();
958 final int scaleHeight = charHeight + fm.getDescent();
960 idGraphics.setColor(Color.white);
961 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
962 idGraphics.setFont(av.getFont());
965 * How many sequences and residues can we fit on a printable page?
967 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
969 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
971 final int alignmentWidth = av.getAlignment().getVisibleWidth();
972 int pagesWide = (alignmentWidth / totalRes) + 1;
974 final int startRes = (pageIndex % pagesWide) * totalRes;
975 final int endRes = Math.min(startRes + totalRes - 1,
978 final int startSeq = (pageIndex / pagesWide) * totalSeq;
979 final int alignmentHeight = av.getAlignment().getHeight();
980 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
982 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
984 if (av.isShowAnnotation())
986 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
989 pagesHigh /= pageHeight;
991 if (pageIndex >= (pagesWide * pagesHigh))
993 return Printable.NO_SUCH_PAGE;
995 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
998 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1000 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1001 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1002 pageWidth - idWidth, scaleHeight);
1003 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1006 * Draw the sequence ids, offset for scale height,
1007 * then reset to top left (0, 0)
1009 idGraphics.translate(0, scaleHeight);
1010 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1011 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1012 : av.getSelectionGroup().getSequences(null);
1013 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1016 idGraphics.setFont(av.getFont());
1017 idGraphics.translate(0, -scaleHeight);
1020 * draw the sequences, offset for scale height, and id width (if using a
1021 * single graphics context), then reset to (0, scale height)
1023 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1024 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1025 endRes, startSeq, endSeq - 1);
1026 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1028 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1031 * draw annotation labels; drawComponent() translates by
1032 * getScrollOffset(), so compensate for that first;
1033 * then reset to (0, scale height)
1035 int offset = getAlabels().getScrollOffset();
1036 idGraphics.translate(0, -offset);
1037 idGraphics.translate(0, alignmentDrawnHeight);
1038 getAlabels().drawComponent(idGraphics, idWidth);
1039 idGraphics.translate(0, -alignmentDrawnHeight);
1042 * draw the annotations starting at
1043 * (idOffset, alignmentHeight) from (0, scaleHeight)
1045 alignmentGraphics.translate(alignmentGraphicsOffset,
1046 alignmentDrawnHeight);
1047 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1048 alignmentGraphics, -1, startRes, endRes + 1);
1051 return Printable.PAGE_EXISTS;
1055 * Prints one page of an alignment in wrapped mode. Returns
1056 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1057 * no page could be drawn (page number out of range).
1067 * @throws PrinterException
1069 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1070 Graphics g) throws PrinterException
1072 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1074 int annotationHeight = 0;
1075 if (av.isShowAnnotation())
1077 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1080 int hgap = av.getCharHeight();
1081 if (av.getScaleAboveWrapped())
1083 hgap += av.getCharHeight();
1086 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1089 int idWidth = getVisibleIdWidth(false);
1091 int maxwidth = av.getAlignment().getVisibleWidth();
1093 int resWidth = getSeqPanel().seqCanvas
1094 .getWrappedCanvasWidth(pageWidth - idWidth);
1095 av.getRanges().setViewportStartAndWidth(0, resWidth);
1097 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1099 g.setColor(Color.white);
1100 g.fillRect(0, 0, pageWidth, pageHeight);
1101 g.setFont(av.getFont());
1102 g.setColor(Color.black);
1105 * method: print the whole wrapped alignment, but with a clip region that
1106 * is restricted to the requested page; this supports selective print of
1107 * single pages or ranges, (at the cost of repeated processing in the
1108 * 'normal' case, when all pages are printed)
1110 g.translate(0, -pageNumber * pageHeight);
1112 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1115 * draw sequence ids and annotation labels (if shown)
1117 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1118 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1120 g.translate(idWidth, 0);
1122 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1125 if ((pageNumber * pageHeight) < totalHeight)
1127 return Printable.PAGE_EXISTS;
1131 return Printable.NO_SUCH_PAGE;
1136 * get current sequence ID panel width, or nominal value if panel were to be
1137 * displayed using default settings
1141 public int getVisibleIdWidth()
1143 return getVisibleIdWidth(true);
1147 * get current sequence ID panel width, or nominal value if panel were to be
1148 * displayed using default settings
1151 * indicate if the Id width for onscreen or offscreen display should
1155 protected int getVisibleIdWidth(boolean onscreen)
1157 // see if rendering offscreen - check preferences and calc width accordingly
1158 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1160 return calculateIdWidth(-1).width;
1162 Integer idwidth = onscreen ? null
1163 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1164 if (idwidth != null)
1166 return idwidth.intValue() + ID_WIDTH_PADDING;
1169 int w = getIdPanel().getWidth();
1170 return (w > 0 ? w : calculateIdWidth().width);
1174 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1175 * writes it to the specified file
1180 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1182 final int borderBottomOffset = 5;
1184 AlignmentDimension aDimension = getAlignmentDimension();
1185 // todo use a lambda function in place of callback here?
1186 ImageWriterI writer = new ImageWriterI()
1189 public void exportImage(Graphics graphics) throws Exception
1191 if (av.getWrapAlignment())
1193 printWrappedAlignment(aDimension.getWidth(),
1194 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1198 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1199 graphics, graphics);
1204 String fileTitle = alignFrame.getTitle();
1205 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1207 int imageWidth = aDimension.getWidth();
1208 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1209 String of = MessageManager.getString("label.alignment");
1210 exporter.doExport(file, this, imageWidth, imageHeight, of);
1214 * Calculates and returns a suitable width and height (in pixels) for an
1219 public AlignmentDimension getAlignmentDimension()
1221 int maxwidth = av.getAlignment().getVisibleWidth();
1223 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1224 + getScalePanel().getHeight();
1225 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1227 if (av.getWrapAlignment())
1229 height = getWrappedHeight();
1230 if (Jalview.isHeadlessMode())
1232 // need to obtain default alignment width and then add in any
1233 // additional allowance for id margin
1234 // this duplicates the calculation in getWrappedHeight but adjusts for
1236 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1237 - alignFrame.getInsets().left - alignFrame.getInsets().right
1238 - getVisibleIdWidth() + getVisibleIdWidth(false);
1242 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1246 else if (av.isShowAnnotation())
1248 height += getAnnotationPanel().adjustPanelHeight() + 3;
1250 return new AlignmentDimension(width, height);
1254 public void makePNGImageMap(File imgMapFile, String imageName)
1256 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1257 // ////////////////////////////////////////////
1258 int idWidth = getVisibleIdWidth(false);
1259 FontMetrics fm = getFontMetrics(av.getFont());
1260 int scaleHeight = av.getCharHeight() + fm.getDescent();
1263 // ////////////////////////////////
1264 if (imgMapFile != null)
1268 int sSize = av.getAlignment().getHeight();
1269 int alwidth = av.getAlignment().getWidth();
1270 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1271 out.println(HTMLOutput.getImageMapHTML());
1272 out.println("<img src=\"" + imageName
1273 + "\" border=\"0\" usemap=\"#Map\" >"
1274 + "<map name=\"Map\">");
1276 for (int s = 0; s < sSize; s++)
1278 int sy = s * av.getCharHeight() + scaleHeight;
1280 SequenceI seq = av.getAlignment().getSequenceAt(s);
1281 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1282 for (int column = 0; column < alwidth; column++)
1284 StringBuilder text = new StringBuilder(512);
1285 String triplet = null;
1286 if (av.getAlignment().isNucleotide())
1288 triplet = ResidueProperties.nucleotideName.get(seq
1289 .getCharAt(column) + "");
1293 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1297 if (triplet == null)
1302 int seqPos = seq.findPosition(column);
1303 int gSize = groups.length;
1304 for (int g = 0; g < gSize; g++)
1306 if (text.length() < 1)
1308 text.append("<area shape=\"rect\" coords=\"")
1309 .append((idWidth + column * av.getCharWidth()))
1310 .append(",").append(sy).append(",")
1311 .append((idWidth + (column + 1) * av.getCharWidth()))
1312 .append(",").append((av.getCharHeight() + sy))
1313 .append("\"").append(" onMouseOver=\"toolTip('")
1314 .append(seqPos).append(" ").append(triplet);
1317 if (groups[g].getStartRes() < column
1318 && groups[g].getEndRes() > column)
1320 text.append("<br><em>").append(groups[g].getName())
1325 if (text.length() < 1)
1327 text.append("<area shape=\"rect\" coords=\"")
1328 .append((idWidth + column * av.getCharWidth()))
1329 .append(",").append(sy).append(",")
1330 .append((idWidth + (column + 1) * av.getCharWidth()))
1331 .append(",").append((av.getCharHeight() + sy))
1332 .append("\"").append(" onMouseOver=\"toolTip('")
1333 .append(seqPos).append(" ").append(triplet);
1335 if (!Comparison.isGap(seq.getCharAt(column)))
1337 List<SequenceFeature> features = seq.findFeatures(column, column);
1338 for (SequenceFeature sf : features)
1340 if (sf.isContactFeature())
1342 text.append("<br>").append(sf.getType()).append(" ")
1343 .append(sf.getBegin()).append(":")
1344 .append(sf.getEnd());
1348 text.append("<br>");
1349 text.append(sf.getType());
1350 String description = sf.getDescription();
1351 if (description != null
1352 && !sf.getType().equals(description))
1354 description = description.replace("\"", """);
1355 text.append(" ").append(description);
1358 String status = sf.getStatus();
1359 if (status != null && !"".equals(status))
1361 text.append(" (").append(status).append(")");
1364 if (text.length() > 1)
1366 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1367 out.println(text.toString());
1372 out.println("</map></body></html>");
1375 } catch (Exception ex)
1377 ex.printStackTrace();
1379 } // /////////END OF IMAGE MAP
1384 * Answers the height of the entire alignment in pixels, assuming it is in
1389 int getWrappedHeight()
1391 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1393 if (System.getProperty("java.awt.headless") != null
1394 && System.getProperty("java.awt.headless").equals("true"))
1396 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1397 - vscroll.getPreferredSize().width
1398 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1401 int chunkWidth = getSeqPanel().seqCanvas
1402 .getWrappedCanvasWidth(seqPanelWidth);
1404 int hgap = av.getCharHeight();
1405 if (av.getScaleAboveWrapped())
1407 hgap += av.getCharHeight();
1410 int annotationHeight = 0;
1411 if (av.isShowAnnotation())
1413 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1414 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1417 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1420 int maxwidth = av.getAlignment().getWidth();
1421 if (av.hasHiddenColumns())
1423 maxwidth = av.getAlignment().getHiddenColumns()
1424 .absoluteToVisibleColumn(maxwidth) - 1;
1427 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1433 * close the panel - deregisters all listeners and nulls any references to
1436 public void closePanel()
1438 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1439 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1440 PaintRefresher.RemoveComponent(this);
1445 * try to ensure references are nulled
1447 if (annotationPanel != null)
1449 annotationPanel.dispose();
1450 annotationPanel = null;
1455 av.removePropertyChangeListener(propertyChangeListener);
1456 propertyChangeListener = null;
1457 StructureSelectionManager ssm = av.getStructureSelectionManager();
1458 ssm.removeStructureViewerListener(getSeqPanel(), null);
1459 ssm.removeSelectionListener(getSeqPanel());
1460 ssm.removeCommandListener(av);
1461 ssm.removeStructureViewerListener(getSeqPanel(), null);
1462 ssm.removeSelectionListener(getSeqPanel());
1468 if (Console.isDebugEnabled())
1470 Console.warn("Closing alignment panel which is already closed.");
1476 * Close any open dialogs that would be orphaned when this one is closed
1478 protected void closeChildFrames()
1480 if (overviewPanel != null)
1482 overviewPanel.dispose();
1483 overviewPanel = null;
1485 if (calculationDialog != null)
1487 calculationDialog.closeFrame();
1488 calculationDialog = null;
1493 * hides or shows dynamic annotation rows based on groups and av state flags
1495 public void updateAnnotation()
1497 updateAnnotation(false, false);
1500 public void updateAnnotation(boolean applyGlobalSettings)
1502 updateAnnotation(applyGlobalSettings, false);
1505 public void updateAnnotation(boolean applyGlobalSettings,
1506 boolean preserveNewGroupSettings)
1508 av.updateGroupAnnotationSettings(applyGlobalSettings,
1509 preserveNewGroupSettings);
1510 adjustAnnotationHeight();
1514 public AlignmentI getAlignment()
1516 return av == null ? null : av.getAlignment();
1520 public String getViewName()
1522 return av.getViewName();
1526 * Make/Unmake this alignment panel the current input focus
1530 public void setSelected(boolean b)
1534 if (alignFrame.getSplitViewContainer() != null)
1537 * bring enclosing SplitFrame to front first if there is one
1539 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1541 alignFrame.setSelected(b);
1542 } catch (Exception ex)
1547 setAlignFrameView();
1550 public void setAlignFrameView()
1552 alignFrame.setDisplayedView(this);
1556 public StructureSelectionManager getStructureSelectionManager()
1558 return av.getStructureSelectionManager();
1562 public void raiseOOMWarning(String string, OutOfMemoryError error)
1564 new OOMWarning(string, error, this);
1568 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1571 return new FeatureRenderer(this);
1575 public jalview.api.FeatureRenderer getFeatureRenderer()
1577 return seqPanel.seqCanvas.getFeatureRenderer();
1580 public void updateFeatureRenderer(
1581 jalview.renderer.seqfeatures.FeatureRenderer fr)
1583 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1586 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1588 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1590 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1594 public ScalePanel getScalePanel()
1599 public void setScalePanel(ScalePanel scalePanel)
1601 this.scalePanel = scalePanel;
1604 public SeqPanel getSeqPanel()
1609 public void setSeqPanel(SeqPanel seqPanel)
1611 this.seqPanel = seqPanel;
1614 public AnnotationPanel getAnnotationPanel()
1616 return annotationPanel;
1619 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1621 this.annotationPanel = annotationPanel;
1624 public AnnotationLabels getAlabels()
1629 public void setAlabels(AnnotationLabels alabels)
1631 this.alabels = alabels;
1634 public IdPanel getIdPanel()
1639 public void setIdPanel(IdPanel idPanel)
1641 this.idPanel = idPanel;
1645 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1646 * The aim is to keep the two alignments 'lined up' on their centre columns.
1649 * holds mapped region(s) of this alignment that we are scrolling
1650 * 'to'; may be modified for sequence offset by this method
1651 * @param verticalOffset
1652 * the number of visible sequences to show above the mapped region
1654 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1656 scrollToPosition(sr, verticalOffset, true);
1660 * Set a flag to say do not scroll any (cDNA/protein) complement.
1664 protected void setToScrollComplementPanel(boolean b)
1666 this.scrollComplementaryPanel = b;
1670 * Get whether to scroll complement panel
1672 * @return true if cDNA/protein complement panels should be scrolled
1674 protected boolean isSetToScrollComplementPanel()
1676 return this.scrollComplementaryPanel;
1682 * @adjustHeight if true, try to recalculate panel height for visible
1685 protected void refresh(boolean adjustHeight)
1687 validateAnnotationDimensions(adjustHeight);
1691 // sort, repaint, update overview
1692 paintAlignment(true, false);
1696 // lightweight repaint
1703 * Property change event fired when a change is made to the viewport ranges
1704 * object associated with this alignment panel's viewport
1706 public void propertyChange(PropertyChangeEvent evt)
1708 // update this panel's scroll values based on the new viewport ranges values
1709 ViewportRanges ranges = av.getRanges();
1710 int x = ranges.getStartRes();
1711 int y = ranges.getStartSeq();
1712 setScrollValues(x, y);
1714 // now update any complementary alignment (its viewport ranges object
1715 // is different so does not get automatically updated)
1716 if (isSetToScrollComplementPanel())
1718 setToScrollComplementPanel(false);
1719 av.scrollComplementaryAlignment();
1720 setToScrollComplementPanel(true);
1725 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1726 * reference should be nulled when the dialog is closed.
1728 * @param calculationChooser
1730 public void setCalculationDialog(CalculationChooser calculationChooser)
1732 calculationDialog = calculationChooser;
1736 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1739 public CalculationChooser getCalculationDialog()
1741 return calculationDialog;