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.jbgui.GAlignmentPanel;
34 import jalview.math.AlignmentDimension;
35 import jalview.schemes.ResidueProperties;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.MessageManager;
38 import jalview.util.Platform;
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.print.PageFormat;
52 import java.awt.print.Printable;
53 import java.awt.print.PrinterException;
54 import java.beans.PropertyChangeEvent;
55 import java.beans.PropertyChangeListener;
57 import java.io.FileWriter;
58 import java.io.PrintWriter;
59 import java.util.List;
61 import javax.swing.SwingUtilities;
67 * @version $Revision: 1.161 $
69 public class AlignmentPanel extends GAlignmentPanel implements
70 AdjustmentListener, Printable, AlignmentViewPanel
72 public AlignViewport av;
74 ViewportRanges vpRanges;
76 OverviewPanel overviewPanel;
78 private SeqPanel seqPanel;
80 private IdPanel idPanel;
82 private boolean headless;
84 IdwidthAdjuster idwidthAdjuster;
87 public AlignFrame alignFrame;
89 private ScalePanel scalePanel;
91 private AnnotationPanel annotationPanel;
93 private AnnotationLabels alabels;
95 // this value is set false when selection area being dragged
96 boolean fastPaint = true;
98 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * true, suppresses invoking the same method recursively.
106 private boolean dontScrollComplement;
108 private PropertyChangeListener propertyChangeListener;
111 * Creates a new AlignmentPanel object.
116 public AlignmentPanel(AlignFrame af, final AlignViewport av)
120 vpRanges = av.getRanges();
121 setSeqPanel(new SeqPanel(av, this));
122 setIdPanel(new IdPanel(av, this));
124 setScalePanel(new ScalePanel(av, this));
126 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
127 idwidthAdjuster = new IdwidthAdjuster(this);
128 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
130 setAnnotationPanel(new AnnotationPanel(this));
131 setAlabels(new AnnotationLabels(this));
133 annotationScroller.setViewportView(getAnnotationPanel());
134 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
136 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
137 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
139 setScrollValues(0, 0);
141 hscroll.addAdjustmentListener(this);
142 vscroll.addAdjustmentListener(this);
144 final AlignmentPanel ap = this;
145 propertyChangeListener = new PropertyChangeListener()
148 public void propertyChange(PropertyChangeEvent evt)
150 if (evt.getPropertyName().equals("alignment"))
152 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
157 av.addPropertyChangeListener(propertyChangeListener);
159 adjustAnnotationHeight();
164 public AlignViewportI getAlignViewport()
169 public void alignmentChanged()
171 av.alignmentChanged(this);
173 alignFrame.updateEditMenuBar();
175 paintAlignment(true);
182 public void fontChanged()
184 // set idCanvas bufferedImage to null
185 // to prevent drawing old image
186 FontMetrics fm = getFontMetrics(av.getFont());
188 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
190 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
191 .getCharHeight() + fm.getDescent()));
193 getIdPanel().getIdCanvas().gg = null;
194 getSeqPanel().seqCanvas.img = null;
195 getAnnotationPanel().adjustPanelHeight();
197 Dimension d = calculateIdWidth();
199 d.setSize(d.width + 4, d.height);
200 getIdPanel().getIdCanvas().setPreferredSize(d);
201 hscrollFillerPanel.setPreferredSize(d);
203 if (overviewPanel != null)
205 overviewPanel.setBoxPosition();
207 if (this.alignFrame.getSplitViewContainer() != null)
209 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
216 * Calculate the width of the alignment labels based on the displayed names
217 * and any bounds on label width set in preferences.
219 * @return Dimension giving the maximum width of the alignment label panel
220 * that should be used.
222 public Dimension calculateIdWidth()
224 // calculate sensible default width when no preference is available
226 if (av.getIdWidth() < 0)
228 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
229 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
230 r = calculateIdWidth(maxwidth);
231 av.setIdWidth(r.width);
236 r.width = av.getIdWidth();
243 * Calculate the width of the alignment labels based on the displayed names
244 * and any bounds on label width set in preferences.
247 * -1 or maximum width allowed for IdWidth
248 * @return Dimension giving the maximum width of the alignment label panel
249 * that should be used.
251 public Dimension calculateIdWidth(int maxwidth)
253 Container c = new Container();
255 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
256 Font.ITALIC, av.font.getSize()));
258 AlignmentI al = av.getAlignment();
263 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
265 SequenceI s = al.getSequenceAt(i);
267 id = s.getDisplayId(av.getShowJVSuffix());
269 if (fm.stringWidth(id) > idWidth)
271 idWidth = fm.stringWidth(id);
277 // Also check annotation label widths
280 if (al.getAlignmentAnnotation() != null)
282 fm = c.getFontMetrics(getAlabels().getFont());
284 while (i < al.getAlignmentAnnotation().length)
286 String label = al.getAlignmentAnnotation()[i].label;
288 if (fm.stringWidth(label) > idWidth)
290 idWidth = fm.stringWidth(label);
297 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
302 * Highlight the given results on the alignment.
305 public void highlightSearchResults(SearchResultsI results)
307 scrollToPosition(results);
308 getSeqPanel().seqCanvas.highlightSearchResults(results);
312 * Scroll the view to show the position of the highlighted region in results
313 * (if any) and redraw the overview
317 public boolean scrollToPosition(SearchResultsI results)
319 return scrollToPosition(results, 0, true, false);
323 * Scroll the view to show the position of the highlighted region in results
326 * @param searchResults
327 * @param redrawOverview
330 public boolean scrollToPosition(SearchResultsI searchResults,
331 boolean redrawOverview)
333 return scrollToPosition(searchResults, 0, redrawOverview, false);
337 * Scroll the view to show the position of the highlighted region in results
341 * @param verticalOffset
342 * if greater than zero, allows scrolling to a position below the
343 * first displayed sequence
344 * @param redrawOverview
345 * - when set, the overview will be recalculated (takes longer)
347 * if true, try to centre the search results horizontally in the view
348 * @return false if results were not found
350 public boolean scrollToPosition(SearchResultsI results,
351 int verticalOffset, boolean redrawOverview, boolean centre)
353 int startv, endv, starts, ends;
354 // TODO: properly locate search results in view when large numbers of hidden
355 // columns exist before highlighted region
356 // do we need to scroll the panel?
357 // TODO: tons of nullpointerexceptions raised here.
358 if (results != null && results.getSize() > 0 && av != null
359 && av.getAlignment() != null)
361 int seqIndex = av.getAlignment().findIndex(results);
366 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
368 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
376 // System.err.println(this.av.viewName + " Seq : " + seqIndex
377 // + " Scroll to " + start + "," + end);
380 * To centre results, scroll to positions half the visible width
381 * left/right of the start/end positions
385 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
386 start = Math.max(start - offset, 0);
387 end = end + offset - 1;
393 if (end == seq.getEnd())
397 if (av.hasHiddenColumns())
399 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
400 start = hidden.findColumnPosition(start);
401 end = hidden.findColumnPosition(end);
404 if (!hidden.isVisible(r[0]))
406 // don't scroll - position isn't visible
413 * allow for offset of target sequence (actually scroll to one above it)
415 seqIndex = Math.max(0, seqIndex - verticalOffset);
417 // System.out.println("start=" + start + ", end=" + end + ", startv="
418 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
419 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
420 if (!av.getWrapAlignment())
422 if ((startv = vpRanges.getStartRes()) >= start)
425 * Scroll left to make start of search results visible
427 // setScrollValues(start - 1, seqIndex); // plus one residue
428 setScrollValues(start, seqIndex);
430 else if ((endv = vpRanges.getEndRes()) <= end)
433 * Scroll right to make end of search results visible
435 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
436 setScrollValues(startv + end - endv, seqIndex);
438 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
441 * Scroll up to make start of search results visible
443 setScrollValues(vpRanges.getStartRes(), seqIndex);
445 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
448 * Scroll down to make end of search results visible
450 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
454 * Else results are already visible - no need to scroll
459 scrollToWrappedVisible(start);
462 if (redrawOverview && overviewPanel != null)
464 overviewPanel.setBoxPosition();
466 paintAlignment(redrawOverview);
470 void scrollToWrappedVisible(int res)
472 int cwidth = getSeqPanel().seqCanvas
473 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
474 if (res < vpRanges.getStartRes()
475 || res >= (vpRanges.getStartRes() + cwidth))
477 vscroll.setValue((res / cwidth));
478 vpRanges.setStartRes(vscroll.getValue() * cwidth);
486 * @return DOCUMENT ME!
488 public OverviewPanel getOverviewPanel()
490 return overviewPanel;
499 public void setOverviewPanel(OverviewPanel op)
507 * Hide or show annotation panel
510 public void setAnnotationVisible(boolean b)
512 if (!av.getWrapAlignment())
514 annotationSpaceFillerHolder.setVisible(b);
515 annotationScroller.setVisible(b);
521 * automatically adjust annotation panel height for new annotation whilst
522 * ensuring the alignment is still visible.
525 public void adjustAnnotationHeight()
527 // TODO: display vertical annotation scrollbar if necessary
528 // this is called after loading new annotation onto alignment
529 if (alignFrame.getHeight() == 0)
531 System.out.println("NEEDS FIXING");
533 validateAnnotationDimensions(true);
535 paintAlignment(true);
539 * calculate the annotation dimensions and refresh slider values accordingly.
540 * need to do repaints/notifys afterwards.
542 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
544 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
546 if (adjustPanelHeight)
548 int rowHeight = av.getCharHeight();
549 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
552 * Estimate available height in the AlignFrame for alignment +
553 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
554 * hscroll, status bar (as these are not laid out we can't inspect their
555 * actual heights). Insets gives frame borders.
557 int stuff = Platform.isAMac() ? 80 : 100;
558 Insets insets = alignFrame.getInsets();
559 int availableHeight = alignFrame.getHeight() - stuff - insets.top
563 * If not enough vertical space, maximize annotation height while keeping
564 * at least two rows of alignment visible
566 if (annotationHeight + alignmentHeight > availableHeight)
568 annotationHeight = Math.min(annotationHeight, availableHeight - 2
574 // maintain same window layout whilst updating sliders
575 annotationHeight = annotationScroller.getSize().height;
579 annotationScroller.setPreferredSize(new Dimension(annotationScroller
580 .getWidth(), annotationHeight));
582 Dimension e = idPanel.getSize();
583 alabels.setSize(new Dimension(e.width, annotationHeight));
585 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
586 annotationSpaceFillerHolder.getWidth(), annotationHeight));
587 annotationScroller.validate();
588 annotationScroller.addNotify();
592 * update alignment layout for viewport settings
597 public void updateLayout()
600 setAnnotationVisible(av.isShowAnnotation());
601 boolean wrap = av.getWrapAlignment();
602 vpRanges.setStartSeq(0);
603 scalePanelHolder.setVisible(!wrap);
604 hscroll.setVisible(!wrap);
605 idwidthAdjuster.setVisible(!wrap);
609 annotationScroller.setVisible(false);
610 annotationSpaceFillerHolder.setVisible(false);
612 else if (av.isShowAnnotation())
614 annotationScroller.setVisible(true);
615 annotationSpaceFillerHolder.setVisible(true);
618 idSpaceFillerPanel1.setVisible(!wrap);
623 // return value is true if the scroll is valid
624 public boolean scrollUp(boolean up)
628 if (vscroll.getValue() < 1)
634 vscroll.setValue(vscroll.getValue() - 1);
638 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
644 vscroll.setValue(vscroll.getValue() + 1);
658 * @return DOCUMENT ME!
660 public boolean scrollRight(boolean right)
664 if (hscroll.getValue() < 1)
670 hscroll.setValue(hscroll.getValue() - 1);
674 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
680 hscroll.setValue(hscroll.getValue() + 1);
689 * Adjust row/column scrollers to show a visible position in the alignment.
692 * visible column to scroll to
694 * visible row to scroll to
697 public void setScrollValues(int x, int y)
699 if (av == null || av.getAlignment() == null)
703 int width = av.getAlignment().getWidth();
704 int height = av.getAlignment().getHeight();
706 if (av.hasHiddenColumns())
708 // reset the width to exclude hidden columns
709 width = av.getAlignment().getHiddenColumns()
710 .findColumnPosition(width);
713 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
714 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
721 if (vextent > height)
726 if ((hextent + x) > width)
731 if ((vextent + y) > height)
733 y = height - vextent;
746 // update endRes after x has (possibly) been adjusted
747 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
748 .getCharWidth())) - 1);
751 * each scroll adjustment triggers adjustmentValueChanged, which resets the
752 * 'do not scroll complement' flag; ensure it is the same for both
755 boolean flag = isDontScrollComplement();
756 hscroll.setValues(x, hextent, 0, width);
757 setDontScrollComplement(flag);
758 vscroll.setValues(y, vextent, 0, height);
768 public void adjustmentValueChanged(AdjustmentEvent evt)
770 int oldX = vpRanges.getStartRes();
771 int oldY = vpRanges.getStartSeq();
773 if (evt.getSource() == hscroll)
775 int x = hscroll.getValue();
776 vpRanges.setStartRes(x);
777 vpRanges.setEndRes((x + (getSeqPanel().seqCanvas.getWidth() / av
778 .getCharWidth())) - 1);
781 if (evt.getSource() == vscroll)
783 int offy = vscroll.getValue();
785 if (av.getWrapAlignment())
789 int rowSize = getSeqPanel().seqCanvas
790 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
791 vpRanges.setStartRes(offy * rowSize);
792 vpRanges.setEndRes((offy + 1) * rowSize);
796 // This is only called if file loaded is a jar file that
797 // was wrapped when saved and user has wrap alignment true
798 // as preference setting
799 SwingUtilities.invokeLater(new Runnable()
804 setScrollValues(vpRanges.getStartRes(),
805 vpRanges.getStartSeq());
812 vpRanges.setStartSeq(offy);
813 vpRanges.setEndSeq(offy
814 + (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight())
819 if (overviewPanel != null)
821 overviewPanel.setBoxPosition();
824 int scrollX = vpRanges.getStartRes() - oldX;
825 int scrollY = vpRanges.getStartSeq() - oldY;
827 if (av.getWrapAlignment() || !fastPaint)
833 // Make sure we're not trying to draw a panel
834 // larger than the visible window
835 if (scrollX > vpRanges.getEndRes() - vpRanges.getStartRes())
837 scrollX = vpRanges.getEndRes() - vpRanges.getStartRes();
839 else if (scrollX < vpRanges.getStartRes() - vpRanges.getEndRes())
841 scrollX = vpRanges.getStartRes() - vpRanges.getEndRes();
844 if (scrollX != 0 || scrollY != 0)
846 getIdPanel().getIdCanvas().fastPaint(scrollY);
847 getSeqPanel().seqCanvas.fastPaint(scrollX, scrollY);
848 getScalePanel().repaint();
850 if (av.isShowAnnotation() && scrollX != 0)
852 getAnnotationPanel().fastPaint(scrollX);
857 * If there is one, scroll the (Protein/cDNA) complementary alignment to
858 * match, unless we are ourselves doing that.
860 if (isDontScrollComplement())
862 setDontScrollComplement(false);
866 av.scrollComplementaryAlignment();
871 * Repaint the alignment including the annotations and overview panels (if
875 public void paintAlignment(boolean updateOverview)
877 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
878 av.isShowAutocalculatedAbove());
879 sorter.sort(getAlignment().getAlignmentAnnotation(),
880 av.getSortAnnotationsBy());
885 // TODO: determine if this paintAlignment changed structure colours
886 av.getStructureSelectionManager().sequenceColoursChanged(this);
888 if (overviewPanel != null)
890 overviewPanel.updateOverviewImage();
902 public void paintComponent(Graphics g)
906 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
907 idPanelHolder.setPreferredSize(d);
908 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
912 * set scroll bar positions; first suppress this being 'followed' in any
913 * complementary split pane
915 setDontScrollComplement(true);
917 if (av.getWrapAlignment())
919 int maxwidth = av.getAlignment().getWidth();
921 if (av.hasHiddenColumns())
923 maxwidth = av.getAlignment().getHiddenColumns()
924 .findColumnPosition(maxwidth) - 1;
927 int canvasWidth = getSeqPanel().seqCanvas
928 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
932 / getSeqPanel().seqCanvas
933 .getWrappedCanvasWidth(getSeqPanel().seqCanvas
935 vscroll.setMaximum(max);
936 vscroll.setUnitIncrement(1);
937 vscroll.setVisibleAmount(1);
942 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
956 * @return DOCUMENT ME!
958 * @throws PrinterException
962 public int print(Graphics pg, PageFormat pf, int pi)
963 throws PrinterException
965 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
967 int pwidth = (int) pf.getImageableWidth();
968 int pheight = (int) pf.getImageableHeight();
970 if (av.getWrapAlignment())
972 return printWrappedAlignment(pwidth, pheight, pi, pg);
976 return printUnwrapped(pwidth, pheight, pi, pg, pg);
992 * @return DOCUMENT ME!
994 * @throws PrinterException
998 * Draws the alignment image, including sequence ids, sequences, and
999 * annotation labels and annotations if shown, on either one or two Graphics
1006 * the graphics context for sequence ids and annotation labels
1007 * @param alignmentGraphics
1008 * the graphics context for sequences and annotations (may or may not
1009 * be the same context as idGraphics)
1011 * @throws PrinterException
1013 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1014 Graphics idGraphics, Graphics alignmentGraphics)
1015 throws PrinterException
1017 final int idWidth = getVisibleIdWidth(false);
1020 * Get the horizontal offset to where we draw the sequences.
1021 * This is idWidth if using a single Graphics context, else zero.
1023 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1025 FontMetrics fm = getFontMetrics(av.getFont());
1026 int charHeight = av.getCharHeight();
1027 int scaleHeight = charHeight + fm.getDescent();
1029 idGraphics.setColor(Color.white);
1030 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1031 idGraphics.setFont(av.getFont());
1034 * How many sequences and residues can we fit on a printable page?
1036 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1038 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1040 int alignmentWidth = av.getAlignment().getWidth();
1041 int pagesWide = (alignmentWidth / totalRes) + 1;
1043 final int startRes = (pi % pagesWide) * totalRes;
1044 int endRes = (startRes + totalRes) - 1;
1046 if (endRes > (alignmentWidth - 1))
1048 endRes = alignmentWidth - 1;
1051 final int startSeq = (pi / pagesWide) * totalSeq;
1052 int endSeq = startSeq + totalSeq;
1054 int alignmentHeight = av.getAlignment().getHeight();
1055 if (endSeq > alignmentHeight)
1057 endSeq = alignmentHeight;
1060 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1063 if (av.isShowAnnotation())
1065 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1068 pagesHigh /= pageHeight;
1070 if (pi >= (pagesWide * pagesHigh))
1072 return Printable.NO_SUCH_PAGE;
1074 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1078 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1080 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1081 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1082 pageWidth - idWidth, scaleHeight);
1083 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1086 * Draw the sequence ids, offset for scale height,
1087 * then reset to top left (0, 0)
1089 idGraphics.translate(0, scaleHeight);
1090 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1091 Color currentColor = null;
1092 Color currentTextColor = null;
1095 for (int i = startSeq; i < endSeq; i++)
1097 seq = av.getAlignment().getSequenceAt(i);
1098 if ((av.getSelectionGroup() != null)
1099 && av.getSelectionGroup().getSequences(null).contains(seq))
1102 * gray out ids of sequences in selection group (if any)
1104 currentColor = Color.gray;
1105 currentTextColor = Color.black;
1109 currentColor = av.getSequenceColour(seq);
1110 currentTextColor = Color.black;
1113 idGraphics.setColor(currentColor);
1114 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1117 idGraphics.setColor(currentTextColor);
1120 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1121 if (av.isRightAlignIds())
1123 fm = idGraphics.getFontMetrics();
1125 - fm.stringWidth(displayId)
1129 idGraphics.drawString(displayId, xPos,
1130 (((i - startSeq) * charHeight) + charHeight)
1131 - (charHeight / 5));
1133 idGraphics.setFont(av.getFont());
1134 idGraphics.translate(0, -scaleHeight);
1137 * draw the sequences, offset for scale height, and id width (if using a
1138 * single graphics context), then reset to (0, scale height)
1140 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1141 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1142 startSeq, endSeq, 0);
1143 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1145 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1148 * draw annotation labels; drawComponent() translates by
1149 * getScrollOffset(), so compensate for that first;
1150 * then reset to (0, scale height)
1152 int offset = getAlabels().getScrollOffset();
1153 idGraphics.translate(0, -offset);
1154 idGraphics.translate(0, alignmentDrawnHeight);
1155 getAlabels().drawComponent(idGraphics, idWidth);
1156 idGraphics.translate(0, -alignmentDrawnHeight);
1159 * draw the annotations starting at
1160 * (idOffset, alignmentHeight) from (0, scaleHeight)
1162 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1163 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1164 alignmentGraphics, -1, startRes, endRes + 1);
1167 return Printable.PAGE_EXISTS;
1182 * @return DOCUMENT ME!
1184 * @throws PrinterException
1187 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1188 Graphics pg) throws PrinterException
1190 int annotationHeight = 0;
1191 AnnotationLabels labels = null;
1192 if (av.isShowAnnotation())
1194 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1195 labels = new AnnotationLabels(av);
1198 int hgap = av.getCharHeight();
1199 if (av.getScaleAboveWrapped())
1201 hgap += av.getCharHeight();
1204 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1207 int idWidth = getVisibleIdWidth(false);
1209 int maxwidth = av.getAlignment().getWidth();
1210 if (av.hasHiddenColumns())
1212 maxwidth = av.getAlignment().getHiddenColumns()
1213 .findColumnPosition(maxwidth) - 1;
1216 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1219 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1221 pg.setColor(Color.white);
1222 pg.fillRect(0, 0, pwidth, pheight);
1223 pg.setFont(av.getFont());
1227 pg.setColor(Color.black);
1229 pg.translate(0, -pi * pheight);
1231 pg.setClip(0, pi * pheight, pwidth, pheight);
1237 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1239 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1240 SequenceI s = av.getAlignment().getSequenceAt(i);
1241 String string = s.getDisplayId(av.getShowJVSuffix());
1243 if (av.isRightAlignIds())
1245 FontMetrics fm = pg.getFontMetrics();
1246 xPos = idWidth - fm.stringWidth(string) - 4;
1248 pg.drawString(string, xPos,
1249 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1250 - (av.getCharHeight() / 5));
1255 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1257 pg.setFont(av.getFont());
1258 labels.drawComponent(pg, idWidth);
1262 - (av.getAlignment().getHeight() * av
1267 } while (ypos < totalHeight);
1269 pg.translate(idWidth, 0);
1271 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1274 if ((pi * pheight) < totalHeight)
1276 return Printable.PAGE_EXISTS;
1281 return Printable.NO_SUCH_PAGE;
1286 * get current sequence ID panel width, or nominal value if panel were to be
1287 * displayed using default settings
1291 public int getVisibleIdWidth()
1293 return getVisibleIdWidth(true);
1297 * get current sequence ID panel width, or nominal value if panel were to be
1298 * displayed using default settings
1301 * indicate if the Id width for onscreen or offscreen display should
1305 public int getVisibleIdWidth(boolean onscreen)
1307 // see if rendering offscreen - check preferences and calc width accordingly
1308 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1310 return calculateIdWidth(-1).width + 4;
1312 Integer idwidth = null;
1314 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1316 int w = getIdPanel().getWidth();
1317 return (w > 0 ? w : calculateIdWidth().width + 4);
1319 return idwidth.intValue() + 4;
1322 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1324 int boarderBottomOffset = 5;
1325 long pSessionId = System.currentTimeMillis();
1326 headless = (System.getProperty("java.awt.headless") != null && System
1327 .getProperty("java.awt.headless").equals("true"));
1328 if (alignFrame != null && !headless)
1332 alignFrame.setProgressBar(MessageManager.formatMessage(
1333 "status.saving_file", new Object[] { type.getLabel() }),
1339 AlignmentDimension aDimension = getAlignmentDimension();
1342 jalview.util.ImageMaker im;
1343 final String imageAction, imageTitle;
1344 if (type == jalview.util.ImageMaker.TYPE.PNG)
1346 imageAction = "Create PNG image from alignment";
1349 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1351 imageAction = "Create EPS file from alignment";
1352 imageTitle = alignFrame.getTitle();
1356 imageAction = "Create SVG file from alignment";
1357 imageTitle = alignFrame.getTitle();
1360 im = new jalview.util.ImageMaker(this, type, imageAction,
1361 aDimension.getWidth(), aDimension.getHeight()
1362 + boarderBottomOffset, file, imageTitle,
1363 alignFrame, pSessionId, headless);
1364 Graphics graphics = im.getGraphics();
1365 if (av.getWrapAlignment())
1367 if (graphics != null)
1369 printWrappedAlignment(aDimension.getWidth(),
1370 aDimension.getHeight() + boarderBottomOffset, 0,
1377 if (graphics != null)
1379 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1380 0, graphics, graphics);
1385 } catch (OutOfMemoryError err)
1388 System.out.println("########################\n" + "OUT OF MEMORY "
1389 + file + "\n" + "########################");
1390 new OOMWarning("Creating Image for " + file, err);
1391 // System.out.println("Create IMAGE: " + err);
1392 } catch (Exception ex)
1394 ex.printStackTrace();
1402 public AlignmentDimension getAlignmentDimension()
1404 int maxwidth = av.getAlignment().getWidth();
1405 if (av.hasHiddenColumns())
1407 maxwidth = av.getAlignment().getHiddenColumns()
1408 .findColumnPosition(maxwidth);
1411 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1412 + getScalePanel().getHeight();
1413 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1415 if (av.getWrapAlignment())
1417 height = getWrappedHeight();
1420 // need to obtain default alignment width and then add in any
1421 // additional allowance for id margin
1422 // this duplicates the calculation in getWrappedHeight but adjusts for
1424 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1425 - alignFrame.getInsets().left
1426 - alignFrame.getInsets().right - getVisibleIdWidth()
1427 + getVisibleIdWidth(false);
1431 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1435 else if (av.isShowAnnotation())
1437 height += getAnnotationPanel().adjustPanelHeight() + 3;
1439 return new AlignmentDimension(width, height);
1446 public void makeEPS(File epsFile)
1448 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1454 public void makePNG(File pngFile)
1456 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1459 public void makeSVG(File svgFile)
1461 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1464 public void makePNGImageMap(File imgMapFile, String imageName)
1466 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1467 // ////////////////////////////////////////////
1468 int idWidth = getVisibleIdWidth(false);
1469 FontMetrics fm = getFontMetrics(av.getFont());
1470 int scaleHeight = av.getCharHeight() + fm.getDescent();
1473 // ////////////////////////////////
1474 if (imgMapFile != null)
1478 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1479 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1480 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1481 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1482 out.println("<img src=\"" + imageName
1483 + "\" border=\"0\" usemap=\"#Map\" >"
1484 + "<map name=\"Map\">");
1486 for (s = 0; s < sSize; s++)
1488 sy = s * av.getCharHeight() + scaleHeight;
1490 SequenceI seq = av.getAlignment().getSequenceAt(s);
1491 SequenceFeature[] features = seq.getSequenceFeatures();
1492 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1493 for (res = 0; res < alwidth; res++)
1495 StringBuilder text = new StringBuilder();
1496 String triplet = null;
1497 if (av.getAlignment().isNucleotide())
1499 triplet = ResidueProperties.nucleotideName.get(seq
1500 .getCharAt(res) + "");
1504 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1508 if (triplet == null)
1513 int alIndex = seq.findPosition(res);
1514 gSize = groups.length;
1515 for (g = 0; g < gSize; g++)
1517 if (text.length() < 1)
1519 text.append("<area shape=\"rect\" coords=\"")
1520 .append((idWidth + res * av.getCharWidth()))
1521 .append(",").append(sy).append(",")
1522 .append((idWidth + (res + 1) * av.getCharWidth()))
1523 .append(",").append((av.getCharHeight() + sy))
1524 .append("\"").append(" onMouseOver=\"toolTip('")
1525 .append(alIndex).append(" ").append(triplet);
1528 if (groups[g].getStartRes() < res
1529 && groups[g].getEndRes() > res)
1531 text.append("<br><em>").append(groups[g].getName())
1536 if (features != null)
1538 if (text.length() < 1)
1540 text.append("<area shape=\"rect\" coords=\"")
1541 .append((idWidth + res * av.getCharWidth()))
1542 .append(",").append(sy).append(",")
1543 .append((idWidth + (res + 1) * av.getCharWidth()))
1544 .append(",").append((av.getCharHeight() + sy))
1545 .append("\"").append(" onMouseOver=\"toolTip('")
1546 .append(alIndex).append(" ").append(triplet);
1548 fSize = features.length;
1549 for (f = 0; f < fSize; f++)
1552 if ((features[f].getBegin() <= seq.findPosition(res))
1553 && (features[f].getEnd() >= seq.findPosition(res)))
1555 if (features[f].isContactFeature())
1557 if (features[f].getBegin() == seq.findPosition(res)
1558 || features[f].getEnd() == seq
1561 text.append("<br>").append(features[f].getType())
1562 .append(" ").append(features[f].getBegin())
1563 .append(":").append(features[f].getEnd());
1568 text.append("<br>");
1569 text.append(features[f].getType());
1570 if (features[f].getDescription() != null
1571 && !features[f].getType().equals(
1572 features[f].getDescription()))
1574 text.append(" ").append(features[f].getDescription());
1577 if (features[f].getValue("status") != null)
1579 text.append(" (").append(features[f].getValue("status"))
1587 if (text.length() > 1)
1589 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1590 out.println(text.toString());
1594 out.println("</map></body></html>");
1597 } catch (Exception ex)
1599 ex.printStackTrace();
1601 } // /////////END OF IMAGE MAP
1605 int getWrappedHeight()
1607 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1609 if (System.getProperty("java.awt.headless") != null
1610 && System.getProperty("java.awt.headless").equals("true"))
1612 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1613 - vscroll.getPreferredSize().width
1614 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1617 int chunkWidth = getSeqPanel().seqCanvas
1618 .getWrappedCanvasWidth(seqPanelWidth);
1620 int hgap = av.getCharHeight();
1621 if (av.getScaleAboveWrapped())
1623 hgap += av.getCharHeight();
1626 int annotationHeight = 0;
1627 if (av.isShowAnnotation())
1629 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1632 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1635 int maxwidth = av.getAlignment().getWidth();
1636 if (av.hasHiddenColumns())
1638 maxwidth = av.getAlignment().getHiddenColumns()
1639 .findColumnPosition(maxwidth) - 1;
1642 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1648 * close the panel - deregisters all listeners and nulls any references to
1651 public void closePanel()
1653 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1654 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1655 PaintRefresher.RemoveComponent(this);
1658 * try to ensure references are nulled
1660 if (annotationPanel != null)
1662 annotationPanel.dispose();
1667 av.removePropertyChangeListener(propertyChangeListener);
1668 jalview.structure.StructureSelectionManager ssm = av
1669 .getStructureSelectionManager();
1670 ssm.removeStructureViewerListener(getSeqPanel(), null);
1671 ssm.removeSelectionListener(getSeqPanel());
1672 ssm.removeCommandListener(av);
1673 ssm.removeStructureViewerListener(getSeqPanel(), null);
1674 ssm.removeSelectionListener(getSeqPanel());
1680 if (Cache.log.isDebugEnabled())
1682 Cache.log.warn("Closing alignment panel which is already closed.");
1688 * hides or shows dynamic annotation rows based on groups and av state flags
1690 public void updateAnnotation()
1692 updateAnnotation(false, false);
1695 public void updateAnnotation(boolean applyGlobalSettings)
1697 updateAnnotation(applyGlobalSettings, false);
1700 public void updateAnnotation(boolean applyGlobalSettings,
1701 boolean preserveNewGroupSettings)
1703 av.updateGroupAnnotationSettings(applyGlobalSettings,
1704 preserveNewGroupSettings);
1705 adjustAnnotationHeight();
1709 public AlignmentI getAlignment()
1711 return av == null ? null : av.getAlignment();
1715 public String getViewName()
1721 * Make/Unmake this alignment panel the current input focus
1725 public void setSelected(boolean b)
1729 if (alignFrame.getSplitViewContainer() != null)
1732 * bring enclosing SplitFrame to front first if there is one
1734 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1736 alignFrame.setSelected(b);
1737 } catch (Exception ex)
1743 alignFrame.setDisplayedView(this);
1748 public StructureSelectionManager getStructureSelectionManager()
1750 return av.getStructureSelectionManager();
1754 public void raiseOOMWarning(String string, OutOfMemoryError error)
1756 new OOMWarning(string, error, this);
1760 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1763 return new FeatureRenderer(this);
1767 public jalview.api.FeatureRenderer getFeatureRenderer()
1769 return seqPanel.seqCanvas.getFeatureRenderer();
1772 public void updateFeatureRenderer(
1773 jalview.renderer.seqfeatures.FeatureRenderer fr)
1775 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1778 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1780 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1782 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1786 public ScalePanel getScalePanel()
1791 public void setScalePanel(ScalePanel scalePanel)
1793 this.scalePanel = scalePanel;
1796 public SeqPanel getSeqPanel()
1801 public void setSeqPanel(SeqPanel seqPanel)
1803 this.seqPanel = seqPanel;
1806 public AnnotationPanel getAnnotationPanel()
1808 return annotationPanel;
1811 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1813 this.annotationPanel = annotationPanel;
1816 public AnnotationLabels getAlabels()
1821 public void setAlabels(AnnotationLabels alabels)
1823 this.alabels = alabels;
1826 public IdPanel getIdPanel()
1831 public void setIdPanel(IdPanel idPanel)
1833 this.idPanel = idPanel;
1837 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1838 * The aim is to keep the two alignments 'lined up' on their centre columns.
1841 * holds mapped region(s) of this alignment that we are scrolling
1842 * 'to'; may be modified for sequence offset by this method
1843 * @param verticalOffset
1844 * the number of visible sequences to show above the mapped region
1846 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1849 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1850 * mapped), we can make the scroll-to location a sequence above the one
1853 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1854 List<SequenceI> seqs = av.getAlignment().getSequences();
1857 * This is like AlignmentI.findIndex(seq) but here we are matching the
1858 * dataset sequence not the aligned sequence
1860 boolean matched = false;
1861 for (SequenceI seq : seqs)
1863 if (mappedTo == seq.getDatasetSequence())
1871 return; // failsafe, shouldn't happen
1875 * Scroll to position but centring the target residue.
1877 scrollToPosition(sr, verticalOffset, true, true);
1881 * Set a flag to say do not scroll any (cDNA/protein) complement.
1885 protected void setDontScrollComplement(boolean b)
1887 this.dontScrollComplement = b;
1890 protected boolean isDontScrollComplement()
1892 return this.dontScrollComplement;
1898 * @adjustHeight if true, try to recalculate panel height for visible
1901 protected void refresh(boolean adjustHeight)
1903 validateAnnotationDimensions(adjustHeight);
1907 // sort, repaint, update overview
1908 paintAlignment(true);
1912 // lightweight repaint