2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportListenerI;
39 import jalview.viewmodel.ViewportRanges;
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.ComponentAdapter;
52 import java.awt.event.ComponentEvent;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.beans.PropertyChangeEvent;
57 import java.beans.PropertyChangeListener;
59 import java.io.FileWriter;
60 import java.io.PrintWriter;
61 import java.util.List;
63 import javax.swing.SwingUtilities;
69 * @version $Revision: 1.161 $
71 public class AlignmentPanel extends GAlignmentPanel implements
72 AdjustmentListener, Printable, AlignmentViewPanel,
75 public AlignViewport av;
77 ViewportRanges vpRanges;
79 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 // this value is set false when selection area being dragged
99 boolean fastPaint = true;
101 private int hextent = 0;
103 private int vextent = 0;
106 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107 * false, suppresses invoking the same method recursively.
109 private boolean scrollComplementaryPanel = true;
111 private PropertyChangeListener propertyChangeListener;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
123 vpRanges = av.getRanges();
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 addComponentListener(new ComponentAdapter()
150 public void componentResized(ComponentEvent evt)
152 // reset the viewport ranges when the alignment panel is resized
153 // in particular, this initialises the end residue value when Jalview
155 if (av.getWrapAlignment())
157 int widthInRes = getSeqPanel().seqCanvas
158 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
159 vpRanges.setViewportWidth(widthInRes);
163 int widthInRes = getSeqPanel().seqCanvas.getWidth()
165 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
166 / av.getCharHeight();
168 vpRanges.setViewportWidth(widthInRes);
169 vpRanges.setViewportHeight(heightInSeq);
175 final AlignmentPanel ap = this;
176 propertyChangeListener = new PropertyChangeListener()
179 public void propertyChange(PropertyChangeEvent evt)
181 if (evt.getPropertyName().equals("alignment"))
183 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
188 av.addPropertyChangeListener(propertyChangeListener);
190 av.getRanges().addPropertyChangeListener(this);
192 adjustAnnotationHeight();
197 public AlignViewportI getAlignViewport()
202 public void alignmentChanged()
204 av.alignmentChanged(this);
206 alignFrame.updateEditMenuBar();
208 paintAlignment(true);
215 public void fontChanged()
217 // set idCanvas bufferedImage to null
218 // to prevent drawing old image
219 FontMetrics fm = getFontMetrics(av.getFont());
221 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
223 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
224 .getCharHeight() + fm.getDescent()));
226 getIdPanel().getIdCanvas().gg = null;
227 getSeqPanel().seqCanvas.img = null;
228 getAnnotationPanel().adjustPanelHeight();
230 Dimension d = calculateIdWidth();
232 d.setSize(d.width + 4, d.height);
233 getIdPanel().getIdCanvas().setPreferredSize(d);
234 hscrollFillerPanel.setPreferredSize(d);
236 if (this.alignFrame.getSplitViewContainer() != null)
238 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
245 * Calculate the width of the alignment labels based on the displayed names
246 * and any bounds on label width set in preferences.
248 * @return Dimension giving the maximum width of the alignment label panel
249 * that should be used.
251 public Dimension calculateIdWidth()
253 // calculate sensible default width when no preference is available
255 if (av.getIdWidth() < 0)
257 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
258 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
259 r = calculateIdWidth(maxwidth);
260 av.setIdWidth(r.width);
265 r.width = av.getIdWidth();
272 * Calculate the width of the alignment labels based on the displayed names
273 * and any bounds on label width set in preferences.
276 * -1 or maximum width allowed for IdWidth
277 * @return Dimension giving the maximum width of the alignment label panel
278 * that should be used.
280 public Dimension calculateIdWidth(int maxwidth)
282 Container c = new Container();
284 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
285 Font.ITALIC, av.font.getSize()));
287 AlignmentI al = av.getAlignment();
292 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
294 SequenceI s = al.getSequenceAt(i);
296 id = s.getDisplayId(av.getShowJVSuffix());
298 if (fm.stringWidth(id) > idWidth)
300 idWidth = fm.stringWidth(id);
306 // Also check annotation label widths
309 if (al.getAlignmentAnnotation() != null)
311 fm = c.getFontMetrics(getAlabels().getFont());
313 while (i < al.getAlignmentAnnotation().length)
315 String label = al.getAlignmentAnnotation()[i].label;
317 if (fm.stringWidth(label) > idWidth)
319 idWidth = fm.stringWidth(label);
326 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
331 * Highlight the given results on the alignment.
334 public void highlightSearchResults(SearchResultsI results)
336 scrollToPosition(results);
337 getSeqPanel().seqCanvas.highlightSearchResults(results);
341 * Scroll the view to show the position of the highlighted region in results
342 * (if any) and redraw the overview
346 public boolean scrollToPosition(SearchResultsI results)
348 return scrollToPosition(results, 0, true, false);
352 * Scroll the view to show the position of the highlighted region in results
355 * @param searchResults
356 * @param redrawOverview
359 public boolean scrollToPosition(SearchResultsI searchResults,
360 boolean redrawOverview)
362 return scrollToPosition(searchResults, 0, redrawOverview, false);
366 * Scroll the view to show the position of the highlighted region in results
370 * @param verticalOffset
371 * if greater than zero, allows scrolling to a position below the
372 * first displayed sequence
373 * @param redrawOverview
374 * - when set, the overview will be recalculated (takes longer)
376 * if true, try to centre the search results horizontally in the view
377 * @return false if results were not found
379 public boolean scrollToPosition(SearchResultsI results,
380 int verticalOffset, boolean redrawOverview, boolean centre)
382 int startv, endv, starts, ends;
383 // TODO: properly locate search results in view when large numbers of hidden
384 // columns exist before highlighted region
385 // do we need to scroll the panel?
386 // TODO: tons of nullpointerexceptions raised here.
387 if (results != null && results.getSize() > 0 && av != null
388 && av.getAlignment() != null)
390 int seqIndex = av.getAlignment().findIndex(results);
395 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
397 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
406 * To centre results, scroll to positions half the visible width
407 * left/right of the start/end positions
411 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
412 start = Math.max(start - offset, 0);
413 end = end + offset - 1;
419 if (end == seq.getEnd())
423 if (av.hasHiddenColumns())
425 start = av.getColumnSelection().findColumnPosition(start);
426 end = av.getColumnSelection().findColumnPosition(end);
429 if (!av.getColumnSelection().isVisible(r[0]))
431 // don't scroll - position isn't visible
438 * allow for offset of target sequence (actually scroll to one above it)
440 seqIndex = Math.max(0, seqIndex - verticalOffset);
442 if (!av.getWrapAlignment())
444 if ((startv = vpRanges.getStartRes()) >= start)
447 * Scroll left to make start of search results visible
449 setScrollValues(start, seqIndex);
451 else if ((endv = vpRanges.getEndRes()) <= end)
454 * Scroll right to make end of search results visible
456 setScrollValues(startv + end - endv, seqIndex);
458 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
461 * Scroll up to make start of search results visible
463 setScrollValues(vpRanges.getStartRes(), seqIndex);
465 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
468 * Scroll down to make end of search results visible
470 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
474 * Else results are already visible - no need to scroll
479 vpRanges.scrollToWrappedVisible(start);
483 paintAlignment(redrawOverview);
490 * @return DOCUMENT ME!
492 public OverviewPanel getOverviewPanel()
494 return overviewPanel;
503 public void setOverviewPanel(OverviewPanel op)
511 * Hide or show annotation panel
514 public void setAnnotationVisible(boolean b)
516 if (!av.getWrapAlignment())
518 annotationSpaceFillerHolder.setVisible(b);
519 annotationScroller.setVisible(b);
525 * automatically adjust annotation panel height for new annotation whilst
526 * ensuring the alignment is still visible.
529 public void adjustAnnotationHeight()
531 // TODO: display vertical annotation scrollbar if necessary
532 // this is called after loading new annotation onto alignment
533 if (alignFrame.getHeight() == 0)
535 System.out.println("NEEDS FIXING");
537 validateAnnotationDimensions(true);
539 paintAlignment(true);
543 * calculate the annotation dimensions and refresh slider values accordingly.
544 * need to do repaints/notifys afterwards.
546 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
548 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
550 if (adjustPanelHeight)
552 int rowHeight = av.getCharHeight();
553 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
556 * Estimate available height in the AlignFrame for alignment +
557 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
558 * hscroll, status bar (as these are not laid out we can't inspect their
559 * actual heights). Insets gives frame borders.
561 int stuff = Platform.isAMac() ? 80 : 100;
562 Insets insets = alignFrame.getInsets();
563 int availableHeight = alignFrame.getHeight() - stuff - insets.top
567 * If not enough vertical space, maximize annotation height while keeping
568 * at least two rows of alignment visible
570 if (annotationHeight + alignmentHeight > availableHeight)
572 annotationHeight = Math.min(annotationHeight, availableHeight - 2
578 // maintain same window layout whilst updating sliders
579 annotationHeight = annotationScroller.getSize().height;
583 annotationScroller.setPreferredSize(new Dimension(annotationScroller
584 .getWidth(), annotationHeight));
586 Dimension e = idPanel.getSize();
587 alabels.setSize(new Dimension(e.width, annotationHeight));
589 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
590 annotationSpaceFillerHolder.getWidth(), annotationHeight));
591 annotationScroller.validate();
592 annotationScroller.addNotify();
596 * update alignment layout for viewport settings
601 public void updateLayout()
604 setAnnotationVisible(av.isShowAnnotation());
605 boolean wrap = av.getWrapAlignment();
606 vpRanges.setStartSeq(0);
607 scalePanelHolder.setVisible(!wrap);
608 hscroll.setVisible(!wrap);
609 idwidthAdjuster.setVisible(!wrap);
613 annotationScroller.setVisible(false);
614 annotationSpaceFillerHolder.setVisible(false);
616 else if (av.isShowAnnotation())
618 annotationScroller.setVisible(true);
619 annotationSpaceFillerHolder.setVisible(true);
624 int widthInRes = getSeqPanel().seqCanvas
625 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
626 vpRanges.setViewportWidth(widthInRes);
630 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
631 .getCharWidth()) - 1;
632 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
633 .getCharHeight()) - 1;
635 vpRanges.setViewportWidth(widthInRes);
636 vpRanges.setViewportHeight(heightInSeq);
639 idSpaceFillerPanel1.setVisible(!wrap);
646 * Adjust row/column scrollers to show a visible position in the alignment.
649 * visible column to scroll to
651 * visible row to scroll to
654 public void setScrollValues(int xpos, int ypos)
659 if (av == null || av.getAlignment() == null)
664 if (av.getWrapAlignment())
666 setScrollingForWrappedPanel(x);
670 int width = av.getAlignment().getWidth();
671 int height = av.getAlignment().getHeight();
673 if (av.hasHiddenColumns())
675 // reset the width to exclude hidden columns
676 width = av.getColumnSelection().findColumnPosition(width);
679 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
680 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
687 if (vextent > height)
692 if ((hextent + x) > width)
697 if ((vextent + y) > height)
699 y = height - vextent;
712 // update the scroll values
713 hscroll.setValues(x, hextent, 0, width);
714 vscroll.setValues(y, vextent, 0, height);
719 * Respond to adjustment event when horizontal or vertical scrollbar is
723 * adjustment event encoding whether hscroll or vscroll changed
726 public void adjustmentValueChanged(AdjustmentEvent evt)
728 int oldX = vpRanges.getStartRes();
729 int oldwidth = vpRanges.getViewportWidth();
730 int oldY = vpRanges.getStartSeq();
731 int oldheight = vpRanges.getViewportHeight();
733 if (av.getWrapAlignment())
735 if (evt.getSource() == hscroll)
737 return; // no horizontal scroll when wrapped
739 else if (evt.getSource() == vscroll)
741 int offy = vscroll.getValue();
742 int rowSize = getSeqPanel().seqCanvas
743 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
745 // if we're scrolling to the position we're already at, stop
746 // this prevents infinite recursion of events when the scroll/viewport
747 // ranges values are the same
748 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
754 vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
759 // This is only called if file loaded is a jar file that
760 // was wrapped when saved and user has wrap alignment true
761 // as preference setting
762 SwingUtilities.invokeLater(new Runnable()
767 // When updating scrolling to use ViewportChange events, this code
768 // could not be validated and it is not clear if it is now being
769 // called. Log warning here in case it is called and unforeseen
772 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
774 // scroll to start of panel
775 vpRanges.setStartRes(0);
776 vpRanges.setStartSeq(0);
785 if (evt.getSource() == hscroll)
787 int x = hscroll.getValue();
788 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
790 // if we're scrolling to the position we're already at, stop
791 // this prevents infinite recursion of events when the scroll/viewport
792 // ranges values are the same
793 if ((x == oldX) && (width == oldwidth))
797 vpRanges.setViewportStartAndWidth(x, width);
799 else if (evt.getSource() == vscroll)
801 int y = vscroll.getValue();
802 int height = getSeqPanel().seqCanvas.getHeight()
803 / av.getCharHeight();
805 // if we're scrolling to the position we're already at, stop
806 // this prevents infinite recursion of events when the scroll/viewport
807 // ranges values are the same
808 if ((y == oldY) && (height == oldheight))
812 vpRanges.setViewportStartAndHeight(y, height);
822 * Repaint the alignment including the annotations and overview panels (if
826 public void paintAlignment(boolean updateOverview)
828 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
829 av.isShowAutocalculatedAbove());
830 sorter.sort(getAlignment().getAlignmentAnnotation(),
831 av.getSortAnnotationsBy());
836 // TODO: determine if this paintAlignment changed structure colours
837 av.getStructureSelectionManager().sequenceColoursChanged(this);
839 if (overviewPanel != null)
841 overviewPanel.updateOverviewImage();
853 public void paintComponent(Graphics g)
857 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
858 idPanelHolder.setPreferredSize(d);
859 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
863 * set scroll bar positions
865 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
869 * Set vertical scroll bar parameters for wrapped panel
871 * the residue to scroll to
873 private void setScrollingForWrappedPanel(int res)
875 // get the width of the alignment in residues
876 int maxwidth = av.getAlignment().getWidth();
877 if (av.hasHiddenColumns())
879 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
882 // get the width of the canvas in residues
883 int canvasWidth = getSeqPanel().seqCanvas
884 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
887 // position we want to scroll to is number of canvasWidth's to get there
888 int current = res / canvasWidth;
890 // max scroll position: add one because extent is 1 and scrollbar value
891 // can only be set to at most max - extent
892 int max = maxwidth / canvasWidth + 1;
893 vscroll.setUnitIncrement(1);
894 vscroll.setValues(current, 1, 0, max);
908 * @return DOCUMENT ME!
910 * @throws PrinterException
914 public int print(Graphics pg, PageFormat pf, int pi)
915 throws PrinterException
917 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
919 int pwidth = (int) pf.getImageableWidth();
920 int pheight = (int) pf.getImageableHeight();
922 if (av.getWrapAlignment())
924 return printWrappedAlignment(pwidth, pheight, pi, pg);
928 return printUnwrapped(pwidth, pheight, pi, pg, pg);
944 * @return DOCUMENT ME!
946 * @throws PrinterException
950 * Draws the alignment image, including sequence ids, sequences, and
951 * annotation labels and annotations if shown, on either one or two Graphics
958 * the graphics context for sequence ids and annotation labels
959 * @param alignmentGraphics
960 * the graphics context for sequences and annotations (may or may not
961 * be the same context as idGraphics)
963 * @throws PrinterException
965 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
966 Graphics idGraphics, Graphics alignmentGraphics)
967 throws PrinterException
969 final int idWidth = getVisibleIdWidth(false);
972 * Get the horizontal offset to where we draw the sequences.
973 * This is idWidth if using a single Graphics context, else zero.
975 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
977 FontMetrics fm = getFontMetrics(av.getFont());
978 int charHeight = av.getCharHeight();
979 int scaleHeight = charHeight + fm.getDescent();
981 idGraphics.setColor(Color.white);
982 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
983 idGraphics.setFont(av.getFont());
986 * How many sequences and residues can we fit on a printable page?
988 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
990 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
992 int alignmentWidth = av.getAlignment().getWidth();
993 int pagesWide = (alignmentWidth / totalRes) + 1;
995 final int startRes = (pi % pagesWide) * totalRes;
996 int endRes = (startRes + totalRes) - 1;
998 if (endRes > (alignmentWidth - 1))
1000 endRes = alignmentWidth - 1;
1003 final int startSeq = (pi / pagesWide) * totalSeq;
1004 int endSeq = startSeq + totalSeq;
1006 int alignmentHeight = av.getAlignment().getHeight();
1007 if (endSeq > alignmentHeight)
1009 endSeq = alignmentHeight;
1012 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1015 if (av.isShowAnnotation())
1017 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1020 pagesHigh /= pageHeight;
1022 if (pi >= (pagesWide * pagesHigh))
1024 return Printable.NO_SUCH_PAGE;
1026 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1030 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1032 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1033 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1034 pageWidth - idWidth, scaleHeight);
1035 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1038 * Draw the sequence ids, offset for scale height,
1039 * then reset to top left (0, 0)
1041 idGraphics.translate(0, scaleHeight);
1042 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1043 Color currentColor = null;
1044 Color currentTextColor = null;
1047 for (int i = startSeq; i < endSeq; i++)
1049 seq = av.getAlignment().getSequenceAt(i);
1050 if ((av.getSelectionGroup() != null)
1051 && av.getSelectionGroup().getSequences(null).contains(seq))
1054 * gray out ids of sequences in selection group (if any)
1056 currentColor = Color.gray;
1057 currentTextColor = Color.black;
1061 currentColor = av.getSequenceColour(seq);
1062 currentTextColor = Color.black;
1065 idGraphics.setColor(currentColor);
1066 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1069 idGraphics.setColor(currentTextColor);
1072 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1073 if (av.isRightAlignIds())
1075 fm = idGraphics.getFontMetrics();
1077 - fm.stringWidth(displayId)
1081 idGraphics.drawString(displayId, xPos,
1082 (((i - startSeq) * charHeight) + charHeight)
1083 - (charHeight / 5));
1085 idGraphics.setFont(av.getFont());
1086 idGraphics.translate(0, -scaleHeight);
1089 * draw the sequences, offset for scale height, and id width (if using a
1090 * single graphics context), then reset to (0, scale height)
1092 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1093 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1094 startSeq, endSeq, 0);
1095 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1097 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1100 * draw annotation labels; drawComponent() translates by
1101 * getScrollOffset(), so compensate for that first;
1102 * then reset to (0, scale height)
1104 int offset = getAlabels().getScrollOffset();
1105 idGraphics.translate(0, -offset);
1106 idGraphics.translate(0, alignmentDrawnHeight);
1107 getAlabels().drawComponent(idGraphics, idWidth);
1108 idGraphics.translate(0, -alignmentDrawnHeight);
1111 * draw the annotations starting at
1112 * (idOffset, alignmentHeight) from (0, scaleHeight)
1114 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1115 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1116 alignmentGraphics, -1, startRes, endRes + 1);
1119 return Printable.PAGE_EXISTS;
1134 * @return DOCUMENT ME!
1136 * @throws PrinterException
1139 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1140 Graphics pg) throws PrinterException
1142 int annotationHeight = 0;
1143 AnnotationLabels labels = null;
1144 if (av.isShowAnnotation())
1146 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1147 labels = new AnnotationLabels(av);
1150 int hgap = av.getCharHeight();
1151 if (av.getScaleAboveWrapped())
1153 hgap += av.getCharHeight();
1156 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1159 int idWidth = getVisibleIdWidth(false);
1161 int maxwidth = av.getAlignment().getWidth();
1162 if (av.hasHiddenColumns())
1164 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1167 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1170 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1172 pg.setColor(Color.white);
1173 pg.fillRect(0, 0, pwidth, pheight);
1174 pg.setFont(av.getFont());
1178 pg.setColor(Color.black);
1180 pg.translate(0, -pi * pheight);
1182 pg.setClip(0, pi * pheight, pwidth, pheight);
1188 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1190 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1191 SequenceI s = av.getAlignment().getSequenceAt(i);
1192 String string = s.getDisplayId(av.getShowJVSuffix());
1194 if (av.isRightAlignIds())
1196 FontMetrics fm = pg.getFontMetrics();
1197 xPos = idWidth - fm.stringWidth(string) - 4;
1199 pg.drawString(string, xPos,
1200 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1201 - (av.getCharHeight() / 5));
1206 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1208 pg.setFont(av.getFont());
1209 labels.drawComponent(pg, idWidth);
1213 - (av.getAlignment().getHeight() * av
1218 } while (ypos < totalHeight);
1220 pg.translate(idWidth, 0);
1222 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1225 if ((pi * pheight) < totalHeight)
1227 return Printable.PAGE_EXISTS;
1232 return Printable.NO_SUCH_PAGE;
1237 * get current sequence ID panel width, or nominal value if panel were to be
1238 * displayed using default settings
1242 public int getVisibleIdWidth()
1244 return getVisibleIdWidth(true);
1248 * get current sequence ID panel width, or nominal value if panel were to be
1249 * displayed using default settings
1252 * indicate if the Id width for onscreen or offscreen display should
1256 public int getVisibleIdWidth(boolean onscreen)
1258 // see if rendering offscreen - check preferences and calc width accordingly
1259 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1261 return calculateIdWidth(-1).width + 4;
1263 Integer idwidth = null;
1265 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1267 int w = getIdPanel().getWidth();
1268 return (w > 0 ? w : calculateIdWidth().width + 4);
1270 return idwidth.intValue() + 4;
1273 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1275 int boarderBottomOffset = 5;
1276 long pSessionId = System.currentTimeMillis();
1277 headless = (System.getProperty("java.awt.headless") != null && System
1278 .getProperty("java.awt.headless").equals("true"));
1279 if (alignFrame != null && !headless)
1283 alignFrame.setProgressBar(MessageManager.formatMessage(
1284 "status.saving_file", new Object[] { type.getLabel() }),
1290 AlignmentDimension aDimension = getAlignmentDimension();
1293 jalview.util.ImageMaker im;
1294 final String imageAction, imageTitle;
1295 if (type == jalview.util.ImageMaker.TYPE.PNG)
1297 imageAction = "Create PNG image from alignment";
1300 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1302 imageAction = "Create EPS file from alignment";
1303 imageTitle = alignFrame.getTitle();
1307 imageAction = "Create SVG file from alignment";
1308 imageTitle = alignFrame.getTitle();
1311 im = new jalview.util.ImageMaker(this, type, imageAction,
1312 aDimension.getWidth(), aDimension.getHeight()
1313 + boarderBottomOffset, file, imageTitle,
1314 alignFrame, pSessionId, headless);
1315 Graphics graphics = im.getGraphics();
1316 if (av.getWrapAlignment())
1318 if (graphics != null)
1320 printWrappedAlignment(aDimension.getWidth(),
1321 aDimension.getHeight() + boarderBottomOffset, 0,
1328 if (graphics != null)
1330 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1331 0, graphics, graphics);
1336 } catch (OutOfMemoryError err)
1339 System.out.println("########################\n" + "OUT OF MEMORY "
1340 + file + "\n" + "########################");
1341 new OOMWarning("Creating Image for " + file, err);
1342 // System.out.println("Create IMAGE: " + err);
1343 } catch (Exception ex)
1345 ex.printStackTrace();
1353 public AlignmentDimension getAlignmentDimension()
1355 int maxwidth = av.getAlignment().getWidth();
1356 if (av.hasHiddenColumns())
1358 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1361 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1362 + getScalePanel().getHeight();
1363 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1365 if (av.getWrapAlignment())
1367 height = getWrappedHeight();
1370 // need to obtain default alignment width and then add in any
1371 // additional allowance for id margin
1372 // this duplicates the calculation in getWrappedHeight but adjusts for
1374 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1375 - alignFrame.getInsets().left
1376 - alignFrame.getInsets().right - getVisibleIdWidth()
1377 + getVisibleIdWidth(false);
1381 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1385 else if (av.isShowAnnotation())
1387 height += getAnnotationPanel().adjustPanelHeight() + 3;
1389 return new AlignmentDimension(width, height);
1396 public void makeEPS(File epsFile)
1398 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1404 public void makePNG(File pngFile)
1406 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1409 public void makeSVG(File svgFile)
1411 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1414 public void makePNGImageMap(File imgMapFile, String imageName)
1416 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1417 // ////////////////////////////////////////////
1418 int idWidth = getVisibleIdWidth(false);
1419 FontMetrics fm = getFontMetrics(av.getFont());
1420 int scaleHeight = av.getCharHeight() + fm.getDescent();
1423 // ////////////////////////////////
1424 if (imgMapFile != null)
1428 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1429 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1430 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1431 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1432 out.println("<img src=\"" + imageName
1433 + "\" border=\"0\" usemap=\"#Map\" >"
1434 + "<map name=\"Map\">");
1436 for (s = 0; s < sSize; s++)
1438 sy = s * av.getCharHeight() + scaleHeight;
1440 SequenceI seq = av.getAlignment().getSequenceAt(s);
1441 SequenceFeature[] features = seq.getSequenceFeatures();
1442 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1443 for (res = 0; res < alwidth; res++)
1445 StringBuilder text = new StringBuilder();
1446 String triplet = null;
1447 if (av.getAlignment().isNucleotide())
1449 triplet = ResidueProperties.nucleotideName.get(seq
1450 .getCharAt(res) + "");
1454 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1458 if (triplet == null)
1463 int alIndex = seq.findPosition(res);
1464 gSize = groups.length;
1465 for (g = 0; g < gSize; g++)
1467 if (text.length() < 1)
1469 text.append("<area shape=\"rect\" coords=\"")
1470 .append((idWidth + res * av.getCharWidth()))
1471 .append(",").append(sy).append(",")
1472 .append((idWidth + (res + 1) * av.getCharWidth()))
1473 .append(",").append((av.getCharHeight() + sy))
1474 .append("\"").append(" onMouseOver=\"toolTip('")
1475 .append(alIndex).append(" ").append(triplet);
1478 if (groups[g].getStartRes() < res
1479 && groups[g].getEndRes() > res)
1481 text.append("<br><em>").append(groups[g].getName())
1486 if (features != null)
1488 if (text.length() < 1)
1490 text.append("<area shape=\"rect\" coords=\"")
1491 .append((idWidth + res * av.getCharWidth()))
1492 .append(",").append(sy).append(",")
1493 .append((idWidth + (res + 1) * av.getCharWidth()))
1494 .append(",").append((av.getCharHeight() + sy))
1495 .append("\"").append(" onMouseOver=\"toolTip('")
1496 .append(alIndex).append(" ").append(triplet);
1498 fSize = features.length;
1499 for (f = 0; f < fSize; f++)
1502 if ((features[f].getBegin() <= seq.findPosition(res))
1503 && (features[f].getEnd() >= seq.findPosition(res)))
1505 if (features[f].isContactFeature())
1507 if (features[f].getBegin() == seq.findPosition(res)
1508 || features[f].getEnd() == seq
1511 text.append("<br>").append(features[f].getType())
1512 .append(" ").append(features[f].getBegin())
1513 .append(":").append(features[f].getEnd());
1518 text.append("<br>");
1519 text.append(features[f].getType());
1520 if (features[f].getDescription() != null
1521 && !features[f].getType().equals(
1522 features[f].getDescription()))
1524 text.append(" ").append(features[f].getDescription());
1527 if (features[f].getValue("status") != null)
1529 text.append(" (").append(features[f].getValue("status"))
1537 if (text.length() > 1)
1539 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1540 out.println(text.toString());
1544 out.println("</map></body></html>");
1547 } catch (Exception ex)
1549 ex.printStackTrace();
1551 } // /////////END OF IMAGE MAP
1555 int getWrappedHeight()
1557 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1559 if (System.getProperty("java.awt.headless") != null
1560 && System.getProperty("java.awt.headless").equals("true"))
1562 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1563 - vscroll.getPreferredSize().width
1564 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1567 int chunkWidth = getSeqPanel().seqCanvas
1568 .getWrappedCanvasWidth(seqPanelWidth);
1570 int hgap = av.getCharHeight();
1571 if (av.getScaleAboveWrapped())
1573 hgap += av.getCharHeight();
1576 int annotationHeight = 0;
1577 if (av.isShowAnnotation())
1579 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1582 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1585 int maxwidth = av.getAlignment().getWidth();
1586 if (av.hasHiddenColumns())
1588 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1591 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1597 * close the panel - deregisters all listeners and nulls any references to
1600 public void closePanel()
1602 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1603 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1604 PaintRefresher.RemoveComponent(this);
1607 * try to ensure references are nulled
1609 if (annotationPanel != null)
1611 annotationPanel.dispose();
1616 av.removePropertyChangeListener(propertyChangeListener);
1617 jalview.structure.StructureSelectionManager ssm = av
1618 .getStructureSelectionManager();
1619 ssm.removeStructureViewerListener(getSeqPanel(), null);
1620 ssm.removeSelectionListener(getSeqPanel());
1621 ssm.removeCommandListener(av);
1622 ssm.removeStructureViewerListener(getSeqPanel(), null);
1623 ssm.removeSelectionListener(getSeqPanel());
1629 if (Cache.log.isDebugEnabled())
1631 Cache.log.warn("Closing alignment panel which is already closed.");
1637 * hides or shows dynamic annotation rows based on groups and av state flags
1639 public void updateAnnotation()
1641 updateAnnotation(false, false);
1644 public void updateAnnotation(boolean applyGlobalSettings)
1646 updateAnnotation(applyGlobalSettings, false);
1649 public void updateAnnotation(boolean applyGlobalSettings,
1650 boolean preserveNewGroupSettings)
1652 av.updateGroupAnnotationSettings(applyGlobalSettings,
1653 preserveNewGroupSettings);
1654 adjustAnnotationHeight();
1658 public AlignmentI getAlignment()
1660 return av == null ? null : av.getAlignment();
1664 public String getViewName()
1670 * Make/Unmake this alignment panel the current input focus
1674 public void setSelected(boolean b)
1678 if (alignFrame.getSplitViewContainer() != null)
1681 * bring enclosing SplitFrame to front first if there is one
1683 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1685 alignFrame.setSelected(b);
1686 } catch (Exception ex)
1692 alignFrame.setDisplayedView(this);
1697 public StructureSelectionManager getStructureSelectionManager()
1699 return av.getStructureSelectionManager();
1703 public void raiseOOMWarning(String string, OutOfMemoryError error)
1705 new OOMWarning(string, error, this);
1709 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1712 return new FeatureRenderer(this);
1716 public jalview.api.FeatureRenderer getFeatureRenderer()
1718 return seqPanel.seqCanvas.getFeatureRenderer();
1721 public void updateFeatureRenderer(
1722 jalview.renderer.seqfeatures.FeatureRenderer fr)
1724 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1727 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1729 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1731 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1735 public ScalePanel getScalePanel()
1740 public void setScalePanel(ScalePanel scalePanel)
1742 this.scalePanel = scalePanel;
1745 public SeqPanel getSeqPanel()
1750 public void setSeqPanel(SeqPanel seqPanel)
1752 this.seqPanel = seqPanel;
1755 public AnnotationPanel getAnnotationPanel()
1757 return annotationPanel;
1760 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1762 this.annotationPanel = annotationPanel;
1765 public AnnotationLabels getAlabels()
1770 public void setAlabels(AnnotationLabels alabels)
1772 this.alabels = alabels;
1775 public IdPanel getIdPanel()
1780 public void setIdPanel(IdPanel idPanel)
1782 this.idPanel = idPanel;
1786 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1787 * The aim is to keep the two alignments 'lined up' on their centre columns.
1790 * holds mapped region(s) of this alignment that we are scrolling
1791 * 'to'; may be modified for sequence offset by this method
1792 * @param verticalOffset
1793 * the number of visible sequences to show above the mapped region
1795 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1798 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1799 * mapped), we can make the scroll-to location a sequence above the one
1802 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1803 List<SequenceI> seqs = av.getAlignment().getSequences();
1806 * This is like AlignmentI.findIndex(seq) but here we are matching the
1807 * dataset sequence not the aligned sequence
1809 boolean matched = false;
1810 for (SequenceI seq : seqs)
1812 if (mappedTo == seq.getDatasetSequence())
1820 return; // failsafe, shouldn't happen
1824 * Scroll to position but centring the target residue.
1826 scrollToPosition(sr, verticalOffset, true, true);
1830 * Set a flag to say do not scroll any (cDNA/protein) complement.
1834 protected void setToScrollComplementPanel(boolean b)
1836 this.scrollComplementaryPanel = b;
1840 * Get whether to scroll complement panel
1842 * @return true if cDNA/protein complement panels should be scrolled
1844 protected boolean isSetToScrollComplementPanel()
1846 return this.scrollComplementaryPanel;
1852 * @adjustHeight if true, try to recalculate panel height for visible
1855 protected void refresh(boolean adjustHeight)
1857 validateAnnotationDimensions(adjustHeight);
1861 // sort, repaint, update overview
1862 paintAlignment(true);
1866 // lightweight repaint
1873 * Property change event fired when a change is made to the viewport ranges
1874 * object associated with this alignment panel's viewport
1876 public void propertyChange(PropertyChangeEvent evt)
1878 // update this panel's scroll values based on the new viewport ranges values
1879 int x = vpRanges.getStartRes();
1880 int y = vpRanges.getStartSeq();
1881 setScrollValues(x, y);
1883 // now update any complementary alignment (its viewport ranges object
1884 // is different so does not get automatically updated)
1885 if (isSetToScrollComplementPanel())
1887 setToScrollComplementPanel(false);
1888 av.scrollComplementaryAlignment();
1889 setToScrollComplementPanel(true);