2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.ViewportListenerI;
42 import jalview.viewmodel.ViewportRanges;
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Container;
47 import java.awt.Dimension;
49 import java.awt.FontMetrics;
50 import java.awt.Graphics;
51 import java.awt.Insets;
52 import java.awt.event.AdjustmentEvent;
53 import java.awt.event.AdjustmentListener;
54 import java.awt.event.ComponentAdapter;
55 import java.awt.event.ComponentEvent;
56 import java.awt.print.PageFormat;
57 import java.awt.print.Printable;
58 import java.awt.print.PrinterException;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
62 import java.io.FileWriter;
63 import java.io.PrintWriter;
64 import java.util.List;
66 import javax.swing.SwingUtilities;
72 * @version $Revision: 1.161 $
74 public class AlignmentPanel extends GAlignmentPanel implements
75 AdjustmentListener, Printable, AlignmentViewPanel,
78 public AlignViewport av;
80 ViewportRanges vpRanges;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 private boolean headless;
90 IdwidthAdjuster idwidthAdjuster;
93 public AlignFrame alignFrame;
95 private ScalePanel scalePanel;
97 private AnnotationPanel annotationPanel;
99 private AnnotationLabels alabels;
101 // this value is set false when selection area being dragged
102 boolean fastPaint = true;
104 private int hextent = 0;
106 private int vextent = 0;
109 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110 * false, suppresses invoking the same method recursively.
112 private boolean scrollComplementaryPanel = true;
114 private PropertyChangeListener propertyChangeListener;
116 private CalculationChooser calculationDialog;
119 * Creates a new AlignmentPanel object.
124 public AlignmentPanel(AlignFrame af, final AlignViewport av)
128 vpRanges = av.getRanges();
129 setSeqPanel(new SeqPanel(av, this));
130 setIdPanel(new IdPanel(av, this));
132 setScalePanel(new ScalePanel(av, this));
134 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135 idwidthAdjuster = new IdwidthAdjuster(this);
136 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
138 setAnnotationPanel(new AnnotationPanel(this));
139 setAlabels(new AnnotationLabels(this));
141 annotationScroller.setViewportView(getAnnotationPanel());
142 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
144 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
147 setScrollValues(0, 0);
149 hscroll.addAdjustmentListener(this);
150 vscroll.addAdjustmentListener(this);
152 addComponentListener(new ComponentAdapter()
155 public void componentResized(ComponentEvent evt)
157 // reset the viewport ranges when the alignment panel is resized
158 // in particular, this initialises the end residue value when Jalview
160 if (av.getWrapAlignment())
162 int widthInRes = getSeqPanel().seqCanvas
163 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164 vpRanges.setViewportWidth(widthInRes);
168 int widthInRes = getSeqPanel().seqCanvas.getWidth()
170 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171 / av.getCharHeight();
173 vpRanges.setViewportWidth(widthInRes);
174 vpRanges.setViewportHeight(heightInSeq);
180 final AlignmentPanel ap = this;
181 propertyChangeListener = new PropertyChangeListener()
184 public void propertyChange(PropertyChangeEvent evt)
186 if (evt.getPropertyName().equals("alignment"))
188 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
193 av.addPropertyChangeListener(propertyChangeListener);
195 av.getRanges().addPropertyChangeListener(this);
197 adjustAnnotationHeight();
202 public AlignViewportI getAlignViewport()
207 public void alignmentChanged()
209 av.alignmentChanged(this);
211 if (getCalculationDialog() != null)
213 getCalculationDialog().validateCalcTypes();
216 alignFrame.updateEditMenuBar();
218 paintAlignment(true);
225 public void fontChanged()
227 // set idCanvas bufferedImage to null
228 // to prevent drawing old image
229 FontMetrics fm = getFontMetrics(av.getFont());
231 scalePanelHolder.setPreferredSize(new Dimension(10, av.getCharHeight()
233 idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
234 .getCharHeight() + fm.getDescent()));
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
242 d.setSize(d.width + 4, d.height);
243 getIdPanel().getIdCanvas().setPreferredSize(d);
244 hscrollFillerPanel.setPreferredSize(d);
246 if (this.alignFrame.getSplitViewContainer() != null)
248 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
255 * Calculate the width of the alignment labels based on the displayed names
256 * and any bounds on label width set in preferences.
258 * @return Dimension giving the maximum width of the alignment label panel
259 * that should be used.
261 public Dimension calculateIdWidth()
263 // calculate sensible default width when no preference is available
265 if (av.getIdWidth() < 0)
267 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
268 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
269 r = calculateIdWidth(maxwidth);
270 av.setIdWidth(r.width);
275 r.width = av.getIdWidth();
282 * Calculate the width of the alignment labels based on the displayed names
283 * and any bounds on label width set in preferences.
286 * -1 or maximum width allowed for IdWidth
287 * @return Dimension giving the maximum width of the alignment label panel
288 * that should be used.
290 public Dimension calculateIdWidth(int maxwidth)
292 Container c = new Container();
294 FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
295 Font.ITALIC, av.font.getSize()));
297 AlignmentI al = av.getAlignment();
302 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
304 SequenceI s = al.getSequenceAt(i);
306 id = s.getDisplayId(av.getShowJVSuffix());
308 if (fm.stringWidth(id) > idWidth)
310 idWidth = fm.stringWidth(id);
316 // Also check annotation label widths
319 if (al.getAlignmentAnnotation() != null)
321 fm = c.getFontMetrics(getAlabels().getFont());
323 while (i < al.getAlignmentAnnotation().length)
325 String label = al.getAlignmentAnnotation()[i].label;
327 if (fm.stringWidth(label) > idWidth)
329 idWidth = fm.stringWidth(label);
336 return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
341 * Highlight the given results on the alignment.
344 public void highlightSearchResults(SearchResultsI results)
346 scrollToPosition(results);
347 getSeqPanel().seqCanvas.highlightSearchResults(results);
351 * Scroll the view to show the position of the highlighted region in results
352 * (if any) and redraw the overview
356 public boolean scrollToPosition(SearchResultsI results)
358 return scrollToPosition(results, 0, true, false);
362 * Scroll the view to show the position of the highlighted region in results
365 * @param searchResults
366 * @param redrawOverview
369 public boolean scrollToPosition(SearchResultsI searchResults,
370 boolean redrawOverview)
372 return scrollToPosition(searchResults, 0, redrawOverview, false);
376 * Scroll the view to show the position of the highlighted region in results
380 * @param verticalOffset
381 * if greater than zero, allows scrolling to a position below the
382 * first displayed sequence
383 * @param redrawOverview
384 * - when set, the overview will be recalculated (takes longer)
386 * if true, try to centre the search results horizontally in the view
387 * @return false if results were not found
389 public boolean scrollToPosition(SearchResultsI results,
390 int verticalOffset, boolean redrawOverview, boolean centre)
392 int startv, endv, starts, ends;
393 // TODO: properly locate search results in view when large numbers of hidden
394 // columns exist before highlighted region
395 // do we need to scroll the panel?
396 // TODO: tons of nullpointerexceptions raised here.
397 if (results != null && results.getSize() > 0 && av != null
398 && av.getAlignment() != null)
400 int seqIndex = av.getAlignment().findIndex(results);
405 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
407 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
416 * To centre results, scroll to positions half the visible width
417 * left/right of the start/end positions
421 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
422 start = Math.max(start - offset, 0);
423 end = end + offset - 1;
429 if (end == seq.getEnd())
433 if (av.hasHiddenColumns())
435 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
436 start = hidden.findColumnPosition(start);
437 end = hidden.findColumnPosition(end);
440 if (!hidden.isVisible(r[0]))
442 // don't scroll - position isn't visible
449 * allow for offset of target sequence (actually scroll to one above it)
451 seqIndex = Math.max(0, seqIndex - verticalOffset);
453 if (!av.getWrapAlignment())
455 if ((startv = vpRanges.getStartRes()) >= start)
458 * Scroll left to make start of search results visible
460 setScrollValues(start, seqIndex);
462 else if ((endv = vpRanges.getEndRes()) <= end)
465 * Scroll right to make end of search results visible
467 setScrollValues(startv + end - endv, seqIndex);
469 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
472 * Scroll up to make start of search results visible
474 setScrollValues(vpRanges.getStartRes(), seqIndex);
476 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
479 * Scroll down to make end of search results visible
481 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
485 * Else results are already visible - no need to scroll
490 vpRanges.scrollToWrappedVisible(start);
494 paintAlignment(redrawOverview);
501 * @return DOCUMENT ME!
503 public OverviewPanel getOverviewPanel()
505 return overviewPanel;
514 public void setOverviewPanel(OverviewPanel op)
522 * Hide or show annotation panel
525 public void setAnnotationVisible(boolean b)
527 if (!av.getWrapAlignment())
529 annotationSpaceFillerHolder.setVisible(b);
530 annotationScroller.setVisible(b);
536 * automatically adjust annotation panel height for new annotation whilst
537 * ensuring the alignment is still visible.
540 public void adjustAnnotationHeight()
542 // TODO: display vertical annotation scrollbar if necessary
543 // this is called after loading new annotation onto alignment
544 if (alignFrame.getHeight() == 0)
546 System.out.println("NEEDS FIXING");
548 validateAnnotationDimensions(true);
550 paintAlignment(true);
554 * calculate the annotation dimensions and refresh slider values accordingly.
555 * need to do repaints/notifys afterwards.
557 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
559 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
561 if (adjustPanelHeight)
563 int rowHeight = av.getCharHeight();
564 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
567 * Estimate available height in the AlignFrame for alignment +
568 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
569 * hscroll, status bar (as these are not laid out we can't inspect their
570 * actual heights). Insets gives frame borders.
572 int stuff = Platform.isAMac() ? 80 : 100;
573 Insets insets = alignFrame.getInsets();
574 int availableHeight = alignFrame.getHeight() - stuff - insets.top
578 * If not enough vertical space, maximize annotation height while keeping
579 * at least two rows of alignment visible
581 if (annotationHeight + alignmentHeight > availableHeight)
583 annotationHeight = Math.min(annotationHeight, availableHeight - 2
589 // maintain same window layout whilst updating sliders
590 annotationHeight = annotationScroller.getSize().height;
594 annotationScroller.setPreferredSize(new Dimension(annotationScroller
595 .getWidth(), annotationHeight));
597 Dimension e = idPanel.getSize();
598 alabels.setSize(new Dimension(e.width, annotationHeight));
600 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
601 annotationSpaceFillerHolder.getWidth(), annotationHeight));
602 annotationScroller.validate();
603 annotationScroller.addNotify();
607 * update alignment layout for viewport settings
612 public void updateLayout()
615 setAnnotationVisible(av.isShowAnnotation());
616 boolean wrap = av.getWrapAlignment();
617 vpRanges.setStartSeq(0);
618 scalePanelHolder.setVisible(!wrap);
619 hscroll.setVisible(!wrap);
620 idwidthAdjuster.setVisible(!wrap);
624 annotationScroller.setVisible(false);
625 annotationSpaceFillerHolder.setVisible(false);
627 else if (av.isShowAnnotation())
629 annotationScroller.setVisible(true);
630 annotationSpaceFillerHolder.setVisible(true);
635 int widthInRes = getSeqPanel().seqCanvas
636 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
637 vpRanges.setViewportWidth(widthInRes);
641 int widthInRes = (getSeqPanel().seqCanvas.getWidth() / av
642 .getCharWidth()) - 1;
643 int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
644 .getCharHeight()) - 1;
646 vpRanges.setViewportWidth(widthInRes);
647 vpRanges.setViewportHeight(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 xpos, int ypos)
670 if (av == null || av.getAlignment() == null)
675 if (av.getWrapAlignment())
677 setScrollingForWrappedPanel(x);
681 int width = av.getAlignment().getWidth();
682 int height = av.getAlignment().getHeight();
684 if (av.hasHiddenColumns())
686 // reset the width to exclude hidden columns
687 width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
690 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
691 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
698 if (vextent > height)
703 if ((hextent + x) > width)
708 if ((vextent + y) > height)
710 y = height - vextent;
723 // update the scroll values
724 hscroll.setValues(x, hextent, 0, width);
725 vscroll.setValues(y, vextent, 0, height);
730 * Respond to adjustment event when horizontal or vertical scrollbar is
734 * adjustment event encoding whether hscroll or vscroll changed
737 public void adjustmentValueChanged(AdjustmentEvent evt)
739 int oldX = vpRanges.getStartRes();
740 int oldwidth = vpRanges.getViewportWidth();
741 int oldY = vpRanges.getStartSeq();
742 int oldheight = vpRanges.getViewportHeight();
744 if (av.getWrapAlignment())
746 if (evt.getSource() == hscroll)
748 return; // no horizontal scroll when wrapped
750 else if (evt.getSource() == vscroll)
752 int offy = vscroll.getValue();
753 int rowSize = getSeqPanel().seqCanvas
754 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
756 // if we're scrolling to the position we're already at, stop
757 // this prevents infinite recursion of events when the scroll/viewport
758 // ranges values are the same
759 if ((offy * rowSize == oldX) && (oldwidth == rowSize))
765 vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
770 // This is only called if file loaded is a jar file that
771 // was wrapped when saved and user has wrap alignment true
772 // as preference setting
773 SwingUtilities.invokeLater(new Runnable()
778 // When updating scrolling to use ViewportChange events, this code
779 // could not be validated and it is not clear if it is now being
780 // called. Log warning here in case it is called and unforeseen
783 .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
785 // scroll to start of panel
786 vpRanges.setStartRes(0);
787 vpRanges.setStartSeq(0);
796 if (evt.getSource() == hscroll)
798 int x = hscroll.getValue();
799 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
801 // if we're scrolling to the position we're already at, stop
802 // this prevents infinite recursion of events when the scroll/viewport
803 // ranges values are the same
804 if ((x == oldX) && (width == oldwidth))
808 vpRanges.setViewportStartAndWidth(x, width);
810 else if (evt.getSource() == vscroll)
812 int y = vscroll.getValue();
813 int height = getSeqPanel().seqCanvas.getHeight()
814 / av.getCharHeight();
816 // if we're scrolling to the position we're already at, stop
817 // this prevents infinite recursion of events when the scroll/viewport
818 // ranges values are the same
819 if ((y == oldY) && (height == oldheight))
823 vpRanges.setViewportStartAndHeight(y, height);
833 * Repaint the alignment including the annotations and overview panels (if
837 public void paintAlignment(boolean updateOverview)
839 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
840 av.isShowAutocalculatedAbove());
841 sorter.sort(getAlignment().getAlignmentAnnotation(),
842 av.getSortAnnotationsBy());
847 // TODO: determine if this paintAlignment changed structure colours
848 av.getStructureSelectionManager().sequenceColoursChanged(this);
850 if (overviewPanel != null)
852 overviewPanel.updateOverviewImage();
864 public void paintComponent(Graphics g)
868 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
869 idPanelHolder.setPreferredSize(d);
870 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
874 * set scroll bar positions
876 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
880 * Set vertical scroll bar parameters for wrapped panel
882 * the residue to scroll to
884 private void setScrollingForWrappedPanel(int res)
886 // get the width of the alignment in residues
887 int maxwidth = av.getAlignment().getWidth();
888 if (av.hasHiddenColumns())
890 maxwidth = av.getAlignment().getHiddenColumns()
891 .findColumnPosition(maxwidth) - 1;
894 // get the width of the canvas in residues
895 int canvasWidth = getSeqPanel().seqCanvas
896 .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
899 // position we want to scroll to is number of canvasWidth's to get there
900 int current = res / canvasWidth;
902 // max scroll position: add one because extent is 1 and scrollbar value
903 // can only be set to at most max - extent
904 int max = maxwidth / canvasWidth + 1;
905 vscroll.setUnitIncrement(1);
906 vscroll.setValues(current, 1, 0, max);
920 * @return DOCUMENT ME!
922 * @throws PrinterException
926 public int print(Graphics pg, PageFormat pf, int pi)
927 throws PrinterException
929 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
931 int pwidth = (int) pf.getImageableWidth();
932 int pheight = (int) pf.getImageableHeight();
934 if (av.getWrapAlignment())
936 return printWrappedAlignment(pwidth, pheight, pi, pg);
940 return printUnwrapped(pwidth, pheight, pi, pg, pg);
956 * @return DOCUMENT ME!
958 * @throws PrinterException
962 * Draws the alignment image, including sequence ids, sequences, and
963 * annotation labels and annotations if shown, on either one or two Graphics
970 * the graphics context for sequence ids and annotation labels
971 * @param alignmentGraphics
972 * the graphics context for sequences and annotations (may or may not
973 * be the same context as idGraphics)
975 * @throws PrinterException
977 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
978 Graphics idGraphics, Graphics alignmentGraphics)
979 throws PrinterException
981 final int idWidth = getVisibleIdWidth(false);
984 * Get the horizontal offset to where we draw the sequences.
985 * This is idWidth if using a single Graphics context, else zero.
987 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
989 FontMetrics fm = getFontMetrics(av.getFont());
990 int charHeight = av.getCharHeight();
991 int scaleHeight = charHeight + fm.getDescent();
993 idGraphics.setColor(Color.white);
994 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
995 idGraphics.setFont(av.getFont());
998 * How many sequences and residues can we fit on a printable page?
1000 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1002 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1004 int alignmentWidth = av.getAlignment().getWidth();
1005 int pagesWide = (alignmentWidth / totalRes) + 1;
1007 final int startRes = (pi % pagesWide) * totalRes;
1008 int endRes = (startRes + totalRes) - 1;
1010 if (endRes > (alignmentWidth - 1))
1012 endRes = alignmentWidth - 1;
1015 final int startSeq = (pi / pagesWide) * totalSeq;
1016 int endSeq = startSeq + totalSeq;
1018 int alignmentHeight = av.getAlignment().getHeight();
1019 if (endSeq > alignmentHeight)
1021 endSeq = alignmentHeight;
1024 int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1027 if (av.isShowAnnotation())
1029 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1032 pagesHigh /= pageHeight;
1034 if (pi >= (pagesWide * pagesHigh))
1036 return Printable.NO_SUCH_PAGE;
1038 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1042 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1044 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1045 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1046 pageWidth - idWidth, scaleHeight);
1047 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1050 * Draw the sequence ids, offset for scale height,
1051 * then reset to top left (0, 0)
1053 idGraphics.translate(0, scaleHeight);
1054 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1055 Color currentColor = null;
1056 Color currentTextColor = null;
1059 for (int i = startSeq; i < endSeq; i++)
1061 seq = av.getAlignment().getSequenceAt(i);
1062 if ((av.getSelectionGroup() != null)
1063 && av.getSelectionGroup().getSequences(null).contains(seq))
1066 * gray out ids of sequences in selection group (if any)
1068 currentColor = Color.gray;
1069 currentTextColor = Color.black;
1073 currentColor = av.getSequenceColour(seq);
1074 currentTextColor = Color.black;
1077 idGraphics.setColor(currentColor);
1078 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1081 idGraphics.setColor(currentTextColor);
1084 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1085 if (av.isRightAlignIds())
1087 fm = idGraphics.getFontMetrics();
1089 - fm.stringWidth(displayId)
1093 idGraphics.drawString(displayId, xPos,
1094 (((i - startSeq) * charHeight) + charHeight)
1095 - (charHeight / 5));
1097 idGraphics.setFont(av.getFont());
1098 idGraphics.translate(0, -scaleHeight);
1101 * draw the sequences, offset for scale height, and id width (if using a
1102 * single graphics context), then reset to (0, scale height)
1104 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1105 getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1106 startSeq, endSeq, 0);
1107 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1109 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1112 * draw annotation labels; drawComponent() translates by
1113 * getScrollOffset(), so compensate for that first;
1114 * then reset to (0, scale height)
1116 int offset = getAlabels().getScrollOffset();
1117 idGraphics.translate(0, -offset);
1118 idGraphics.translate(0, alignmentDrawnHeight);
1119 getAlabels().drawComponent(idGraphics, idWidth);
1120 idGraphics.translate(0, -alignmentDrawnHeight);
1123 * draw the annotations starting at
1124 * (idOffset, alignmentHeight) from (0, scaleHeight)
1126 alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1127 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1128 alignmentGraphics, -1, startRes, endRes + 1);
1131 return Printable.PAGE_EXISTS;
1146 * @return DOCUMENT ME!
1148 * @throws PrinterException
1151 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1152 Graphics pg) throws PrinterException
1154 int annotationHeight = 0;
1155 AnnotationLabels labels = null;
1156 if (av.isShowAnnotation())
1158 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1159 labels = new AnnotationLabels(av);
1162 int hgap = av.getCharHeight();
1163 if (av.getScaleAboveWrapped())
1165 hgap += av.getCharHeight();
1168 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1171 int idWidth = getVisibleIdWidth(false);
1173 int maxwidth = av.getAlignment().getWidth();
1174 if (av.hasHiddenColumns())
1176 maxwidth = av.getAlignment().getHiddenColumns()
1177 .findColumnPosition(maxwidth) - 1;
1180 int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1183 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1185 pg.setColor(Color.white);
1186 pg.fillRect(0, 0, pwidth, pheight);
1187 pg.setFont(av.getFont());
1191 pg.setColor(Color.black);
1193 pg.translate(0, -pi * pheight);
1195 pg.setClip(0, pi * pheight, pwidth, pheight);
1201 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1203 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1204 SequenceI s = av.getAlignment().getSequenceAt(i);
1205 String string = s.getDisplayId(av.getShowJVSuffix());
1207 if (av.isRightAlignIds())
1209 FontMetrics fm = pg.getFontMetrics();
1210 xPos = idWidth - fm.stringWidth(string) - 4;
1212 pg.drawString(string, xPos,
1213 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1214 - (av.getCharHeight() / 5));
1219 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1221 pg.setFont(av.getFont());
1222 labels.drawComponent(pg, idWidth);
1226 - (av.getAlignment().getHeight() * av
1231 } while (ypos < totalHeight);
1233 pg.translate(idWidth, 0);
1235 getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1238 if ((pi * pheight) < totalHeight)
1240 return Printable.PAGE_EXISTS;
1245 return Printable.NO_SUCH_PAGE;
1250 * get current sequence ID panel width, or nominal value if panel were to be
1251 * displayed using default settings
1255 public int getVisibleIdWidth()
1257 return getVisibleIdWidth(true);
1261 * get current sequence ID panel width, or nominal value if panel were to be
1262 * displayed using default settings
1265 * indicate if the Id width for onscreen or offscreen display should
1269 public int getVisibleIdWidth(boolean onscreen)
1271 // see if rendering offscreen - check preferences and calc width accordingly
1272 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1274 return calculateIdWidth(-1).width + 4;
1276 Integer idwidth = null;
1278 || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1280 int w = getIdPanel().getWidth();
1281 return (w > 0 ? w : calculateIdWidth().width + 4);
1283 return idwidth.intValue() + 4;
1286 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1288 int boarderBottomOffset = 5;
1289 long pSessionId = System.currentTimeMillis();
1290 headless = (System.getProperty("java.awt.headless") != null && System
1291 .getProperty("java.awt.headless").equals("true"));
1292 if (alignFrame != null && !headless)
1296 alignFrame.setProgressBar(MessageManager.formatMessage(
1297 "status.saving_file", new Object[] { type.getLabel() }),
1303 AlignmentDimension aDimension = getAlignmentDimension();
1306 jalview.util.ImageMaker im;
1307 final String imageAction, imageTitle;
1308 if (type == jalview.util.ImageMaker.TYPE.PNG)
1310 imageAction = "Create PNG image from alignment";
1313 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1315 imageAction = "Create EPS file from alignment";
1316 imageTitle = alignFrame.getTitle();
1320 imageAction = "Create SVG file from alignment";
1321 imageTitle = alignFrame.getTitle();
1324 im = new jalview.util.ImageMaker(this, type, imageAction,
1325 aDimension.getWidth(), aDimension.getHeight()
1326 + boarderBottomOffset, file, imageTitle,
1327 alignFrame, pSessionId, headless);
1328 Graphics graphics = im.getGraphics();
1329 if (av.getWrapAlignment())
1331 if (graphics != null)
1333 printWrappedAlignment(aDimension.getWidth(),
1334 aDimension.getHeight() + boarderBottomOffset, 0,
1341 if (graphics != null)
1343 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1344 0, graphics, graphics);
1349 } catch (OutOfMemoryError err)
1352 System.out.println("########################\n" + "OUT OF MEMORY "
1353 + file + "\n" + "########################");
1354 new OOMWarning("Creating Image for " + file, err);
1355 // System.out.println("Create IMAGE: " + err);
1356 } catch (Exception ex)
1358 ex.printStackTrace();
1366 public AlignmentDimension getAlignmentDimension()
1368 int maxwidth = av.getAlignment().getWidth();
1369 if (av.hasHiddenColumns())
1371 maxwidth = av.getAlignment().getHiddenColumns()
1372 .findColumnPosition(maxwidth);
1375 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1376 + getScalePanel().getHeight();
1377 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1379 if (av.getWrapAlignment())
1381 height = getWrappedHeight();
1384 // need to obtain default alignment width and then add in any
1385 // additional allowance for id margin
1386 // this duplicates the calculation in getWrappedHeight but adjusts for
1388 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1389 - alignFrame.getInsets().left
1390 - alignFrame.getInsets().right - getVisibleIdWidth()
1391 + getVisibleIdWidth(false);
1395 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1399 else if (av.isShowAnnotation())
1401 height += getAnnotationPanel().adjustPanelHeight() + 3;
1403 return new AlignmentDimension(width, height);
1410 public void makeEPS(File epsFile)
1412 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1418 public void makePNG(File pngFile)
1420 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1423 public void makeSVG(File svgFile)
1425 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1428 public void makePNGImageMap(File imgMapFile, String imageName)
1430 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1431 // ////////////////////////////////////////////
1432 int idWidth = getVisibleIdWidth(false);
1433 FontMetrics fm = getFontMetrics(av.getFont());
1434 int scaleHeight = av.getCharHeight() + fm.getDescent();
1437 // ////////////////////////////////
1438 if (imgMapFile != null)
1442 int sSize = av.getAlignment().getHeight();
1443 int alwidth = av.getAlignment().getWidth();
1444 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1445 out.println(HTMLOutput.getImageMapHTML());
1446 out.println("<img src=\"" + imageName
1447 + "\" border=\"0\" usemap=\"#Map\" >"
1448 + "<map name=\"Map\">");
1450 for (int s = 0; s < sSize; s++)
1452 int sy = s * av.getCharHeight() + scaleHeight;
1454 SequenceI seq = av.getAlignment().getSequenceAt(s);
1455 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1456 for (int column = 0; column < alwidth; column++)
1458 StringBuilder text = new StringBuilder(512);
1459 String triplet = null;
1460 if (av.getAlignment().isNucleotide())
1462 triplet = ResidueProperties.nucleotideName.get(seq
1463 .getCharAt(column) + "");
1467 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1471 if (triplet == null)
1476 int seqPos = seq.findPosition(column);
1477 int gSize = groups.length;
1478 for (int g = 0; g < gSize; g++)
1480 if (text.length() < 1)
1482 text.append("<area shape=\"rect\" coords=\"")
1483 .append((idWidth + column * av.getCharWidth()))
1484 .append(",").append(sy).append(",")
1485 .append((idWidth + (column + 1) * av.getCharWidth()))
1486 .append(",").append((av.getCharHeight() + sy))
1487 .append("\"").append(" onMouseOver=\"toolTip('")
1488 .append(seqPos).append(" ").append(triplet);
1491 if (groups[g].getStartRes() < column
1492 && groups[g].getEndRes() > column)
1494 text.append("<br><em>").append(groups[g].getName())
1499 if (text.length() < 1)
1501 text.append("<area shape=\"rect\" coords=\"")
1502 .append((idWidth + column * av.getCharWidth()))
1503 .append(",").append(sy).append(",")
1504 .append((idWidth + (column + 1) * av.getCharWidth()))
1505 .append(",").append((av.getCharHeight() + sy))
1506 .append("\"").append(" onMouseOver=\"toolTip('")
1507 .append(seqPos).append(" ").append(triplet);
1509 if (!Comparison.isGap(seq.getCharAt(column)))
1511 List<SequenceFeature> features = seq.findFeatures(column, column);
1512 for (SequenceFeature sf : features)
1514 if (sf.isContactFeature())
1516 text.append("<br>").append(sf.getType()).append(" ")
1517 .append(sf.getBegin()).append(":")
1518 .append(sf.getEnd());
1522 text.append("<br>");
1523 text.append(sf.getType());
1524 String description = sf.getDescription();
1525 if (description != null
1526 && !sf.getType().equals(description))
1528 description = description.replace("\"", """);
1529 text.append(" ").append(description);
1532 String status = sf.getStatus();
1533 if (status != null && !"".equals(status))
1535 text.append(" (").append(status).append(")");
1538 if (text.length() > 1)
1540 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1541 out.println(text.toString());
1546 out.println("</map></body></html>");
1549 } catch (Exception ex)
1551 ex.printStackTrace();
1553 } // /////////END OF IMAGE MAP
1557 int getWrappedHeight()
1559 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1561 if (System.getProperty("java.awt.headless") != null
1562 && System.getProperty("java.awt.headless").equals("true"))
1564 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1565 - vscroll.getPreferredSize().width
1566 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1569 int chunkWidth = getSeqPanel().seqCanvas
1570 .getWrappedCanvasWidth(seqPanelWidth);
1572 int hgap = av.getCharHeight();
1573 if (av.getScaleAboveWrapped())
1575 hgap += av.getCharHeight();
1578 int annotationHeight = 0;
1579 if (av.isShowAnnotation())
1581 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1584 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1587 int maxwidth = av.getAlignment().getWidth();
1588 if (av.hasHiddenColumns())
1590 maxwidth = av.getAlignment().getHiddenColumns()
1591 .findColumnPosition(maxwidth) - 1;
1594 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1600 * close the panel - deregisters all listeners and nulls any references to
1603 public void closePanel()
1605 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1606 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1607 PaintRefresher.RemoveComponent(this);
1612 * try to ensure references are nulled
1614 if (annotationPanel != null)
1616 annotationPanel.dispose();
1621 av.removePropertyChangeListener(propertyChangeListener);
1622 jalview.structure.StructureSelectionManager ssm = av
1623 .getStructureSelectionManager();
1624 ssm.removeStructureViewerListener(getSeqPanel(), null);
1625 ssm.removeSelectionListener(getSeqPanel());
1626 ssm.removeCommandListener(av);
1627 ssm.removeStructureViewerListener(getSeqPanel(), null);
1628 ssm.removeSelectionListener(getSeqPanel());
1634 if (Cache.log.isDebugEnabled())
1636 Cache.log.warn("Closing alignment panel which is already closed.");
1642 * Close any open dialogs that would be orphaned when this one is closed
1644 protected void closeChildFrames()
1646 if (calculationDialog != null)
1648 calculationDialog.closeFrame();
1653 * hides or shows dynamic annotation rows based on groups and av state flags
1655 public void updateAnnotation()
1657 updateAnnotation(false, false);
1660 public void updateAnnotation(boolean applyGlobalSettings)
1662 updateAnnotation(applyGlobalSettings, false);
1665 public void updateAnnotation(boolean applyGlobalSettings,
1666 boolean preserveNewGroupSettings)
1668 av.updateGroupAnnotationSettings(applyGlobalSettings,
1669 preserveNewGroupSettings);
1670 adjustAnnotationHeight();
1674 public AlignmentI getAlignment()
1676 return av == null ? null : av.getAlignment();
1680 public String getViewName()
1686 * Make/Unmake this alignment panel the current input focus
1690 public void setSelected(boolean b)
1694 if (alignFrame.getSplitViewContainer() != null)
1697 * bring enclosing SplitFrame to front first if there is one
1699 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1701 alignFrame.setSelected(b);
1702 } catch (Exception ex)
1708 alignFrame.setDisplayedView(this);
1713 public StructureSelectionManager getStructureSelectionManager()
1715 return av.getStructureSelectionManager();
1719 public void raiseOOMWarning(String string, OutOfMemoryError error)
1721 new OOMWarning(string, error, this);
1725 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1728 return new FeatureRenderer(this);
1732 public jalview.api.FeatureRenderer getFeatureRenderer()
1734 return seqPanel.seqCanvas.getFeatureRenderer();
1737 public void updateFeatureRenderer(
1738 jalview.renderer.seqfeatures.FeatureRenderer fr)
1740 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1743 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1745 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1747 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1751 public ScalePanel getScalePanel()
1756 public void setScalePanel(ScalePanel scalePanel)
1758 this.scalePanel = scalePanel;
1761 public SeqPanel getSeqPanel()
1766 public void setSeqPanel(SeqPanel seqPanel)
1768 this.seqPanel = seqPanel;
1771 public AnnotationPanel getAnnotationPanel()
1773 return annotationPanel;
1776 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1778 this.annotationPanel = annotationPanel;
1781 public AnnotationLabels getAlabels()
1786 public void setAlabels(AnnotationLabels alabels)
1788 this.alabels = alabels;
1791 public IdPanel getIdPanel()
1796 public void setIdPanel(IdPanel idPanel)
1798 this.idPanel = idPanel;
1802 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1803 * The aim is to keep the two alignments 'lined up' on their centre columns.
1806 * holds mapped region(s) of this alignment that we are scrolling
1807 * 'to'; may be modified for sequence offset by this method
1808 * @param verticalOffset
1809 * the number of visible sequences to show above the mapped region
1811 public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1814 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1815 * mapped), we can make the scroll-to location a sequence above the one
1818 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1819 List<SequenceI> seqs = av.getAlignment().getSequences();
1822 * This is like AlignmentI.findIndex(seq) but here we are matching the
1823 * dataset sequence not the aligned sequence
1825 boolean matched = false;
1826 for (SequenceI seq : seqs)
1828 if (mappedTo == seq.getDatasetSequence())
1836 return; // failsafe, shouldn't happen
1840 * Scroll to position but centring the target residue.
1842 scrollToPosition(sr, verticalOffset, true, true);
1846 * Set a flag to say do not scroll any (cDNA/protein) complement.
1850 protected void setToScrollComplementPanel(boolean b)
1852 this.scrollComplementaryPanel = b;
1856 * Get whether to scroll complement panel
1858 * @return true if cDNA/protein complement panels should be scrolled
1860 protected boolean isSetToScrollComplementPanel()
1862 return this.scrollComplementaryPanel;
1868 * @adjustHeight if true, try to recalculate panel height for visible
1871 protected void refresh(boolean adjustHeight)
1873 validateAnnotationDimensions(adjustHeight);
1877 // sort, repaint, update overview
1878 paintAlignment(true);
1882 // lightweight repaint
1889 * Property change event fired when a change is made to the viewport ranges
1890 * object associated with this alignment panel's viewport
1892 public void propertyChange(PropertyChangeEvent evt)
1894 // update this panel's scroll values based on the new viewport ranges values
1895 int x = vpRanges.getStartRes();
1896 int y = vpRanges.getStartSeq();
1897 setScrollValues(x, y);
1899 // now update any complementary alignment (its viewport ranges object
1900 // is different so does not get automatically updated)
1901 if (isSetToScrollComplementPanel())
1903 setToScrollComplementPanel(false);
1904 av.scrollComplementaryAlignment();
1905 setToScrollComplementPanel(true);
1910 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1911 * reference should be nulled when the dialog is closed.
1913 * @param calculationChooser
1915 public void setCalculationDialog(CalculationChooser calculationChooser)
1917 calculationDialog = calculationChooser;
1921 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1924 public CalculationChooser getCalculationDialog()
1926 return calculationDialog;