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.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,
73 public AlignViewport av;
75 ViewportRanges vpRanges;
77 OverviewPanel overviewPanel;
79 private SeqPanel seqPanel;
81 private IdPanel idPanel;
83 private boolean headless;
85 IdwidthAdjuster idwidthAdjuster;
88 public AlignFrame alignFrame;
90 private ScalePanel scalePanel;
92 private AnnotationPanel annotationPanel;
94 private AnnotationLabels alabels;
96 // this value is set false when selection area being dragged
97 boolean fastPaint = true;
99 private int hextent = 0;
101 private int vextent = 0;
104 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
105 * true, suppresses invoking the same method recursively.
107 private boolean dontScrollComplement;
109 private PropertyChangeListener propertyChangeListener;
112 * Creates a new AlignmentPanel object.
117 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 vpRanges = av.getRanges();
122 setSeqPanel(new SeqPanel(av, this));
123 setIdPanel(new IdPanel(av, this));
125 setScalePanel(new ScalePanel(av, this));
127 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
128 idwidthAdjuster = new IdwidthAdjuster(this);
129 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
131 setAnnotationPanel(new AnnotationPanel(this));
132 setAlabels(new AnnotationLabels(this));
134 annotationScroller.setViewportView(getAnnotationPanel());
135 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
137 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
138 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
140 setScrollValues(0, 0);
142 hscroll.addAdjustmentListener(this);
143 vscroll.addAdjustmentListener(this);
145 final AlignmentPanel ap = this;
146 propertyChangeListener = new PropertyChangeListener()
149 public void propertyChange(PropertyChangeEvent evt)
151 if (evt.getPropertyName().equals("alignment"))
153 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
158 av.addPropertyChangeListener(propertyChangeListener);
160 av.getRanges().addPropertyChangeListener(this);
162 adjustAnnotationHeight();
167 public AlignViewportI getAlignViewport()
172 public void alignmentChanged()
174 av.alignmentChanged(this);
176 alignFrame.updateEditMenuBar();
178 paintAlignment(true);
185 public void fontChanged()
187 // set idCanvas bufferedImage to null
188 // to prevent drawing old image
189 FontMetrics fm = getFontMetrics(av.getFont());
191 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
193 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
194 .getCharHeight() + fm.getDescent()));
196 getIdPanel().getIdCanvas().gg = null;
197 getSeqPanel().seqCanvas.img = null;
198 getAnnotationPanel().adjustPanelHeight();
200 Dimension d = calculateIdWidth();
202 d.setSize(d.width + 4, d.height);
203 getIdPanel().getIdCanvas().setPreferredSize(d);
204 hscrollFillerPanel.setPreferredSize(d);
206 if (overviewPanel != null)
208 overviewPanel.setBoxPosition();
210 if (this.alignFrame.getSplitViewContainer() != null)
212 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
219 * Calculate the width of the alignment labels based on the displayed names
220 * and any bounds on label width set in preferences.
222 * @return Dimension giving the maximum width of the alignment label panel
223 * that should be used.
225 public Dimension calculateIdWidth()
227 // calculate sensible default width when no preference is available
229 if (av.getIdWidth() < 0)
231 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
232 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
233 r = calculateIdWidth(maxwidth);
234 av.setIdWidth(r.width);
239 r.width = av.getIdWidth();
246 * Calculate the width of the alignment labels based on the displayed names
247 * and any bounds on label width set in preferences.
250 * -1 or maximum width allowed for IdWidth
251 * @return Dimension giving the maximum width of the alignment label panel
252 * that should be used.
254 public Dimension calculateIdWidth(int maxwidth)
256 Container c = new Container();
258 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
259 Font.ITALIC, av.font.getSize()));
261 AlignmentI al = av.getAlignment();
266 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
268 SequenceI s = al.getSequenceAt(i);
270 id = s.getDisplayId(av.getShowJVSuffix());
272 if (fm.stringWidth(id) > idWidth)
274 idWidth = fm.stringWidth(id);
280 // Also check annotation label widths
283 if (al.getAlignmentAnnotation() != null)
285 fm = c.getFontMetrics(getAlabels().getFont());
287 while (i < al.getAlignmentAnnotation().length)
289 String label = al.getAlignmentAnnotation()[i].label;
291 if (fm.stringWidth(label) > idWidth)
293 idWidth = fm.stringWidth(label);
300 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
305 * Highlight the given results on the alignment.
308 public void highlightSearchResults(SearchResultsI results)
310 scrollToPosition(results);
311 getSeqPanel().seqCanvas.highlightSearchResults(results);
315 * Scroll the view to show the position of the highlighted region in results
316 * (if any) and redraw the overview
320 public boolean scrollToPosition(SearchResultsI results)
322 return scrollToPosition(results, 0, true, false);
326 * Scroll the view to show the position of the highlighted region in results
329 * @param searchResults
330 * @param redrawOverview
333 public boolean scrollToPosition(SearchResultsI searchResults,
334 boolean redrawOverview)
336 return scrollToPosition(searchResults, 0, redrawOverview, false);
340 * Scroll the view to show the position of the highlighted region in results
344 * @param verticalOffset
345 * if greater than zero, allows scrolling to a position below the
346 * first displayed sequence
347 * @param redrawOverview
348 * - when set, the overview will be recalculated (takes longer)
350 * if true, try to centre the search results horizontally in the view
351 * @return false if results were not found
353 public boolean scrollToPosition(SearchResultsI results,
354 int verticalOffset, boolean redrawOverview, boolean centre)
356 int startv, endv, starts, ends;
357 // TODO: properly locate search results in view when large numbers of hidden
358 // columns exist before highlighted region
359 // do we need to scroll the panel?
360 // TODO: tons of nullpointerexceptions raised here.
361 if (results != null && results.getSize() > 0 && av != null
362 && av.getAlignment() != null)
364 int seqIndex = av.getAlignment().findIndex(results);
369 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
371 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
379 // System.err.println(this.av.viewName + " Seq : " + seqIndex
380 // + " Scroll to " + start + "," + end);
383 * To centre results, scroll to positions half the visible width
384 * left/right of the start/end positions
388 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
389 start = Math.max(start - offset, 0);
390 end = end + offset - 1;
396 if (end == seq.getEnd())
400 if (av.hasHiddenColumns())
402 start = av.getColumnSelection().findColumnPosition(start);
403 end = av.getColumnSelection().findColumnPosition(end);
406 if (!av.getColumnSelection().isVisible(r[0]))
408 // don't scroll - position isn't visible
415 * allow for offset of target sequence (actually scroll to one above it)
417 seqIndex = Math.max(0, seqIndex - verticalOffset);
419 // System.out.println("start=" + start + ", end=" + end + ", startv="
420 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
421 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
422 if (!av.getWrapAlignment())
424 if ((startv = vpRanges.getStartRes()) >= start)
427 * Scroll left to make start of search results visible
429 // setScrollValues(start - 1, seqIndex); // plus one residue
430 setScrollValues(start, seqIndex);
432 else if ((endv = vpRanges.getEndRes()) <= end)
435 * Scroll right to make end of search results visible
437 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
438 setScrollValues(startv + end - endv, seqIndex);
440 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
443 * Scroll up to make start of search results visible
445 setScrollValues(vpRanges.getStartRes(), seqIndex);
447 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
450 * Scroll down to make end of search results visible
452 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
456 * Else results are already visible - no need to scroll
461 scrollToWrappedVisible(start);
464 if (redrawOverview && overviewPanel != null)
466 overviewPanel.setBoxPosition();
468 paintAlignment(redrawOverview);
472 void scrollToWrappedVisible(int res)
474 int cwidth = getSeqPanel().seqCanvas
475 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
476 if (res < vpRanges.getStartRes()
477 || res >= (vpRanges.getStartRes() + cwidth))
479 vscroll.setValue((res / cwidth));
487 * @return DOCUMENT ME!
489 public OverviewPanel getOverviewPanel()
491 return overviewPanel;
500 public void setOverviewPanel(OverviewPanel op)
508 * Hide or show annotation panel
511 public void setAnnotationVisible(boolean b)
513 if (!av.getWrapAlignment())
515 annotationSpaceFillerHolder.setVisible(b);
516 annotationScroller.setVisible(b);
522 * automatically adjust annotation panel height for new annotation whilst
523 * ensuring the alignment is still visible.
526 public void adjustAnnotationHeight()
528 // TODO: display vertical annotation scrollbar if necessary
529 // this is called after loading new annotation onto alignment
530 if (alignFrame.getHeight() == 0)
532 System.out.println("NEEDS FIXING");
534 validateAnnotationDimensions(true);
536 paintAlignment(true);
540 * calculate the annotation dimensions and refresh slider values accordingly.
541 * need to do repaints/notifys afterwards.
543 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
545 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
547 if (adjustPanelHeight)
549 int rowHeight = av.getCharHeight();
550 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
553 * Estimate available height in the AlignFrame for alignment +
554 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
555 * hscroll, status bar (as these are not laid out we can't inspect their
556 * actual heights). Insets gives frame borders.
558 int stuff = Platform.isAMac() ? 80 : 100;
559 Insets insets = alignFrame.getInsets();
560 int availableHeight = alignFrame.getHeight() - stuff - insets.top
564 * If not enough vertical space, maximize annotation height while keeping
565 * at least two rows of alignment visible
567 if (annotationHeight + alignmentHeight > availableHeight)
569 annotationHeight = Math.min(annotationHeight, availableHeight - 2
575 // maintain same window layout whilst updating sliders
576 annotationHeight = annotationScroller.getSize().height;
580 annotationScroller.setPreferredSize(new Dimension(annotationScroller
581 .getWidth(), annotationHeight));
583 Dimension e = idPanel.getSize();
584 alabels.setSize(new Dimension(e.width, annotationHeight));
586 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
587 annotationSpaceFillerHolder.getWidth(), annotationHeight));
588 annotationScroller.validate();
589 annotationScroller.addNotify();
593 * update alignment layout for viewport settings
598 public void updateLayout()
601 setAnnotationVisible(av.isShowAnnotation());
602 boolean wrap = av.getWrapAlignment();
603 vpRanges.setStartSeq(0);
604 scalePanelHolder.setVisible(!wrap);
605 hscroll.setVisible(!wrap);
606 idwidthAdjuster.setVisible(!wrap);
610 annotationScroller.setVisible(false);
611 annotationSpaceFillerHolder.setVisible(false);
613 else if (av.isShowAnnotation())
615 annotationScroller.setVisible(true);
616 annotationSpaceFillerHolder.setVisible(true);
619 idSpaceFillerPanel1.setVisible(!wrap);
624 // return value is true if the scroll is valid
625 public boolean scrollUp(boolean up)
629 if (vscroll.getValue() < 1)
635 vscroll.setValue(vscroll.getValue() - 1);
639 if ((vextent + vscroll.getValue()) >= av.getAlignment().getHeight())
645 vscroll.setValue(vscroll.getValue() + 1);
659 * @return DOCUMENT ME!
661 public boolean scrollRight(boolean right)
665 if (hscroll.getValue() < 1)
671 hscroll.setValue(hscroll.getValue() - 1);
675 if ((hextent + hscroll.getValue()) >= av.getAlignment().getWidth())
681 hscroll.setValue(hscroll.getValue() + 1);
690 * Adjust row/column scrollers to show a visible position in the alignment.
693 * visible column to scroll to
695 * visible row to scroll to
698 public void setScrollValues(int x, int y)
700 if (av == null || av.getAlignment() == null)
705 if (av.getWrapAlignment())
707 setScrollingForWrappedPanel(x);
712 int width = av.getAlignment().getWidth();
713 int height = av.getAlignment().getHeight();
715 if (av.hasHiddenColumns())
717 // reset the width to exclude hidden columns
718 width = av.getColumnSelection().findColumnPosition(width);
721 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
722 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
729 if (vextent > height)
734 if ((hextent + x) > width)
739 if ((vextent + y) > height)
741 y = height - vextent;
754 // update the scroll values
755 hscroll.setValues(x, hextent, 0, width);
756 vscroll.setValues(y, vextent, 0, height);
767 public void adjustmentValueChanged(AdjustmentEvent evt)
769 int oldX = vpRanges.getStartRes();
770 int oldY = vpRanges.getStartSeq();
772 if (av.getWrapAlignment())
774 if (evt.getSource() == hscroll)
776 return; // no horizontal scroll when wrapped
778 else if (evt.getSource() == vscroll)
780 int offy = vscroll.getValue();
781 int rowSize = getSeqPanel().seqCanvas
782 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
784 // if we're scrolling to the position we're already at, stop
785 // this prevents infinite recursion of events when the scroll/viewport
786 // ranges values are the same
787 if (offy * rowSize == oldX)
793 vpRanges.setStartEndRes(offy * rowSize, (offy + 1) * rowSize);
797 // This is only called if file loaded is a jar file that
798 // was wrapped when saved and user has wrap alignment true
799 // as preference setting
800 SwingUtilities.invokeLater(new Runnable()
805 setScrollValues(vpRanges.getStartRes(),
806 vpRanges.getStartSeq());
816 if (evt.getSource() == hscroll)
818 int x = hscroll.getValue();
820 // if we're scrolling to the position we're already at, stop
821 // this prevents infinite recursion of events when the scroll/viewport
822 // ranges values are the same
827 vpRanges.setStartEndRes(x,
828 (x + (getSeqPanel().seqCanvas.getWidth() / av
829 .getCharWidth())) - 1);
831 else if (evt.getSource() == vscroll)
833 int offy = vscroll.getValue();
835 // if we're scrolling to the position we're already at, stop
836 // this prevents infinite recursion of events when the scroll/viewport
837 // ranges values are the same
842 vpRanges.setStartEndSeq(
845 + (getSeqPanel().seqCanvas.getHeight() / av
846 .getCharHeight()) - 1);
856 * Repaint the alignment including the annotations and overview panels (if
860 public void paintAlignment(boolean updateOverview)
862 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
863 av.isShowAutocalculatedAbove());
864 sorter.sort(getAlignment().getAlignmentAnnotation(),
865 av.getSortAnnotationsBy());
870 // TODO: determine if this paintAlignment changed structure colours
871 av.getStructureSelectionManager().sequenceColoursChanged(this);
873 if (overviewPanel != null)
875 overviewPanel.updateOverviewImage();
887 public void paintComponent(Graphics g)
891 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
892 idPanelHolder.setPreferredSize(d);
893 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
897 * set scroll bar positions
899 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
903 * Set vertical scroll bar parameters for wrapped panel
905 * the residue to scroll to
907 private void setScrollingForWrappedPanel(int res)
909 // get the width of the alignment in residues
910 int maxwidth = av.getAlignment().getWidth();
911 if (av.hasHiddenColumns())
913 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
916 // get the width of the canvas in residues
917 int canvasWidth = getSeqPanel().seqCanvas
918 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
921 // position we want to scroll to is number of canvasWidth's to get there
922 int current = res / canvasWidth;
924 // max scroll position: add one because extent is 1 and scrollbar value
925 // can only be set to at most max - extent
926 int max = maxwidth / canvasWidth + 1;
927 vscroll.setUnitIncrement(1);
928 vscroll.setValues(current, 1, 0, max);
942 * @return DOCUMENT ME!
944 * @throws PrinterException
948 public int print(Graphics pg, PageFormat pf, int pi)
949 throws PrinterException
951 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
953 int pwidth = (int) pf.getImageableWidth();
954 int pheight = (int) pf.getImageableHeight();
956 if (av.getWrapAlignment())
958 return printWrappedAlignment(pwidth, pheight, pi, pg);
962 return printUnwrapped(pwidth, pheight, pi, pg, pg);
978 * @return DOCUMENT ME!
980 * @throws PrinterException
984 * Draws the alignment image, including sequence ids, sequences, and
985 * annotation labels and annotations if shown, on either one or two Graphics
992 * the graphics context for sequence ids and annotation labels
993 * @param alignmentGraphics
994 * the graphics context for sequences and annotations (may or may not
995 * be the same context as idGraphics)
997 * @throws PrinterException
999 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
1000 Graphics idGraphics, Graphics alignmentGraphics)
1001 throws PrinterException
1003 final int idWidth = getVisibleIdWidth(false);
1006 * Get the horizontal offset to where we draw the sequences.
1007 * This is idWidth if using a single Graphics context, else zero.
1009 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
1011 FontMetrics fm = getFontMetrics(av.getFont());
1012 int charHeight = av.getCharHeight();
1013 int scaleHeight = charHeight + fm.getDescent();
1015 idGraphics.setColor(Color.white);
1016 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1017 idGraphics.setFont(av.getFont());
1020 * How many sequences and residues can we fit on a printable page?
1022 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1024 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1026 int alignmentWidth = av.getAlignment().getWidth();
1027 int pagesWide = (alignmentWidth / totalRes) + 1;
1029 final int startRes = (pi % pagesWide) * totalRes;
1030 int endRes = (startRes + totalRes) - 1;
1032 if (endRes > (alignmentWidth - 1))
1034 endRes = alignmentWidth - 1;
1037 final int startSeq = (pi / pagesWide) * totalSeq;
1038 int endSeq = startSeq + totalSeq;
1040 int alignmentHeight = av.getAlignment().getHeight();
1041 if (endSeq > alignmentHeight)
1043 endSeq = alignmentHeight;
1046 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1049 if (av.isShowAnnotation())
1051 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1054 pagesHigh /= pageHeight;
1056 if (pi >= (pagesWide * pagesHigh))
1058 return Printable.NO_SUCH_PAGE;
1060 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1064 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1066 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1067 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1068 pageWidth - idWidth, scaleHeight);
1069 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1072 * Draw the sequence ids, offset for scale height,
1073 * then reset to top left (0, 0)
1075 idGraphics.translate(0, scaleHeight);
1076 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1077 Color currentColor = null;
1078 Color currentTextColor = null;
1081 for (int i = startSeq; i < endSeq; i++)
1083 seq = av.getAlignment().getSequenceAt(i);
1084 if ((av.getSelectionGroup() != null)
1085 && av.getSelectionGroup().getSequences(null).contains(seq))
1088 * gray out ids of sequences in selection group (if any)
1090 currentColor = Color.gray;
1091 currentTextColor = Color.black;
1095 currentColor = av.getSequenceColour(seq);
1096 currentTextColor = Color.black;
1099 idGraphics.setColor(currentColor);
1100 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1103 idGraphics.setColor(currentTextColor);
1106 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1107 if (av.isRightAlignIds())
1109 fm = idGraphics.getFontMetrics();
1111 - fm.stringWidth(displayId)
1115 idGraphics.drawString(displayId, xPos,
1116 (((i - startSeq) * charHeight) + charHeight)
1117 - (charHeight / 5));
1119 idGraphics.setFont(av.getFont());
1120 idGraphics.translate(0, -scaleHeight);
1123 * draw the sequences, offset for scale height, and id width (if using a
1124 * single graphics context), then reset to (0, scale height)
1126 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1127 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1128 startSeq, endSeq, 0);
1129 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1131 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1134 * draw annotation labels; drawComponent() translates by
1135 * getScrollOffset(), so compensate for that first;
1136 * then reset to (0, scale height)
1138 int offset = getAlabels().getScrollOffset();
1139 idGraphics.translate(0, -offset);
1140 idGraphics.translate(0, alignmentDrawnHeight);
1141 getAlabels().drawComponent(idGraphics, idWidth);
1142 idGraphics.translate(0, -alignmentDrawnHeight);
1145 * draw the annotations starting at
1146 * (idOffset, alignmentHeight) from (0, scaleHeight)
1148 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1149 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1150 alignmentGraphics, -1, startRes, endRes + 1);
1153 return Printable.PAGE_EXISTS;
1168 * @return DOCUMENT ME!
1170 * @throws PrinterException
1173 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1174 Graphics pg) throws PrinterException
1176 int annotationHeight = 0;
1177 AnnotationLabels labels = null;
1178 if (av.isShowAnnotation())
1180 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1181 labels = new AnnotationLabels(av);
1184 int hgap = av.getCharHeight();
1185 if (av.getScaleAboveWrapped())
1187 hgap += av.getCharHeight();
1190 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1193 int idWidth = getVisibleIdWidth(false);
1195 int maxwidth = av.getAlignment().getWidth();
1196 if (av.hasHiddenColumns())
1198 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1201 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1204 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1206 pg.setColor(Color.white);
1207 pg.fillRect(0, 0, pwidth, pheight);
1208 pg.setFont(av.getFont());
1212 pg.setColor(Color.black);
1214 pg.translate(0, -pi * pheight);
1216 pg.setClip(0, pi * pheight, pwidth, pheight);
1222 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1224 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1225 SequenceI s = av.getAlignment().getSequenceAt(i);
1226 String string = s.getDisplayId(av.getShowJVSuffix());
1228 if (av.isRightAlignIds())
1230 FontMetrics fm = pg.getFontMetrics();
1231 xPos = idWidth - fm.stringWidth(string) - 4;
1233 pg.drawString(string, xPos,
1234 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1235 - (av.getCharHeight() / 5));
1240 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1242 pg.setFont(av.getFont());
1243 labels.drawComponent(pg, idWidth);
1247 - (av.getAlignment().getHeight() * av
1252 } while (ypos < totalHeight);
1254 pg.translate(idWidth, 0);
1256 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1259 if ((pi * pheight) < totalHeight)
1261 return Printable.PAGE_EXISTS;
1266 return Printable.NO_SUCH_PAGE;
1271 * get current sequence ID panel width, or nominal value if panel were to be
1272 * displayed using default settings
1276 public int getVisibleIdWidth()
1278 return getVisibleIdWidth(true);
1282 * get current sequence ID panel width, or nominal value if panel were to be
1283 * displayed using default settings
1286 * indicate if the Id width for onscreen or offscreen display should
1290 public int getVisibleIdWidth(boolean onscreen)
1292 // see if rendering offscreen - check preferences and calc width accordingly
1293 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1295 return calculateIdWidth(-1).width + 4;
1297 Integer idwidth = null;
1299 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1301 int w = getIdPanel().getWidth();
1302 return (w > 0 ? w : calculateIdWidth().width + 4);
1304 return idwidth.intValue() + 4;
1307 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1309 int boarderBottomOffset = 5;
1310 long pSessionId = System.currentTimeMillis();
1311 headless = (System.getProperty("java.awt.headless") != null && System
1312 .getProperty("java.awt.headless").equals("true"));
1313 if (alignFrame != null && !headless)
1317 alignFrame.setProgressBar(MessageManager.formatMessage(
1318 "status.saving_file", new Object[] { type.getLabel() }),
1324 AlignmentDimension aDimension = getAlignmentDimension();
1327 jalview.util.ImageMaker im;
1328 final String imageAction, imageTitle;
1329 if (type == jalview.util.ImageMaker.TYPE.PNG)
1331 imageAction = "Create PNG image from alignment";
1334 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1336 imageAction = "Create EPS file from alignment";
1337 imageTitle = alignFrame.getTitle();
1341 imageAction = "Create SVG file from alignment";
1342 imageTitle = alignFrame.getTitle();
1345 im = new jalview.util.ImageMaker(this, type, imageAction,
1346 aDimension.getWidth(), aDimension.getHeight()
1347 + boarderBottomOffset, file, imageTitle,
1348 alignFrame, pSessionId, headless);
1349 Graphics graphics = im.getGraphics();
1350 if (av.getWrapAlignment())
1352 if (graphics != null)
1354 printWrappedAlignment(aDimension.getWidth(),
1355 aDimension.getHeight() + boarderBottomOffset, 0,
1362 if (graphics != null)
1364 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1365 0, graphics, graphics);
1370 } catch (OutOfMemoryError err)
1373 System.out.println("########################\n" + "OUT OF MEMORY "
1374 + file + "\n" + "########################");
1375 new OOMWarning("Creating Image for " + file, err);
1376 // System.out.println("Create IMAGE: " + err);
1377 } catch (Exception ex)
1379 ex.printStackTrace();
1387 public AlignmentDimension getAlignmentDimension()
1389 int maxwidth = av.getAlignment().getWidth();
1390 if (av.hasHiddenColumns())
1392 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1395 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1396 + getScalePanel().getHeight();
1397 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1399 if (av.getWrapAlignment())
1401 height = getWrappedHeight();
1404 // need to obtain default alignment width and then add in any
1405 // additional allowance for id margin
1406 // this duplicates the calculation in getWrappedHeight but adjusts for
1408 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1409 - alignFrame.getInsets().left
1410 - alignFrame.getInsets().right - getVisibleIdWidth()
1411 + getVisibleIdWidth(false);
1415 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1419 else if (av.isShowAnnotation())
1421 height += getAnnotationPanel().adjustPanelHeight() + 3;
1423 return new AlignmentDimension(width, height);
1430 public void makeEPS(File epsFile)
1432 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1438 public void makePNG(File pngFile)
1440 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1443 public void makeSVG(File svgFile)
1445 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1448 public void makePNGImageMap(File imgMapFile, String imageName)
1450 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1451 // ////////////////////////////////////////////
1452 int idWidth = getVisibleIdWidth(false);
1453 FontMetrics fm = getFontMetrics(av.getFont());
1454 int scaleHeight = av.getCharHeight() + fm.getDescent();
1457 // ////////////////////////////////
1458 if (imgMapFile != null)
1462 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1463 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1464 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1465 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1466 out.println("<img src=\"" + imageName
1467 + "\" border=\"0\" usemap=\"#Map\" >"
1468 + "<map name=\"Map\">");
1470 for (s = 0; s < sSize; s++)
1472 sy = s * av.getCharHeight() + scaleHeight;
1474 SequenceI seq = av.getAlignment().getSequenceAt(s);
1475 SequenceFeature[] features = seq.getSequenceFeatures();
1476 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1477 for (res = 0; res < alwidth; res++)
1479 StringBuilder text = new StringBuilder();
1480 String triplet = null;
1481 if (av.getAlignment().isNucleotide())
1483 triplet = ResidueProperties.nucleotideName.get(seq
1484 .getCharAt(res) + "");
1488 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1492 if (triplet == null)
1497 int alIndex = seq.findPosition(res);
1498 gSize = groups.length;
1499 for (g = 0; g < gSize; g++)
1501 if (text.length() < 1)
1503 text.append("<area shape=\"rect\" coords=\"")
1504 .append((idWidth + res * av.getCharWidth()))
1505 .append(",").append(sy).append(",")
1506 .append((idWidth + (res + 1) * av.getCharWidth()))
1507 .append(",").append((av.getCharHeight() + sy))
1508 .append("\"").append(" onMouseOver=\"toolTip('")
1509 .append(alIndex).append(" ").append(triplet);
1512 if (groups[g].getStartRes() < res
1513 && groups[g].getEndRes() > res)
1515 text.append("<br><em>").append(groups[g].getName())
1520 if (features != null)
1522 if (text.length() < 1)
1524 text.append("<area shape=\"rect\" coords=\"")
1525 .append((idWidth + res * av.getCharWidth()))
1526 .append(",").append(sy).append(",")
1527 .append((idWidth + (res + 1) * av.getCharWidth()))
1528 .append(",").append((av.getCharHeight() + sy))
1529 .append("\"").append(" onMouseOver=\"toolTip('")
1530 .append(alIndex).append(" ").append(triplet);
1532 fSize = features.length;
1533 for (f = 0; f < fSize; f++)
1536 if ((features[f].getBegin() <= seq.findPosition(res))
1537 && (features[f].getEnd() >= seq.findPosition(res)))
1539 if (features[f].isContactFeature())
1541 if (features[f].getBegin() == seq.findPosition(res)
1542 || features[f].getEnd() == seq
1545 text.append("<br>").append(features[f].getType())
1546 .append(" ").append(features[f].getBegin())
1547 .append(":").append(features[f].getEnd());
1552 text.append("<br>");
1553 text.append(features[f].getType());
1554 if (features[f].getDescription() != null
1555 && !features[f].getType().equals(
1556 features[f].getDescription()))
1558 text.append(" ").append(features[f].getDescription());
1561 if (features[f].getValue("status") != null)
1563 text.append(" (").append(features[f].getValue("status"))
1571 if (text.length() > 1)
1573 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1574 out.println(text.toString());
1578 out.println("</map></body></html>");
1581 } catch (Exception ex)
1583 ex.printStackTrace();
1585 } // /////////END OF IMAGE MAP
1589 int getWrappedHeight()
1591 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1593 if (System.getProperty("java.awt.headless") != null
1594 && System.getProperty("java.awt.headless").equals("true"))
1596 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1597 - vscroll.getPreferredSize().width
1598 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1601 int chunkWidth = getSeqPanel().seqCanvas
1602 .getWrappedCanvasWidth(seqPanelWidth);
1604 int hgap = av.getCharHeight();
1605 if (av.getScaleAboveWrapped())
1607 hgap += av.getCharHeight();
1610 int annotationHeight = 0;
1611 if (av.isShowAnnotation())
1613 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1616 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1619 int maxwidth = av.getAlignment().getWidth();
1620 if (av.hasHiddenColumns())
1622 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1625 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1631 * close the panel - deregisters all listeners and nulls any references to
1634 public void closePanel()
1636 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1637 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1638 PaintRefresher.RemoveComponent(this);
1641 * try to ensure references are nulled
1643 if (annotationPanel != null)
1645 annotationPanel.dispose();
1650 av.removePropertyChangeListener(propertyChangeListener);
1651 jalview.structure.StructureSelectionManager ssm = av
1652 .getStructureSelectionManager();
1653 ssm.removeStructureViewerListener(getSeqPanel(), null);
1654 ssm.removeSelectionListener(getSeqPanel());
1655 ssm.removeCommandListener(av);
1656 ssm.removeStructureViewerListener(getSeqPanel(), null);
1657 ssm.removeSelectionListener(getSeqPanel());
1663 if (Cache.log.isDebugEnabled())
1665 Cache.log.warn("Closing alignment panel which is already closed.");
1671 * hides or shows dynamic annotation rows based on groups and av state flags
1673 public void updateAnnotation()
1675 updateAnnotation(false, false);
1678 public void updateAnnotation(boolean applyGlobalSettings)
1680 updateAnnotation(applyGlobalSettings, false);
1683 public void updateAnnotation(boolean applyGlobalSettings,
1684 boolean preserveNewGroupSettings)
1686 av.updateGroupAnnotationSettings(applyGlobalSettings,
1687 preserveNewGroupSettings);
1688 adjustAnnotationHeight();
1692 public AlignmentI getAlignment()
1694 return av == null ? null : av.getAlignment();
1698 public String getViewName()
1704 * Make/Unmake this alignment panel the current input focus
1708 public void setSelected(boolean b)
1712 if (alignFrame.getSplitViewContainer() != null)
1715 * bring enclosing SplitFrame to front first if there is one
1717 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1719 alignFrame.setSelected(b);
1720 } catch (Exception ex)
1726 alignFrame.setDisplayedView(this);
1731 public StructureSelectionManager getStructureSelectionManager()
1733 return av.getStructureSelectionManager();
1737 public void raiseOOMWarning(String string, OutOfMemoryError error)
1739 new OOMWarning(string, error, this);
1743 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1746 return new FeatureRenderer(this);
1750 public jalview.api.FeatureRenderer getFeatureRenderer()
1752 return seqPanel.seqCanvas.getFeatureRenderer();
1755 public void updateFeatureRenderer(
1756 jalview.renderer.seqfeatures.FeatureRenderer fr)
1758 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1761 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1763 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1765 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1769 public ScalePanel getScalePanel()
1774 public void setScalePanel(ScalePanel scalePanel)
1776 this.scalePanel = scalePanel;
1779 public SeqPanel getSeqPanel()
1784 public void setSeqPanel(SeqPanel seqPanel)
1786 this.seqPanel = seqPanel;
1789 public AnnotationPanel getAnnotationPanel()
1791 return annotationPanel;
1794 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1796 this.annotationPanel = annotationPanel;
1799 public AnnotationLabels getAlabels()
1804 public void setAlabels(AnnotationLabels alabels)
1806 this.alabels = alabels;
1809 public IdPanel getIdPanel()
1814 public void setIdPanel(IdPanel idPanel)
1816 this.idPanel = idPanel;
1820 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1821 * The aim is to keep the two alignments 'lined up' on their centre columns.
1824 * holds mapped region(s) of this alignment that we are scrolling
1825 * 'to'; may be modified for sequence offset by this method
1826 * @param verticalOffset
1827 * the number of visible sequences to show above the mapped region
1829 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1832 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1833 * mapped), we can make the scroll-to location a sequence above the one
1836 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1837 List<SequenceI> seqs = av.getAlignment().getSequences();
1840 * This is like AlignmentI.findIndex(seq) but here we are matching the
1841 * dataset sequence not the aligned sequence
1843 boolean matched = false;
1844 for (SequenceI seq : seqs)
1846 if (mappedTo == seq.getDatasetSequence())
1854 return; // failsafe, shouldn't happen
1858 * Scroll to position but centring the target residue.
1860 scrollToPosition(sr, verticalOffset, true, true);
1864 * Set a flag to say do not scroll any (cDNA/protein) complement.
1868 protected void setDontScrollComplement(boolean b)
1870 this.dontScrollComplement = b;
1873 protected boolean isDontScrollComplement()
1875 return this.dontScrollComplement;
1881 * @adjustHeight if true, try to recalculate panel height for visible
1884 protected void refresh(boolean adjustHeight)
1886 validateAnnotationDimensions(adjustHeight);
1890 // sort, repaint, update overview
1891 paintAlignment(true);
1895 // lightweight repaint
1902 * Property change event fired when a change is made to the viewport ranges
1903 * object associated with this alignment panel's viewport
1905 public void propertyChange(PropertyChangeEvent evt)
1907 // update this panel's scroll values based on the new viewport ranges values
1908 int x = vpRanges.getStartRes();
1909 int y = vpRanges.getStartSeq();
1910 setScrollValues(x, y);
1912 // now update any complementary alignment (its viewport ranges object
1913 // is different so does not get automatically updated)
1914 av.scrollComplementaryAlignment();