2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportListenerI;
39 import jalview.viewmodel.ViewportRanges;
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.ComponentAdapter;
52 import java.awt.event.ComponentEvent;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.beans.PropertyChangeEvent;
57 import java.beans.PropertyChangeListener;
59 import java.io.FileWriter;
60 import java.io.PrintWriter;
61 import java.util.List;
63 import javax.swing.SwingUtilities;
69 * @version $Revision: 1.161 $
71 public class AlignmentPanel extends GAlignmentPanel implements
72 AdjustmentListener, Printable, AlignmentViewPanel,
75 public AlignViewport av;
77 ViewportRanges vpRanges;
79 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 // this value is set false when selection area being dragged
99 boolean fastPaint = true;
101 private int hextent = 0;
103 private int vextent = 0;
106 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107 * true, suppresses invoking the same method recursively.
109 private boolean dontScrollComplement;
111 private PropertyChangeListener propertyChangeListener;
114 * Creates a new AlignmentPanel object.
119 public AlignmentPanel(AlignFrame af, final AlignViewport av)
123 vpRanges = av.getRanges();
124 setSeqPanel(new SeqPanel(av, this));
125 setIdPanel(new IdPanel(av, this));
127 setScalePanel(new ScalePanel(av, this));
129 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
130 idwidthAdjuster = new IdwidthAdjuster(this);
131 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
133 setAnnotationPanel(new AnnotationPanel(this));
134 setAlabels(new AnnotationLabels(this));
136 annotationScroller.setViewportView(getAnnotationPanel());
137 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
139 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
140 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
142 setScrollValues(0, 0);
144 hscroll.addAdjustmentListener(this);
145 vscroll.addAdjustmentListener(this);
147 addComponentListener(new ComponentAdapter()
150 public void componentResized(ComponentEvent evt)
152 // reset the viewport ranges when the alignment panel is resized
153 // in particular, this initialises the end residue value when Jalview
155 if (av.getWrapAlignment())
157 int widthInRes = getSeqPanel().seqCanvas
158 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
159 vpRanges.setStartEndRes(vpRanges.getStartRes(),
160 vpRanges.getStartRes() + widthInRes);
164 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
165 .getCharWidth()) - 1;
166 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av.getCharHeight()) - 1;
168 vpRanges.setStartEndRes(vpRanges.getStartRes(),
169 vpRanges.getStartRes() + widthInRes);
170 vpRanges.setStartEndSeq(vpRanges.getStartSeq(),
171 vpRanges.getStartSeq() + heightInSeq);
177 final AlignmentPanel ap = this;
178 propertyChangeListener = new PropertyChangeListener()
181 public void propertyChange(PropertyChangeEvent evt)
183 if (evt.getPropertyName().equals("alignment"))
185 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
190 av.addPropertyChangeListener(propertyChangeListener);
192 av.getRanges().addPropertyChangeListener(this);
194 adjustAnnotationHeight();
199 public AlignViewportI getAlignViewport()
204 public void alignmentChanged()
206 av.alignmentChanged(this);
208 alignFrame.updateEditMenuBar();
210 paintAlignment(true);
217 public void fontChanged()
219 // set idCanvas bufferedImage to null
220 // to prevent drawing old image
221 FontMetrics fm = getFontMetrics(av.getFont());
223 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
225 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
226 .getCharHeight() + fm.getDescent()));
228 getIdPanel().getIdCanvas().gg = null;
229 getSeqPanel().seqCanvas.img = null;
230 getAnnotationPanel().adjustPanelHeight();
232 Dimension d = calculateIdWidth();
234 d.setSize(d.width + 4, d.height);
235 getIdPanel().getIdCanvas().setPreferredSize(d);
236 hscrollFillerPanel.setPreferredSize(d);
238 if (this.alignFrame.getSplitViewContainer() != null)
240 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
247 * Calculate the width of the alignment labels based on the displayed names
248 * and any bounds on label width set in preferences.
250 * @return Dimension giving the maximum width of the alignment label panel
251 * that should be used.
253 public Dimension calculateIdWidth()
255 // calculate sensible default width when no preference is available
257 if (av.getIdWidth() < 0)
259 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
260 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
261 r = calculateIdWidth(maxwidth);
262 av.setIdWidth(r.width);
267 r.width = av.getIdWidth();
274 * Calculate the width of the alignment labels based on the displayed names
275 * and any bounds on label width set in preferences.
278 * -1 or maximum width allowed for IdWidth
279 * @return Dimension giving the maximum width of the alignment label panel
280 * that should be used.
282 public Dimension calculateIdWidth(int maxwidth)
284 Container c = new Container();
286 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
287 Font.ITALIC, av.font.getSize()));
289 AlignmentI al = av.getAlignment();
294 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
296 SequenceI s = al.getSequenceAt(i);
298 id = s.getDisplayId(av.getShowJVSuffix());
300 if (fm.stringWidth(id) > idWidth)
302 idWidth = fm.stringWidth(id);
308 // Also check annotation label widths
311 if (al.getAlignmentAnnotation() != null)
313 fm = c.getFontMetrics(getAlabels().getFont());
315 while (i < al.getAlignmentAnnotation().length)
317 String label = al.getAlignmentAnnotation()[i].label;
319 if (fm.stringWidth(label) > idWidth)
321 idWidth = fm.stringWidth(label);
328 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
333 * Highlight the given results on the alignment.
336 public void highlightSearchResults(SearchResultsI results)
338 scrollToPosition(results);
339 getSeqPanel().seqCanvas.highlightSearchResults(results);
343 * Scroll the view to show the position of the highlighted region in results
344 * (if any) and redraw the overview
348 public boolean scrollToPosition(SearchResultsI results)
350 return scrollToPosition(results, 0, true, false);
354 * Scroll the view to show the position of the highlighted region in results
357 * @param searchResults
358 * @param redrawOverview
361 public boolean scrollToPosition(SearchResultsI searchResults,
362 boolean redrawOverview)
364 return scrollToPosition(searchResults, 0, redrawOverview, false);
368 * Scroll the view to show the position of the highlighted region in results
372 * @param verticalOffset
373 * if greater than zero, allows scrolling to a position below the
374 * first displayed sequence
375 * @param redrawOverview
376 * - when set, the overview will be recalculated (takes longer)
378 * if true, try to centre the search results horizontally in the view
379 * @return false if results were not found
381 public boolean scrollToPosition(SearchResultsI results,
382 int verticalOffset, boolean redrawOverview, boolean centre)
384 int startv, endv, starts, ends;
385 // TODO: properly locate search results in view when large numbers of hidden
386 // columns exist before highlighted region
387 // do we need to scroll the panel?
388 // TODO: tons of nullpointerexceptions raised here.
389 if (results != null && results.getSize() > 0 && av != null
390 && av.getAlignment() != null)
392 int seqIndex = av.getAlignment().findIndex(results);
397 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
399 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
407 // System.err.println(this.av.viewName + " Seq : " + seqIndex
408 // + " Scroll to " + start + "," + end);
411 * To centre results, scroll to positions half the visible width
412 * left/right of the start/end positions
416 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
417 start = Math.max(start - offset, 0);
418 end = end + offset - 1;
424 if (end == seq.getEnd())
428 if (av.hasHiddenColumns())
430 start = av.getColumnSelection().findColumnPosition(start);
431 end = av.getColumnSelection().findColumnPosition(end);
434 if (!av.getColumnSelection().isVisible(r[0]))
436 // don't scroll - position isn't visible
443 * allow for offset of target sequence (actually scroll to one above it)
445 seqIndex = Math.max(0, seqIndex - verticalOffset);
447 // System.out.println("start=" + start + ", end=" + end + ", startv="
448 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
449 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
450 if (!av.getWrapAlignment())
452 if ((startv = vpRanges.getStartRes()) >= start)
455 * Scroll left to make start of search results visible
457 // setScrollValues(start - 1, seqIndex); // plus one residue
458 setScrollValues(start, seqIndex);
460 else if ((endv = vpRanges.getEndRes()) <= end)
463 * Scroll right to make end of search results visible
465 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
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.setStartEndRes(vpRanges.getStartRes(),
637 vpRanges.getStartRes() + widthInRes - 1);
641 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
642 .getCharWidth()) - 1;
643 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
644 .getCharHeight()) - 1;
646 vpRanges.setStartEndRes(vpRanges.getStartRes(), widthInRes);
647 vpRanges.setStartEndSeq(vpRanges.getStartSeq(), heightInSeq);
650 idSpaceFillerPanel1.setVisible(!wrap);
657 * Adjust row/column scrollers to show a visible position in the alignment.
660 * visible column to scroll to
662 * visible row to scroll to
665 public void setScrollValues(int x, int y)
667 if (av == null || av.getAlignment() == null)
672 if (av.getWrapAlignment())
674 setScrollingForWrappedPanel(x);
679 int width = av.getAlignment().getWidth();
680 int height = av.getAlignment().getHeight();
682 if (av.hasHiddenColumns())
684 // reset the width to exclude hidden columns
685 width = av.getColumnSelection().findColumnPosition(width);
688 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
689 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
696 if (vextent > height)
701 if ((hextent + x) > width)
706 if ((vextent + y) > height)
708 y = height - vextent;
721 // update the scroll values
722 hscroll.setValues(x, hextent, 0, width);
723 vscroll.setValues(y, vextent, 0, height);
734 public void adjustmentValueChanged(AdjustmentEvent evt)
736 int oldX = vpRanges.getStartRes();
737 int oldwidth = vpRanges.getViewportWidth();
738 int oldY = vpRanges.getStartSeq();
739 int oldheight = vpRanges.getViewportHeight();
741 if (av.getWrapAlignment())
743 if (evt.getSource() == hscroll)
745 return; // no horizontal scroll when wrapped
747 else if (evt.getSource() == vscroll)
749 int offy = vscroll.getValue();
750 int rowSize = getSeqPanel().seqCanvas
751 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
753 // if we're scrolling to the position we're already at, stop
754 // this prevents infinite recursion of events when the scroll/viewport
755 // ranges values are the same
756 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
762 vpRanges.setStartEndRes(offy * rowSize, (offy + 1) * rowSize - 1);
766 // This is only called if file loaded is a jar file that
767 // was wrapped when saved and user has wrap alignment true
768 // as preference setting
769 SwingUtilities.invokeLater(new Runnable()
774 setScrollValues(vpRanges.getStartRes(),
775 vpRanges.getStartSeq());
785 if (evt.getSource() == hscroll)
787 int x = hscroll.getValue();
788 int width = (getSeqPanel().seqCanvas.getWidth() / av.getCharWidth()) - 1;
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.setStartEndRes(x, x + width);
799 else if (evt.getSource() == vscroll)
801 int y = vscroll.getValue();
802 int height = (getSeqPanel().seqCanvas.getHeight() / av
803 .getCharHeight()) - 1;
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.setStartEndSeq(y, 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 setDontScrollComplement(boolean b)
1836 this.dontScrollComplement = b;
1839 protected boolean isDontScrollComplement()
1841 return this.dontScrollComplement;
1847 * @adjustHeight if true, try to recalculate panel height for visible
1850 protected void refresh(boolean adjustHeight)
1852 validateAnnotationDimensions(adjustHeight);
1856 // sort, repaint, update overview
1857 paintAlignment(true);
1861 // lightweight repaint
1868 * Property change event fired when a change is made to the viewport ranges
1869 * object associated with this alignment panel's viewport
1871 public void propertyChange(PropertyChangeEvent evt)
1873 // update this panel's scroll values based on the new viewport ranges values
1874 int x = vpRanges.getStartRes();
1875 int y = vpRanges.getStartSeq();
1876 setScrollValues(x, y);
1878 // now update any complementary alignment (its viewport ranges object
1879 // is different so does not get automatically updated)
1880 if (!isDontScrollComplement())
1882 setDontScrollComplement(true);
1883 av.scrollComplementaryAlignment();
1884 setDontScrollComplement(false);