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.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportListenerI;
39 import jalview.viewmodel.ViewportRanges;
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.ComponentAdapter;
52 import java.awt.event.ComponentEvent;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.beans.PropertyChangeEvent;
57 import java.beans.PropertyChangeListener;
59 import java.io.FileWriter;
60 import java.io.PrintWriter;
61 import java.util.List;
63 import javax.swing.SwingUtilities;
69 * @version $Revision: 1.161 $
71 public class AlignmentPanel extends GAlignmentPanel implements
72 AdjustmentListener, Printable, AlignmentViewPanel,
75 public AlignViewport av;
77 ViewportRanges vpRanges;
79 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 // this value is set false when selection area being dragged
99 boolean fastPaint = true;
101 private int hextent = 0;
103 private int vextent = 0;
106 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107 * true, suppresses invoking the same method recursively.
109 private boolean dontScrollComplement;
111 private PropertyChangeListener propertyChangeListener;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
123 vpRanges = av.getRanges();
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 addComponentListener(new ComponentAdapter()
150 public void componentResized(ComponentEvent evt)
152 // reset the viewport ranges when the alignment panel is resized
153 // in particular, this initialises the end residue value when Jalview
155 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
156 .getCharWidth()) - 1;
157 int currentStartRes = vpRanges.getStartRes();
158 if (av.getWrapAlignment())
160 widthInRes = getSeqPanel().seqCanvas
161 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164 vpRanges.setStartEndRes(currentStartRes, widthInRes);
169 final AlignmentPanel ap = this;
170 propertyChangeListener = new PropertyChangeListener()
173 public void propertyChange(PropertyChangeEvent evt)
175 if (evt.getPropertyName().equals("alignment"))
177 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
182 av.addPropertyChangeListener(propertyChangeListener);
184 av.getRanges().addPropertyChangeListener(this);
186 adjustAnnotationHeight();
191 public AlignViewportI getAlignViewport()
196 public void alignmentChanged()
198 av.alignmentChanged(this);
200 alignFrame.updateEditMenuBar();
202 paintAlignment(true);
209 public void fontChanged()
211 // set idCanvas bufferedImage to null
212 // to prevent drawing old image
213 FontMetrics fm = getFontMetrics(av.getFont());
215 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
217 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
218 .getCharHeight() + fm.getDescent()));
220 getIdPanel().getIdCanvas().gg = null;
221 getSeqPanel().seqCanvas.img = null;
222 getAnnotationPanel().adjustPanelHeight();
224 Dimension d = calculateIdWidth();
226 d.setSize(d.width + 4, d.height);
227 getIdPanel().getIdCanvas().setPreferredSize(d);
228 hscrollFillerPanel.setPreferredSize(d);
230 if (overviewPanel != null)
232 overviewPanel.setBoxPosition();
234 if (this.alignFrame.getSplitViewContainer() != null)
236 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
243 * Calculate the width of the alignment labels based on the displayed names
244 * and any bounds on label width set in preferences.
246 * @return Dimension giving the maximum width of the alignment label panel
247 * that should be used.
249 public Dimension calculateIdWidth()
251 // calculate sensible default width when no preference is available
253 if (av.getIdWidth() < 0)
255 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
256 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
257 r = calculateIdWidth(maxwidth);
258 av.setIdWidth(r.width);
263 r.width = av.getIdWidth();
270 * Calculate the width of the alignment labels based on the displayed names
271 * and any bounds on label width set in preferences.
274 * -1 or maximum width allowed for IdWidth
275 * @return Dimension giving the maximum width of the alignment label panel
276 * that should be used.
278 public Dimension calculateIdWidth(int maxwidth)
280 Container c = new Container();
282 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
283 Font.ITALIC, av.font.getSize()));
285 AlignmentI al = av.getAlignment();
290 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
292 SequenceI s = al.getSequenceAt(i);
294 id = s.getDisplayId(av.getShowJVSuffix());
296 if (fm.stringWidth(id) > idWidth)
298 idWidth = fm.stringWidth(id);
304 // Also check annotation label widths
307 if (al.getAlignmentAnnotation() != null)
309 fm = c.getFontMetrics(getAlabels().getFont());
311 while (i < al.getAlignmentAnnotation().length)
313 String label = al.getAlignmentAnnotation()[i].label;
315 if (fm.stringWidth(label) > idWidth)
317 idWidth = fm.stringWidth(label);
324 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
329 * Highlight the given results on the alignment.
332 public void highlightSearchResults(SearchResultsI results)
334 scrollToPosition(results);
335 getSeqPanel().seqCanvas.highlightSearchResults(results);
339 * Scroll the view to show the position of the highlighted region in results
340 * (if any) and redraw the overview
344 public boolean scrollToPosition(SearchResultsI results)
346 return scrollToPosition(results, 0, true, false);
350 * Scroll the view to show the position of the highlighted region in results
353 * @param searchResults
354 * @param redrawOverview
357 public boolean scrollToPosition(SearchResultsI searchResults,
358 boolean redrawOverview)
360 return scrollToPosition(searchResults, 0, redrawOverview, false);
364 * Scroll the view to show the position of the highlighted region in results
368 * @param verticalOffset
369 * if greater than zero, allows scrolling to a position below the
370 * first displayed sequence
371 * @param redrawOverview
372 * - when set, the overview will be recalculated (takes longer)
374 * if true, try to centre the search results horizontally in the view
375 * @return false if results were not found
377 public boolean scrollToPosition(SearchResultsI results,
378 int verticalOffset, boolean redrawOverview, boolean centre)
380 int startv, endv, starts, ends;
381 // TODO: properly locate search results in view when large numbers of hidden
382 // columns exist before highlighted region
383 // do we need to scroll the panel?
384 // TODO: tons of nullpointerexceptions raised here.
385 if (results != null && results.getSize() > 0 && av != null
386 && 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());
403 // System.err.println(this.av.viewName + " Seq : " + seqIndex
404 // + " Scroll to " + start + "," + end);
407 * To centre results, scroll to positions half the visible width
408 * left/right of the start/end positions
412 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
413 start = Math.max(start - offset, 0);
414 end = end + offset - 1;
420 if (end == seq.getEnd())
424 if (av.hasHiddenColumns())
426 start = av.getColumnSelection().findColumnPosition(start);
427 end = av.getColumnSelection().findColumnPosition(end);
430 if (!av.getColumnSelection().isVisible(r[0]))
432 // don't scroll - position isn't visible
439 * allow for offset of target sequence (actually scroll to one above it)
441 seqIndex = Math.max(0, seqIndex - verticalOffset);
443 // System.out.println("start=" + start + ", end=" + end + ", startv="
444 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
445 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
446 if (!av.getWrapAlignment())
448 if ((startv = vpRanges.getStartRes()) >= start)
451 * Scroll left to make start of search results visible
453 // setScrollValues(start - 1, seqIndex); // plus one residue
454 setScrollValues(start, seqIndex);
456 else if ((endv = vpRanges.getEndRes()) <= end)
459 * Scroll right to make end of search results visible
461 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
462 setScrollValues(startv + end - endv, seqIndex);
464 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
467 * Scroll up to make start of search results visible
469 setScrollValues(vpRanges.getStartRes(), seqIndex);
471 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
474 * Scroll down to make end of search results visible
476 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
480 * Else results are already visible - no need to scroll
485 scrollToWrappedVisible(start);
488 if (redrawOverview && overviewPanel != null)
490 overviewPanel.setBoxPosition();
492 paintAlignment(redrawOverview);
496 void scrollToWrappedVisible(int res)
498 int cwidth = getSeqPanel().seqCanvas
499 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
500 if (res < vpRanges.getStartRes()
501 || res >= (vpRanges.getStartRes() + cwidth))
503 vscroll.setValue((res / cwidth));
511 * @return DOCUMENT ME!
513 public OverviewPanel getOverviewPanel()
515 return overviewPanel;
524 public void setOverviewPanel(OverviewPanel op)
532 * Hide or show annotation panel
535 public void setAnnotationVisible(boolean b)
537 if (!av.getWrapAlignment())
539 annotationSpaceFillerHolder.setVisible(b);
540 annotationScroller.setVisible(b);
546 * automatically adjust annotation panel height for new annotation whilst
547 * ensuring the alignment is still visible.
550 public void adjustAnnotationHeight()
552 // TODO: display vertical annotation scrollbar if necessary
553 // this is called after loading new annotation onto alignment
554 if (alignFrame.getHeight() == 0)
556 System.out.println("NEEDS FIXING");
558 validateAnnotationDimensions(true);
560 paintAlignment(true);
564 * calculate the annotation dimensions and refresh slider values accordingly.
565 * need to do repaints/notifys afterwards.
567 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
569 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
571 if (adjustPanelHeight)
573 int rowHeight = av.getCharHeight();
574 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
577 * Estimate available height in the AlignFrame for alignment +
578 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
579 * hscroll, status bar (as these are not laid out we can't inspect their
580 * actual heights). Insets gives frame borders.
582 int stuff = Platform.isAMac() ? 80 : 100;
583 Insets insets = alignFrame.getInsets();
584 int availableHeight = alignFrame.getHeight() - stuff - insets.top
588 * If not enough vertical space, maximize annotation height while keeping
589 * at least two rows of alignment visible
591 if (annotationHeight + alignmentHeight > availableHeight)
593 annotationHeight = Math.min(annotationHeight, availableHeight - 2
599 // maintain same window layout whilst updating sliders
600 annotationHeight = annotationScroller.getSize().height;
604 annotationScroller.setPreferredSize(new Dimension(annotationScroller
605 .getWidth(), annotationHeight));
607 Dimension e = idPanel.getSize();
608 alabels.setSize(new Dimension(e.width, annotationHeight));
610 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
611 annotationSpaceFillerHolder.getWidth(), annotationHeight));
612 annotationScroller.validate();
613 annotationScroller.addNotify();
617 * update alignment layout for viewport settings
622 public void updateLayout()
625 setAnnotationVisible(av.isShowAnnotation());
626 boolean wrap = av.getWrapAlignment();
627 vpRanges.setStartSeq(0);
628 scalePanelHolder.setVisible(!wrap);
629 hscroll.setVisible(!wrap);
630 idwidthAdjuster.setVisible(!wrap);
634 annotationScroller.setVisible(false);
635 annotationSpaceFillerHolder.setVisible(false);
637 else if (av.isShowAnnotation())
639 annotationScroller.setVisible(true);
640 annotationSpaceFillerHolder.setVisible(true);
643 idSpaceFillerPanel1.setVisible(!wrap);
648 // return value is true if the scroll is valid
649 public boolean scrollUp(boolean up)
653 if (vscroll.getValue() < 1)
659 vscroll.setValue(vscroll.getValue() - 1);
663 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
669 vscroll.setValue(vscroll.getValue() + 1);
683 * @return DOCUMENT ME!
685 public boolean scrollRight(boolean right)
689 if (hscroll.getValue() < 1)
695 hscroll.setValue(hscroll.getValue() - 1);
699 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
705 hscroll.setValue(hscroll.getValue() + 1);
714 * Adjust row/column scrollers to show a visible position in the alignment.
717 * visible column to scroll to
719 * visible row to scroll to
722 public void setScrollValues(int x, int y)
724 if (av == null || av.getAlignment() == null)
729 if (av.getWrapAlignment())
731 setScrollingForWrappedPanel(x);
736 int width = av.getAlignment().getWidth();
737 int height = av.getAlignment().getHeight();
739 if (av.hasHiddenColumns())
741 // reset the width to exclude hidden columns
742 width = av.getColumnSelection().findColumnPosition(width);
745 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
746 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
753 if (vextent > height)
758 if ((hextent + x) > width)
763 if ((vextent + y) > height)
765 y = height - vextent;
778 // update the scroll values
779 hscroll.setValues(x, hextent, 0, width);
780 vscroll.setValues(y, vextent, 0, height);
791 public void adjustmentValueChanged(AdjustmentEvent evt)
793 int oldX = vpRanges.getStartRes();
794 int oldY = vpRanges.getStartSeq();
796 if (av.getWrapAlignment())
798 if (evt.getSource() == hscroll)
800 return; // no horizontal scroll when wrapped
802 else if (evt.getSource() == vscroll)
804 int offy = vscroll.getValue();
805 int rowSize = getSeqPanel().seqCanvas
806 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
808 // if we're scrolling to the position we're already at, stop
809 // this prevents infinite recursion of events when the scroll/viewport
810 // ranges values are the same
811 if (offy * rowSize == oldX)
817 vpRanges.setStartEndRes(offy * rowSize, (offy + 1) * rowSize);
821 // This is only called if file loaded is a jar file that
822 // was wrapped when saved and user has wrap alignment true
823 // as preference setting
824 SwingUtilities.invokeLater(new Runnable()
829 setScrollValues(vpRanges.getStartRes(),
830 vpRanges.getStartSeq());
840 if (evt.getSource() == hscroll)
842 int x = hscroll.getValue();
844 // if we're scrolling to the position we're already at, stop
845 // this prevents infinite recursion of events when the scroll/viewport
846 // ranges values are the same
851 vpRanges.setStartEndRes(x,
852 (x + (getSeqPanel().seqCanvas.getWidth() / av
853 .getCharWidth())) - 1);
855 else if (evt.getSource() == vscroll)
857 int offy = vscroll.getValue();
859 // if we're scrolling to the position we're already at, stop
860 // this prevents infinite recursion of events when the scroll/viewport
861 // ranges values are the same
866 vpRanges.setStartEndSeq(
869 + (getSeqPanel().seqCanvas.getHeight() / av
870 .getCharHeight()) - 1);
880 * Repaint the alignment including the annotations and overview panels (if
884 public void paintAlignment(boolean updateOverview)
886 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
887 av.isShowAutocalculatedAbove());
888 sorter.sort(getAlignment().getAlignmentAnnotation(),
889 av.getSortAnnotationsBy());
894 // TODO: determine if this paintAlignment changed structure colours
895 av.getStructureSelectionManager().sequenceColoursChanged(this);
897 if (overviewPanel != null)
899 overviewPanel.updateOverviewImage();
911 public void paintComponent(Graphics g)
915 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
916 idPanelHolder.setPreferredSize(d);
917 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
921 * set scroll bar positions
923 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
927 * Set vertical scroll bar parameters for wrapped panel
929 * the residue to scroll to
931 private void setScrollingForWrappedPanel(int res)
933 // get the width of the alignment in residues
934 int maxwidth = av.getAlignment().getWidth();
935 if (av.hasHiddenColumns())
937 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
940 // get the width of the canvas in residues
941 int canvasWidth = getSeqPanel().seqCanvas
942 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
945 // position we want to scroll to is number of canvasWidth's to get there
946 int current = res / canvasWidth;
948 // max scroll position: add one because extent is 1 and scrollbar value
949 // can only be set to at most max - extent
950 int max = maxwidth / canvasWidth + 1;
951 vscroll.setUnitIncrement(1);
952 vscroll.setValues(current, 1, 0, max);
966 * @return DOCUMENT ME!
968 * @throws PrinterException
972 public int print(Graphics pg, PageFormat pf, int pi)
973 throws PrinterException
975 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
977 int pwidth = (int) pf.getImageableWidth();
978 int pheight = (int) pf.getImageableHeight();
980 if (av.getWrapAlignment())
982 return printWrappedAlignment(pwidth, pheight, pi, pg);
986 return printUnwrapped(pwidth, pheight, pi, pg, pg);
1002 * @return DOCUMENT ME!
1004 * @throws PrinterException
1008 * Draws the alignment image, including sequence ids, sequences, and
1009 * annotation labels and annotations if shown, on either one or two Graphics
1016 * the graphics context for sequence ids and annotation labels
1017 * @param alignmentGraphics
1018 * the graphics context for sequences and annotations (may or may not
1019 * be the same context as idGraphics)
1021 * @throws PrinterException
1023 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1024 Graphics idGraphics, Graphics alignmentGraphics)
1025 throws PrinterException
1027 final int idWidth = getVisibleIdWidth(false);
1030 * Get the horizontal offset to where we draw the sequences.
1031 * This is idWidth if using a single Graphics context, else zero.
1033 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1035 FontMetrics fm = getFontMetrics(av.getFont());
1036 int charHeight = av.getCharHeight();
1037 int scaleHeight = charHeight + fm.getDescent();
1039 idGraphics.setColor(Color.white);
1040 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1041 idGraphics.setFont(av.getFont());
1044 * How many sequences and residues can we fit on a printable page?
1046 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1048 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1050 int alignmentWidth = av.getAlignment().getWidth();
1051 int pagesWide = (alignmentWidth / totalRes) + 1;
1053 final int startRes = (pi % pagesWide) * totalRes;
1054 int endRes = (startRes + totalRes) - 1;
1056 if (endRes > (alignmentWidth - 1))
1058 endRes = alignmentWidth - 1;
1061 final int startSeq = (pi / pagesWide) * totalSeq;
1062 int endSeq = startSeq + totalSeq;
1064 int alignmentHeight = av.getAlignment().getHeight();
1065 if (endSeq > alignmentHeight)
1067 endSeq = alignmentHeight;
1070 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1073 if (av.isShowAnnotation())
1075 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1078 pagesHigh /= pageHeight;
1080 if (pi >= (pagesWide * pagesHigh))
1082 return Printable.NO_SUCH_PAGE;
1084 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1088 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1090 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1091 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1092 pageWidth - idWidth, scaleHeight);
1093 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1096 * Draw the sequence ids, offset for scale height,
1097 * then reset to top left (0, 0)
1099 idGraphics.translate(0, scaleHeight);
1100 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1101 Color currentColor = null;
1102 Color currentTextColor = null;
1105 for (int i = startSeq; i < endSeq; i++)
1107 seq = av.getAlignment().getSequenceAt(i);
1108 if ((av.getSelectionGroup() != null)
1109 && av.getSelectionGroup().getSequences(null).contains(seq))
1112 * gray out ids of sequences in selection group (if any)
1114 currentColor = Color.gray;
1115 currentTextColor = Color.black;
1119 currentColor = av.getSequenceColour(seq);
1120 currentTextColor = Color.black;
1123 idGraphics.setColor(currentColor);
1124 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1127 idGraphics.setColor(currentTextColor);
1130 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1131 if (av.isRightAlignIds())
1133 fm = idGraphics.getFontMetrics();
1135 - fm.stringWidth(displayId)
1139 idGraphics.drawString(displayId, xPos,
1140 (((i - startSeq) * charHeight) + charHeight)
1141 - (charHeight / 5));
1143 idGraphics.setFont(av.getFont());
1144 idGraphics.translate(0, -scaleHeight);
1147 * draw the sequences, offset for scale height, and id width (if using a
1148 * single graphics context), then reset to (0, scale height)
1150 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1151 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1152 startSeq, endSeq, 0);
1153 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1155 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1158 * draw annotation labels; drawComponent() translates by
1159 * getScrollOffset(), so compensate for that first;
1160 * then reset to (0, scale height)
1162 int offset = getAlabels().getScrollOffset();
1163 idGraphics.translate(0, -offset);
1164 idGraphics.translate(0, alignmentDrawnHeight);
1165 getAlabels().drawComponent(idGraphics, idWidth);
1166 idGraphics.translate(0, -alignmentDrawnHeight);
1169 * draw the annotations starting at
1170 * (idOffset, alignmentHeight) from (0, scaleHeight)
1172 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1173 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1174 alignmentGraphics, -1, startRes, endRes + 1);
1177 return Printable.PAGE_EXISTS;
1192 * @return DOCUMENT ME!
1194 * @throws PrinterException
1197 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1198 Graphics pg) throws PrinterException
1200 int annotationHeight = 0;
1201 AnnotationLabels labels = null;
1202 if (av.isShowAnnotation())
1204 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1205 labels = new AnnotationLabels(av);
1208 int hgap = av.getCharHeight();
1209 if (av.getScaleAboveWrapped())
1211 hgap += av.getCharHeight();
1214 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1217 int idWidth = getVisibleIdWidth(false);
1219 int maxwidth = av.getAlignment().getWidth();
1220 if (av.hasHiddenColumns())
1222 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1225 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1228 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1230 pg.setColor(Color.white);
1231 pg.fillRect(0, 0, pwidth, pheight);
1232 pg.setFont(av.getFont());
1236 pg.setColor(Color.black);
1238 pg.translate(0, -pi * pheight);
1240 pg.setClip(0, pi * pheight, pwidth, pheight);
1246 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1248 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1249 SequenceI s = av.getAlignment().getSequenceAt(i);
1250 String string = s.getDisplayId(av.getShowJVSuffix());
1252 if (av.isRightAlignIds())
1254 FontMetrics fm = pg.getFontMetrics();
1255 xPos = idWidth - fm.stringWidth(string) - 4;
1257 pg.drawString(string, xPos,
1258 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1259 - (av.getCharHeight() / 5));
1264 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1266 pg.setFont(av.getFont());
1267 labels.drawComponent(pg, idWidth);
1271 - (av.getAlignment().getHeight() * av
1276 } while (ypos < totalHeight);
1278 pg.translate(idWidth, 0);
1280 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1283 if ((pi * pheight) < totalHeight)
1285 return Printable.PAGE_EXISTS;
1290 return Printable.NO_SUCH_PAGE;
1295 * get current sequence ID panel width, or nominal value if panel were to be
1296 * displayed using default settings
1300 public int getVisibleIdWidth()
1302 return getVisibleIdWidth(true);
1306 * get current sequence ID panel width, or nominal value if panel were to be
1307 * displayed using default settings
1310 * indicate if the Id width for onscreen or offscreen display should
1314 public int getVisibleIdWidth(boolean onscreen)
1316 // see if rendering offscreen - check preferences and calc width accordingly
1317 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1319 return calculateIdWidth(-1).width + 4;
1321 Integer idwidth = null;
1323 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1325 int w = getIdPanel().getWidth();
1326 return (w > 0 ? w : calculateIdWidth().width + 4);
1328 return idwidth.intValue() + 4;
1331 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1333 int boarderBottomOffset = 5;
1334 long pSessionId = System.currentTimeMillis();
1335 headless = (System.getProperty("java.awt.headless") != null && System
1336 .getProperty("java.awt.headless").equals("true"));
1337 if (alignFrame != null && !headless)
1341 alignFrame.setProgressBar(MessageManager.formatMessage(
1342 "status.saving_file", new Object[] { type.getLabel() }),
1348 AlignmentDimension aDimension = getAlignmentDimension();
1351 jalview.util.ImageMaker im;
1352 final String imageAction, imageTitle;
1353 if (type == jalview.util.ImageMaker.TYPE.PNG)
1355 imageAction = "Create PNG image from alignment";
1358 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1360 imageAction = "Create EPS file from alignment";
1361 imageTitle = alignFrame.getTitle();
1365 imageAction = "Create SVG file from alignment";
1366 imageTitle = alignFrame.getTitle();
1369 im = new jalview.util.ImageMaker(this, type, imageAction,
1370 aDimension.getWidth(), aDimension.getHeight()
1371 + boarderBottomOffset, file, imageTitle,
1372 alignFrame, pSessionId, headless);
1373 Graphics graphics = im.getGraphics();
1374 if (av.getWrapAlignment())
1376 if (graphics != null)
1378 printWrappedAlignment(aDimension.getWidth(),
1379 aDimension.getHeight() + boarderBottomOffset, 0,
1386 if (graphics != null)
1388 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1389 0, graphics, graphics);
1394 } catch (OutOfMemoryError err)
1397 System.out.println("########################\n" + "OUT OF MEMORY "
1398 + file + "\n" + "########################");
1399 new OOMWarning("Creating Image for " + file, err);
1400 // System.out.println("Create IMAGE: " + err);
1401 } catch (Exception ex)
1403 ex.printStackTrace();
1411 public AlignmentDimension getAlignmentDimension()
1413 int maxwidth = av.getAlignment().getWidth();
1414 if (av.hasHiddenColumns())
1416 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1419 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1420 + getScalePanel().getHeight();
1421 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1423 if (av.getWrapAlignment())
1425 height = getWrappedHeight();
1428 // need to obtain default alignment width and then add in any
1429 // additional allowance for id margin
1430 // this duplicates the calculation in getWrappedHeight but adjusts for
1432 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1433 - alignFrame.getInsets().left
1434 - alignFrame.getInsets().right - getVisibleIdWidth()
1435 + getVisibleIdWidth(false);
1439 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1443 else if (av.isShowAnnotation())
1445 height += getAnnotationPanel().adjustPanelHeight() + 3;
1447 return new AlignmentDimension(width, height);
1454 public void makeEPS(File epsFile)
1456 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1462 public void makePNG(File pngFile)
1464 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1467 public void makeSVG(File svgFile)
1469 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1472 public void makePNGImageMap(File imgMapFile, String imageName)
1474 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1475 // ////////////////////////////////////////////
1476 int idWidth = getVisibleIdWidth(false);
1477 FontMetrics fm = getFontMetrics(av.getFont());
1478 int scaleHeight = av.getCharHeight() + fm.getDescent();
1481 // ////////////////////////////////
1482 if (imgMapFile != null)
1486 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1487 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1488 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1489 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1490 out.println("<img src=\"" + imageName
1491 + "\" border=\"0\" usemap=\"#Map\" >"
1492 + "<map name=\"Map\">");
1494 for (s = 0; s < sSize; s++)
1496 sy = s * av.getCharHeight() + scaleHeight;
1498 SequenceI seq = av.getAlignment().getSequenceAt(s);
1499 SequenceFeature[] features = seq.getSequenceFeatures();
1500 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1501 for (res = 0; res < alwidth; res++)
1503 StringBuilder text = new StringBuilder();
1504 String triplet = null;
1505 if (av.getAlignment().isNucleotide())
1507 triplet = ResidueProperties.nucleotideName.get(seq
1508 .getCharAt(res) + "");
1512 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1516 if (triplet == null)
1521 int alIndex = seq.findPosition(res);
1522 gSize = groups.length;
1523 for (g = 0; g < gSize; g++)
1525 if (text.length() < 1)
1527 text.append("<area shape=\"rect\" coords=\"")
1528 .append((idWidth + res * av.getCharWidth()))
1529 .append(",").append(sy).append(",")
1530 .append((idWidth + (res + 1) * av.getCharWidth()))
1531 .append(",").append((av.getCharHeight() + sy))
1532 .append("\"").append(" onMouseOver=\"toolTip('")
1533 .append(alIndex).append(" ").append(triplet);
1536 if (groups[g].getStartRes() < res
1537 && groups[g].getEndRes() > res)
1539 text.append("<br><em>").append(groups[g].getName())
1544 if (features != null)
1546 if (text.length() < 1)
1548 text.append("<area shape=\"rect\" coords=\"")
1549 .append((idWidth + res * av.getCharWidth()))
1550 .append(",").append(sy).append(",")
1551 .append((idWidth + (res + 1) * av.getCharWidth()))
1552 .append(",").append((av.getCharHeight() + sy))
1553 .append("\"").append(" onMouseOver=\"toolTip('")
1554 .append(alIndex).append(" ").append(triplet);
1556 fSize = features.length;
1557 for (f = 0; f < fSize; f++)
1560 if ((features[f].getBegin() <= seq.findPosition(res))
1561 && (features[f].getEnd() >= seq.findPosition(res)))
1563 if (features[f].isContactFeature())
1565 if (features[f].getBegin() == seq.findPosition(res)
1566 || features[f].getEnd() == seq
1569 text.append("<br>").append(features[f].getType())
1570 .append(" ").append(features[f].getBegin())
1571 .append(":").append(features[f].getEnd());
1576 text.append("<br>");
1577 text.append(features[f].getType());
1578 if (features[f].getDescription() != null
1579 && !features[f].getType().equals(
1580 features[f].getDescription()))
1582 text.append(" ").append(features[f].getDescription());
1585 if (features[f].getValue("status") != null)
1587 text.append(" (").append(features[f].getValue("status"))
1595 if (text.length() > 1)
1597 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1598 out.println(text.toString());
1602 out.println("</map></body></html>");
1605 } catch (Exception ex)
1607 ex.printStackTrace();
1609 } // /////////END OF IMAGE MAP
1613 int getWrappedHeight()
1615 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1617 if (System.getProperty("java.awt.headless") != null
1618 && System.getProperty("java.awt.headless").equals("true"))
1620 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1621 - vscroll.getPreferredSize().width
1622 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1625 int chunkWidth = getSeqPanel().seqCanvas
1626 .getWrappedCanvasWidth(seqPanelWidth);
1628 int hgap = av.getCharHeight();
1629 if (av.getScaleAboveWrapped())
1631 hgap += av.getCharHeight();
1634 int annotationHeight = 0;
1635 if (av.isShowAnnotation())
1637 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1640 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1643 int maxwidth = av.getAlignment().getWidth();
1644 if (av.hasHiddenColumns())
1646 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1649 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1655 * close the panel - deregisters all listeners and nulls any references to
1658 public void closePanel()
1660 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1661 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1662 PaintRefresher.RemoveComponent(this);
1665 * try to ensure references are nulled
1667 if (annotationPanel != null)
1669 annotationPanel.dispose();
1674 av.removePropertyChangeListener(propertyChangeListener);
1675 jalview.structure.StructureSelectionManager ssm = av
1676 .getStructureSelectionManager();
1677 ssm.removeStructureViewerListener(getSeqPanel(), null);
1678 ssm.removeSelectionListener(getSeqPanel());
1679 ssm.removeCommandListener(av);
1680 ssm.removeStructureViewerListener(getSeqPanel(), null);
1681 ssm.removeSelectionListener(getSeqPanel());
1687 if (Cache.log.isDebugEnabled())
1689 Cache.log.warn("Closing alignment panel which is already closed.");
1695 * hides or shows dynamic annotation rows based on groups and av state flags
1697 public void updateAnnotation()
1699 updateAnnotation(false, false);
1702 public void updateAnnotation(boolean applyGlobalSettings)
1704 updateAnnotation(applyGlobalSettings, false);
1707 public void updateAnnotation(boolean applyGlobalSettings,
1708 boolean preserveNewGroupSettings)
1710 av.updateGroupAnnotationSettings(applyGlobalSettings,
1711 preserveNewGroupSettings);
1712 adjustAnnotationHeight();
1716 public AlignmentI getAlignment()
1718 return av == null ? null : av.getAlignment();
1722 public String getViewName()
1728 * Make/Unmake this alignment panel the current input focus
1732 public void setSelected(boolean b)
1736 if (alignFrame.getSplitViewContainer() != null)
1739 * bring enclosing SplitFrame to front first if there is one
1741 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1743 alignFrame.setSelected(b);
1744 } catch (Exception ex)
1750 alignFrame.setDisplayedView(this);
1755 public StructureSelectionManager getStructureSelectionManager()
1757 return av.getStructureSelectionManager();
1761 public void raiseOOMWarning(String string, OutOfMemoryError error)
1763 new OOMWarning(string, error, this);
1767 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1770 return new FeatureRenderer(this);
1774 public jalview.api.FeatureRenderer getFeatureRenderer()
1776 return seqPanel.seqCanvas.getFeatureRenderer();
1779 public void updateFeatureRenderer(
1780 jalview.renderer.seqfeatures.FeatureRenderer fr)
1782 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1785 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1787 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1789 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1793 public ScalePanel getScalePanel()
1798 public void setScalePanel(ScalePanel scalePanel)
1800 this.scalePanel = scalePanel;
1803 public SeqPanel getSeqPanel()
1808 public void setSeqPanel(SeqPanel seqPanel)
1810 this.seqPanel = seqPanel;
1813 public AnnotationPanel getAnnotationPanel()
1815 return annotationPanel;
1818 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1820 this.annotationPanel = annotationPanel;
1823 public AnnotationLabels getAlabels()
1828 public void setAlabels(AnnotationLabels alabels)
1830 this.alabels = alabels;
1833 public IdPanel getIdPanel()
1838 public void setIdPanel(IdPanel idPanel)
1840 this.idPanel = idPanel;
1844 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1845 * The aim is to keep the two alignments 'lined up' on their centre columns.
1848 * holds mapped region(s) of this alignment that we are scrolling
1849 * 'to'; may be modified for sequence offset by this method
1850 * @param verticalOffset
1851 * the number of visible sequences to show above the mapped region
1853 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1856 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1857 * mapped), we can make the scroll-to location a sequence above the one
1860 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1861 List<SequenceI> seqs = av.getAlignment().getSequences();
1864 * This is like AlignmentI.findIndex(seq) but here we are matching the
1865 * dataset sequence not the aligned sequence
1867 boolean matched = false;
1868 for (SequenceI seq : seqs)
1870 if (mappedTo == seq.getDatasetSequence())
1878 return; // failsafe, shouldn't happen
1882 * Scroll to position but centring the target residue.
1884 scrollToPosition(sr, verticalOffset, true, true);
1888 * Set a flag to say do not scroll any (cDNA/protein) complement.
1892 protected void setDontScrollComplement(boolean b)
1894 this.dontScrollComplement = b;
1897 protected boolean isDontScrollComplement()
1899 return this.dontScrollComplement;
1905 * @adjustHeight if true, try to recalculate panel height for visible
1908 protected void refresh(boolean adjustHeight)
1910 validateAnnotationDimensions(adjustHeight);
1914 // sort, repaint, update overview
1915 paintAlignment(true);
1919 // lightweight repaint
1926 * Property change event fired when a change is made to the viewport ranges
1927 * object associated with this alignment panel's viewport
1929 public void propertyChange(PropertyChangeEvent evt)
1931 // update this panel's scroll values based on the new viewport ranges values
1932 int x = vpRanges.getStartRes();
1933 int y = vpRanges.getStartSeq();
1934 setScrollValues(x, y);
1936 // now update any complementary alignment (its viewport ranges object
1937 // is different so does not get automatically updated)
1938 if (!isDontScrollComplement())
1940 setDontScrollComplement(true);
1941 av.scrollComplementaryAlignment();
1942 setDontScrollComplement(false);