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.ViewportListenerI;
40 import jalview.viewmodel.ViewportRanges;
42 import java.awt.BorderLayout;
43 import java.awt.Color;
44 import java.awt.Container;
45 import java.awt.Dimension;
47 import java.awt.FontMetrics;
48 import java.awt.Graphics;
49 import java.awt.Insets;
50 import java.awt.event.AdjustmentEvent;
51 import java.awt.event.AdjustmentListener;
52 import java.awt.event.ComponentAdapter;
53 import java.awt.event.ComponentEvent;
54 import java.awt.print.PageFormat;
55 import java.awt.print.Printable;
56 import java.awt.print.PrinterException;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
62 import java.util.List;
64 import javax.swing.SwingUtilities;
70 * @version $Revision: 1.161 $
72 public class AlignmentPanel extends GAlignmentPanel implements
73 AdjustmentListener, Printable, AlignmentViewPanel,
76 public AlignViewport av;
78 ViewportRanges vpRanges;
80 OverviewPanel overviewPanel;
82 private SeqPanel seqPanel;
84 private IdPanel idPanel;
86 private boolean headless;
88 IdwidthAdjuster idwidthAdjuster;
91 public AlignFrame alignFrame;
93 private ScalePanel scalePanel;
95 private AnnotationPanel annotationPanel;
97 private AnnotationLabels alabels;
99 // this value is set false when selection area being dragged
100 boolean fastPaint = true;
102 private int hextent = 0;
104 private int vextent = 0;
107 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
108 * false, suppresses invoking the same method recursively.
110 private boolean scrollComplementaryPanel = true;
112 private PropertyChangeListener propertyChangeListener;
114 private CalculationChooser calculationDialog;
117 * Creates a new AlignmentPanel object.
122 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 vpRanges = av.getRanges();
127 setSeqPanel(new SeqPanel(av, this));
128 setIdPanel(new IdPanel(av, this));
130 setScalePanel(new ScalePanel(av, this));
132 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
133 idwidthAdjuster = new IdwidthAdjuster(this);
134 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
136 setAnnotationPanel(new AnnotationPanel(this));
137 setAlabels(new AnnotationLabels(this));
139 annotationScroller.setViewportView(getAnnotationPanel());
140 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
142 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
143 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
145 setScrollValues(0, 0);
147 hscroll.addAdjustmentListener(this);
148 vscroll.addAdjustmentListener(this);
150 addComponentListener(new ComponentAdapter()
153 public void componentResized(ComponentEvent evt)
155 // reset the viewport ranges when the alignment panel is resized
156 // in particular, this initialises the end residue value when Jalview
158 if (av.getWrapAlignment())
160 int widthInRes = getSeqPanel().seqCanvas
161 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
162 vpRanges.setViewportWidth(widthInRes);
166 int widthInRes = getSeqPanel().seqCanvas.getWidth()
168 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
169 / av.getCharHeight();
171 vpRanges.setViewportWidth(widthInRes);
172 vpRanges.setViewportHeight(heightInSeq);
178 final AlignmentPanel ap = this;
179 propertyChangeListener = new PropertyChangeListener()
182 public void propertyChange(PropertyChangeEvent evt)
184 if (evt.getPropertyName().equals("alignment"))
186 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
191 av.addPropertyChangeListener(propertyChangeListener);
193 av.getRanges().addPropertyChangeListener(this);
195 adjustAnnotationHeight();
200 public AlignViewportI getAlignViewport()
205 public void alignmentChanged()
207 av.alignmentChanged(this);
209 if (getCalculationDialog() != null)
211 getCalculationDialog().validateCalcTypes();
214 alignFrame.updateEditMenuBar();
216 paintAlignment(true);
223 public void fontChanged()
225 // set idCanvas bufferedImage to null
226 // to prevent drawing old image
227 FontMetrics fm = getFontMetrics(av.getFont());
229 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
231 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
232 .getCharHeight() + fm.getDescent()));
234 getIdPanel().getIdCanvas().gg = null;
235 getSeqPanel().seqCanvas.img = null;
236 getAnnotationPanel().adjustPanelHeight();
238 Dimension d = calculateIdWidth();
240 d.setSize(d.width + 4, d.height);
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
244 if (this.alignFrame.getSplitViewContainer() != null)
246 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
253 * Calculate the width of the alignment labels based on the displayed names
254 * and any bounds on label width set in preferences.
256 * @return Dimension giving the maximum width of the alignment label panel
257 * that should be used.
259 public Dimension calculateIdWidth()
261 // calculate sensible default width when no preference is available
263 if (av.getIdWidth() < 0)
265 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
266 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
267 r = calculateIdWidth(maxwidth);
268 av.setIdWidth(r.width);
273 r.width = av.getIdWidth();
280 * Calculate the width of the alignment labels based on the displayed names
281 * and any bounds on label width set in preferences.
284 * -1 or maximum width allowed for IdWidth
285 * @return Dimension giving the maximum width of the alignment label panel
286 * that should be used.
288 public Dimension calculateIdWidth(int maxwidth)
290 Container c = new Container();
292 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
293 Font.ITALIC, av.font.getSize()));
295 AlignmentI al = av.getAlignment();
300 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
302 SequenceI s = al.getSequenceAt(i);
304 id = s.getDisplayId(av.getShowJVSuffix());
306 if (fm.stringWidth(id) > idWidth)
308 idWidth = fm.stringWidth(id);
314 // Also check annotation label widths
317 if (al.getAlignmentAnnotation() != null)
319 fm = c.getFontMetrics(getAlabels().getFont());
321 while (i < al.getAlignmentAnnotation().length)
323 String label = al.getAlignmentAnnotation()[i].label;
325 if (fm.stringWidth(label) > idWidth)
327 idWidth = fm.stringWidth(label);
334 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
339 * Highlight the given results on the alignment.
342 public void highlightSearchResults(SearchResultsI results)
344 scrollToPosition(results);
345 getSeqPanel().seqCanvas.highlightSearchResults(results);
349 * Scroll the view to show the position of the highlighted region in results
350 * (if any) and redraw the overview
354 public boolean scrollToPosition(SearchResultsI results)
356 return scrollToPosition(results, 0, true, false);
360 * Scroll the view to show the position of the highlighted region in results
363 * @param searchResults
364 * @param redrawOverview
367 public boolean scrollToPosition(SearchResultsI searchResults,
368 boolean redrawOverview)
370 return scrollToPosition(searchResults, 0, redrawOverview, false);
374 * Scroll the view to show the position of the highlighted region in results
378 * @param verticalOffset
379 * if greater than zero, allows scrolling to a position below the
380 * first displayed sequence
381 * @param redrawOverview
382 * - when set, the overview will be recalculated (takes longer)
384 * if true, try to centre the search results horizontally in the view
385 * @return false if results were not found
387 public boolean scrollToPosition(SearchResultsI results,
388 int verticalOffset, boolean redrawOverview, boolean centre)
390 int startv, endv, starts, ends;
391 // TODO: properly locate search results in view when large numbers of hidden
392 // columns exist before highlighted region
393 // do we need to scroll the panel?
394 // TODO: tons of nullpointerexceptions raised here.
395 if (results != null && results.getSize() > 0 && av != null
396 && av.getAlignment() != null)
398 int seqIndex = av.getAlignment().findIndex(results);
403 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
405 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
414 * To centre results, scroll to positions half the visible width
415 * left/right of the start/end positions
419 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2
421 start = Math.max(start - offset, 0);
422 end = end + offset - 1;
428 if (end == seq.getEnd())
432 if (av.hasHiddenColumns())
434 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
435 start = hidden.findColumnPosition(start);
436 end = hidden.findColumnPosition(end);
439 if (!hidden.isVisible(r[0]))
441 // don't scroll - position isn't visible
448 * allow for offset of target sequence (actually scroll to one above it)
450 seqIndex = Math.max(0, seqIndex - verticalOffset);
452 if (!av.getWrapAlignment())
454 if ((startv = vpRanges.getStartRes()) >= start)
457 * Scroll left to make start of search results visible
459 setScrollValues(start, seqIndex);
461 else if ((endv = vpRanges.getEndRes()) <= end)
464 * Scroll right to make end of search results visible
466 setScrollValues(startv + end - endv, seqIndex);
468 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
471 * Scroll up to make start of search results visible
473 setScrollValues(vpRanges.getStartRes(), seqIndex);
475 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
478 * Scroll down to make end of search results visible
480 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
484 * Else results are already visible - no need to scroll
489 vpRanges.scrollToWrappedVisible(start);
493 paintAlignment(redrawOverview);
500 * @return DOCUMENT ME!
502 public OverviewPanel getOverviewPanel()
504 return overviewPanel;
513 public void setOverviewPanel(OverviewPanel op)
521 * Hide or show annotation panel
524 public void setAnnotationVisible(boolean b)
526 if (!av.getWrapAlignment())
528 annotationSpaceFillerHolder.setVisible(b);
529 annotationScroller.setVisible(b);
535 * automatically adjust annotation panel height for new annotation whilst
536 * ensuring the alignment is still visible.
539 public void adjustAnnotationHeight()
541 // TODO: display vertical annotation scrollbar if necessary
542 // this is called after loading new annotation onto alignment
543 if (alignFrame.getHeight() == 0)
545 System.out.println("NEEDS FIXING");
547 validateAnnotationDimensions(true);
549 paintAlignment(true);
553 * calculate the annotation dimensions and refresh slider values accordingly.
554 * need to do repaints/notifys afterwards.
556 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
558 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
560 if (adjustPanelHeight)
562 int rowHeight = av.getCharHeight();
563 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
566 * Estimate available height in the AlignFrame for alignment +
567 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
568 * hscroll, status bar (as these are not laid out we can't inspect their
569 * actual heights). Insets gives frame borders.
571 int stuff = Platform.isAMac() ? 80 : 100;
572 Insets insets = alignFrame.getInsets();
573 int availableHeight = alignFrame.getHeight() - stuff - insets.top
577 * If not enough vertical space, maximize annotation height while keeping
578 * at least two rows of alignment visible
580 if (annotationHeight + alignmentHeight > availableHeight)
582 annotationHeight = Math.min(annotationHeight, availableHeight - 2
588 // maintain same window layout whilst updating sliders
589 annotationHeight = annotationScroller.getSize().height;
593 annotationScroller.setPreferredSize(new Dimension(annotationScroller
594 .getWidth(), annotationHeight));
596 Dimension e = idPanel.getSize();
597 alabels.setSize(new Dimension(e.width, annotationHeight));
599 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
600 annotationSpaceFillerHolder.getWidth(), annotationHeight));
601 annotationScroller.validate();
602 annotationScroller.addNotify();
606 * update alignment layout for viewport settings
611 public void updateLayout()
614 setAnnotationVisible(av.isShowAnnotation());
615 boolean wrap = av.getWrapAlignment();
616 vpRanges.setStartSeq(0);
617 scalePanelHolder.setVisible(!wrap);
618 hscroll.setVisible(!wrap);
619 idwidthAdjuster.setVisible(!wrap);
623 annotationScroller.setVisible(false);
624 annotationSpaceFillerHolder.setVisible(false);
626 else if (av.isShowAnnotation())
628 annotationScroller.setVisible(true);
629 annotationSpaceFillerHolder.setVisible(true);
634 int widthInRes = getSeqPanel().seqCanvas
635 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
636 vpRanges.setViewportWidth(widthInRes);
640 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
641 .getCharWidth()) - 1;
642 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
643 .getCharHeight()) - 1;
645 vpRanges.setViewportWidth(widthInRes);
646 vpRanges.setViewportHeight(heightInSeq);
649 idSpaceFillerPanel1.setVisible(!wrap);
656 * Adjust row/column scrollers to show a visible position in the alignment.
659 * visible column to scroll to
661 * visible row to scroll to
664 public void setScrollValues(int xpos, int ypos)
669 if (av == null || av.getAlignment() == null)
674 if (av.getWrapAlignment())
676 setScrollingForWrappedPanel(x);
680 int width = av.getAlignment().getWidth();
681 int height = av.getAlignment().getHeight();
683 if (av.hasHiddenColumns())
685 // reset the width to exclude hidden columns
686 width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
689 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
690 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
697 if (vextent > height)
702 if ((hextent + x) > width)
707 if ((vextent + y) > height)
709 y = height - vextent;
722 // update the scroll values
723 hscroll.setValues(x, hextent, 0, width);
724 vscroll.setValues(y, vextent, 0, height);
729 * Respond to adjustment event when horizontal or vertical scrollbar is
733 * adjustment event encoding whether hscroll or vscroll changed
736 public void adjustmentValueChanged(AdjustmentEvent evt)
738 int oldX = vpRanges.getStartRes();
739 int oldwidth = vpRanges.getViewportWidth();
740 int oldY = vpRanges.getStartSeq();
741 int oldheight = vpRanges.getViewportHeight();
743 if (av.getWrapAlignment())
745 if (evt.getSource() == hscroll)
747 return; // no horizontal scroll when wrapped
749 else if (evt.getSource() == vscroll)
751 int offy = vscroll.getValue();
752 int rowSize = getSeqPanel().seqCanvas
753 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
755 // if we're scrolling to the position we're already at, stop
756 // this prevents infinite recursion of events when the scroll/viewport
757 // ranges values are the same
758 int newX = offy * rowSize;
759 newX += oldX % rowSize; // horizontal scroll offset if any
760 if ((newX == oldX) && (oldwidth == rowSize))
766 // limit page up/down to one width's worth of positions
767 newX = newX > oldX ? oldX + rowSize : oldX - rowSize;
768 vpRanges.setViewportStartAndWidth(newX, rowSize);
773 // This is only called if file loaded is a jar file that
774 // was wrapped when saved and user has wrap alignment true
775 // as preference setting
776 SwingUtilities.invokeLater(new Runnable()
781 // When updating scrolling to use ViewportChange events, this code
782 // could not be validated and it is not clear if it is now being
783 // called. Log warning here in case it is called and unforeseen
786 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
788 // scroll to start of panel
789 vpRanges.setStartRes(0);
790 vpRanges.setStartSeq(0);
799 if (evt.getSource() == hscroll)
801 int x = hscroll.getValue();
802 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
804 // if we're scrolling to the position we're already at, stop
805 // this prevents infinite recursion of events when the scroll/viewport
806 // ranges values are the same
807 if ((x == oldX) && (width == oldwidth))
811 vpRanges.setViewportStartAndWidth(x, width);
813 else if (evt.getSource() == vscroll)
815 int y = vscroll.getValue();
816 int height = getSeqPanel().seqCanvas.getHeight()
817 / av.getCharHeight();
819 // if we're scrolling to the position we're already at, stop
820 // this prevents infinite recursion of events when the scroll/viewport
821 // ranges values are the same
822 if ((y == oldY) && (height == oldheight))
826 vpRanges.setViewportStartAndHeight(y, height);
836 * Repaint the alignment including the annotations and overview panels (if
840 public void paintAlignment(boolean updateOverview)
842 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
843 av.isShowAutocalculatedAbove());
844 sorter.sort(getAlignment().getAlignmentAnnotation(),
845 av.getSortAnnotationsBy());
850 // TODO: determine if this paintAlignment changed structure colours
851 av.getStructureSelectionManager().sequenceColoursChanged(this);
853 if (overviewPanel != null)
855 overviewPanel.updateOverviewImage();
867 public void paintComponent(Graphics g)
871 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
872 idPanelHolder.setPreferredSize(d);
873 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
877 * set scroll bar positions
879 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
883 * Set vertical scroll bar parameters for wrapped panel
885 * the residue to scroll to
887 private void setScrollingForWrappedPanel(int res)
889 // get the width of the alignment in residues
890 int maxwidth = av.getAlignment().getWidth();
891 if (av.hasHiddenColumns())
893 maxwidth = av.getAlignment().getHiddenColumns()
894 .findColumnPosition(maxwidth) - 1;
897 // get the width of the canvas in residues
898 int canvasWidth = getSeqPanel().seqCanvas
899 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
902 // position we want to scroll to is number of canvasWidth's to get there
903 int current = res / canvasWidth;
905 // max scroll position: add one because extent is 1 and scrollbar value
906 // can only be set to at most max - extent
907 int max = maxwidth / canvasWidth + 1;
908 vscroll.setUnitIncrement(1);
909 vscroll.setValues(current, 1, 0, max);
923 * @return DOCUMENT ME!
925 * @throws PrinterException
929 public int print(Graphics pg, PageFormat pf, int pi)
930 throws PrinterException
932 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
934 int pwidth = (int) pf.getImageableWidth();
935 int pheight = (int) pf.getImageableHeight();
937 if (av.getWrapAlignment())
939 return printWrappedAlignment(pwidth, pheight, pi, pg);
943 return printUnwrapped(pwidth, pheight, pi, pg, pg);
959 * @return DOCUMENT ME!
961 * @throws PrinterException
965 * Draws the alignment image, including sequence ids, sequences, and
966 * annotation labels and annotations if shown, on either one or two Graphics
973 * the graphics context for sequence ids and annotation labels
974 * @param alignmentGraphics
975 * the graphics context for sequences and annotations (may or may not
976 * be the same context as idGraphics)
978 * @throws PrinterException
980 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
981 Graphics idGraphics, Graphics alignmentGraphics)
982 throws PrinterException
984 final int idWidth = getVisibleIdWidth(false);
987 * Get the horizontal offset to where we draw the sequences.
988 * This is idWidth if using a single Graphics context, else zero.
990 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
992 FontMetrics fm = getFontMetrics(av.getFont());
993 int charHeight = av.getCharHeight();
994 int scaleHeight = charHeight + fm.getDescent();
996 idGraphics.setColor(Color.white);
997 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
998 idGraphics.setFont(av.getFont());
1001 * How many sequences and residues can we fit on a printable page?
1003 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1005 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1007 int alignmentWidth = av.getAlignment().getWidth();
1008 int pagesWide = (alignmentWidth / totalRes) + 1;
1010 final int startRes = (pi % pagesWide) * totalRes;
1011 int endRes = (startRes + totalRes) - 1;
1013 if (endRes > (alignmentWidth - 1))
1015 endRes = alignmentWidth - 1;
1018 final int startSeq = (pi / pagesWide) * totalSeq;
1019 int endSeq = startSeq + totalSeq;
1021 int alignmentHeight = av.getAlignment().getHeight();
1022 if (endSeq > alignmentHeight)
1024 endSeq = alignmentHeight;
1027 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1030 if (av.isShowAnnotation())
1032 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1035 pagesHigh /= pageHeight;
1037 if (pi >= (pagesWide * pagesHigh))
1039 return Printable.NO_SUCH_PAGE;
1041 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1045 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1047 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1048 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1049 pageWidth - idWidth, scaleHeight);
1050 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1053 * Draw the sequence ids, offset for scale height,
1054 * then reset to top left (0, 0)
1056 idGraphics.translate(0, scaleHeight);
1057 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1058 Color currentColor = null;
1059 Color currentTextColor = null;
1062 for (int i = startSeq; i < endSeq; i++)
1064 seq = av.getAlignment().getSequenceAt(i);
1065 if ((av.getSelectionGroup() != null)
1066 && av.getSelectionGroup().getSequences(null).contains(seq))
1069 * gray out ids of sequences in selection group (if any)
1071 currentColor = Color.gray;
1072 currentTextColor = Color.black;
1076 currentColor = av.getSequenceColour(seq);
1077 currentTextColor = Color.black;
1080 idGraphics.setColor(currentColor);
1081 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1084 idGraphics.setColor(currentTextColor);
1087 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1088 if (av.isRightAlignIds())
1090 fm = idGraphics.getFontMetrics();
1092 - fm.stringWidth(displayId)
1096 idGraphics.drawString(displayId, xPos,
1097 (((i - startSeq) * charHeight) + charHeight)
1098 - (charHeight / 5));
1100 idGraphics.setFont(av.getFont());
1101 idGraphics.translate(0, -scaleHeight);
1104 * draw the sequences, offset for scale height, and id width (if using a
1105 * single graphics context), then reset to (0, scale height)
1107 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1108 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1109 startSeq, endSeq, 0);
1110 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1112 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1115 * draw annotation labels; drawComponent() translates by
1116 * getScrollOffset(), so compensate for that first;
1117 * then reset to (0, scale height)
1119 int offset = getAlabels().getScrollOffset();
1120 idGraphics.translate(0, -offset);
1121 idGraphics.translate(0, alignmentDrawnHeight);
1122 getAlabels().drawComponent(idGraphics, idWidth);
1123 idGraphics.translate(0, -alignmentDrawnHeight);
1126 * draw the annotations starting at
1127 * (idOffset, alignmentHeight) from (0, scaleHeight)
1129 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1130 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1131 alignmentGraphics, -1, startRes, endRes + 1);
1134 return Printable.PAGE_EXISTS;
1149 * @return DOCUMENT ME!
1151 * @throws PrinterException
1154 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1155 Graphics pg) throws PrinterException
1157 int annotationHeight = 0;
1158 AnnotationLabels labels = null;
1159 if (av.isShowAnnotation())
1161 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1162 labels = new AnnotationLabels(av);
1165 int hgap = av.getCharHeight();
1166 if (av.getScaleAboveWrapped())
1168 hgap += av.getCharHeight();
1171 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1174 int idWidth = getVisibleIdWidth(false);
1176 int maxwidth = av.getAlignment().getWidth();
1177 if (av.hasHiddenColumns())
1179 maxwidth = av.getAlignment().getHiddenColumns()
1180 .findColumnPosition(maxwidth) - 1;
1183 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1186 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1188 pg.setColor(Color.white);
1189 pg.fillRect(0, 0, pwidth, pheight);
1190 pg.setFont(av.getFont());
1194 pg.setColor(Color.black);
1196 pg.translate(0, -pi * pheight);
1198 pg.setClip(0, pi * pheight, pwidth, pheight);
1204 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1206 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1207 SequenceI s = av.getAlignment().getSequenceAt(i);
1208 String string = s.getDisplayId(av.getShowJVSuffix());
1210 if (av.isRightAlignIds())
1212 FontMetrics fm = pg.getFontMetrics();
1213 xPos = idWidth - fm.stringWidth(string) - 4;
1215 pg.drawString(string, xPos,
1216 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1217 - (av.getCharHeight() / 5));
1222 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1224 pg.setFont(av.getFont());
1225 labels.drawComponent(pg, idWidth);
1229 - (av.getAlignment().getHeight() * av
1234 } while (ypos < totalHeight);
1236 pg.translate(idWidth, 0);
1238 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1241 if ((pi * pheight) < totalHeight)
1243 return Printable.PAGE_EXISTS;
1248 return Printable.NO_SUCH_PAGE;
1253 * get current sequence ID panel width, or nominal value if panel were to be
1254 * displayed using default settings
1258 public int getVisibleIdWidth()
1260 return getVisibleIdWidth(true);
1264 * get current sequence ID panel width, or nominal value if panel were to be
1265 * displayed using default settings
1268 * indicate if the Id width for onscreen or offscreen display should
1272 public int getVisibleIdWidth(boolean onscreen)
1274 // see if rendering offscreen - check preferences and calc width accordingly
1275 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1277 return calculateIdWidth(-1).width + 4;
1279 Integer idwidth = null;
1281 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1283 int w = getIdPanel().getWidth();
1284 return (w > 0 ? w : calculateIdWidth().width + 4);
1286 return idwidth.intValue() + 4;
1289 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1291 int boarderBottomOffset = 5;
1292 long pSessionId = System.currentTimeMillis();
1293 headless = (System.getProperty("java.awt.headless") != null && System
1294 .getProperty("java.awt.headless").equals("true"));
1295 if (alignFrame != null && !headless)
1299 alignFrame.setProgressBar(MessageManager.formatMessage(
1300 "status.saving_file", new Object[] { type.getLabel() }),
1306 AlignmentDimension aDimension = getAlignmentDimension();
1309 jalview.util.ImageMaker im;
1310 final String imageAction, imageTitle;
1311 if (type == jalview.util.ImageMaker.TYPE.PNG)
1313 imageAction = "Create PNG image from alignment";
1316 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1318 imageAction = "Create EPS file from alignment";
1319 imageTitle = alignFrame.getTitle();
1323 imageAction = "Create SVG file from alignment";
1324 imageTitle = alignFrame.getTitle();
1327 im = new jalview.util.ImageMaker(this, type, imageAction,
1328 aDimension.getWidth(), aDimension.getHeight()
1329 + boarderBottomOffset, file, imageTitle,
1330 alignFrame, pSessionId, headless);
1331 Graphics graphics = im.getGraphics();
1332 if (av.getWrapAlignment())
1334 if (graphics != null)
1336 printWrappedAlignment(aDimension.getWidth(),
1337 aDimension.getHeight() + boarderBottomOffset, 0,
1344 if (graphics != null)
1346 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1347 0, graphics, graphics);
1352 } catch (OutOfMemoryError err)
1355 System.out.println("########################\n" + "OUT OF MEMORY "
1356 + file + "\n" + "########################");
1357 new OOMWarning("Creating Image for " + file, err);
1358 // System.out.println("Create IMAGE: " + err);
1359 } catch (Exception ex)
1361 ex.printStackTrace();
1369 public AlignmentDimension getAlignmentDimension()
1371 int maxwidth = av.getAlignment().getWidth();
1372 if (av.hasHiddenColumns())
1374 maxwidth = av.getAlignment().getHiddenColumns()
1375 .findColumnPosition(maxwidth);
1378 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1379 + getScalePanel().getHeight();
1380 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1382 if (av.getWrapAlignment())
1384 height = getWrappedHeight();
1387 // need to obtain default alignment width and then add in any
1388 // additional allowance for id margin
1389 // this duplicates the calculation in getWrappedHeight but adjusts for
1391 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1392 - alignFrame.getInsets().left
1393 - alignFrame.getInsets().right - getVisibleIdWidth()
1394 + getVisibleIdWidth(false);
1398 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1402 else if (av.isShowAnnotation())
1404 height += getAnnotationPanel().adjustPanelHeight() + 3;
1406 return new AlignmentDimension(width, height);
1413 public void makeEPS(File epsFile)
1415 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1421 public void makePNG(File pngFile)
1423 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1426 public void makeSVG(File svgFile)
1428 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1431 public void makePNGImageMap(File imgMapFile, String imageName)
1433 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1434 // ////////////////////////////////////////////
1435 int idWidth = getVisibleIdWidth(false);
1436 FontMetrics fm = getFontMetrics(av.getFont());
1437 int scaleHeight = av.getCharHeight() + fm.getDescent();
1440 // ////////////////////////////////
1441 if (imgMapFile != null)
1445 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1446 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1447 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1448 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1449 out.println("<img src=\"" + imageName
1450 + "\" border=\"0\" usemap=\"#Map\" >"
1451 + "<map name=\"Map\">");
1453 for (s = 0; s < sSize; s++)
1455 sy = s * av.getCharHeight() + scaleHeight;
1457 SequenceI seq = av.getAlignment().getSequenceAt(s);
1458 SequenceFeature[] features = seq.getSequenceFeatures();
1459 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1460 for (res = 0; res < alwidth; res++)
1462 StringBuilder text = new StringBuilder();
1463 String triplet = null;
1464 if (av.getAlignment().isNucleotide())
1466 triplet = ResidueProperties.nucleotideName.get(seq
1467 .getCharAt(res) + "");
1471 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1475 if (triplet == null)
1480 int alIndex = seq.findPosition(res);
1481 gSize = groups.length;
1482 for (g = 0; g < gSize; g++)
1484 if (text.length() < 1)
1486 text.append("<area shape=\"rect\" coords=\"")
1487 .append((idWidth + res * av.getCharWidth()))
1488 .append(",").append(sy).append(",")
1489 .append((idWidth + (res + 1) * av.getCharWidth()))
1490 .append(",").append((av.getCharHeight() + sy))
1491 .append("\"").append(" onMouseOver=\"toolTip('")
1492 .append(alIndex).append(" ").append(triplet);
1495 if (groups[g].getStartRes() < res
1496 && groups[g].getEndRes() > res)
1498 text.append("<br><em>").append(groups[g].getName())
1503 if (features != null)
1505 if (text.length() < 1)
1507 text.append("<area shape=\"rect\" coords=\"")
1508 .append((idWidth + res * av.getCharWidth()))
1509 .append(",").append(sy).append(",")
1510 .append((idWidth + (res + 1) * av.getCharWidth()))
1511 .append(",").append((av.getCharHeight() + sy))
1512 .append("\"").append(" onMouseOver=\"toolTip('")
1513 .append(alIndex).append(" ").append(triplet);
1515 fSize = features.length;
1516 for (f = 0; f < fSize; f++)
1519 if ((features[f].getBegin() <= seq.findPosition(res))
1520 && (features[f].getEnd() >= seq.findPosition(res)))
1522 if (features[f].isContactFeature())
1524 if (features[f].getBegin() == seq.findPosition(res)
1525 || features[f].getEnd() == seq
1528 text.append("<br>").append(features[f].getType())
1529 .append(" ").append(features[f].getBegin())
1530 .append(":").append(features[f].getEnd());
1535 text.append("<br>");
1536 text.append(features[f].getType());
1537 if (features[f].getDescription() != null
1538 && !features[f].getType().equals(
1539 features[f].getDescription()))
1541 text.append(" ").append(features[f].getDescription());
1544 if (features[f].getValue("status") != null)
1546 text.append(" (").append(features[f].getValue("status"))
1554 if (text.length() > 1)
1556 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1557 out.println(text.toString());
1561 out.println("</map></body></html>");
1564 } catch (Exception ex)
1566 ex.printStackTrace();
1568 } // /////////END OF IMAGE MAP
1572 int getWrappedHeight()
1574 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1576 if (System.getProperty("java.awt.headless") != null
1577 && System.getProperty("java.awt.headless").equals("true"))
1579 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1580 - vscroll.getPreferredSize().width
1581 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1584 int chunkWidth = getSeqPanel().seqCanvas
1585 .getWrappedCanvasWidth(seqPanelWidth);
1587 int hgap = av.getCharHeight();
1588 if (av.getScaleAboveWrapped())
1590 hgap += av.getCharHeight();
1593 int annotationHeight = 0;
1594 if (av.isShowAnnotation())
1596 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1599 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1602 int maxwidth = av.getAlignment().getWidth();
1603 if (av.hasHiddenColumns())
1605 maxwidth = av.getAlignment().getHiddenColumns()
1606 .findColumnPosition(maxwidth) - 1;
1609 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1615 * close the panel - deregisters all listeners and nulls any references to
1618 public void closePanel()
1620 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1621 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1622 PaintRefresher.RemoveComponent(this);
1627 * try to ensure references are nulled
1629 if (annotationPanel != null)
1631 annotationPanel.dispose();
1636 av.removePropertyChangeListener(propertyChangeListener);
1637 jalview.structure.StructureSelectionManager ssm = av
1638 .getStructureSelectionManager();
1639 ssm.removeStructureViewerListener(getSeqPanel(), null);
1640 ssm.removeSelectionListener(getSeqPanel());
1641 ssm.removeCommandListener(av);
1642 ssm.removeStructureViewerListener(getSeqPanel(), null);
1643 ssm.removeSelectionListener(getSeqPanel());
1649 if (Cache.log.isDebugEnabled())
1651 Cache.log.warn("Closing alignment panel which is already closed.");
1657 * Close any open dialogs that would be orphaned when this one is closed
1659 protected void closeChildFrames()
1661 if (calculationDialog != null)
1663 calculationDialog.closeFrame();
1668 * hides or shows dynamic annotation rows based on groups and av state flags
1670 public void updateAnnotation()
1672 updateAnnotation(false, false);
1675 public void updateAnnotation(boolean applyGlobalSettings)
1677 updateAnnotation(applyGlobalSettings, false);
1680 public void updateAnnotation(boolean applyGlobalSettings,
1681 boolean preserveNewGroupSettings)
1683 av.updateGroupAnnotationSettings(applyGlobalSettings,
1684 preserveNewGroupSettings);
1685 adjustAnnotationHeight();
1689 public AlignmentI getAlignment()
1691 return av == null ? null : av.getAlignment();
1695 public String getViewName()
1701 * Make/Unmake this alignment panel the current input focus
1705 public void setSelected(boolean b)
1709 if (alignFrame.getSplitViewContainer() != null)
1712 * bring enclosing SplitFrame to front first if there is one
1714 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1716 alignFrame.setSelected(b);
1717 } catch (Exception ex)
1723 alignFrame.setDisplayedView(this);
1728 public StructureSelectionManager getStructureSelectionManager()
1730 return av.getStructureSelectionManager();
1734 public void raiseOOMWarning(String string, OutOfMemoryError error)
1736 new OOMWarning(string, error, this);
1740 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1743 return new FeatureRenderer(this);
1747 public jalview.api.FeatureRenderer getFeatureRenderer()
1749 return seqPanel.seqCanvas.getFeatureRenderer();
1752 public void updateFeatureRenderer(
1753 jalview.renderer.seqfeatures.FeatureRenderer fr)
1755 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1758 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1760 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1762 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1766 public ScalePanel getScalePanel()
1771 public void setScalePanel(ScalePanel scalePanel)
1773 this.scalePanel = scalePanel;
1776 public SeqPanel getSeqPanel()
1781 public void setSeqPanel(SeqPanel seqPanel)
1783 this.seqPanel = seqPanel;
1786 public AnnotationPanel getAnnotationPanel()
1788 return annotationPanel;
1791 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1793 this.annotationPanel = annotationPanel;
1796 public AnnotationLabels getAlabels()
1801 public void setAlabels(AnnotationLabels alabels)
1803 this.alabels = alabels;
1806 public IdPanel getIdPanel()
1811 public void setIdPanel(IdPanel idPanel)
1813 this.idPanel = idPanel;
1817 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1818 * The aim is to keep the two alignments 'lined up' on their centre columns.
1821 * holds mapped region(s) of this alignment that we are scrolling
1822 * 'to'; may be modified for sequence offset by this method
1823 * @param verticalOffset
1824 * the number of visible sequences to show above the mapped region
1826 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1829 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1830 * mapped), we can make the scroll-to location a sequence above the one
1833 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1834 List<SequenceI> seqs = av.getAlignment().getSequences();
1837 * This is like AlignmentI.findIndex(seq) but here we are matching the
1838 * dataset sequence not the aligned sequence
1840 boolean matched = false;
1841 for (SequenceI seq : seqs)
1843 if (mappedTo == seq.getDatasetSequence())
1851 return; // failsafe, shouldn't happen
1855 * Scroll to position but centring the target residue.
1857 scrollToPosition(sr, verticalOffset, true, true);
1861 * Set a flag to say do not scroll any (cDNA/protein) complement.
1865 protected void setToScrollComplementPanel(boolean b)
1867 this.scrollComplementaryPanel = b;
1871 * Get whether to scroll complement panel
1873 * @return true if cDNA/protein complement panels should be scrolled
1875 protected boolean isSetToScrollComplementPanel()
1877 return this.scrollComplementaryPanel;
1883 * @adjustHeight if true, try to recalculate panel height for visible
1886 protected void refresh(boolean adjustHeight)
1888 validateAnnotationDimensions(adjustHeight);
1892 // sort, repaint, update overview
1893 paintAlignment(true);
1897 // lightweight repaint
1904 * Property change event fired when a change is made to the viewport ranges
1905 * object associated with this alignment panel's viewport
1907 public void propertyChange(PropertyChangeEvent evt)
1909 // update this panel's scroll values based on the new viewport ranges values
1910 int x = vpRanges.getStartRes();
1911 int y = vpRanges.getStartSeq();
1912 setScrollValues(x, y);
1914 // now update any complementary alignment (its viewport ranges object
1915 // is different so does not get automatically updated)
1916 if (isSetToScrollComplementPanel())
1918 setToScrollComplementPanel(false);
1919 av.scrollComplementaryAlignment();
1920 setToScrollComplementPanel(true);
1925 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1926 * reference should be nulled when the dialog is closed.
1928 * @param calculationChooser
1930 public void setCalculationDialog(CalculationChooser calculationChooser)
1932 calculationDialog = calculationChooser;
1936 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1939 public CalculationChooser getCalculationDialog()
1941 return calculationDialog;