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,
78 public AlignViewport av;
80 ViewportRanges vpRanges;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 private boolean headless;
90 IdwidthAdjuster idwidthAdjuster;
93 public AlignFrame alignFrame;
95 private ScalePanel scalePanel;
97 private AnnotationPanel annotationPanel;
99 private AnnotationLabels alabels;
101 // this value is set false when selection area being dragged
102 boolean fastPaint = true;
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)
128 vpRanges = av.getRanges();
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 if (av.getWrapAlignment())
162 int widthInRes = getSeqPanel().seqCanvas
163 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164 vpRanges.setViewportWidth(widthInRes);
168 int widthInRes = getSeqPanel().seqCanvas.getWidth()
170 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171 / av.getCharHeight();
173 vpRanges.setViewportWidth(widthInRes);
174 vpRanges.setViewportHeight(heightInSeq);
180 final AlignmentPanel ap = this;
181 propertyChangeListener = new PropertyChangeListener()
184 public void propertyChange(PropertyChangeEvent evt)
186 if (evt.getPropertyName().equals("alignment"))
188 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
193 av.addPropertyChangeListener(propertyChangeListener);
195 av.getRanges().addPropertyChangeListener(this);
197 adjustAnnotationHeight();
202 public AlignViewportI getAlignViewport()
207 public void alignmentChanged()
209 av.alignmentChanged(this);
211 if (getCalculationDialog() != null)
213 getCalculationDialog().validateCalcTypes();
216 alignFrame.updateEditMenuBar();
218 paintAlignment(true);
225 public void fontChanged()
227 // set idCanvas bufferedImage to null
228 // to prevent drawing old image
229 FontMetrics fm = getFontMetrics(av.getFont());
231 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
233 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
234 .getCharHeight() + fm.getDescent()));
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);
246 if (this.alignFrame.getSplitViewContainer() != null)
248 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
255 * Calculate the width of the alignment labels based on the displayed names
256 * and any bounds on label width set in preferences.
258 * @return Dimension giving the maximum width of the alignment label panel
259 * that should be used.
261 public Dimension calculateIdWidth()
263 // calculate sensible default width when no preference is available
265 if (av.getIdWidth() < 0)
267 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
268 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
269 r = calculateIdWidth(maxwidth);
270 av.setIdWidth(r.width);
275 r.width = av.getIdWidth();
282 * Calculate the width of the alignment labels based on the displayed names
283 * and any bounds on label width set in preferences.
286 * -1 or maximum width allowed for IdWidth
287 * @return Dimension giving the maximum width of the alignment label panel
288 * that should be used.
290 public Dimension calculateIdWidth(int maxwidth)
292 Container c = new Container();
294 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
295 Font.ITALIC, av.font.getSize()));
297 AlignmentI al = av.getAlignment();
302 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
304 SequenceI s = al.getSequenceAt(i);
306 id = s.getDisplayId(av.getShowJVSuffix());
308 if (fm.stringWidth(id) > idWidth)
310 idWidth = fm.stringWidth(id);
316 // Also check annotation label widths
319 if (al.getAlignmentAnnotation() != null)
321 fm = c.getFontMetrics(getAlabels().getFont());
323 while (i < al.getAlignmentAnnotation().length)
325 String label = al.getAlignmentAnnotation()[i].label;
327 if (fm.stringWidth(label) > idWidth)
329 idWidth = fm.stringWidth(label);
336 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
341 * Highlight the given results on the alignment.
344 public void highlightSearchResults(SearchResultsI results)
346 scrollToPosition(results);
347 getSeqPanel().seqCanvas.highlightSearchResults(results);
351 * Scroll the view to show the position of the highlighted region in results
352 * (if any) and redraw the overview
356 public boolean scrollToPosition(SearchResultsI results)
358 return scrollToPosition(results, 0, true, false);
362 * Scroll the view to show the position of the highlighted region in results
365 * @param searchResults
366 * @param redrawOverview
369 public boolean scrollToPosition(SearchResultsI searchResults,
370 boolean redrawOverview)
372 return scrollToPosition(searchResults, 0, redrawOverview, false);
376 * Scroll the view to show the position of the highlighted region in results
380 * @param verticalOffset
381 * if greater than zero, allows scrolling to a position below the
382 * first displayed sequence
383 * @param redrawOverview
384 * - when set, the overview will be recalculated (takes longer)
386 * if true, try to centre the search results horizontally in the view
387 * @return false if results were not found
389 public boolean scrollToPosition(SearchResultsI results,
390 int verticalOffset, boolean redrawOverview, boolean centre)
392 int startv, endv, starts, ends;
393 // TODO: properly locate search results in view when large numbers of hidden
394 // columns exist before highlighted region
395 // do we need to scroll the panel?
396 // TODO: tons of nullpointerexceptions raised here.
397 if (results != null && results.getSize() > 0 && av != null
398 && av.getAlignment() != null)
400 int seqIndex = av.getAlignment().findIndex(results);
405 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
407 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
416 * To centre results, scroll to positions half the visible width
417 * left/right of the start/end positions
421 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2
423 start = Math.max(start - offset, 0);
424 end = end + offset - 1;
430 if (end == seq.getEnd())
434 if (av.hasHiddenColumns())
436 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
437 start = hidden.findColumnPosition(start);
438 end = hidden.findColumnPosition(end);
441 if (!hidden.isVisible(r[0]))
443 // don't scroll - position isn't visible
450 * allow for offset of target sequence (actually scroll to one above it)
452 seqIndex = Math.max(0, seqIndex - verticalOffset);
454 if (!av.getWrapAlignment())
456 if ((startv = vpRanges.getStartRes()) >= start)
459 * Scroll left to make start of search results visible
461 setScrollValues(start, seqIndex);
463 else if ((endv = vpRanges.getEndRes()) <= end)
466 * Scroll right to make end of search results visible
468 setScrollValues(startv + end - endv, seqIndex);
470 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
473 * Scroll up to make start of search results visible
475 setScrollValues(vpRanges.getStartRes(), seqIndex);
477 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
480 * Scroll down to make end of search results visible
482 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
486 * Else results are already visible - no need to scroll
491 vpRanges.scrollToWrappedVisible(start);
495 paintAlignment(redrawOverview);
502 * @return DOCUMENT ME!
504 public OverviewPanel getOverviewPanel()
506 return overviewPanel;
515 public void setOverviewPanel(OverviewPanel op)
523 * Hide or show annotation panel
526 public void setAnnotationVisible(boolean b)
528 if (!av.getWrapAlignment())
530 annotationSpaceFillerHolder.setVisible(b);
531 annotationScroller.setVisible(b);
537 * automatically adjust annotation panel height for new annotation whilst
538 * ensuring the alignment is still visible.
541 public void adjustAnnotationHeight()
543 // TODO: display vertical annotation scrollbar if necessary
544 // this is called after loading new annotation onto alignment
545 if (alignFrame.getHeight() == 0)
547 System.out.println("NEEDS FIXING");
549 validateAnnotationDimensions(true);
551 paintAlignment(true);
555 * calculate the annotation dimensions and refresh slider values accordingly.
556 * need to do repaints/notifys afterwards.
558 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
560 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
562 if (adjustPanelHeight)
564 int rowHeight = av.getCharHeight();
565 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
568 * Estimate available height in the AlignFrame for alignment +
569 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
570 * hscroll, status bar (as these are not laid out we can't inspect their
571 * actual heights). Insets gives frame borders.
573 int stuff = Platform.isAMac() ? 80 : 100;
574 Insets insets = alignFrame.getInsets();
575 int availableHeight = alignFrame.getHeight() - stuff - insets.top
579 * If not enough vertical space, maximize annotation height while keeping
580 * at least two rows of alignment visible
582 if (annotationHeight + alignmentHeight > availableHeight)
584 annotationHeight = Math.min(annotationHeight, availableHeight - 2
590 // maintain same window layout whilst updating sliders
591 annotationHeight = annotationScroller.getSize().height;
595 annotationScroller.setPreferredSize(new Dimension(annotationScroller
596 .getWidth(), annotationHeight));
598 Dimension e = idPanel.getSize();
599 alabels.setSize(new Dimension(e.width, annotationHeight));
601 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
602 annotationSpaceFillerHolder.getWidth(), annotationHeight));
603 annotationScroller.validate();
604 annotationScroller.addNotify();
608 * update alignment layout for viewport settings
613 public void updateLayout()
616 setAnnotationVisible(av.isShowAnnotation());
617 boolean wrap = av.getWrapAlignment();
618 vpRanges.setStartSeq(0);
619 scalePanelHolder.setVisible(!wrap);
620 hscroll.setVisible(!wrap);
621 idwidthAdjuster.setVisible(!wrap);
625 annotationScroller.setVisible(false);
626 annotationSpaceFillerHolder.setVisible(false);
628 else if (av.isShowAnnotation())
630 annotationScroller.setVisible(true);
631 annotationSpaceFillerHolder.setVisible(true);
636 int widthInRes = getSeqPanel().seqCanvas
637 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
638 vpRanges.setViewportWidth(widthInRes);
642 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
643 .getCharWidth()) - 1;
644 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
645 .getCharHeight()) - 1;
647 vpRanges.setViewportWidth(widthInRes);
648 vpRanges.setViewportHeight(heightInSeq);
651 idSpaceFillerPanel1.setVisible(!wrap);
658 * Adjust row/column scrollers to show a visible position in the alignment.
661 * visible column to scroll to
663 * visible row to scroll to
666 public void setScrollValues(int xpos, int ypos)
671 if (av == null || av.getAlignment() == null)
676 if (av.getWrapAlignment())
678 setScrollingForWrappedPanel(x);
682 int width = av.getAlignment().getWidth();
683 int height = av.getAlignment().getHeight();
685 if (av.hasHiddenColumns())
687 // reset the width to exclude hidden columns
688 width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
691 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
692 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
699 if (vextent > height)
704 if ((hextent + x) > width)
709 if ((vextent + y) > height)
711 y = height - vextent;
724 // update the scroll values
725 hscroll.setValues(x, hextent, 0, width);
726 vscroll.setValues(y, vextent, 0, height);
731 * Respond to adjustment event when horizontal or vertical scrollbar is
735 * adjustment event encoding whether hscroll or vscroll changed
738 public void adjustmentValueChanged(AdjustmentEvent evt)
740 int oldX = vpRanges.getStartRes();
741 int oldwidth = vpRanges.getViewportWidth();
742 int oldY = vpRanges.getStartSeq();
743 int oldheight = vpRanges.getViewportHeight();
745 if (av.getWrapAlignment())
747 if (evt.getSource() == hscroll)
749 return; // no horizontal scroll when wrapped
751 else if (evt.getSource() == vscroll)
753 int offy = vscroll.getValue();
754 int rowSize = getSeqPanel().seqCanvas
755 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
757 // if we're scrolling to the position we're already at, stop
758 // this prevents infinite recursion of events when the scroll/viewport
759 // ranges values are the same
760 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
766 vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
771 // This is only called if file loaded is a jar file that
772 // was wrapped when saved and user has wrap alignment true
773 // as preference setting
774 SwingUtilities.invokeLater(new Runnable()
779 // When updating scrolling to use ViewportChange events, this code
780 // could not be validated and it is not clear if it is now being
781 // called. Log warning here in case it is called and unforeseen
784 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
786 // scroll to start of panel
787 vpRanges.setStartRes(0);
788 vpRanges.setStartSeq(0);
797 if (evt.getSource() == hscroll)
799 int x = hscroll.getValue();
800 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
802 // if we're scrolling to the position we're already at, stop
803 // this prevents infinite recursion of events when the scroll/viewport
804 // ranges values are the same
805 if ((x == oldX) && (width == oldwidth))
809 vpRanges.setViewportStartAndWidth(x, width);
811 else if (evt.getSource() == vscroll)
813 int y = vscroll.getValue();
814 int height = getSeqPanel().seqCanvas.getHeight()
815 / av.getCharHeight();
817 // if we're scrolling to the position we're already at, stop
818 // this prevents infinite recursion of events when the scroll/viewport
819 // ranges values are the same
820 if ((y == oldY) && (height == oldheight))
824 vpRanges.setViewportStartAndHeight(y, height);
834 * Repaint the alignment including the annotations and overview panels (if
838 public void paintAlignment(boolean updateOverview)
840 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
841 av.isShowAutocalculatedAbove());
842 sorter.sort(getAlignment().getAlignmentAnnotation(),
843 av.getSortAnnotationsBy());
848 // TODO: determine if this paintAlignment changed structure colours
849 av.getStructureSelectionManager().sequenceColoursChanged(this);
851 if (overviewPanel != null)
853 overviewPanel.updateOverviewImage();
865 public void paintComponent(Graphics g)
869 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
870 idPanelHolder.setPreferredSize(d);
871 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
875 * set scroll bar positions
877 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
881 * Set vertical scroll bar parameters for wrapped panel
883 * the residue to scroll to
885 private void setScrollingForWrappedPanel(int res)
887 // get the width of the alignment in residues
888 int maxwidth = av.getAlignment().getWidth();
889 if (av.hasHiddenColumns())
891 maxwidth = av.getAlignment().getHiddenColumns()
892 .findColumnPosition(maxwidth) - 1;
895 // get the width of the canvas in residues
896 int canvasWidth = getSeqPanel().seqCanvas
897 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
900 // position we want to scroll to is number of canvasWidth's to get there
901 int current = res / canvasWidth;
903 // max scroll position: add one because extent is 1 and scrollbar value
904 // can only be set to at most max - extent
905 int max = maxwidth / canvasWidth + 1;
906 vscroll.setUnitIncrement(1);
907 vscroll.setValues(current, 1, 0, max);
921 * @return DOCUMENT ME!
923 * @throws PrinterException
927 public int print(Graphics pg, PageFormat pf, int pi)
928 throws PrinterException
930 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
932 int pwidth = (int) pf.getImageableWidth();
933 int pheight = (int) pf.getImageableHeight();
935 if (av.getWrapAlignment())
937 return printWrappedAlignment(pwidth, pheight, pi, pg);
941 return printUnwrapped(pwidth, pheight, pi, pg, pg);
957 * @return DOCUMENT ME!
959 * @throws PrinterException
963 * Draws the alignment image, including sequence ids, sequences, and
964 * annotation labels and annotations if shown, on either one or two Graphics
971 * the graphics context for sequence ids and annotation labels
972 * @param alignmentGraphics
973 * the graphics context for sequences and annotations (may or may not
974 * be the same context as idGraphics)
976 * @throws PrinterException
978 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
979 Graphics idGraphics, Graphics alignmentGraphics)
980 throws PrinterException
982 final int idWidth = getVisibleIdWidth(false);
985 * Get the horizontal offset to where we draw the sequences.
986 * This is idWidth if using a single Graphics context, else zero.
988 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
990 FontMetrics fm = getFontMetrics(av.getFont());
991 int charHeight = av.getCharHeight();
992 int scaleHeight = charHeight + fm.getDescent();
994 idGraphics.setColor(Color.white);
995 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
996 idGraphics.setFont(av.getFont());
999 * How many sequences and residues can we fit on a printable page?
1001 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1003 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1005 int alignmentWidth = av.getAlignment().getWidth();
1006 int pagesWide = (alignmentWidth / totalRes) + 1;
1008 final int startRes = (pi % pagesWide) * totalRes;
1009 int endRes = (startRes + totalRes) - 1;
1011 if (endRes > (alignmentWidth - 1))
1013 endRes = alignmentWidth - 1;
1016 final int startSeq = (pi / pagesWide) * totalSeq;
1017 int endSeq = startSeq + totalSeq;
1019 int alignmentHeight = av.getAlignment().getHeight();
1020 if (endSeq > alignmentHeight)
1022 endSeq = alignmentHeight;
1025 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1028 if (av.isShowAnnotation())
1030 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1033 pagesHigh /= pageHeight;
1035 if (pi >= (pagesWide * pagesHigh))
1037 return Printable.NO_SUCH_PAGE;
1039 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1043 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1045 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1046 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1047 pageWidth - idWidth, scaleHeight);
1048 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1051 * Draw the sequence ids, offset for scale height,
1052 * then reset to top left (0, 0)
1054 idGraphics.translate(0, scaleHeight);
1055 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1056 Color currentColor = null;
1057 Color currentTextColor = null;
1060 for (int i = startSeq; i < endSeq; i++)
1062 seq = av.getAlignment().getSequenceAt(i);
1063 if ((av.getSelectionGroup() != null)
1064 && av.getSelectionGroup().getSequences(null).contains(seq))
1067 * gray out ids of sequences in selection group (if any)
1069 currentColor = Color.gray;
1070 currentTextColor = Color.black;
1074 currentColor = av.getSequenceColour(seq);
1075 currentTextColor = Color.black;
1078 idGraphics.setColor(currentColor);
1079 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1082 idGraphics.setColor(currentTextColor);
1085 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1086 if (av.isRightAlignIds())
1088 fm = idGraphics.getFontMetrics();
1090 - fm.stringWidth(displayId)
1094 idGraphics.drawString(displayId, xPos,
1095 (((i - startSeq) * charHeight) + charHeight)
1096 - (charHeight / 5));
1098 idGraphics.setFont(av.getFont());
1099 idGraphics.translate(0, -scaleHeight);
1102 * draw the sequences, offset for scale height, and id width (if using a
1103 * single graphics context), then reset to (0, scale height)
1105 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1106 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1107 startSeq, endSeq, 0);
1108 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1110 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1113 * draw annotation labels; drawComponent() translates by
1114 * getScrollOffset(), so compensate for that first;
1115 * then reset to (0, scale height)
1117 int offset = getAlabels().getScrollOffset();
1118 idGraphics.translate(0, -offset);
1119 idGraphics.translate(0, alignmentDrawnHeight);
1120 getAlabels().drawComponent(idGraphics, idWidth);
1121 idGraphics.translate(0, -alignmentDrawnHeight);
1124 * draw the annotations starting at
1125 * (idOffset, alignmentHeight) from (0, scaleHeight)
1127 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1128 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1129 alignmentGraphics, -1, startRes, endRes + 1);
1132 return Printable.PAGE_EXISTS;
1147 * @return DOCUMENT ME!
1149 * @throws PrinterException
1152 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1153 Graphics pg) throws PrinterException
1155 int annotationHeight = 0;
1156 AnnotationLabels labels = null;
1157 if (av.isShowAnnotation())
1159 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1160 labels = new AnnotationLabels(av);
1163 int hgap = av.getCharHeight();
1164 if (av.getScaleAboveWrapped())
1166 hgap += av.getCharHeight();
1169 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1172 int idWidth = getVisibleIdWidth(false);
1174 int maxwidth = av.getAlignment().getWidth();
1175 if (av.hasHiddenColumns())
1177 maxwidth = av.getAlignment().getHiddenColumns()
1178 .findColumnPosition(maxwidth) - 1;
1181 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1184 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1186 pg.setColor(Color.white);
1187 pg.fillRect(0, 0, pwidth, pheight);
1188 pg.setFont(av.getFont());
1192 pg.setColor(Color.black);
1194 pg.translate(0, -pi * pheight);
1196 pg.setClip(0, pi * pheight, pwidth, pheight);
1202 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1204 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1205 SequenceI s = av.getAlignment().getSequenceAt(i);
1206 String string = s.getDisplayId(av.getShowJVSuffix());
1208 if (av.isRightAlignIds())
1210 FontMetrics fm = pg.getFontMetrics();
1211 xPos = idWidth - fm.stringWidth(string) - 4;
1213 pg.drawString(string, xPos,
1214 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1215 - (av.getCharHeight() / 5));
1220 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1222 pg.setFont(av.getFont());
1223 labels.drawComponent(pg, idWidth);
1227 - (av.getAlignment().getHeight() * av
1232 } while (ypos < totalHeight);
1234 pg.translate(idWidth, 0);
1236 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1239 if ((pi * pheight) < totalHeight)
1241 return Printable.PAGE_EXISTS;
1246 return Printable.NO_SUCH_PAGE;
1251 * get current sequence ID panel width, or nominal value if panel were to be
1252 * displayed using default settings
1256 public int getVisibleIdWidth()
1258 return getVisibleIdWidth(true);
1262 * get current sequence ID panel width, or nominal value if panel were to be
1263 * displayed using default settings
1266 * indicate if the Id width for onscreen or offscreen display should
1270 public int getVisibleIdWidth(boolean onscreen)
1272 // see if rendering offscreen - check preferences and calc width accordingly
1273 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1275 return calculateIdWidth(-1).width + 4;
1277 Integer idwidth = null;
1279 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1281 int w = getIdPanel().getWidth();
1282 return (w > 0 ? w : calculateIdWidth().width + 4);
1284 return idwidth.intValue() + 4;
1287 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1289 int boarderBottomOffset = 5;
1290 long pSessionId = System.currentTimeMillis();
1291 headless = (System.getProperty("java.awt.headless") != null && System
1292 .getProperty("java.awt.headless").equals("true"));
1293 if (alignFrame != null && !headless)
1297 alignFrame.setProgressBar(MessageManager.formatMessage(
1298 "status.saving_file", new Object[] { type.getLabel() }),
1304 AlignmentDimension aDimension = getAlignmentDimension();
1307 jalview.util.ImageMaker im;
1308 final String imageAction, imageTitle;
1309 if (type == jalview.util.ImageMaker.TYPE.PNG)
1311 imageAction = "Create PNG image from alignment";
1314 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1316 imageAction = "Create EPS file from alignment";
1317 imageTitle = alignFrame.getTitle();
1321 imageAction = "Create SVG file from alignment";
1322 imageTitle = alignFrame.getTitle();
1325 im = new jalview.util.ImageMaker(this, type, imageAction,
1326 aDimension.getWidth(), aDimension.getHeight()
1327 + boarderBottomOffset, file, imageTitle,
1328 alignFrame, pSessionId, headless);
1329 Graphics graphics = im.getGraphics();
1330 if (av.getWrapAlignment())
1332 if (graphics != null)
1334 printWrappedAlignment(aDimension.getWidth(),
1335 aDimension.getHeight() + boarderBottomOffset, 0,
1342 if (graphics != null)
1344 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1345 0, graphics, graphics);
1350 } catch (OutOfMemoryError err)
1353 System.out.println("########################\n" + "OUT OF MEMORY "
1354 + file + "\n" + "########################");
1355 new OOMWarning("Creating Image for " + file, err);
1356 // System.out.println("Create IMAGE: " + err);
1357 } catch (Exception ex)
1359 ex.printStackTrace();
1367 public AlignmentDimension getAlignmentDimension()
1369 int maxwidth = av.getAlignment().getWidth();
1370 if (av.hasHiddenColumns())
1372 maxwidth = av.getAlignment().getHiddenColumns()
1373 .findColumnPosition(maxwidth);
1376 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1377 + getScalePanel().getHeight();
1378 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1380 if (av.getWrapAlignment())
1382 height = getWrappedHeight();
1385 // need to obtain default alignment width and then add in any
1386 // additional allowance for id margin
1387 // this duplicates the calculation in getWrappedHeight but adjusts for
1389 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1390 - alignFrame.getInsets().left
1391 - alignFrame.getInsets().right - getVisibleIdWidth()
1392 + getVisibleIdWidth(false);
1396 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1400 else if (av.isShowAnnotation())
1402 height += getAnnotationPanel().adjustPanelHeight() + 3;
1404 return new AlignmentDimension(width, height);
1411 public void makeEPS(File epsFile)
1413 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1419 public void makePNG(File pngFile)
1421 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1424 public void makeSVG(File svgFile)
1426 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1429 public void makePNGImageMap(File imgMapFile, String imageName)
1431 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1432 // ////////////////////////////////////////////
1433 int idWidth = getVisibleIdWidth(false);
1434 FontMetrics fm = getFontMetrics(av.getFont());
1435 int scaleHeight = av.getCharHeight() + fm.getDescent();
1438 // ////////////////////////////////
1439 if (imgMapFile != null)
1443 int sSize = av.getAlignment().getHeight();
1444 int alwidth = av.getAlignment().getWidth();
1445 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1446 out.println(HTMLOutput.getImageMapHTML());
1447 out.println("<img src=\"" + imageName
1448 + "\" border=\"0\" usemap=\"#Map\" >"
1449 + "<map name=\"Map\">");
1451 for (int s = 0; s < sSize; s++)
1453 int sy = s * av.getCharHeight() + scaleHeight;
1455 SequenceI seq = av.getAlignment().getSequenceAt(s);
1456 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1457 for (int column = 0; column < alwidth; column++)
1459 StringBuilder text = new StringBuilder(512);
1460 String triplet = null;
1461 if (av.getAlignment().isNucleotide())
1463 triplet = ResidueProperties.nucleotideName.get(seq
1464 .getCharAt(column) + "");
1468 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1472 if (triplet == null)
1477 int seqPos = seq.findPosition(column);
1478 int gSize = groups.length;
1479 for (int g = 0; g < gSize; g++)
1481 if (text.length() < 1)
1483 text.append("<area shape=\"rect\" coords=\"")
1484 .append((idWidth + column * av.getCharWidth()))
1485 .append(",").append(sy).append(",")
1486 .append((idWidth + (column + 1) * av.getCharWidth()))
1487 .append(",").append((av.getCharHeight() + sy))
1488 .append("\"").append(" onMouseOver=\"toolTip('")
1489 .append(seqPos).append(" ").append(triplet);
1492 if (groups[g].getStartRes() < column
1493 && groups[g].getEndRes() > column)
1495 text.append("<br><em>").append(groups[g].getName())
1500 if (text.length() < 1)
1502 text.append("<area shape=\"rect\" coords=\"")
1503 .append((idWidth + column * av.getCharWidth()))
1504 .append(",").append(sy).append(",")
1505 .append((idWidth + (column + 1) * av.getCharWidth()))
1506 .append(",").append((av.getCharHeight() + sy))
1507 .append("\"").append(" onMouseOver=\"toolTip('")
1508 .append(seqPos).append(" ").append(triplet);
1510 if (!Comparison.isGap(seq.getCharAt(column)))
1512 List<SequenceFeature> features = seq.findFeatures(column, column);
1513 for (SequenceFeature sf : features)
1515 if (sf.isContactFeature())
1517 text.append("<br>").append(sf.getType()).append(" ")
1518 .append(sf.getBegin()).append(":")
1519 .append(sf.getEnd());
1523 text.append("<br>");
1524 text.append(sf.getType());
1525 String description = sf.getDescription();
1526 if (description != null
1527 && !sf.getType().equals(description))
1529 description = description.replace("\"", """);
1530 text.append(" ").append(description);
1533 String status = sf.getStatus();
1534 if (status != null && !"".equals(status))
1536 text.append(" (").append(status).append(")");
1539 if (text.length() > 1)
1541 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1542 out.println(text.toString());
1547 out.println("</map></body></html>");
1550 } catch (Exception ex)
1552 ex.printStackTrace();
1554 } // /////////END OF IMAGE MAP
1558 int getWrappedHeight()
1560 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1562 if (System.getProperty("java.awt.headless") != null
1563 && System.getProperty("java.awt.headless").equals("true"))
1565 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1566 - vscroll.getPreferredSize().width
1567 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1570 int chunkWidth = getSeqPanel().seqCanvas
1571 .getWrappedCanvasWidth(seqPanelWidth);
1573 int hgap = av.getCharHeight();
1574 if (av.getScaleAboveWrapped())
1576 hgap += av.getCharHeight();
1579 int annotationHeight = 0;
1580 if (av.isShowAnnotation())
1582 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1585 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1588 int maxwidth = av.getAlignment().getWidth();
1589 if (av.hasHiddenColumns())
1591 maxwidth = av.getAlignment().getHiddenColumns()
1592 .findColumnPosition(maxwidth) - 1;
1595 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1601 * close the panel - deregisters all listeners and nulls any references to
1604 public void closePanel()
1606 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1607 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1608 PaintRefresher.RemoveComponent(this);
1613 * try to ensure references are nulled
1615 if (annotationPanel != null)
1617 annotationPanel.dispose();
1622 av.removePropertyChangeListener(propertyChangeListener);
1623 jalview.structure.StructureSelectionManager ssm = av
1624 .getStructureSelectionManager();
1625 ssm.removeStructureViewerListener(getSeqPanel(), null);
1626 ssm.removeSelectionListener(getSeqPanel());
1627 ssm.removeCommandListener(av);
1628 ssm.removeStructureViewerListener(getSeqPanel(), null);
1629 ssm.removeSelectionListener(getSeqPanel());
1635 if (Cache.log.isDebugEnabled())
1637 Cache.log.warn("Closing alignment panel which is already closed.");
1643 * Close any open dialogs that would be orphaned when this one is closed
1645 protected void closeChildFrames()
1647 if (calculationDialog != null)
1649 calculationDialog.closeFrame();
1654 * hides or shows dynamic annotation rows based on groups and av state flags
1656 public void updateAnnotation()
1658 updateAnnotation(false, false);
1661 public void updateAnnotation(boolean applyGlobalSettings)
1663 updateAnnotation(applyGlobalSettings, false);
1666 public void updateAnnotation(boolean applyGlobalSettings,
1667 boolean preserveNewGroupSettings)
1669 av.updateGroupAnnotationSettings(applyGlobalSettings,
1670 preserveNewGroupSettings);
1671 adjustAnnotationHeight();
1675 public AlignmentI getAlignment()
1677 return av == null ? null : av.getAlignment();
1681 public String getViewName()
1687 * Make/Unmake this alignment panel the current input focus
1691 public void setSelected(boolean b)
1695 if (alignFrame.getSplitViewContainer() != null)
1698 * bring enclosing SplitFrame to front first if there is one
1700 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1702 alignFrame.setSelected(b);
1703 } catch (Exception ex)
1709 alignFrame.setDisplayedView(this);
1714 public StructureSelectionManager getStructureSelectionManager()
1716 return av.getStructureSelectionManager();
1720 public void raiseOOMWarning(String string, OutOfMemoryError error)
1722 new OOMWarning(string, error, this);
1726 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1729 return new FeatureRenderer(this);
1733 public jalview.api.FeatureRenderer getFeatureRenderer()
1735 return seqPanel.seqCanvas.getFeatureRenderer();
1738 public void updateFeatureRenderer(
1739 jalview.renderer.seqfeatures.FeatureRenderer fr)
1741 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1744 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1746 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1748 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1752 public ScalePanel getScalePanel()
1757 public void setScalePanel(ScalePanel scalePanel)
1759 this.scalePanel = scalePanel;
1762 public SeqPanel getSeqPanel()
1767 public void setSeqPanel(SeqPanel seqPanel)
1769 this.seqPanel = seqPanel;
1772 public AnnotationPanel getAnnotationPanel()
1774 return annotationPanel;
1777 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1779 this.annotationPanel = annotationPanel;
1782 public AnnotationLabels getAlabels()
1787 public void setAlabels(AnnotationLabels alabels)
1789 this.alabels = alabels;
1792 public IdPanel getIdPanel()
1797 public void setIdPanel(IdPanel idPanel)
1799 this.idPanel = idPanel;
1803 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1804 * The aim is to keep the two alignments 'lined up' on their centre columns.
1807 * holds mapped region(s) of this alignment that we are scrolling
1808 * 'to'; may be modified for sequence offset by this method
1809 * @param verticalOffset
1810 * the number of visible sequences to show above the mapped region
1812 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1815 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1816 * mapped), we can make the scroll-to location a sequence above the one
1819 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1820 List<SequenceI> seqs = av.getAlignment().getSequences();
1823 * This is like AlignmentI.findIndex(seq) but here we are matching the
1824 * dataset sequence not the aligned sequence
1826 boolean matched = false;
1827 for (SequenceI seq : seqs)
1829 if (mappedTo == seq.getDatasetSequence())
1837 return; // failsafe, shouldn't happen
1841 * Scroll to position but centring the target residue.
1843 scrollToPosition(sr, verticalOffset, true, true);
1847 * Set a flag to say do not scroll any (cDNA/protein) complement.
1851 protected void setToScrollComplementPanel(boolean b)
1853 this.scrollComplementaryPanel = b;
1857 * Get whether to scroll complement panel
1859 * @return true if cDNA/protein complement panels should be scrolled
1861 protected boolean isSetToScrollComplementPanel()
1863 return this.scrollComplementaryPanel;
1869 * @adjustHeight if true, try to recalculate panel height for visible
1872 protected void refresh(boolean adjustHeight)
1874 validateAnnotationDimensions(adjustHeight);
1878 // sort, repaint, update overview
1879 paintAlignment(true);
1883 // lightweight repaint
1890 * Property change event fired when a change is made to the viewport ranges
1891 * object associated with this alignment panel's viewport
1893 public void propertyChange(PropertyChangeEvent evt)
1895 // update this panel's scroll values based on the new viewport ranges values
1896 int x = vpRanges.getStartRes();
1897 int y = vpRanges.getStartSeq();
1898 setScrollValues(x, y);
1900 // now update any complementary alignment (its viewport ranges object
1901 // is different so does not get automatically updated)
1902 if (isSetToScrollComplementPanel())
1904 setToScrollComplementPanel(false);
1905 av.scrollComplementaryAlignment();
1906 setToScrollComplementPanel(true);
1911 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1912 * reference should be nulled when the dialog is closed.
1914 * @param calculationChooser
1916 public void setCalculationDialog(CalculationChooser calculationChooser)
1918 calculationDialog = calculationChooser;
1922 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1925 public CalculationChooser getCalculationDialog()
1927 return calculationDialog;