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.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
66 import javax.swing.SwingUtilities;
72 * @version $Revision: 1.161 $
74 public class AlignmentPanel extends GAlignmentPanel implements
75 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
77 public AlignViewport av;
79 ViewportRanges vpRanges;
81 OverviewPanel overviewPanel;
83 private SeqPanel seqPanel;
85 private IdPanel idPanel;
87 private boolean headless;
89 IdwidthAdjuster idwidthAdjuster;
92 public AlignFrame alignFrame;
94 private ScalePanel scalePanel;
96 private AnnotationPanel annotationPanel;
98 private AnnotationLabels alabels;
100 // this value is set false when selection area being dragged
101 boolean fastPaint = true;
103 private int hextent = 0;
105 private int vextent = 0;
108 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
109 * false, suppresses invoking the same method recursively.
111 private boolean scrollComplementaryPanel = true;
113 private PropertyChangeListener propertyChangeListener;
115 private CalculationChooser calculationDialog;
118 * Creates a new AlignmentPanel object.
123 public AlignmentPanel(AlignFrame af, final AlignViewport av)
127 vpRanges = av.getRanges();
128 setSeqPanel(new SeqPanel(av, this));
129 setIdPanel(new IdPanel(av, this));
131 setScalePanel(new ScalePanel(av, this));
133 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
134 idwidthAdjuster = new IdwidthAdjuster(this);
135 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137 setAnnotationPanel(new AnnotationPanel(this));
138 setAlabels(new AnnotationLabels(this));
140 annotationScroller.setViewportView(getAnnotationPanel());
141 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
144 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146 setScrollValues(0, 0);
148 hscroll.addAdjustmentListener(this);
149 vscroll.addAdjustmentListener(this);
151 addComponentListener(new ComponentAdapter()
154 public void componentResized(ComponentEvent evt)
156 // reset the viewport ranges when the alignment panel is resized
157 // in particular, this initialises the end residue value when Jalview
159 if (av.getWrapAlignment())
161 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
162 getSeqPanel().seqCanvas.getWidth());
163 vpRanges.setViewportWidth(widthInRes);
167 int widthInRes = getSeqPanel().seqCanvas.getWidth()
169 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
170 / av.getCharHeight();
172 vpRanges.setViewportWidth(widthInRes);
173 vpRanges.setViewportHeight(heightInSeq);
179 final AlignmentPanel ap = this;
180 propertyChangeListener = new PropertyChangeListener()
183 public void propertyChange(PropertyChangeEvent evt)
185 if (evt.getPropertyName().equals("alignment"))
187 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
192 av.addPropertyChangeListener(propertyChangeListener);
194 av.getRanges().addPropertyChangeListener(this);
196 adjustAnnotationHeight();
201 public AlignViewportI getAlignViewport()
206 public void alignmentChanged()
208 av.alignmentChanged(this);
210 if (getCalculationDialog() != null)
212 getCalculationDialog().validateCalcTypes();
215 alignFrame.updateEditMenuBar();
217 paintAlignment(true);
224 public void fontChanged()
226 // set idCanvas bufferedImage to null
227 // to prevent drawing old image
228 FontMetrics fm = getFontMetrics(av.getFont());
230 scalePanelHolder.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idSpaceFillerPanel1.setPreferredSize(
233 new Dimension(10, av.getCharHeight() + fm.getDescent()));
234 idwidthAdjuster.invalidate();
235 scalePanelHolder.invalidate();
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
242 d.setSize(d.width + 4, d.height);
243 getIdPanel().getIdCanvas().setPreferredSize(d);
244 hscrollFillerPanel.setPreferredSize(d);
250 * Calculate the width of the alignment labels based on the displayed names
251 * and any bounds on label width set in preferences.
253 * @return Dimension giving the maximum width of the alignment label panel
254 * that should be used.
256 public Dimension calculateIdWidth()
258 // calculate sensible default width when no preference is available
260 if (av.getIdWidth() < 0)
262 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
263 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
264 r = calculateIdWidth(maxwidth);
265 av.setIdWidth(r.width);
270 r.width = av.getIdWidth();
277 * Calculate the width of the alignment labels based on the displayed names
278 * and any bounds on label width set in preferences.
281 * -1 or maximum width allowed for IdWidth
282 * @return Dimension giving the maximum width of the alignment label panel
283 * that should be used.
285 public Dimension calculateIdWidth(int maxwidth)
287 Container c = new Container();
289 FontMetrics fm = c.getFontMetrics(
290 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
292 AlignmentI al = av.getAlignment();
297 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
299 SequenceI s = al.getSequenceAt(i);
301 id = s.getDisplayId(av.getShowJVSuffix());
303 if (fm.stringWidth(id) > idWidth)
305 idWidth = fm.stringWidth(id);
311 // Also check annotation label widths
314 if (al.getAlignmentAnnotation() != null)
316 fm = c.getFontMetrics(getAlabels().getFont());
318 while (i < al.getAlignmentAnnotation().length)
320 String label = al.getAlignmentAnnotation()[i].label;
322 if (fm.stringWidth(label) > idWidth)
324 idWidth = fm.stringWidth(label);
331 return new Dimension(
332 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
336 * Highlight the given results on the alignment.
339 public void highlightSearchResults(SearchResultsI results)
341 boolean scrolled = scrollToPosition(results, 0, true, false);
343 boolean noFastPaint = scrolled && av.getWrapAlignment();
345 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
349 * Scroll the view to show the position of the highlighted region in results
352 * @param searchResults
353 * @param redrawOverview
356 public boolean scrollToPosition(SearchResultsI searchResults,
357 boolean redrawOverview)
359 return scrollToPosition(searchResults, 0, redrawOverview, false);
363 * Scrolls the view (if necessary) to show the position of the first
364 * highlighted region in results (if any). Answers true if the view was
365 * scrolled, or false if no matched region was found, or it is already
369 * @param verticalOffset
370 * if greater than zero, allows scrolling to a position below the
371 * first displayed sequence
372 * @param redrawOverview
373 * - when set, the overview will be recalculated (takes longer)
375 * if true, try to centre the search results horizontally in the view
378 protected boolean scrollToPosition(SearchResultsI results,
379 int verticalOffset, boolean redrawOverview, boolean centre)
381 int startv, endv, starts, ends;
383 if (results == null || results.isEmpty() || av == null
384 || av.getAlignment() == null)
388 int seqIndex = av.getAlignment().findIndex(results);
393 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
395 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
404 * To centre results, scroll to positions half the visible width
405 * left/right of the start/end positions
409 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
410 start = Math.max(start - offset, 0);
411 end = end + offset - 1;
417 if (end == seq.getEnd())
422 if (av.hasHiddenColumns())
424 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
425 start = hidden.findColumnPosition(start);
426 end = hidden.findColumnPosition(end);
429 if (!hidden.isVisible(r[0]))
431 // don't scroll - position isn't visible
438 * allow for offset of target sequence (actually scroll to one above it)
440 seqIndex = Math.max(0, seqIndex - verticalOffset);
441 boolean scrollNeeded = true;
443 if (!av.getWrapAlignment())
445 if ((startv = vpRanges.getStartRes()) >= start)
448 * Scroll left to make start of search results visible
450 setScrollValues(start, seqIndex);
452 else if ((endv = vpRanges.getEndRes()) <= end)
455 * Scroll right to make end of search results visible
457 setScrollValues(startv + end - endv, seqIndex);
459 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
462 * Scroll up to make start of search results visible
464 setScrollValues(vpRanges.getStartRes(), seqIndex);
466 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
469 * Scroll down to make end of search results visible
471 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
475 * Else results are already visible - no need to scroll
477 scrollNeeded = false;
481 scrollNeeded = vpRanges.scrollToWrappedVisible(start);
484 paintAlignment(redrawOverview);
492 * @return DOCUMENT ME!
494 public OverviewPanel getOverviewPanel()
496 return overviewPanel;
505 public void setOverviewPanel(OverviewPanel op)
513 * Hide or show annotation panel
516 public void setAnnotationVisible(boolean b)
518 if (!av.getWrapAlignment())
520 annotationSpaceFillerHolder.setVisible(b);
521 annotationScroller.setVisible(b);
527 * automatically adjust annotation panel height for new annotation whilst
528 * ensuring the alignment is still visible.
531 public void adjustAnnotationHeight()
533 // TODO: display vertical annotation scrollbar if necessary
534 // this is called after loading new annotation onto alignment
535 if (alignFrame.getHeight() == 0)
537 System.out.println("NEEDS FIXING");
539 validateAnnotationDimensions(true);
541 paintAlignment(true);
545 * calculate the annotation dimensions and refresh slider values accordingly.
546 * need to do repaints/notifys afterwards.
548 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
550 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
552 if (adjustPanelHeight)
554 int rowHeight = av.getCharHeight();
555 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
558 * Estimate available height in the AlignFrame for alignment +
559 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
560 * hscroll, status bar (as these are not laid out we can't inspect their
561 * actual heights). Insets gives frame borders.
563 int stuff = Platform.isAMac() ? 80 : 100;
564 Insets insets = alignFrame.getInsets();
565 int availableHeight = alignFrame.getHeight() - stuff - insets.top
569 * If not enough vertical space, maximize annotation height while keeping
570 * at least two rows of alignment visible
572 if (annotationHeight + alignmentHeight > availableHeight)
574 annotationHeight = Math.min(annotationHeight,
575 availableHeight - 2 * rowHeight);
580 // maintain same window layout whilst updating sliders
581 annotationHeight = annotationScroller.getSize().height;
585 annotationScroller.setPreferredSize(
586 new Dimension(annotationScroller.getWidth(), annotationHeight));
588 Dimension e = idPanel.getSize();
589 alabels.setSize(new Dimension(e.width, annotationHeight));
591 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
592 annotationSpaceFillerHolder.getWidth(), annotationHeight));
593 annotationScroller.validate();
594 annotationScroller.addNotify();
598 * update alignment layout for viewport settings
603 public void updateLayout()
606 setAnnotationVisible(av.isShowAnnotation());
607 boolean wrap = av.getWrapAlignment();
608 vpRanges.setStartSeq(0);
609 scalePanelHolder.setVisible(!wrap);
610 hscroll.setVisible(!wrap);
611 idwidthAdjuster.setVisible(!wrap);
615 annotationScroller.setVisible(false);
616 annotationSpaceFillerHolder.setVisible(false);
618 else if (av.isShowAnnotation())
620 annotationScroller.setVisible(true);
621 annotationSpaceFillerHolder.setVisible(true);
624 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
626 { // may not yet be laid out
629 int widthInRes = getSeqPanel().seqCanvas
630 .getWrappedCanvasWidth(canvasWidth);
631 vpRanges.setViewportWidth(widthInRes);
635 int widthInRes = (canvasWidth / av.getCharWidth()) - 1;
636 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
637 / av.getCharHeight()) - 1;
639 vpRanges.setViewportWidth(widthInRes);
640 vpRanges.setViewportHeight(heightInSeq);
644 idSpaceFillerPanel1.setVisible(!wrap);
650 * Adjust row/column scrollers to show a visible position in the alignment.
653 * visible column to scroll to
655 * visible row to scroll to
658 public void setScrollValues(int xpos, int ypos)
663 if (av == null || av.getAlignment() == null)
668 if (av.getWrapAlignment())
670 setScrollingForWrappedPanel(x);
674 int width = av.getAlignment().getWidth();
675 int height = av.getAlignment().getHeight();
677 if (av.hasHiddenColumns())
679 // reset the width to exclude hidden columns
680 width = av.getAlignment().getHiddenColumns()
681 .findColumnPosition(width);
684 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
685 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
692 if (vextent > height)
697 if ((hextent + x) > width)
702 if ((vextent + y) > height)
704 y = height - vextent;
717 // update the scroll values
718 hscroll.setValues(x, hextent, 0, width);
719 vscroll.setValues(y, vextent, 0, height);
724 * Respond to adjustment event when horizontal or vertical scrollbar is
728 * adjustment event encoding whether hscroll or vscroll changed
731 public void adjustmentValueChanged(AdjustmentEvent evt)
733 if (av.getWrapAlignment())
735 adjustScrollingWrapped(evt);
739 if (evt.getSource() == hscroll)
741 int oldX = vpRanges.getStartRes();
742 int oldwidth = vpRanges.getViewportWidth();
743 int x = hscroll.getValue();
744 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
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 ((x == oldX) && (width == oldwidth))
753 vpRanges.setViewportStartAndWidth(x, width);
755 else if (evt.getSource() == vscroll)
757 int oldY = vpRanges.getStartSeq();
758 int oldheight = vpRanges.getViewportHeight();
759 int y = vscroll.getValue();
760 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
762 // if we're scrolling to the position we're already at, stop
763 // this prevents infinite recursion of events when the scroll/viewport
764 // ranges values are the same
765 if ((y == oldY) && (height == oldheight))
769 vpRanges.setViewportStartAndHeight(y, height);
778 * Responds to a scroll change by setting the start position of the viewport.
783 protected void adjustScrollingWrapped(AdjustmentEvent evt)
785 if (evt.getSource() == hscroll)
787 return; // no horizontal scroll when wrapped
789 if (evt.getSource() == vscroll)
791 int newY = vscroll.getValue();
794 * if we're scrolling to the position we're already at, stop
795 * this prevents infinite recursion of events when the scroll/viewport
796 * ranges values are the same
798 int oldX = vpRanges.getStartRes();
799 int oldY = vpRanges.getWrappedScrollPosition(oldX);
807 * limit page up/down to one width's worth of positions
809 int rowSize = vpRanges.getViewportWidth();
810 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
811 vpRanges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
816 // This is only called if file loaded is a jar file that
817 // was wrapped when saved and user has wrap alignment true
818 // as preference setting
819 SwingUtilities.invokeLater(new Runnable()
824 // When updating scrolling to use ViewportChange events, this code
825 // could not be validated and it is not clear if it is now being
826 // called. Log warning here in case it is called and unforeseen
829 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
831 // scroll to start of panel
832 vpRanges.setStartRes(0);
833 vpRanges.setStartSeq(0);
841 * Repaint the alignment including the annotations and overview panels (if
845 public void paintAlignment(boolean updateOverview)
847 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
848 av.isShowAutocalculatedAbove());
849 sorter.sort(getAlignment().getAlignmentAnnotation(),
850 av.getSortAnnotationsBy());
855 // TODO: determine if this paintAlignment changed structure colours
856 av.getStructureSelectionManager().sequenceColoursChanged(this);
858 if (overviewPanel != null)
860 overviewPanel.updateOverviewImage();
872 public void paintComponent(Graphics g)
876 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
877 idPanelHolder.setPreferredSize(d);
878 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
882 * set scroll bar positions
884 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
888 * Set vertical scroll bar position, and number of increments, for wrapped
891 * @param topLeftColumn
892 * the column position at top left (0..)
894 private void setScrollingForWrappedPanel(int topLeftColumn)
896 int scrollPosition = vpRanges.getWrappedScrollPosition(topLeftColumn);
897 int maxScroll = vpRanges.getWrappedMaxScroll(topLeftColumn);
900 * a scrollbar's value can be set to at most (maximum-extent)
901 * so we add extent (1) to the maxScroll value
903 vscroll.setUnitIncrement(1);
904 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
917 * @return DOCUMENT ME!
919 * @throws PrinterException
923 public int print(Graphics pg, PageFormat pf, int pi)
924 throws PrinterException
926 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
928 int pwidth = (int) pf.getImageableWidth();
929 int pheight = (int) pf.getImageableHeight();
931 if (av.getWrapAlignment())
933 return printWrappedAlignment(pwidth, pheight, pi, pg);
937 return printUnwrapped(pwidth, pheight, pi, pg, pg);
953 * @return DOCUMENT ME!
955 * @throws PrinterException
959 * Draws the alignment image, including sequence ids, sequences, and
960 * annotation labels and annotations if shown, on either one or two Graphics
967 * the graphics context for sequence ids and annotation labels
968 * @param alignmentGraphics
969 * the graphics context for sequences and annotations (may or may not
970 * be the same context as idGraphics)
972 * @throws PrinterException
974 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
975 Graphics idGraphics, Graphics alignmentGraphics)
976 throws PrinterException
978 final int idWidth = getVisibleIdWidth(false);
981 * Get the horizontal offset to where we draw the sequences.
982 * This is idWidth if using a single Graphics context, else zero.
984 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
987 FontMetrics fm = getFontMetrics(av.getFont());
988 int charHeight = av.getCharHeight();
989 int scaleHeight = charHeight + fm.getDescent();
991 idGraphics.setColor(Color.white);
992 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
993 idGraphics.setFont(av.getFont());
996 * How many sequences and residues can we fit on a printable page?
998 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1000 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1002 int alignmentWidth = av.getAlignment().getWidth();
1003 int pagesWide = (alignmentWidth / totalRes) + 1;
1005 final int startRes = (pi % pagesWide) * totalRes;
1006 int endRes = (startRes + totalRes) - 1;
1008 if (endRes > (alignmentWidth - 1))
1010 endRes = alignmentWidth - 1;
1013 final int startSeq = (pi / pagesWide) * totalSeq;
1014 int endSeq = startSeq + totalSeq;
1016 int alignmentHeight = av.getAlignment().getHeight();
1017 if (endSeq > alignmentHeight)
1019 endSeq = alignmentHeight;
1022 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1024 if (av.isShowAnnotation())
1026 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1029 pagesHigh /= pageHeight;
1031 if (pi >= (pagesWide * pagesHigh))
1033 return Printable.NO_SUCH_PAGE;
1035 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1038 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1040 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1041 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1042 pageWidth - idWidth, scaleHeight);
1043 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1046 * Draw the sequence ids, offset for scale height,
1047 * then reset to top left (0, 0)
1049 idGraphics.translate(0, scaleHeight);
1050 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1051 Color currentColor = null;
1052 Color currentTextColor = null;
1055 for (int i = startSeq; i < endSeq; i++)
1057 seq = av.getAlignment().getSequenceAt(i);
1058 if ((av.getSelectionGroup() != null)
1059 && av.getSelectionGroup().getSequences(null).contains(seq))
1062 * gray out ids of sequences in selection group (if any)
1064 currentColor = Color.gray;
1065 currentTextColor = Color.black;
1069 currentColor = av.getSequenceColour(seq);
1070 currentTextColor = Color.black;
1073 idGraphics.setColor(currentColor);
1074 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1077 idGraphics.setColor(currentTextColor);
1080 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1081 if (av.isRightAlignIds())
1083 fm = idGraphics.getFontMetrics();
1084 xPos = idWidth - fm.stringWidth(displayId) - 4;
1087 idGraphics.drawString(displayId, xPos,
1088 (((i - startSeq) * charHeight) + charHeight)
1089 - (charHeight / 5));
1091 idGraphics.setFont(av.getFont());
1092 idGraphics.translate(0, -scaleHeight);
1095 * draw the sequences, offset for scale height, and id width (if using a
1096 * single graphics context), then reset to (0, scale height)
1098 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1099 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1100 endRes, startSeq, endSeq);
1101 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1103 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1106 * draw annotation labels; drawComponent() translates by
1107 * getScrollOffset(), so compensate for that first;
1108 * then reset to (0, scale height)
1110 int offset = getAlabels().getScrollOffset();
1111 idGraphics.translate(0, -offset);
1112 idGraphics.translate(0, alignmentDrawnHeight);
1113 getAlabels().drawComponent(idGraphics, idWidth);
1114 idGraphics.translate(0, -alignmentDrawnHeight);
1117 * draw the annotations starting at
1118 * (idOffset, alignmentHeight) from (0, scaleHeight)
1120 alignmentGraphics.translate(alignmentGraphicsOffset,
1121 alignmentDrawnHeight);
1122 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1123 alignmentGraphics, -1, startRes, endRes + 1);
1126 return Printable.PAGE_EXISTS;
1141 * @return DOCUMENT ME!
1143 * @throws PrinterException
1146 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1147 Graphics pg) throws PrinterException
1149 int annotationHeight = 0;
1150 AnnotationLabels labels = null;
1151 if (av.isShowAnnotation())
1153 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1154 labels = new AnnotationLabels(av);
1157 int hgap = av.getCharHeight();
1158 if (av.getScaleAboveWrapped())
1160 hgap += av.getCharHeight();
1163 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1166 int idWidth = getVisibleIdWidth(false);
1168 int maxwidth = av.getAlignment().getWidth();
1169 if (av.hasHiddenColumns())
1171 maxwidth = av.getAlignment().getHiddenColumns()
1172 .findColumnPosition(maxwidth) - 1;
1175 int resWidth = getSeqPanel().seqCanvas
1176 .getWrappedCanvasWidth(pwidth - idWidth);
1178 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1180 pg.setColor(Color.white);
1181 pg.fillRect(0, 0, pwidth, pheight);
1182 pg.setFont(av.getFont());
1186 pg.setColor(Color.black);
1188 pg.translate(0, -pi * pheight);
1190 pg.setClip(0, pi * pheight, pwidth, pheight);
1196 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1198 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1199 SequenceI s = av.getAlignment().getSequenceAt(i);
1200 String string = s.getDisplayId(av.getShowJVSuffix());
1202 if (av.isRightAlignIds())
1204 FontMetrics fm = pg.getFontMetrics();
1205 xPos = idWidth - fm.stringWidth(string) - 4;
1207 pg.drawString(string, xPos,
1208 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1209 - (av.getCharHeight() / 5));
1213 pg.translate(-3, ypos
1214 + (av.getAlignment().getHeight() * av.getCharHeight()));
1216 pg.setFont(av.getFont());
1217 labels.drawComponent(pg, idWidth);
1218 pg.translate(+3, -ypos
1219 - (av.getAlignment().getHeight() * av.getCharHeight()));
1223 } while (ypos < totalHeight);
1225 pg.translate(idWidth, 0);
1227 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1230 if ((pi * pheight) < totalHeight)
1232 return Printable.PAGE_EXISTS;
1237 return Printable.NO_SUCH_PAGE;
1242 * get current sequence ID panel width, or nominal value if panel were to be
1243 * displayed using default settings
1247 public int getVisibleIdWidth()
1249 return getVisibleIdWidth(true);
1253 * get current sequence ID panel width, or nominal value if panel were to be
1254 * displayed using default settings
1257 * indicate if the Id width for onscreen or offscreen display should
1261 public int getVisibleIdWidth(boolean onscreen)
1263 // see if rendering offscreen - check preferences and calc width accordingly
1264 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1266 return calculateIdWidth(-1).width + 4;
1268 Integer idwidth = null;
1269 if (onscreen || (idwidth = Cache
1270 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1272 int w = getIdPanel().getWidth();
1273 return (w > 0 ? w : calculateIdWidth().width + 4);
1275 return idwidth.intValue() + 4;
1278 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1280 int boarderBottomOffset = 5;
1281 long pSessionId = System.currentTimeMillis();
1282 headless = (System.getProperty("java.awt.headless") != null
1283 && System.getProperty("java.awt.headless").equals("true"));
1284 if (alignFrame != null && !headless)
1288 alignFrame.setProgressBar(MessageManager
1289 .formatMessage("status.saving_file", new Object[]
1290 { type.getLabel() }), pSessionId);
1295 AlignmentDimension aDimension = getAlignmentDimension();
1298 jalview.util.ImageMaker im;
1299 final String imageAction, imageTitle;
1300 if (type == jalview.util.ImageMaker.TYPE.PNG)
1302 imageAction = "Create PNG image from alignment";
1305 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1307 imageAction = "Create EPS file from alignment";
1308 imageTitle = alignFrame.getTitle();
1312 imageAction = "Create SVG file from alignment";
1313 imageTitle = alignFrame.getTitle();
1316 im = new jalview.util.ImageMaker(this, type, imageAction,
1317 aDimension.getWidth(),
1318 aDimension.getHeight() + boarderBottomOffset, file,
1319 imageTitle, alignFrame, pSessionId, headless);
1320 Graphics graphics = im.getGraphics();
1321 if (av.getWrapAlignment())
1323 if (graphics != null)
1325 printWrappedAlignment(aDimension.getWidth(),
1326 aDimension.getHeight() + boarderBottomOffset, 0,
1333 if (graphics != null)
1335 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1336 graphics, graphics);
1341 } catch (OutOfMemoryError err)
1344 System.out.println("########################\n" + "OUT OF MEMORY "
1345 + file + "\n" + "########################");
1346 new OOMWarning("Creating Image for " + file, err);
1347 // System.out.println("Create IMAGE: " + err);
1348 } catch (Exception ex)
1350 ex.printStackTrace();
1358 public AlignmentDimension getAlignmentDimension()
1360 int maxwidth = av.getAlignment().getWidth();
1361 if (av.hasHiddenColumns())
1363 maxwidth = av.getAlignment().getHiddenColumns()
1364 .findColumnPosition(maxwidth);
1367 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1368 + getScalePanel().getHeight();
1369 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1371 if (av.getWrapAlignment())
1373 height = getWrappedHeight();
1376 // need to obtain default alignment width and then add in any
1377 // additional allowance for id margin
1378 // this duplicates the calculation in getWrappedHeight but adjusts for
1380 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1381 - alignFrame.getInsets().left - alignFrame.getInsets().right
1382 - getVisibleIdWidth() + getVisibleIdWidth(false);
1386 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1390 else if (av.isShowAnnotation())
1392 height += getAnnotationPanel().adjustPanelHeight() + 3;
1394 return new AlignmentDimension(width, height);
1401 public void makeEPS(File epsFile)
1403 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1409 public void makePNG(File pngFile)
1411 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1414 public void makeSVG(File svgFile)
1416 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1419 public void makePNGImageMap(File imgMapFile, String imageName)
1421 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1422 // ////////////////////////////////////////////
1423 int idWidth = getVisibleIdWidth(false);
1424 FontMetrics fm = getFontMetrics(av.getFont());
1425 int scaleHeight = av.getCharHeight() + fm.getDescent();
1428 // ////////////////////////////////
1429 if (imgMapFile != null)
1433 int sSize = av.getAlignment().getHeight();
1434 int alwidth = av.getAlignment().getWidth();
1435 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1436 out.println(HTMLOutput.getImageMapHTML());
1437 out.println("<img src=\"" + imageName
1438 + "\" border=\"0\" usemap=\"#Map\" >"
1439 + "<map name=\"Map\">");
1441 for (int s = 0; s < sSize; s++)
1443 int sy = s * av.getCharHeight() + scaleHeight;
1445 SequenceI seq = av.getAlignment().getSequenceAt(s);
1446 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1447 for (int column = 0; column < alwidth; column++)
1449 StringBuilder text = new StringBuilder(512);
1450 String triplet = null;
1451 if (av.getAlignment().isNucleotide())
1453 triplet = ResidueProperties.nucleotideName.get(seq
1454 .getCharAt(column) + "");
1458 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1462 if (triplet == null)
1467 int seqPos = seq.findPosition(column);
1468 int gSize = groups.length;
1469 for (int g = 0; g < gSize; g++)
1471 if (text.length() < 1)
1473 text.append("<area shape=\"rect\" coords=\"")
1474 .append((idWidth + column * av.getCharWidth()))
1475 .append(",").append(sy).append(",")
1476 .append((idWidth + (column + 1) * av.getCharWidth()))
1477 .append(",").append((av.getCharHeight() + sy))
1478 .append("\"").append(" onMouseOver=\"toolTip('")
1479 .append(seqPos).append(" ").append(triplet);
1482 if (groups[g].getStartRes() < column
1483 && groups[g].getEndRes() > column)
1485 text.append("<br><em>").append(groups[g].getName())
1490 if (text.length() < 1)
1492 text.append("<area shape=\"rect\" coords=\"")
1493 .append((idWidth + column * av.getCharWidth()))
1494 .append(",").append(sy).append(",")
1495 .append((idWidth + (column + 1) * av.getCharWidth()))
1496 .append(",").append((av.getCharHeight() + sy))
1497 .append("\"").append(" onMouseOver=\"toolTip('")
1498 .append(seqPos).append(" ").append(triplet);
1500 if (!Comparison.isGap(seq.getCharAt(column)))
1502 List<SequenceFeature> features = seq.findFeatures(column, column);
1503 for (SequenceFeature sf : features)
1505 if (sf.isContactFeature())
1507 text.append("<br>").append(sf.getType()).append(" ")
1508 .append(sf.getBegin()).append(":")
1509 .append(sf.getEnd());
1513 text.append("<br>");
1514 text.append(sf.getType());
1515 String description = sf.getDescription();
1516 if (description != null
1517 && !sf.getType().equals(description))
1519 description = description.replace("\"", """);
1520 text.append(" ").append(description);
1523 String status = sf.getStatus();
1524 if (status != null && !"".equals(status))
1526 text.append(" (").append(status).append(")");
1529 if (text.length() > 1)
1531 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1532 out.println(text.toString());
1537 out.println("</map></body></html>");
1540 } catch (Exception ex)
1542 ex.printStackTrace();
1544 } // /////////END OF IMAGE MAP
1548 int getWrappedHeight()
1550 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1552 if (System.getProperty("java.awt.headless") != null
1553 && System.getProperty("java.awt.headless").equals("true"))
1555 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1556 - vscroll.getPreferredSize().width
1557 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1560 int chunkWidth = getSeqPanel().seqCanvas
1561 .getWrappedCanvasWidth(seqPanelWidth);
1563 int hgap = av.getCharHeight();
1564 if (av.getScaleAboveWrapped())
1566 hgap += av.getCharHeight();
1569 int annotationHeight = 0;
1570 if (av.isShowAnnotation())
1572 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1575 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1578 int maxwidth = av.getAlignment().getWidth();
1579 if (av.hasHiddenColumns())
1581 maxwidth = av.getAlignment().getHiddenColumns()
1582 .findColumnPosition(maxwidth) - 1;
1585 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1591 * close the panel - deregisters all listeners and nulls any references to
1594 public void closePanel()
1596 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1597 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1598 PaintRefresher.RemoveComponent(this);
1603 * try to ensure references are nulled
1605 if (annotationPanel != null)
1607 annotationPanel.dispose();
1612 av.removePropertyChangeListener(propertyChangeListener);
1613 jalview.structure.StructureSelectionManager ssm = av
1614 .getStructureSelectionManager();
1615 ssm.removeStructureViewerListener(getSeqPanel(), null);
1616 ssm.removeSelectionListener(getSeqPanel());
1617 ssm.removeCommandListener(av);
1618 ssm.removeStructureViewerListener(getSeqPanel(), null);
1619 ssm.removeSelectionListener(getSeqPanel());
1625 if (Cache.log.isDebugEnabled())
1627 Cache.log.warn("Closing alignment panel which is already closed.");
1633 * Close any open dialogs that would be orphaned when this one is closed
1635 protected void closeChildFrames()
1637 if (calculationDialog != null)
1639 calculationDialog.closeFrame();
1644 * hides or shows dynamic annotation rows based on groups and av state flags
1646 public void updateAnnotation()
1648 updateAnnotation(false, false);
1651 public void updateAnnotation(boolean applyGlobalSettings)
1653 updateAnnotation(applyGlobalSettings, false);
1656 public void updateAnnotation(boolean applyGlobalSettings,
1657 boolean preserveNewGroupSettings)
1659 av.updateGroupAnnotationSettings(applyGlobalSettings,
1660 preserveNewGroupSettings);
1661 adjustAnnotationHeight();
1665 public AlignmentI getAlignment()
1667 return av == null ? null : av.getAlignment();
1671 public String getViewName()
1677 * Make/Unmake this alignment panel the current input focus
1681 public void setSelected(boolean b)
1685 if (alignFrame.getSplitViewContainer() != null)
1688 * bring enclosing SplitFrame to front first if there is one
1690 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1692 alignFrame.setSelected(b);
1693 } catch (Exception ex)
1699 alignFrame.setDisplayedView(this);
1704 public StructureSelectionManager getStructureSelectionManager()
1706 return av.getStructureSelectionManager();
1710 public void raiseOOMWarning(String string, OutOfMemoryError error)
1712 new OOMWarning(string, error, this);
1716 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1719 return new FeatureRenderer(this);
1723 public jalview.api.FeatureRenderer getFeatureRenderer()
1725 return seqPanel.seqCanvas.getFeatureRenderer();
1728 public void updateFeatureRenderer(
1729 jalview.renderer.seqfeatures.FeatureRenderer fr)
1731 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1734 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1736 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1738 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1742 public ScalePanel getScalePanel()
1747 public void setScalePanel(ScalePanel scalePanel)
1749 this.scalePanel = scalePanel;
1752 public SeqPanel getSeqPanel()
1757 public void setSeqPanel(SeqPanel seqPanel)
1759 this.seqPanel = seqPanel;
1762 public AnnotationPanel getAnnotationPanel()
1764 return annotationPanel;
1767 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1769 this.annotationPanel = annotationPanel;
1772 public AnnotationLabels getAlabels()
1777 public void setAlabels(AnnotationLabels alabels)
1779 this.alabels = alabels;
1782 public IdPanel getIdPanel()
1787 public void setIdPanel(IdPanel idPanel)
1789 this.idPanel = idPanel;
1793 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1794 * The aim is to keep the two alignments 'lined up' on their centre columns.
1797 * holds mapped region(s) of this alignment that we are scrolling
1798 * 'to'; may be modified for sequence offset by this method
1799 * @param verticalOffset
1800 * the number of visible sequences to show above the mapped region
1802 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1805 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1806 * mapped), we can make the scroll-to location a sequence above the one
1809 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1810 List<SequenceI> seqs = av.getAlignment().getSequences();
1813 * This is like AlignmentI.findIndex(seq) but here we are matching the
1814 * dataset sequence not the aligned sequence
1816 boolean matched = false;
1817 for (SequenceI seq : seqs)
1819 if (mappedTo == seq.getDatasetSequence())
1827 return; // failsafe, shouldn't happen
1831 * Scroll to position but centring the target residue.
1833 scrollToPosition(sr, verticalOffset, true, true);
1837 * Set a flag to say do not scroll any (cDNA/protein) complement.
1841 protected void setToScrollComplementPanel(boolean b)
1843 this.scrollComplementaryPanel = b;
1847 * Get whether to scroll complement panel
1849 * @return true if cDNA/protein complement panels should be scrolled
1851 protected boolean isSetToScrollComplementPanel()
1853 return this.scrollComplementaryPanel;
1859 * @adjustHeight if true, try to recalculate panel height for visible
1862 protected void refresh(boolean adjustHeight)
1864 validateAnnotationDimensions(adjustHeight);
1868 // sort, repaint, update overview
1869 paintAlignment(true);
1873 // lightweight repaint
1880 * Property change event fired when a change is made to the viewport ranges
1881 * object associated with this alignment panel's viewport
1883 public void propertyChange(PropertyChangeEvent evt)
1885 // update this panel's scroll values based on the new viewport ranges values
1886 int x = vpRanges.getStartRes();
1887 int y = vpRanges.getStartSeq();
1888 setScrollValues(x, y);
1890 // now update any complementary alignment (its viewport ranges object
1891 // is different so does not get automatically updated)
1892 if (isSetToScrollComplementPanel())
1894 setToScrollComplementPanel(false);
1895 av.scrollComplementaryAlignment();
1896 setToScrollComplementPanel(true);
1901 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1902 * reference should be nulled when the dialog is closed.
1904 * @param calculationChooser
1906 public void setCalculationDialog(CalculationChooser calculationChooser)
1908 calculationDialog = calculationChooser;
1912 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1915 public CalculationChooser getCalculationDialog()
1917 return calculationDialog;