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, ViewportListenerI
77 public AlignViewport av;
79 ViewportRanges vpRanges;
81 OverviewPanel overviewPanel;
83 private SeqPanel seqPanel;
85 private IdPanel idPanel;
87 private boolean headless;
89 IdwidthAdjuster idwidthAdjuster;
92 public AlignFrame alignFrame;
94 private ScalePanel scalePanel;
96 private AnnotationPanel annotationPanel;
98 private AnnotationLabels alabels;
100 // this value is set false when selection area being dragged
101 boolean fastPaint = true;
103 private int hextent = 0;
105 private int vextent = 0;
108 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
109 * false, suppresses invoking the same method recursively.
111 private boolean scrollComplementaryPanel = true;
113 private PropertyChangeListener propertyChangeListener;
115 private CalculationChooser calculationDialog;
118 * Creates a new AlignmentPanel object.
123 public AlignmentPanel(AlignFrame af, final AlignViewport av)
127 vpRanges = av.getRanges();
128 setSeqPanel(new SeqPanel(av, this));
129 setIdPanel(new IdPanel(av, this));
131 setScalePanel(new ScalePanel(av, this));
133 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
134 idwidthAdjuster = new IdwidthAdjuster(this);
135 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137 setAnnotationPanel(new AnnotationPanel(this));
138 setAlabels(new AnnotationLabels(this));
140 annotationScroller.setViewportView(getAnnotationPanel());
141 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
144 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146 setScrollValues(0, 0);
148 hscroll.addAdjustmentListener(this);
149 vscroll.addAdjustmentListener(this);
151 addComponentListener(new ComponentAdapter()
154 public void componentResized(ComponentEvent evt)
156 // reset the viewport ranges when the alignment panel is resized
157 // in particular, this initialises the end residue value when Jalview
159 if (av.getWrapAlignment())
161 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
162 getSeqPanel().seqCanvas.getWidth());
163 vpRanges.setViewportWidth(widthInRes);
167 int widthInRes = getSeqPanel().seqCanvas.getWidth()
169 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
170 / av.getCharHeight();
172 vpRanges.setViewportWidth(widthInRes);
173 vpRanges.setViewportHeight(heightInSeq);
179 final AlignmentPanel ap = this;
180 propertyChangeListener = new PropertyChangeListener()
183 public void propertyChange(PropertyChangeEvent evt)
185 if (evt.getPropertyName().equals("alignment"))
187 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
192 av.addPropertyChangeListener(propertyChangeListener);
194 av.getRanges().addPropertyChangeListener(this);
196 adjustAnnotationHeight();
201 public AlignViewportI getAlignViewport()
206 public void alignmentChanged()
208 av.alignmentChanged(this);
210 if (getCalculationDialog() != null)
212 getCalculationDialog().validateCalcTypes();
215 alignFrame.updateEditMenuBar();
217 paintAlignment(true);
224 public void fontChanged()
226 // set idCanvas bufferedImage to null
227 // to prevent drawing old image
228 FontMetrics fm = getFontMetrics(av.getFont());
230 scalePanelHolder.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idSpaceFillerPanel1.setPreferredSize(
233 new Dimension(10, av.getCharHeight() + fm.getDescent()));
235 getIdPanel().getIdCanvas().gg = null;
236 getSeqPanel().seqCanvas.img = null;
237 getAnnotationPanel().adjustPanelHeight();
239 Dimension d = calculateIdWidth();
241 d.setSize(d.width + 4, d.height);
242 getIdPanel().getIdCanvas().setPreferredSize(d);
243 hscrollFillerPanel.setPreferredSize(d);
245 if (this.alignFrame.getSplitViewContainer() != null)
247 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
254 * Calculate the width of the alignment labels based on the displayed names
255 * and any bounds on label width set in preferences.
257 * @return Dimension giving the maximum width of the alignment label panel
258 * that should be used.
260 public Dimension calculateIdWidth()
262 // calculate sensible default width when no preference is available
264 if (av.getIdWidth() < 0)
266 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
267 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
268 r = calculateIdWidth(maxwidth);
269 av.setIdWidth(r.width);
274 r.width = av.getIdWidth();
281 * Calculate the width of the alignment labels based on the displayed names
282 * and any bounds on label width set in preferences.
285 * -1 or maximum width allowed for IdWidth
286 * @return Dimension giving the maximum width of the alignment label panel
287 * that should be used.
289 public Dimension calculateIdWidth(int maxwidth)
291 Container c = new Container();
293 FontMetrics fm = c.getFontMetrics(
294 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
296 AlignmentI al = av.getAlignment();
301 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
303 SequenceI s = al.getSequenceAt(i);
305 id = s.getDisplayId(av.getShowJVSuffix());
307 if (fm.stringWidth(id) > idWidth)
309 idWidth = fm.stringWidth(id);
315 // Also check annotation label widths
318 if (al.getAlignmentAnnotation() != null)
320 fm = c.getFontMetrics(getAlabels().getFont());
322 while (i < al.getAlignmentAnnotation().length)
324 String label = al.getAlignmentAnnotation()[i].label;
326 if (fm.stringWidth(label) > idWidth)
328 idWidth = fm.stringWidth(label);
335 return new Dimension(
336 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
340 * Highlight the given results on the alignment.
343 public void highlightSearchResults(SearchResultsI results)
345 boolean scrolled = scrollToPosition(results, 0, true, false);
347 boolean noFastPaint = scrolled && av.getWrapAlignment();
349 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
353 * Scroll the view to show the position of the highlighted region in results
356 * @param searchResults
357 * @param redrawOverview
360 public boolean scrollToPosition(SearchResultsI searchResults,
361 boolean redrawOverview)
363 return scrollToPosition(searchResults, 0, redrawOverview, false);
367 * Scrolls the view (if necessary) to show the position of the first
368 * highlighted region in results (if any). Answers true if the view was
369 * scrolled, or false if no matched region was found, or it is already
373 * @param verticalOffset
374 * if greater than zero, allows scrolling to a position below the
375 * first displayed sequence
376 * @param redrawOverview
377 * - when set, the overview will be recalculated (takes longer)
379 * if true, try to centre the search results horizontally in the view
382 protected boolean scrollToPosition(SearchResultsI results,
383 int verticalOffset, boolean redrawOverview, boolean centre)
385 int startv, endv, starts, ends;
387 if (results == null || results.isEmpty() || av == null
388 || 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());
408 * To centre results, scroll to positions half the visible width
409 * left/right of the start/end positions
413 int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
414 start = Math.max(start - offset, 0);
415 end = end + offset - 1;
421 if (end == seq.getEnd())
426 if (av.hasHiddenColumns())
428 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
429 start = hidden.findColumnPosition(start);
430 end = hidden.findColumnPosition(end);
433 if (!hidden.isVisible(r[0]))
435 // don't scroll - position isn't visible
442 * allow for offset of target sequence (actually scroll to one above it)
444 seqIndex = Math.max(0, seqIndex - verticalOffset);
445 boolean scrollNeeded = true;
447 if (!av.getWrapAlignment())
449 if ((startv = vpRanges.getStartRes()) >= start)
452 * Scroll left to make start of search results visible
454 setScrollValues(start, seqIndex);
456 else if ((endv = vpRanges.getEndRes()) <= end)
459 * Scroll right to make end of search results visible
461 setScrollValues(startv + end - endv, seqIndex);
463 else if ((starts = vpRanges.getStartSeq()) > seqIndex)
466 * Scroll up to make start of search results visible
468 setScrollValues(vpRanges.getStartRes(), seqIndex);
470 else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
473 * Scroll down to make end of search results visible
475 setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
479 * Else results are already visible - no need to scroll
481 scrollNeeded = false;
485 scrollNeeded = vpRanges.scrollToWrappedVisible(start);
488 paintAlignment(redrawOverview);
496 * @return DOCUMENT ME!
498 public OverviewPanel getOverviewPanel()
500 return overviewPanel;
509 public void setOverviewPanel(OverviewPanel op)
517 * Hide or show annotation panel
520 public void setAnnotationVisible(boolean b)
522 if (!av.getWrapAlignment())
524 annotationSpaceFillerHolder.setVisible(b);
525 annotationScroller.setVisible(b);
531 * automatically adjust annotation panel height for new annotation whilst
532 * ensuring the alignment is still visible.
535 public void adjustAnnotationHeight()
537 // TODO: display vertical annotation scrollbar if necessary
538 // this is called after loading new annotation onto alignment
539 if (alignFrame.getHeight() == 0)
541 System.out.println("NEEDS FIXING");
543 validateAnnotationDimensions(true);
545 paintAlignment(true);
549 * calculate the annotation dimensions and refresh slider values accordingly.
550 * need to do repaints/notifys afterwards.
552 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
554 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
556 if (adjustPanelHeight)
558 int rowHeight = av.getCharHeight();
559 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
562 * Estimate available height in the AlignFrame for alignment +
563 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
564 * hscroll, status bar (as these are not laid out we can't inspect their
565 * actual heights). Insets gives frame borders.
567 int stuff = Platform.isAMac() ? 80 : 100;
568 Insets insets = alignFrame.getInsets();
569 int availableHeight = alignFrame.getHeight() - stuff - insets.top
573 * If not enough vertical space, maximize annotation height while keeping
574 * at least two rows of alignment visible
576 if (annotationHeight + alignmentHeight > availableHeight)
578 annotationHeight = Math.min(annotationHeight,
579 availableHeight - 2 * rowHeight);
584 // maintain same window layout whilst updating sliders
585 annotationHeight = annotationScroller.getSize().height;
589 annotationScroller.setPreferredSize(
590 new Dimension(annotationScroller.getWidth(), annotationHeight));
592 Dimension e = idPanel.getSize();
593 alabels.setSize(new Dimension(e.width, annotationHeight));
595 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
596 annotationSpaceFillerHolder.getWidth(), annotationHeight));
597 annotationScroller.validate();
598 annotationScroller.addNotify();
602 * update alignment layout for viewport settings
607 public void updateLayout()
610 setAnnotationVisible(av.isShowAnnotation());
611 boolean wrap = av.getWrapAlignment();
612 vpRanges.setStartSeq(0);
613 scalePanelHolder.setVisible(!wrap);
614 hscroll.setVisible(!wrap);
615 idwidthAdjuster.setVisible(!wrap);
619 annotationScroller.setVisible(false);
620 annotationSpaceFillerHolder.setVisible(false);
622 else if (av.isShowAnnotation())
624 annotationScroller.setVisible(true);
625 annotationSpaceFillerHolder.setVisible(true);
628 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
630 { // may not yet be laid out
633 int widthInRes = getSeqPanel().seqCanvas
634 .getWrappedCanvasWidth(canvasWidth);
635 vpRanges.setViewportWidth(widthInRes);
639 int widthInRes = (canvasWidth / av.getCharWidth()) - 1;
640 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
641 / av.getCharHeight()) - 1;
643 vpRanges.setViewportWidth(widthInRes);
644 vpRanges.setViewportHeight(heightInSeq);
648 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 xpos, int ypos)
667 if (av == null || av.getAlignment() == null)
672 if (av.getWrapAlignment())
674 setScrollingForWrappedPanel(x);
678 int width = av.getAlignment().getWidth();
679 int height = av.getAlignment().getHeight();
681 if (av.hasHiddenColumns())
683 // reset the width to exclude hidden columns
684 width = av.getAlignment().getHiddenColumns()
685 .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);
728 * Respond to adjustment event when horizontal or vertical scrollbar is
732 * adjustment event encoding whether hscroll or vscroll changed
735 public void adjustmentValueChanged(AdjustmentEvent evt)
737 if (av.getWrapAlignment())
739 adjustScrollingWrapped(evt);
743 if (evt.getSource() == hscroll)
745 int oldX = vpRanges.getStartRes();
746 int oldwidth = vpRanges.getViewportWidth();
747 int x = hscroll.getValue();
748 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
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 ((x == oldX) && (width == oldwidth))
757 vpRanges.setViewportStartAndWidth(x, width);
759 else if (evt.getSource() == vscroll)
761 int oldY = vpRanges.getStartSeq();
762 int oldheight = vpRanges.getViewportHeight();
763 int y = vscroll.getValue();
764 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
766 // if we're scrolling to the position we're already at, stop
767 // this prevents infinite recursion of events when the scroll/viewport
768 // ranges values are the same
769 if ((y == oldY) && (height == oldheight))
773 vpRanges.setViewportStartAndHeight(y, height);
782 * Responds to a scroll change by setting the start position of the viewport.
787 protected void adjustScrollingWrapped(AdjustmentEvent evt)
789 if (evt.getSource() == hscroll)
791 return; // no horizontal scroll when wrapped
793 if (evt.getSource() == vscroll)
795 int newY = vscroll.getValue();
798 * if we're scrolling to the position we're already at, stop
799 * this prevents infinite recursion of events when the scroll/viewport
800 * ranges values are the same
802 int oldX = vpRanges.getStartRes();
803 int oldY = vpRanges.getWrappedScrollPosition(oldX);
811 * limit page up/down to one width's worth of positions
813 int rowSize = vpRanges.getViewportWidth();
814 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
815 vpRanges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
820 // This is only called if file loaded is a jar file that
821 // was wrapped when saved and user has wrap alignment true
822 // as preference setting
823 SwingUtilities.invokeLater(new Runnable()
828 // When updating scrolling to use ViewportChange events, this code
829 // could not be validated and it is not clear if it is now being
830 // called. Log warning here in case it is called and unforeseen
833 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
835 // scroll to start of panel
836 vpRanges.setStartRes(0);
837 vpRanges.setStartSeq(0);
845 * Repaint the alignment including the annotations and overview panels (if
849 public void paintAlignment(boolean updateOverview)
851 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
852 av.isShowAutocalculatedAbove());
853 sorter.sort(getAlignment().getAlignmentAnnotation(),
854 av.getSortAnnotationsBy());
859 // TODO: determine if this paintAlignment changed structure colours
860 av.getStructureSelectionManager().sequenceColoursChanged(this);
862 if (overviewPanel != null)
864 overviewPanel.updateOverviewImage();
876 public void paintComponent(Graphics g)
880 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
881 idPanelHolder.setPreferredSize(d);
882 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
886 * set scroll bar positions
888 setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
892 * Set vertical scroll bar position, and number of increments, for wrapped
895 * @param topLeftColumn
896 * the column position at top left (0..)
898 private void setScrollingForWrappedPanel(int topLeftColumn)
900 int scrollPosition = vpRanges.getWrappedScrollPosition(topLeftColumn);
901 int maxScroll = vpRanges.getWrappedMaxScroll(topLeftColumn);
904 * a scrollbar's value can be set to at most (maximum-extent)
905 * so we add extent (1) to the maxScroll value
907 vscroll.setUnitIncrement(1);
908 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
921 * @return DOCUMENT ME!
923 * @throws PrinterException
927 public int print(Graphics pg, PageFormat pf, int pi)
928 throws PrinterException
930 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
932 int pwidth = (int) pf.getImageableWidth();
933 int pheight = (int) pf.getImageableHeight();
935 if (av.getWrapAlignment())
937 return printWrappedAlignment(pwidth, pheight, pi, pg);
941 return printUnwrapped(pwidth, pheight, pi, pg, pg);
957 * @return DOCUMENT ME!
959 * @throws PrinterException
963 * Draws the alignment image, including sequence ids, sequences, and
964 * annotation labels and annotations if shown, on either one or two Graphics
971 * the graphics context for sequence ids and annotation labels
972 * @param alignmentGraphics
973 * the graphics context for sequences and annotations (may or may not
974 * be the same context as idGraphics)
976 * @throws PrinterException
978 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
979 Graphics idGraphics, Graphics alignmentGraphics)
980 throws PrinterException
982 final int idWidth = getVisibleIdWidth(false);
985 * Get the horizontal offset to where we draw the sequences.
986 * This is idWidth if using a single Graphics context, else zero.
988 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
991 FontMetrics fm = getFontMetrics(av.getFont());
992 int charHeight = av.getCharHeight();
993 int scaleHeight = charHeight + fm.getDescent();
995 idGraphics.setColor(Color.white);
996 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
997 idGraphics.setFont(av.getFont());
1000 * How many sequences and residues can we fit on a printable page?
1002 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1004 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1006 int alignmentWidth = av.getAlignment().getWidth();
1007 int pagesWide = (alignmentWidth / totalRes) + 1;
1009 final int startRes = (pi % pagesWide) * totalRes;
1010 int endRes = (startRes + totalRes) - 1;
1012 if (endRes > (alignmentWidth - 1))
1014 endRes = alignmentWidth - 1;
1017 final int startSeq = (pi / pagesWide) * totalSeq;
1018 int endSeq = startSeq + totalSeq;
1020 int alignmentHeight = av.getAlignment().getHeight();
1021 if (endSeq > alignmentHeight)
1023 endSeq = alignmentHeight;
1026 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1028 if (av.isShowAnnotation())
1030 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1033 pagesHigh /= pageHeight;
1035 if (pi >= (pagesWide * pagesHigh))
1037 return Printable.NO_SUCH_PAGE;
1039 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
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();
1088 xPos = idWidth - fm.stringWidth(displayId) - 4;
1091 idGraphics.drawString(displayId, xPos,
1092 (((i - startSeq) * charHeight) + charHeight)
1093 - (charHeight / 5));
1095 idGraphics.setFont(av.getFont());
1096 idGraphics.translate(0, -scaleHeight);
1099 * draw the sequences, offset for scale height, and id width (if using a
1100 * single graphics context), then reset to (0, scale height)
1102 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1103 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1104 endRes, startSeq, endSeq);
1105 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1107 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1110 * draw annotation labels; drawComponent() translates by
1111 * getScrollOffset(), so compensate for that first;
1112 * then reset to (0, scale height)
1114 int offset = getAlabels().getScrollOffset();
1115 idGraphics.translate(0, -offset);
1116 idGraphics.translate(0, alignmentDrawnHeight);
1117 getAlabels().drawComponent(idGraphics, idWidth);
1118 idGraphics.translate(0, -alignmentDrawnHeight);
1121 * draw the annotations starting at
1122 * (idOffset, alignmentHeight) from (0, scaleHeight)
1124 alignmentGraphics.translate(alignmentGraphicsOffset,
1125 alignmentDrawnHeight);
1126 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1127 alignmentGraphics, -1, startRes, endRes + 1);
1130 return Printable.PAGE_EXISTS;
1145 * @return DOCUMENT ME!
1147 * @throws PrinterException
1150 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1151 Graphics pg) throws PrinterException
1153 int annotationHeight = 0;
1154 AnnotationLabels labels = null;
1155 if (av.isShowAnnotation())
1157 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1158 labels = new AnnotationLabels(av);
1161 int hgap = av.getCharHeight();
1162 if (av.getScaleAboveWrapped())
1164 hgap += av.getCharHeight();
1167 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1170 int idWidth = getVisibleIdWidth(false);
1172 int maxwidth = av.getAlignment().getWidth();
1173 if (av.hasHiddenColumns())
1175 maxwidth = av.getAlignment().getHiddenColumns()
1176 .findColumnPosition(maxwidth) - 1;
1179 int resWidth = getSeqPanel().seqCanvas
1180 .getWrappedCanvasWidth(pwidth - idWidth);
1182 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1184 pg.setColor(Color.white);
1185 pg.fillRect(0, 0, pwidth, pheight);
1186 pg.setFont(av.getFont());
1190 pg.setColor(Color.black);
1192 pg.translate(0, -pi * pheight);
1194 pg.setClip(0, pi * pheight, pwidth, pheight);
1200 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1202 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1203 SequenceI s = av.getAlignment().getSequenceAt(i);
1204 String string = s.getDisplayId(av.getShowJVSuffix());
1206 if (av.isRightAlignIds())
1208 FontMetrics fm = pg.getFontMetrics();
1209 xPos = idWidth - fm.stringWidth(string) - 4;
1211 pg.drawString(string, xPos,
1212 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1213 - (av.getCharHeight() / 5));
1217 pg.translate(-3, ypos
1218 + (av.getAlignment().getHeight() * av.getCharHeight()));
1220 pg.setFont(av.getFont());
1221 labels.drawComponent(pg, idWidth);
1222 pg.translate(+3, -ypos
1223 - (av.getAlignment().getHeight() * av.getCharHeight()));
1227 } while (ypos < totalHeight);
1229 pg.translate(idWidth, 0);
1231 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg,
1235 if ((pi * pheight) < totalHeight)
1237 return Printable.PAGE_EXISTS;
1242 return Printable.NO_SUCH_PAGE;
1247 * get current sequence ID panel width, or nominal value if panel were to be
1248 * displayed using default settings
1252 public int getVisibleIdWidth()
1254 return getVisibleIdWidth(true);
1258 * get current sequence ID panel width, or nominal value if panel were to be
1259 * displayed using default settings
1262 * indicate if the Id width for onscreen or offscreen display should
1266 public int getVisibleIdWidth(boolean onscreen)
1268 // see if rendering offscreen - check preferences and calc width accordingly
1269 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1271 return calculateIdWidth(-1).width + 4;
1273 Integer idwidth = null;
1274 if (onscreen || (idwidth = Cache
1275 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1277 int w = getIdPanel().getWidth();
1278 return (w > 0 ? w : calculateIdWidth().width + 4);
1280 return idwidth.intValue() + 4;
1283 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1285 int boarderBottomOffset = 5;
1286 long pSessionId = System.currentTimeMillis();
1287 headless = (System.getProperty("java.awt.headless") != null
1288 && System.getProperty("java.awt.headless").equals("true"));
1289 if (alignFrame != null && !headless)
1293 alignFrame.setProgressBar(MessageManager
1294 .formatMessage("status.saving_file", new Object[]
1295 { type.getLabel() }), pSessionId);
1300 AlignmentDimension aDimension = getAlignmentDimension();
1303 jalview.util.ImageMaker im;
1304 final String imageAction, imageTitle;
1305 if (type == jalview.util.ImageMaker.TYPE.PNG)
1307 imageAction = "Create PNG image from alignment";
1310 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1312 imageAction = "Create EPS file from alignment";
1313 imageTitle = alignFrame.getTitle();
1317 imageAction = "Create SVG file from alignment";
1318 imageTitle = alignFrame.getTitle();
1321 im = new jalview.util.ImageMaker(this, type, imageAction,
1322 aDimension.getWidth(),
1323 aDimension.getHeight() + boarderBottomOffset, file,
1324 imageTitle, alignFrame, pSessionId, headless);
1325 Graphics graphics = im.getGraphics();
1326 if (av.getWrapAlignment())
1328 if (graphics != null)
1330 printWrappedAlignment(aDimension.getWidth(),
1331 aDimension.getHeight() + boarderBottomOffset, 0,
1338 if (graphics != null)
1340 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1341 graphics, graphics);
1346 } catch (OutOfMemoryError err)
1349 System.out.println("########################\n" + "OUT OF MEMORY "
1350 + file + "\n" + "########################");
1351 new OOMWarning("Creating Image for " + file, err);
1352 // System.out.println("Create IMAGE: " + err);
1353 } catch (Exception ex)
1355 ex.printStackTrace();
1363 public AlignmentDimension getAlignmentDimension()
1365 int maxwidth = av.getAlignment().getWidth();
1366 if (av.hasHiddenColumns())
1368 maxwidth = av.getAlignment().getHiddenColumns()
1369 .findColumnPosition(maxwidth);
1372 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1373 + getScalePanel().getHeight();
1374 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1376 if (av.getWrapAlignment())
1378 height = getWrappedHeight();
1381 // need to obtain default alignment width and then add in any
1382 // additional allowance for id margin
1383 // this duplicates the calculation in getWrappedHeight but adjusts for
1385 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1386 - alignFrame.getInsets().left - alignFrame.getInsets().right
1387 - getVisibleIdWidth() + getVisibleIdWidth(false);
1391 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1395 else if (av.isShowAnnotation())
1397 height += getAnnotationPanel().adjustPanelHeight() + 3;
1399 return new AlignmentDimension(width, height);
1406 public void makeEPS(File epsFile)
1408 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1414 public void makePNG(File pngFile)
1416 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1419 public void makeSVG(File svgFile)
1421 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1424 public void makePNGImageMap(File imgMapFile, String imageName)
1426 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1427 // ////////////////////////////////////////////
1428 int idWidth = getVisibleIdWidth(false);
1429 FontMetrics fm = getFontMetrics(av.getFont());
1430 int scaleHeight = av.getCharHeight() + fm.getDescent();
1433 // ////////////////////////////////
1434 if (imgMapFile != null)
1438 int sSize = av.getAlignment().getHeight();
1439 int alwidth = av.getAlignment().getWidth();
1440 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1441 out.println(HTMLOutput.getImageMapHTML());
1442 out.println("<img src=\"" + imageName
1443 + "\" border=\"0\" usemap=\"#Map\" >"
1444 + "<map name=\"Map\">");
1446 for (int s = 0; s < sSize; s++)
1448 int sy = s * av.getCharHeight() + scaleHeight;
1450 SequenceI seq = av.getAlignment().getSequenceAt(s);
1451 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1452 for (int column = 0; column < alwidth; column++)
1454 StringBuilder text = new StringBuilder(512);
1455 String triplet = null;
1456 if (av.getAlignment().isNucleotide())
1458 triplet = ResidueProperties.nucleotideName.get(seq
1459 .getCharAt(column) + "");
1463 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1467 if (triplet == null)
1472 int seqPos = seq.findPosition(column);
1473 int gSize = groups.length;
1474 for (int g = 0; g < gSize; g++)
1476 if (text.length() < 1)
1478 text.append("<area shape=\"rect\" coords=\"")
1479 .append((idWidth + column * av.getCharWidth()))
1480 .append(",").append(sy).append(",")
1481 .append((idWidth + (column + 1) * av.getCharWidth()))
1482 .append(",").append((av.getCharHeight() + sy))
1483 .append("\"").append(" onMouseOver=\"toolTip('")
1484 .append(seqPos).append(" ").append(triplet);
1487 if (groups[g].getStartRes() < column
1488 && groups[g].getEndRes() > column)
1490 text.append("<br><em>").append(groups[g].getName())
1495 if (text.length() < 1)
1497 text.append("<area shape=\"rect\" coords=\"")
1498 .append((idWidth + column * av.getCharWidth()))
1499 .append(",").append(sy).append(",")
1500 .append((idWidth + (column + 1) * av.getCharWidth()))
1501 .append(",").append((av.getCharHeight() + sy))
1502 .append("\"").append(" onMouseOver=\"toolTip('")
1503 .append(seqPos).append(" ").append(triplet);
1505 if (!Comparison.isGap(seq.getCharAt(column)))
1507 List<SequenceFeature> features = seq.findFeatures(column, column);
1508 for (SequenceFeature sf : features)
1510 if (sf.isContactFeature())
1512 text.append("<br>").append(sf.getType()).append(" ")
1513 .append(sf.getBegin()).append(":")
1514 .append(sf.getEnd());
1518 text.append("<br>");
1519 text.append(sf.getType());
1520 String description = sf.getDescription();
1521 if (description != null
1522 && !sf.getType().equals(description))
1524 description = description.replace("\"", """);
1525 text.append(" ").append(description);
1528 String status = sf.getStatus();
1529 if (status != null && !"".equals(status))
1531 text.append(" (").append(status).append(")");
1534 if (text.length() > 1)
1536 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1537 out.println(text.toString());
1542 out.println("</map></body></html>");
1545 } catch (Exception ex)
1547 ex.printStackTrace();
1549 } // /////////END OF IMAGE MAP
1553 int getWrappedHeight()
1555 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1557 if (System.getProperty("java.awt.headless") != null
1558 && System.getProperty("java.awt.headless").equals("true"))
1560 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1561 - vscroll.getPreferredSize().width
1562 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1565 int chunkWidth = getSeqPanel().seqCanvas
1566 .getWrappedCanvasWidth(seqPanelWidth);
1568 int hgap = av.getCharHeight();
1569 if (av.getScaleAboveWrapped())
1571 hgap += av.getCharHeight();
1574 int annotationHeight = 0;
1575 if (av.isShowAnnotation())
1577 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1580 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1583 int maxwidth = av.getAlignment().getWidth();
1584 if (av.hasHiddenColumns())
1586 maxwidth = av.getAlignment().getHiddenColumns()
1587 .findColumnPosition(maxwidth) - 1;
1590 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1596 * close the panel - deregisters all listeners and nulls any references to
1599 public void closePanel()
1601 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1602 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1603 PaintRefresher.RemoveComponent(this);
1608 * try to ensure references are nulled
1610 if (annotationPanel != null)
1612 annotationPanel.dispose();
1617 av.removePropertyChangeListener(propertyChangeListener);
1618 jalview.structure.StructureSelectionManager ssm = av
1619 .getStructureSelectionManager();
1620 ssm.removeStructureViewerListener(getSeqPanel(), null);
1621 ssm.removeSelectionListener(getSeqPanel());
1622 ssm.removeCommandListener(av);
1623 ssm.removeStructureViewerListener(getSeqPanel(), null);
1624 ssm.removeSelectionListener(getSeqPanel());
1630 if (Cache.log.isDebugEnabled())
1632 Cache.log.warn("Closing alignment panel which is already closed.");
1638 * Close any open dialogs that would be orphaned when this one is closed
1640 protected void closeChildFrames()
1642 if (calculationDialog != null)
1644 calculationDialog.closeFrame();
1649 * hides or shows dynamic annotation rows based on groups and av state flags
1651 public void updateAnnotation()
1653 updateAnnotation(false, false);
1656 public void updateAnnotation(boolean applyGlobalSettings)
1658 updateAnnotation(applyGlobalSettings, false);
1661 public void updateAnnotation(boolean applyGlobalSettings,
1662 boolean preserveNewGroupSettings)
1664 av.updateGroupAnnotationSettings(applyGlobalSettings,
1665 preserveNewGroupSettings);
1666 adjustAnnotationHeight();
1670 public AlignmentI getAlignment()
1672 return av == null ? null : av.getAlignment();
1676 public String getViewName()
1682 * Make/Unmake this alignment panel the current input focus
1686 public void setSelected(boolean b)
1690 if (alignFrame.getSplitViewContainer() != null)
1693 * bring enclosing SplitFrame to front first if there is one
1695 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1697 alignFrame.setSelected(b);
1698 } catch (Exception ex)
1704 alignFrame.setDisplayedView(this);
1709 public StructureSelectionManager getStructureSelectionManager()
1711 return av.getStructureSelectionManager();
1715 public void raiseOOMWarning(String string, OutOfMemoryError error)
1717 new OOMWarning(string, error, this);
1721 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1724 return new FeatureRenderer(this);
1728 public jalview.api.FeatureRenderer getFeatureRenderer()
1730 return seqPanel.seqCanvas.getFeatureRenderer();
1733 public void updateFeatureRenderer(
1734 jalview.renderer.seqfeatures.FeatureRenderer fr)
1736 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1739 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1741 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1743 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1747 public ScalePanel getScalePanel()
1752 public void setScalePanel(ScalePanel scalePanel)
1754 this.scalePanel = scalePanel;
1757 public SeqPanel getSeqPanel()
1762 public void setSeqPanel(SeqPanel seqPanel)
1764 this.seqPanel = seqPanel;
1767 public AnnotationPanel getAnnotationPanel()
1769 return annotationPanel;
1772 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1774 this.annotationPanel = annotationPanel;
1777 public AnnotationLabels getAlabels()
1782 public void setAlabels(AnnotationLabels alabels)
1784 this.alabels = alabels;
1787 public IdPanel getIdPanel()
1792 public void setIdPanel(IdPanel idPanel)
1794 this.idPanel = idPanel;
1798 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1799 * The aim is to keep the two alignments 'lined up' on their centre columns.
1802 * holds mapped region(s) of this alignment that we are scrolling
1803 * 'to'; may be modified for sequence offset by this method
1804 * @param verticalOffset
1805 * the number of visible sequences to show above the mapped region
1807 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1810 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1811 * mapped), we can make the scroll-to location a sequence above the one
1814 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1815 List<SequenceI> seqs = av.getAlignment().getSequences();
1818 * This is like AlignmentI.findIndex(seq) but here we are matching the
1819 * dataset sequence not the aligned sequence
1821 boolean matched = false;
1822 for (SequenceI seq : seqs)
1824 if (mappedTo == seq.getDatasetSequence())
1832 return; // failsafe, shouldn't happen
1836 * Scroll to position but centring the target residue.
1838 scrollToPosition(sr, verticalOffset, true, true);
1842 * Set a flag to say do not scroll any (cDNA/protein) complement.
1846 protected void setToScrollComplementPanel(boolean b)
1848 this.scrollComplementaryPanel = b;
1852 * Get whether to scroll complement panel
1854 * @return true if cDNA/protein complement panels should be scrolled
1856 protected boolean isSetToScrollComplementPanel()
1858 return this.scrollComplementaryPanel;
1864 * @adjustHeight if true, try to recalculate panel height for visible
1867 protected void refresh(boolean adjustHeight)
1869 validateAnnotationDimensions(adjustHeight);
1873 // sort, repaint, update overview
1874 paintAlignment(true);
1878 // lightweight repaint
1885 * Property change event fired when a change is made to the viewport ranges
1886 * object associated with this alignment panel's viewport
1888 public void propertyChange(PropertyChangeEvent evt)
1890 // update this panel's scroll values based on the new viewport ranges values
1891 int x = vpRanges.getStartRes();
1892 int y = vpRanges.getStartSeq();
1893 setScrollValues(x, y);
1895 // now update any complementary alignment (its viewport ranges object
1896 // is different so does not get automatically updated)
1897 if (isSetToScrollComplementPanel())
1899 setToScrollComplementPanel(false);
1900 av.scrollComplementaryAlignment();
1901 setToScrollComplementPanel(true);
1906 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1907 * reference should be nulled when the dialog is closed.
1909 * @param calculationChooser
1911 public void setCalculationDialog(CalculationChooser calculationChooser)
1913 calculationDialog = calculationChooser;
1917 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1920 public CalculationChooser getCalculationDialog()
1922 return calculationDialog;