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.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());
405 // System.err.println(this.av.viewName + " Seq : " + seqIndex
406 // + " Scroll to " + start + "," + end);
409 * To centre results, scroll to positions half the visible width
410 * left/right of the start/end positions
414 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
415 start = Math.max(start - offset, 0);
416 end = end + offset - 1;
422 if (end == seq.getEnd())
426 if (av.hasHiddenColumns())
428 start = av.getColumnSelection().findColumnPosition(start);
429 end = av.getColumnSelection().findColumnPosition(end);
432 if (!av.getColumnSelection().isVisible(r[0]))
434 // don't scroll - position isn't visible
441 * allow for offset of target sequence (actually scroll to one above it)
443 seqIndex = Math.max(0, seqIndex - verticalOffset);
445 // System.out.println("start=" + start + ", end=" + end + ", startv="
446 // + av.getStartRes() + ", endv=" + av.getEndRes() + ", starts="
447 // + av.getStartSeq() + ", ends=" + av.getEndSeq());
448 if (!av.getWrapAlignment())
450 if ((startv = vpRanges.getStartRes()) >= start)
453 * Scroll left to make start of search results visible
455 // setScrollValues(start - 1, seqIndex); // plus one residue
456 setScrollValues(start, seqIndex);
458 else if ((endv = vpRanges.getEndRes()) <= end)
461 * Scroll right to make end of search results visible
463 // setScrollValues(startv + 1 + end - endv, seqIndex); // plus one
464 setScrollValues(startv + end - endv, seqIndex);
466 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
469 * Scroll up to make start of search results visible
471 setScrollValues(vpRanges.getStartRes(), seqIndex);
473 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
476 * Scroll down to make end of search results visible
478 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
482 * Else results are already visible - no need to scroll
487 vpRanges.scrollToWrappedVisible(start);
491 paintAlignment(redrawOverview);
498 * @return DOCUMENT ME!
500 public OverviewPanel getOverviewPanel()
502 return overviewPanel;
511 public void setOverviewPanel(OverviewPanel op)
519 * Hide or show annotation panel
522 public void setAnnotationVisible(boolean b)
524 if (!av.getWrapAlignment())
526 annotationSpaceFillerHolder.setVisible(b);
527 annotationScroller.setVisible(b);
533 * automatically adjust annotation panel height for new annotation whilst
534 * ensuring the alignment is still visible.
537 public void adjustAnnotationHeight()
539 // TODO: display vertical annotation scrollbar if necessary
540 // this is called after loading new annotation onto alignment
541 if (alignFrame.getHeight() == 0)
543 System.out.println("NEEDS FIXING");
545 validateAnnotationDimensions(true);
547 paintAlignment(true);
551 * calculate the annotation dimensions and refresh slider values accordingly.
552 * need to do repaints/notifys afterwards.
554 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
556 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
558 if (adjustPanelHeight)
560 int rowHeight = av.getCharHeight();
561 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
564 * Estimate available height in the AlignFrame for alignment +
565 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
566 * hscroll, status bar (as these are not laid out we can't inspect their
567 * actual heights). Insets gives frame borders.
569 int stuff = Platform.isAMac() ? 80 : 100;
570 Insets insets = alignFrame.getInsets();
571 int availableHeight = alignFrame.getHeight() - stuff - insets.top
575 * If not enough vertical space, maximize annotation height while keeping
576 * at least two rows of alignment visible
578 if (annotationHeight + alignmentHeight > availableHeight)
580 annotationHeight = Math.min(annotationHeight, availableHeight - 2
586 // maintain same window layout whilst updating sliders
587 annotationHeight = annotationScroller.getSize().height;
591 annotationScroller.setPreferredSize(new Dimension(annotationScroller
592 .getWidth(), annotationHeight));
594 Dimension e = idPanel.getSize();
595 alabels.setSize(new Dimension(e.width, annotationHeight));
597 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
598 annotationSpaceFillerHolder.getWidth(), annotationHeight));
599 annotationScroller.validate();
600 annotationScroller.addNotify();
604 * update alignment layout for viewport settings
609 public void updateLayout()
612 setAnnotationVisible(av.isShowAnnotation());
613 boolean wrap = av.getWrapAlignment();
614 vpRanges.setStartSeq(0);
615 scalePanelHolder.setVisible(!wrap);
616 hscroll.setVisible(!wrap);
617 idwidthAdjuster.setVisible(!wrap);
621 annotationScroller.setVisible(false);
622 annotationSpaceFillerHolder.setVisible(false);
624 else if (av.isShowAnnotation())
626 annotationScroller.setVisible(true);
627 annotationSpaceFillerHolder.setVisible(true);
632 int widthInRes = getSeqPanel().seqCanvas
633 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
634 vpRanges.setViewportWidth(widthInRes);
638 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
639 .getCharWidth()) - 1;
640 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
641 .getCharHeight()) - 1;
643 vpRanges.setViewportWidth(widthInRes);
644 vpRanges.setViewportHeight(heightInSeq);
647 idSpaceFillerPanel1.setVisible(!wrap);
654 * Adjust row/column scrollers to show a visible position in the alignment.
657 * visible column to scroll to
659 * visible row to scroll to
662 public void setScrollValues(int x, int y)
664 if (av == null || av.getAlignment() == null)
669 if (av.getWrapAlignment())
671 setScrollingForWrappedPanel(x);
676 int width = av.getAlignment().getWidth();
677 int height = av.getAlignment().getHeight();
679 if (av.hasHiddenColumns())
681 // reset the width to exclude hidden columns
682 width = av.getColumnSelection().findColumnPosition(width);
685 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
686 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
693 if (vextent > height)
698 if ((hextent + x) > width)
703 if ((vextent + y) > height)
705 y = height - vextent;
718 // update the scroll values
719 hscroll.setValues(x, hextent, 0, width);
720 vscroll.setValues(y, vextent, 0, height);
731 public void adjustmentValueChanged(AdjustmentEvent evt)
733 int oldX = vpRanges.getStartRes();
734 int oldwidth = vpRanges.getViewportWidth();
735 int oldY = vpRanges.getStartSeq();
736 int oldheight = vpRanges.getViewportHeight();
738 if (av.getWrapAlignment())
740 if (evt.getSource() == hscroll)
742 return; // no horizontal scroll when wrapped
744 else if (evt.getSource() == vscroll)
746 int offy = vscroll.getValue();
747 int rowSize = getSeqPanel().seqCanvas
748 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
750 // if we're scrolling to the position we're already at, stop
751 // this prevents infinite recursion of events when the scroll/viewport
752 // ranges values are the same
753 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
759 vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
763 // This is only called if file loaded is a jar file that
764 // was wrapped when saved and user has wrap alignment true
765 // as preference setting
766 SwingUtilities.invokeLater(new Runnable()
771 setScrollValues(vpRanges.getStartRes(),
772 vpRanges.getStartSeq());
782 if (evt.getSource() == hscroll)
784 int x = hscroll.getValue();
785 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
787 // if we're scrolling to the position we're already at, stop
788 // this prevents infinite recursion of events when the scroll/viewport
789 // ranges values are the same
790 if ((x == oldX) && (width == oldwidth))
794 vpRanges.setViewportStartAndWidth(x, width);
796 else if (evt.getSource() == vscroll)
798 int y = vscroll.getValue();
799 int height = getSeqPanel().seqCanvas.getHeight()
800 / av.getCharHeight();
802 // if we're scrolling to the position we're already at, stop
803 // this prevents infinite recursion of events when the scroll/viewport
804 // ranges values are the same
805 if ((y == oldY) && (height == oldheight))
809 vpRanges.setViewportStartAndHeight(y, height);
819 * Repaint the alignment including the annotations and overview panels (if
823 public void paintAlignment(boolean updateOverview)
825 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
826 av.isShowAutocalculatedAbove());
827 sorter.sort(getAlignment().getAlignmentAnnotation(),
828 av.getSortAnnotationsBy());
833 // TODO: determine if this paintAlignment changed structure colours
834 av.getStructureSelectionManager().sequenceColoursChanged(this);
836 if (overviewPanel != null)
838 overviewPanel.updateOverviewImage();
850 public void paintComponent(Graphics g)
854 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
855 idPanelHolder.setPreferredSize(d);
856 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
860 * set scroll bar positions
862 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
866 * Set vertical scroll bar parameters for wrapped panel
868 * the residue to scroll to
870 private void setScrollingForWrappedPanel(int res)
872 // get the width of the alignment in residues
873 int maxwidth = av.getAlignment().getWidth();
874 if (av.hasHiddenColumns())
876 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
879 // get the width of the canvas in residues
880 int canvasWidth = getSeqPanel().seqCanvas
881 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
884 // position we want to scroll to is number of canvasWidth's to get there
885 int current = res / canvasWidth;
887 // max scroll position: add one because extent is 1 and scrollbar value
888 // can only be set to at most max - extent
889 int max = maxwidth / canvasWidth + 1;
890 vscroll.setUnitIncrement(1);
891 vscroll.setValues(current, 1, 0, max);
905 * @return DOCUMENT ME!
907 * @throws PrinterException
911 public int print(Graphics pg, PageFormat pf, int pi)
912 throws PrinterException
914 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
916 int pwidth = (int) pf.getImageableWidth();
917 int pheight = (int) pf.getImageableHeight();
919 if (av.getWrapAlignment())
921 return printWrappedAlignment(pwidth, pheight, pi, pg);
925 return printUnwrapped(pwidth, pheight, pi, pg, pg);
941 * @return DOCUMENT ME!
943 * @throws PrinterException
947 * Draws the alignment image, including sequence ids, sequences, and
948 * annotation labels and annotations if shown, on either one or two Graphics
955 * the graphics context for sequence ids and annotation labels
956 * @param alignmentGraphics
957 * the graphics context for sequences and annotations (may or may not
958 * be the same context as idGraphics)
960 * @throws PrinterException
962 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
963 Graphics idGraphics, Graphics alignmentGraphics)
964 throws PrinterException
966 final int idWidth = getVisibleIdWidth(false);
969 * Get the horizontal offset to where we draw the sequences.
970 * This is idWidth if using a single Graphics context, else zero.
972 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
974 FontMetrics fm = getFontMetrics(av.getFont());
975 int charHeight = av.getCharHeight();
976 int scaleHeight = charHeight + fm.getDescent();
978 idGraphics.setColor(Color.white);
979 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
980 idGraphics.setFont(av.getFont());
983 * How many sequences and residues can we fit on a printable page?
985 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
987 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
989 int alignmentWidth = av.getAlignment().getWidth();
990 int pagesWide = (alignmentWidth / totalRes) + 1;
992 final int startRes = (pi % pagesWide) * totalRes;
993 int endRes = (startRes + totalRes) - 1;
995 if (endRes > (alignmentWidth - 1))
997 endRes = alignmentWidth - 1;
1000 final int startSeq = (pi / pagesWide) * totalSeq;
1001 int endSeq = startSeq + totalSeq;
1003 int alignmentHeight = av.getAlignment().getHeight();
1004 if (endSeq > alignmentHeight)
1006 endSeq = alignmentHeight;
1009 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1012 if (av.isShowAnnotation())
1014 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1017 pagesHigh /= pageHeight;
1019 if (pi >= (pagesWide * pagesHigh))
1021 return Printable.NO_SUCH_PAGE;
1023 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1027 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1029 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1030 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1031 pageWidth - idWidth, scaleHeight);
1032 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1035 * Draw the sequence ids, offset for scale height,
1036 * then reset to top left (0, 0)
1038 idGraphics.translate(0, scaleHeight);
1039 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1040 Color currentColor = null;
1041 Color currentTextColor = null;
1044 for (int i = startSeq; i < endSeq; i++)
1046 seq = av.getAlignment().getSequenceAt(i);
1047 if ((av.getSelectionGroup() != null)
1048 && av.getSelectionGroup().getSequences(null).contains(seq))
1051 * gray out ids of sequences in selection group (if any)
1053 currentColor = Color.gray;
1054 currentTextColor = Color.black;
1058 currentColor = av.getSequenceColour(seq);
1059 currentTextColor = Color.black;
1062 idGraphics.setColor(currentColor);
1063 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1066 idGraphics.setColor(currentTextColor);
1069 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1070 if (av.isRightAlignIds())
1072 fm = idGraphics.getFontMetrics();
1074 - fm.stringWidth(displayId)
1078 idGraphics.drawString(displayId, xPos,
1079 (((i - startSeq) * charHeight) + charHeight)
1080 - (charHeight / 5));
1082 idGraphics.setFont(av.getFont());
1083 idGraphics.translate(0, -scaleHeight);
1086 * draw the sequences, offset for scale height, and id width (if using a
1087 * single graphics context), then reset to (0, scale height)
1089 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1090 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1091 startSeq, endSeq, 0);
1092 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1094 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1097 * draw annotation labels; drawComponent() translates by
1098 * getScrollOffset(), so compensate for that first;
1099 * then reset to (0, scale height)
1101 int offset = getAlabels().getScrollOffset();
1102 idGraphics.translate(0, -offset);
1103 idGraphics.translate(0, alignmentDrawnHeight);
1104 getAlabels().drawComponent(idGraphics, idWidth);
1105 idGraphics.translate(0, -alignmentDrawnHeight);
1108 * draw the annotations starting at
1109 * (idOffset, alignmentHeight) from (0, scaleHeight)
1111 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1112 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1113 alignmentGraphics, -1, startRes, endRes + 1);
1116 return Printable.PAGE_EXISTS;
1131 * @return DOCUMENT ME!
1133 * @throws PrinterException
1136 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1137 Graphics pg) throws PrinterException
1139 int annotationHeight = 0;
1140 AnnotationLabels labels = null;
1141 if (av.isShowAnnotation())
1143 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1144 labels = new AnnotationLabels(av);
1147 int hgap = av.getCharHeight();
1148 if (av.getScaleAboveWrapped())
1150 hgap += av.getCharHeight();
1153 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1156 int idWidth = getVisibleIdWidth(false);
1158 int maxwidth = av.getAlignment().getWidth();
1159 if (av.hasHiddenColumns())
1161 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1164 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1167 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1169 pg.setColor(Color.white);
1170 pg.fillRect(0, 0, pwidth, pheight);
1171 pg.setFont(av.getFont());
1175 pg.setColor(Color.black);
1177 pg.translate(0, -pi * pheight);
1179 pg.setClip(0, pi * pheight, pwidth, pheight);
1185 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1187 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1188 SequenceI s = av.getAlignment().getSequenceAt(i);
1189 String string = s.getDisplayId(av.getShowJVSuffix());
1191 if (av.isRightAlignIds())
1193 FontMetrics fm = pg.getFontMetrics();
1194 xPos = idWidth - fm.stringWidth(string) - 4;
1196 pg.drawString(string, xPos,
1197 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1198 - (av.getCharHeight() / 5));
1203 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1205 pg.setFont(av.getFont());
1206 labels.drawComponent(pg, idWidth);
1210 - (av.getAlignment().getHeight() * av
1215 } while (ypos < totalHeight);
1217 pg.translate(idWidth, 0);
1219 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1222 if ((pi * pheight) < totalHeight)
1224 return Printable.PAGE_EXISTS;
1229 return Printable.NO_SUCH_PAGE;
1234 * get current sequence ID panel width, or nominal value if panel were to be
1235 * displayed using default settings
1239 public int getVisibleIdWidth()
1241 return getVisibleIdWidth(true);
1245 * get current sequence ID panel width, or nominal value if panel were to be
1246 * displayed using default settings
1249 * indicate if the Id width for onscreen or offscreen display should
1253 public int getVisibleIdWidth(boolean onscreen)
1255 // see if rendering offscreen - check preferences and calc width accordingly
1256 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1258 return calculateIdWidth(-1).width + 4;
1260 Integer idwidth = null;
1262 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1264 int w = getIdPanel().getWidth();
1265 return (w > 0 ? w : calculateIdWidth().width + 4);
1267 return idwidth.intValue() + 4;
1270 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1272 int boarderBottomOffset = 5;
1273 long pSessionId = System.currentTimeMillis();
1274 headless = (System.getProperty("java.awt.headless") != null && System
1275 .getProperty("java.awt.headless").equals("true"));
1276 if (alignFrame != null && !headless)
1280 alignFrame.setProgressBar(MessageManager.formatMessage(
1281 "status.saving_file", new Object[] { type.getLabel() }),
1287 AlignmentDimension aDimension = getAlignmentDimension();
1290 jalview.util.ImageMaker im;
1291 final String imageAction, imageTitle;
1292 if (type == jalview.util.ImageMaker.TYPE.PNG)
1294 imageAction = "Create PNG image from alignment";
1297 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1299 imageAction = "Create EPS file from alignment";
1300 imageTitle = alignFrame.getTitle();
1304 imageAction = "Create SVG file from alignment";
1305 imageTitle = alignFrame.getTitle();
1308 im = new jalview.util.ImageMaker(this, type, imageAction,
1309 aDimension.getWidth(), aDimension.getHeight()
1310 + boarderBottomOffset, file, imageTitle,
1311 alignFrame, pSessionId, headless);
1312 Graphics graphics = im.getGraphics();
1313 if (av.getWrapAlignment())
1315 if (graphics != null)
1317 printWrappedAlignment(aDimension.getWidth(),
1318 aDimension.getHeight() + boarderBottomOffset, 0,
1325 if (graphics != null)
1327 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1328 0, graphics, graphics);
1333 } catch (OutOfMemoryError err)
1336 System.out.println("########################\n" + "OUT OF MEMORY "
1337 + file + "\n" + "########################");
1338 new OOMWarning("Creating Image for " + file, err);
1339 // System.out.println("Create IMAGE: " + err);
1340 } catch (Exception ex)
1342 ex.printStackTrace();
1350 public AlignmentDimension getAlignmentDimension()
1352 int maxwidth = av.getAlignment().getWidth();
1353 if (av.hasHiddenColumns())
1355 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1358 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1359 + getScalePanel().getHeight();
1360 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1362 if (av.getWrapAlignment())
1364 height = getWrappedHeight();
1367 // need to obtain default alignment width and then add in any
1368 // additional allowance for id margin
1369 // this duplicates the calculation in getWrappedHeight but adjusts for
1371 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1372 - alignFrame.getInsets().left
1373 - alignFrame.getInsets().right - getVisibleIdWidth()
1374 + getVisibleIdWidth(false);
1378 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1382 else if (av.isShowAnnotation())
1384 height += getAnnotationPanel().adjustPanelHeight() + 3;
1386 return new AlignmentDimension(width, height);
1393 public void makeEPS(File epsFile)
1395 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1401 public void makePNG(File pngFile)
1403 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1406 public void makeSVG(File svgFile)
1408 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1411 public void makePNGImageMap(File imgMapFile, String imageName)
1413 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1414 // ////////////////////////////////////////////
1415 int idWidth = getVisibleIdWidth(false);
1416 FontMetrics fm = getFontMetrics(av.getFont());
1417 int scaleHeight = av.getCharHeight() + fm.getDescent();
1420 // ////////////////////////////////
1421 if (imgMapFile != null)
1425 int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1426 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1427 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1428 out.println(jalview.io.HTMLOutput.getImageMapHTML());
1429 out.println("<img src=\"" + imageName
1430 + "\" border=\"0\" usemap=\"#Map\" >"
1431 + "<map name=\"Map\">");
1433 for (s = 0; s < sSize; s++)
1435 sy = s * av.getCharHeight() + scaleHeight;
1437 SequenceI seq = av.getAlignment().getSequenceAt(s);
1438 SequenceFeature[] features = seq.getSequenceFeatures();
1439 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1440 for (res = 0; res < alwidth; res++)
1442 StringBuilder text = new StringBuilder();
1443 String triplet = null;
1444 if (av.getAlignment().isNucleotide())
1446 triplet = ResidueProperties.nucleotideName.get(seq
1447 .getCharAt(res) + "");
1451 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1455 if (triplet == null)
1460 int alIndex = seq.findPosition(res);
1461 gSize = groups.length;
1462 for (g = 0; g < gSize; g++)
1464 if (text.length() < 1)
1466 text.append("<area shape=\"rect\" coords=\"")
1467 .append((idWidth + res * av.getCharWidth()))
1468 .append(",").append(sy).append(",")
1469 .append((idWidth + (res + 1) * av.getCharWidth()))
1470 .append(",").append((av.getCharHeight() + sy))
1471 .append("\"").append(" onMouseOver=\"toolTip('")
1472 .append(alIndex).append(" ").append(triplet);
1475 if (groups[g].getStartRes() < res
1476 && groups[g].getEndRes() > res)
1478 text.append("<br><em>").append(groups[g].getName())
1483 if (features != null)
1485 if (text.length() < 1)
1487 text.append("<area shape=\"rect\" coords=\"")
1488 .append((idWidth + res * av.getCharWidth()))
1489 .append(",").append(sy).append(",")
1490 .append((idWidth + (res + 1) * av.getCharWidth()))
1491 .append(",").append((av.getCharHeight() + sy))
1492 .append("\"").append(" onMouseOver=\"toolTip('")
1493 .append(alIndex).append(" ").append(triplet);
1495 fSize = features.length;
1496 for (f = 0; f < fSize; f++)
1499 if ((features[f].getBegin() <= seq.findPosition(res))
1500 && (features[f].getEnd() >= seq.findPosition(res)))
1502 if (features[f].isContactFeature())
1504 if (features[f].getBegin() == seq.findPosition(res)
1505 || features[f].getEnd() == seq
1508 text.append("<br>").append(features[f].getType())
1509 .append(" ").append(features[f].getBegin())
1510 .append(":").append(features[f].getEnd());
1515 text.append("<br>");
1516 text.append(features[f].getType());
1517 if (features[f].getDescription() != null
1518 && !features[f].getType().equals(
1519 features[f].getDescription()))
1521 text.append(" ").append(features[f].getDescription());
1524 if (features[f].getValue("status") != null)
1526 text.append(" (").append(features[f].getValue("status"))
1534 if (text.length() > 1)
1536 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1537 out.println(text.toString());
1541 out.println("</map></body></html>");
1544 } catch (Exception ex)
1546 ex.printStackTrace();
1548 } // /////////END OF IMAGE MAP
1552 int getWrappedHeight()
1554 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1556 if (System.getProperty("java.awt.headless") != null
1557 && System.getProperty("java.awt.headless").equals("true"))
1559 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1560 - vscroll.getPreferredSize().width
1561 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1564 int chunkWidth = getSeqPanel().seqCanvas
1565 .getWrappedCanvasWidth(seqPanelWidth);
1567 int hgap = av.getCharHeight();
1568 if (av.getScaleAboveWrapped())
1570 hgap += av.getCharHeight();
1573 int annotationHeight = 0;
1574 if (av.isShowAnnotation())
1576 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1579 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1582 int maxwidth = av.getAlignment().getWidth();
1583 if (av.hasHiddenColumns())
1585 maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1588 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1594 * close the panel - deregisters all listeners and nulls any references to
1597 public void closePanel()
1599 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1600 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1601 PaintRefresher.RemoveComponent(this);
1604 * try to ensure references are nulled
1606 if (annotationPanel != null)
1608 annotationPanel.dispose();
1613 av.removePropertyChangeListener(propertyChangeListener);
1614 jalview.structure.StructureSelectionManager ssm = av
1615 .getStructureSelectionManager();
1616 ssm.removeStructureViewerListener(getSeqPanel(), null);
1617 ssm.removeSelectionListener(getSeqPanel());
1618 ssm.removeCommandListener(av);
1619 ssm.removeStructureViewerListener(getSeqPanel(), null);
1620 ssm.removeSelectionListener(getSeqPanel());
1626 if (Cache.log.isDebugEnabled())
1628 Cache.log.warn("Closing alignment panel which is already closed.");
1634 * hides or shows dynamic annotation rows based on groups and av state flags
1636 public void updateAnnotation()
1638 updateAnnotation(false, false);
1641 public void updateAnnotation(boolean applyGlobalSettings)
1643 updateAnnotation(applyGlobalSettings, false);
1646 public void updateAnnotation(boolean applyGlobalSettings,
1647 boolean preserveNewGroupSettings)
1649 av.updateGroupAnnotationSettings(applyGlobalSettings,
1650 preserveNewGroupSettings);
1651 adjustAnnotationHeight();
1655 public AlignmentI getAlignment()
1657 return av == null ? null : av.getAlignment();
1661 public String getViewName()
1667 * Make/Unmake this alignment panel the current input focus
1671 public void setSelected(boolean b)
1675 if (alignFrame.getSplitViewContainer() != null)
1678 * bring enclosing SplitFrame to front first if there is one
1680 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1682 alignFrame.setSelected(b);
1683 } catch (Exception ex)
1689 alignFrame.setDisplayedView(this);
1694 public StructureSelectionManager getStructureSelectionManager()
1696 return av.getStructureSelectionManager();
1700 public void raiseOOMWarning(String string, OutOfMemoryError error)
1702 new OOMWarning(string, error, this);
1706 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1709 return new FeatureRenderer(this);
1713 public jalview.api.FeatureRenderer getFeatureRenderer()
1715 return seqPanel.seqCanvas.getFeatureRenderer();
1718 public void updateFeatureRenderer(
1719 jalview.renderer.seqfeatures.FeatureRenderer fr)
1721 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1724 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1726 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1728 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1732 public ScalePanel getScalePanel()
1737 public void setScalePanel(ScalePanel scalePanel)
1739 this.scalePanel = scalePanel;
1742 public SeqPanel getSeqPanel()
1747 public void setSeqPanel(SeqPanel seqPanel)
1749 this.seqPanel = seqPanel;
1752 public AnnotationPanel getAnnotationPanel()
1754 return annotationPanel;
1757 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1759 this.annotationPanel = annotationPanel;
1762 public AnnotationLabels getAlabels()
1767 public void setAlabels(AnnotationLabels alabels)
1769 this.alabels = alabels;
1772 public IdPanel getIdPanel()
1777 public void setIdPanel(IdPanel idPanel)
1779 this.idPanel = idPanel;
1783 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1784 * The aim is to keep the two alignments 'lined up' on their centre columns.
1787 * holds mapped region(s) of this alignment that we are scrolling
1788 * 'to'; may be modified for sequence offset by this method
1789 * @param verticalOffset
1790 * the number of visible sequences to show above the mapped region
1792 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1795 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1796 * mapped), we can make the scroll-to location a sequence above the one
1799 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1800 List<SequenceI> seqs = av.getAlignment().getSequences();
1803 * This is like AlignmentI.findIndex(seq) but here we are matching the
1804 * dataset sequence not the aligned sequence
1806 boolean matched = false;
1807 for (SequenceI seq : seqs)
1809 if (mappedTo == seq.getDatasetSequence())
1817 return; // failsafe, shouldn't happen
1821 * Scroll to position but centring the target residue.
1823 scrollToPosition(sr, verticalOffset, true, true);
1827 * Set a flag to say do not scroll any (cDNA/protein) complement.
1831 protected void setDontScrollComplement(boolean b)
1833 this.dontScrollComplement = b;
1836 protected boolean isDontScrollComplement()
1838 return this.dontScrollComplement;
1844 * @adjustHeight if true, try to recalculate panel height for visible
1847 protected void refresh(boolean adjustHeight)
1849 validateAnnotationDimensions(adjustHeight);
1853 // sort, repaint, update overview
1854 paintAlignment(true);
1858 // lightweight repaint
1865 * Property change event fired when a change is made to the viewport ranges
1866 * object associated with this alignment panel's viewport
1868 public void propertyChange(PropertyChangeEvent evt)
1870 // update this panel's scroll values based on the new viewport ranges values
1871 int x = vpRanges.getStartRes();
1872 int y = vpRanges.getStartSeq();
1873 setScrollValues(x, y);
1875 // now update any complementary alignment (its viewport ranges object
1876 // is different so does not get automatically updated)
1877 if (!isDontScrollComplement())
1879 setDontScrollComplement(true);
1880 av.scrollComplementaryAlignment();
1881 setDontScrollComplement(false);