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 OverviewPanel overviewPanel;
81 private SeqPanel seqPanel;
83 private IdPanel idPanel;
85 private boolean headless;
87 IdwidthAdjuster idwidthAdjuster;
90 public AlignFrame alignFrame;
92 private ScalePanel scalePanel;
94 private AnnotationPanel annotationPanel;
96 private AnnotationLabels alabels;
98 // this value is set false when selection area being dragged
99 boolean fastPaint = true;
101 private int hextent = 0;
103 private int vextent = 0;
106 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107 * false, suppresses invoking the same method recursively.
109 private boolean scrollComplementaryPanel = true;
111 private PropertyChangeListener propertyChangeListener;
113 private CalculationChooser calculationDialog;
116 * Creates a new AlignmentPanel object.
121 public AlignmentPanel(AlignFrame af, final AlignViewport av)
125 setSeqPanel(new SeqPanel(av, this));
126 setIdPanel(new IdPanel(av, this));
128 setScalePanel(new ScalePanel(av, this));
130 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
131 idwidthAdjuster = new IdwidthAdjuster(this);
132 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
134 setAnnotationPanel(new AnnotationPanel(this));
135 setAlabels(new AnnotationLabels(this));
137 annotationScroller.setViewportView(getAnnotationPanel());
138 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
140 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
141 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
143 setScrollValues(0, 0);
145 hscroll.addAdjustmentListener(this);
146 vscroll.addAdjustmentListener(this);
148 addComponentListener(new ComponentAdapter()
151 public void componentResized(ComponentEvent evt)
153 // reset the viewport ranges when the alignment panel is resized
154 // in particular, this initialises the end residue value when Jalview
156 ViewportRanges ranges = av.getRanges();
157 if (av.getWrapAlignment())
159 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
160 getSeqPanel().seqCanvas.getWidth());
161 ranges.setViewportWidth(widthInRes);
165 int widthInRes = getSeqPanel().seqCanvas.getWidth()
167 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
168 / av.getCharHeight();
170 ranges.setViewportWidth(widthInRes);
171 ranges.setViewportHeight(heightInSeq);
177 final AlignmentPanel ap = this;
178 propertyChangeListener = new PropertyChangeListener()
181 public void propertyChange(PropertyChangeEvent evt)
183 if (evt.getPropertyName().equals("alignment"))
185 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
190 av.addPropertyChangeListener(propertyChangeListener);
192 av.getRanges().addPropertyChangeListener(this);
194 adjustAnnotationHeight();
199 public AlignViewportI getAlignViewport()
204 public void alignmentChanged()
206 av.alignmentChanged(this);
208 if (getCalculationDialog() != null)
210 getCalculationDialog().validateCalcTypes();
213 alignFrame.updateEditMenuBar();
215 paintAlignment(true);
222 public void fontChanged()
224 // set idCanvas bufferedImage to null
225 // to prevent drawing old image
226 FontMetrics fm = getFontMetrics(av.getFont());
228 scalePanelHolder.setPreferredSize(
229 new Dimension(10, av.getCharHeight() + fm.getDescent()));
230 idSpaceFillerPanel1.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idwidthAdjuster.invalidate();
233 scalePanelHolder.invalidate();
234 getIdPanel().getIdCanvas().gg = null;
235 getSeqPanel().seqCanvas.img = null;
236 getAnnotationPanel().adjustPanelHeight();
238 Dimension d = calculateIdWidth();
240 d.setSize(d.width + 4, d.height);
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
244 if (this.alignFrame.getSplitViewContainer() != null)
246 ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
253 * Calculate the width of the alignment labels based on the displayed names
254 * and any bounds on label width set in preferences.
256 * @return Dimension giving the maximum width of the alignment label panel
257 * that should be used.
259 public Dimension calculateIdWidth()
261 // calculate sensible default width when no preference is available
263 if (av.getIdWidth() < 0)
265 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
266 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
267 r = calculateIdWidth(maxwidth);
268 av.setIdWidth(r.width);
273 r.width = av.getIdWidth();
280 * Calculate the width of the alignment labels based on the displayed names
281 * and any bounds on label width set in preferences.
284 * -1 or maximum width allowed for IdWidth
285 * @return Dimension giving the maximum width of the alignment label panel
286 * that should be used.
288 public Dimension calculateIdWidth(int maxwidth)
290 Container c = new Container();
292 FontMetrics fm = c.getFontMetrics(
293 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
295 AlignmentI al = av.getAlignment();
300 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
302 SequenceI s = al.getSequenceAt(i);
304 id = s.getDisplayId(av.getShowJVSuffix());
306 if (fm.stringWidth(id) > idWidth)
308 idWidth = fm.stringWidth(id);
314 // Also check annotation label widths
317 if (al.getAlignmentAnnotation() != null)
319 fm = c.getFontMetrics(getAlabels().getFont());
321 while (i < al.getAlignmentAnnotation().length)
323 String label = al.getAlignmentAnnotation()[i].label;
325 if (fm.stringWidth(label) > idWidth)
327 idWidth = fm.stringWidth(label);
334 return new Dimension(
335 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
339 * Highlight the given results on the alignment.
342 public void highlightSearchResults(SearchResultsI results)
344 boolean scrolled = scrollToPosition(results, 0, true, false);
346 boolean noFastPaint = scrolled && av.getWrapAlignment();
348 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
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 * Scrolls the view (if necessary) to show the position of the first
367 * highlighted region in results (if any). Answers true if the view was
368 * scrolled, or false if no matched region was found, or it is already
372 * @param verticalOffset
373 * if greater than zero, allows scrolling to a position below the
374 * first displayed sequence
375 * @param redrawOverview
376 * - when set, the overview will be recalculated (takes longer)
378 * if true, try to centre the search results horizontally in the view
381 protected boolean scrollToPosition(SearchResultsI results,
382 int verticalOffset, boolean redrawOverview, boolean centre)
384 int startv, endv, starts, ends;
385 ViewportRanges ranges = av.getRanges();
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 = (ranges.getEndRes() - ranges.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 = ranges.getStartRes()) >= start)
452 * Scroll left to make start of search results visible
454 setScrollValues(start, seqIndex);
456 else if ((endv = ranges.getEndRes()) <= end)
459 * Scroll right to make end of search results visible
461 setScrollValues(startv + end - endv, seqIndex);
463 else if ((starts = ranges.getStartSeq()) > seqIndex)
466 * Scroll up to make start of search results visible
468 setScrollValues(ranges.getStartRes(), seqIndex);
470 else if ((ends = ranges.getEndSeq()) <= seqIndex)
473 * Scroll down to make end of search results visible
475 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
479 * Else results are already visible - no need to scroll
481 scrollNeeded = false;
485 scrollNeeded = ranges.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 ViewportRanges ranges = av.getRanges();
613 ranges.setStartSeq(0);
614 scalePanelHolder.setVisible(!wrap);
615 hscroll.setVisible(!wrap);
616 idwidthAdjuster.setVisible(!wrap);
620 annotationScroller.setVisible(false);
621 annotationSpaceFillerHolder.setVisible(false);
623 else if (av.isShowAnnotation())
625 annotationScroller.setVisible(true);
626 annotationSpaceFillerHolder.setVisible(true);
629 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
631 { // may not yet be laid out
634 int widthInRes = getSeqPanel().seqCanvas
635 .getWrappedCanvasWidth(canvasWidth);
636 ranges.setViewportWidth(widthInRes);
640 int widthInRes = (canvasWidth / av.getCharWidth()) - 1;
641 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
642 / av.getCharHeight()) - 1;
644 ranges.setViewportWidth(widthInRes);
645 ranges.setViewportHeight(heightInSeq);
649 idSpaceFillerPanel1.setVisible(!wrap);
655 * Adjust row/column scrollers to show a visible position in the alignment.
658 * visible column to scroll to
660 * visible row to scroll to
663 public void setScrollValues(int xpos, int ypos)
668 if (av == null || av.getAlignment() == null)
673 if (av.getWrapAlignment())
675 setScrollingForWrappedPanel(x);
679 int width = av.getAlignment().getWidth();
680 int height = av.getAlignment().getHeight();
682 if (av.hasHiddenColumns())
684 // reset the width to exclude hidden columns
685 width = av.getAlignment().getHiddenColumns()
686 .findColumnPosition(width);
689 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
690 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
697 if (vextent > height)
702 if ((hextent + x) > width)
707 if ((vextent + y) > height)
709 y = height - vextent;
722 // update the scroll values
723 hscroll.setValues(x, hextent, 0, width);
724 vscroll.setValues(y, vextent, 0, height);
729 * Respond to adjustment event when horizontal or vertical scrollbar is
733 * adjustment event encoding whether hscroll or vscroll changed
736 public void adjustmentValueChanged(AdjustmentEvent evt)
738 if (av.getWrapAlignment())
740 adjustScrollingWrapped(evt);
744 ViewportRanges ranges = av.getRanges();
746 if (evt.getSource() == hscroll)
748 int oldX = ranges.getStartRes();
749 int oldwidth = ranges.getViewportWidth();
750 int x = hscroll.getValue();
751 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
753 // if we're scrolling to the position we're already at, stop
754 // this prevents infinite recursion of events when the scroll/viewport
755 // ranges values are the same
756 if ((x == oldX) && (width == oldwidth))
760 ranges.setViewportStartAndWidth(x, width);
762 else if (evt.getSource() == vscroll)
764 int oldY = ranges.getStartSeq();
765 int oldheight = ranges.getViewportHeight();
766 int y = vscroll.getValue();
767 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
769 // if we're scrolling to the position we're already at, stop
770 // this prevents infinite recursion of events when the scroll/viewport
771 // ranges values are the same
772 if ((y == oldY) && (height == oldheight))
776 ranges.setViewportStartAndHeight(y, height);
785 * Responds to a scroll change by setting the start position of the viewport.
790 protected void adjustScrollingWrapped(AdjustmentEvent evt)
792 if (evt.getSource() == hscroll)
794 return; // no horizontal scroll when wrapped
796 final ViewportRanges ranges = av.getRanges();
798 if (evt.getSource() == vscroll)
800 int newY = vscroll.getValue();
803 * if we're scrolling to the position we're already at, stop
804 * this prevents infinite recursion of events when the scroll/viewport
805 * ranges values are the same
807 int oldX = ranges.getStartRes();
808 int oldY = ranges.getWrappedScrollPosition(oldX);
816 * limit page up/down to one width's worth of positions
818 int rowSize = ranges.getViewportWidth();
819 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
820 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
825 // This is only called if file loaded is a jar file that
826 // was wrapped when saved and user has wrap alignment true
827 // as preference setting
828 SwingUtilities.invokeLater(new Runnable()
833 // When updating scrolling to use ViewportChange events, this code
834 // could not be validated and it is not clear if it is now being
835 // called. Log warning here in case it is called and unforeseen
838 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
840 // scroll to start of panel
841 ranges.setStartRes(0);
842 ranges.setStartSeq(0);
850 * Repaint the alignment including the annotations and overview panels (if
854 public void paintAlignment(boolean updateOverview)
856 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
857 av.isShowAutocalculatedAbove());
858 sorter.sort(getAlignment().getAlignmentAnnotation(),
859 av.getSortAnnotationsBy());
864 // TODO: determine if this paintAlignment changed structure colours
865 av.getStructureSelectionManager().sequenceColoursChanged(this);
867 if (overviewPanel != null)
869 overviewPanel.updateOverviewImage();
881 public void paintComponent(Graphics g)
885 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
886 idPanelHolder.setPreferredSize(d);
887 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
891 * set scroll bar positions
893 ViewportRanges ranges = av.getRanges();
894 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
898 * Set vertical scroll bar position, and number of increments, for wrapped
901 * @param topLeftColumn
902 * the column position at top left (0..)
904 private void setScrollingForWrappedPanel(int topLeftColumn)
906 ViewportRanges ranges = av.getRanges();
907 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
908 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
911 * a scrollbar's value can be set to at most (maximum-extent)
912 * so we add extent (1) to the maxScroll value
914 vscroll.setUnitIncrement(1);
915 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
928 * @return DOCUMENT ME!
930 * @throws PrinterException
934 public int print(Graphics pg, PageFormat pf, int pi)
935 throws PrinterException
937 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
939 int pwidth = (int) pf.getImageableWidth();
940 int pheight = (int) pf.getImageableHeight();
942 if (av.getWrapAlignment())
944 return printWrappedAlignment(pwidth, pheight, pi, pg);
948 return printUnwrapped(pwidth, pheight, pi, pg, pg);
964 * @return DOCUMENT ME!
966 * @throws PrinterException
970 * Draws the alignment image, including sequence ids, sequences, and
971 * annotation labels and annotations if shown, on either one or two Graphics
978 * the graphics context for sequence ids and annotation labels
979 * @param alignmentGraphics
980 * the graphics context for sequences and annotations (may or may not
981 * be the same context as idGraphics)
983 * @throws PrinterException
985 public int printUnwrapped(int pageWidth, int pageHeight, int pi,
986 Graphics idGraphics, Graphics alignmentGraphics)
987 throws PrinterException
989 final int idWidth = getVisibleIdWidth(false);
992 * Get the horizontal offset to where we draw the sequences.
993 * This is idWidth if using a single Graphics context, else zero.
995 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
998 FontMetrics fm = getFontMetrics(av.getFont());
999 int charHeight = av.getCharHeight();
1000 int scaleHeight = charHeight + fm.getDescent();
1002 idGraphics.setColor(Color.white);
1003 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1004 idGraphics.setFont(av.getFont());
1007 * How many sequences and residues can we fit on a printable page?
1009 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1011 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1013 int alignmentWidth = av.getAlignment().getWidth();
1014 int pagesWide = (alignmentWidth / totalRes) + 1;
1016 final int startRes = (pi % pagesWide) * totalRes;
1017 int endRes = (startRes + totalRes) - 1;
1019 if (endRes > (alignmentWidth - 1))
1021 endRes = alignmentWidth - 1;
1024 final int startSeq = (pi / pagesWide) * totalSeq;
1025 int endSeq = startSeq + totalSeq;
1027 int alignmentHeight = av.getAlignment().getHeight();
1028 if (endSeq > alignmentHeight)
1030 endSeq = alignmentHeight;
1033 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1035 if (av.isShowAnnotation())
1037 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1040 pagesHigh /= pageHeight;
1042 if (pi >= (pagesWide * pagesHigh))
1044 return Printable.NO_SUCH_PAGE;
1046 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1049 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1051 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1052 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1053 pageWidth - idWidth, scaleHeight);
1054 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1057 * Draw the sequence ids, offset for scale height,
1058 * then reset to top left (0, 0)
1060 idGraphics.translate(0, scaleHeight);
1061 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1062 Color currentColor = null;
1063 Color currentTextColor = null;
1066 for (int i = startSeq; i < endSeq; i++)
1068 seq = av.getAlignment().getSequenceAt(i);
1069 if ((av.getSelectionGroup() != null)
1070 && av.getSelectionGroup().getSequences(null).contains(seq))
1073 * gray out ids of sequences in selection group (if any)
1075 currentColor = Color.gray;
1076 currentTextColor = Color.black;
1080 currentColor = av.getSequenceColour(seq);
1081 currentTextColor = Color.black;
1084 idGraphics.setColor(currentColor);
1085 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1088 idGraphics.setColor(currentTextColor);
1091 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1092 if (av.isRightAlignIds())
1094 fm = idGraphics.getFontMetrics();
1095 xPos = idWidth - fm.stringWidth(displayId) - 4;
1098 idGraphics.drawString(displayId, xPos,
1099 (((i - startSeq) * charHeight) + charHeight)
1100 - (charHeight / 5));
1102 idGraphics.setFont(av.getFont());
1103 idGraphics.translate(0, -scaleHeight);
1106 * draw the sequences, offset for scale height, and id width (if using a
1107 * single graphics context), then reset to (0, scale height)
1109 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1110 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1111 endRes, startSeq, endSeq);
1112 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1114 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1117 * draw annotation labels; drawComponent() translates by
1118 * getScrollOffset(), so compensate for that first;
1119 * then reset to (0, scale height)
1121 int offset = getAlabels().getScrollOffset();
1122 idGraphics.translate(0, -offset);
1123 idGraphics.translate(0, alignmentDrawnHeight);
1124 getAlabels().drawComponent(idGraphics, idWidth);
1125 idGraphics.translate(0, -alignmentDrawnHeight);
1128 * draw the annotations starting at
1129 * (idOffset, alignmentHeight) from (0, scaleHeight)
1131 alignmentGraphics.translate(alignmentGraphicsOffset,
1132 alignmentDrawnHeight);
1133 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1134 alignmentGraphics, -1, startRes, endRes + 1);
1137 return Printable.PAGE_EXISTS;
1152 * @return DOCUMENT ME!
1154 * @throws PrinterException
1157 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1158 Graphics pg) throws PrinterException
1160 int annotationHeight = 0;
1161 AnnotationLabels labels = null;
1162 if (av.isShowAnnotation())
1164 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1165 labels = new AnnotationLabels(av);
1168 int hgap = av.getCharHeight();
1169 if (av.getScaleAboveWrapped())
1171 hgap += av.getCharHeight();
1174 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1177 int idWidth = getVisibleIdWidth(false);
1179 int maxwidth = av.getAlignment().getWidth();
1180 if (av.hasHiddenColumns())
1182 maxwidth = av.getAlignment().getHiddenColumns()
1183 .findColumnPosition(maxwidth) - 1;
1186 int resWidth = getSeqPanel().seqCanvas
1187 .getWrappedCanvasWidth(pwidth - idWidth);
1189 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1191 pg.setColor(Color.white);
1192 pg.fillRect(0, 0, pwidth, pheight);
1193 pg.setFont(av.getFont());
1197 pg.setColor(Color.black);
1199 pg.translate(0, -pi * pheight);
1201 pg.setClip(0, pi * pheight, pwidth, pheight);
1207 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1209 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1210 SequenceI s = av.getAlignment().getSequenceAt(i);
1211 String string = s.getDisplayId(av.getShowJVSuffix());
1213 if (av.isRightAlignIds())
1215 FontMetrics fm = pg.getFontMetrics();
1216 xPos = idWidth - fm.stringWidth(string) - 4;
1218 pg.drawString(string, xPos,
1219 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1220 - (av.getCharHeight() / 5));
1224 pg.translate(-3, ypos
1225 + (av.getAlignment().getHeight() * av.getCharHeight()));
1227 pg.setFont(av.getFont());
1228 labels.drawComponent(pg, idWidth);
1229 pg.translate(+3, -ypos
1230 - (av.getAlignment().getHeight() * av.getCharHeight()));
1234 } while (ypos < totalHeight);
1236 pg.translate(idWidth, 0);
1238 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1241 if ((pi * pheight) < totalHeight)
1243 return Printable.PAGE_EXISTS;
1248 return Printable.NO_SUCH_PAGE;
1253 * get current sequence ID panel width, or nominal value if panel were to be
1254 * displayed using default settings
1258 public int getVisibleIdWidth()
1260 return getVisibleIdWidth(true);
1264 * get current sequence ID panel width, or nominal value if panel were to be
1265 * displayed using default settings
1268 * indicate if the Id width for onscreen or offscreen display should
1272 public int getVisibleIdWidth(boolean onscreen)
1274 // see if rendering offscreen - check preferences and calc width accordingly
1275 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1277 return calculateIdWidth(-1).width + 4;
1279 Integer idwidth = null;
1280 if (onscreen || (idwidth = Cache
1281 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1283 int w = getIdPanel().getWidth();
1284 return (w > 0 ? w : calculateIdWidth().width + 4);
1286 return idwidth.intValue() + 4;
1289 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1291 int boarderBottomOffset = 5;
1292 long pSessionId = System.currentTimeMillis();
1293 headless = (System.getProperty("java.awt.headless") != null
1294 && System.getProperty("java.awt.headless").equals("true"));
1295 if (alignFrame != null && !headless)
1299 alignFrame.setProgressBar(MessageManager
1300 .formatMessage("status.saving_file", new Object[]
1301 { type.getLabel() }), pSessionId);
1306 AlignmentDimension aDimension = getAlignmentDimension();
1309 jalview.util.ImageMaker im;
1310 final String imageAction, imageTitle;
1311 if (type == jalview.util.ImageMaker.TYPE.PNG)
1313 imageAction = "Create PNG image from alignment";
1316 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1318 imageAction = "Create EPS file from alignment";
1319 imageTitle = alignFrame.getTitle();
1323 imageAction = "Create SVG file from alignment";
1324 imageTitle = alignFrame.getTitle();
1327 im = new jalview.util.ImageMaker(this, type, imageAction,
1328 aDimension.getWidth(),
1329 aDimension.getHeight() + boarderBottomOffset, file,
1330 imageTitle, alignFrame, pSessionId, headless);
1331 Graphics graphics = im.getGraphics();
1332 if (av.getWrapAlignment())
1334 if (graphics != null)
1336 printWrappedAlignment(aDimension.getWidth(),
1337 aDimension.getHeight() + boarderBottomOffset, 0,
1344 if (graphics != null)
1346 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1347 graphics, graphics);
1352 } catch (OutOfMemoryError err)
1355 System.out.println("########################\n" + "OUT OF MEMORY "
1356 + file + "\n" + "########################");
1357 new OOMWarning("Creating Image for " + file, err);
1358 // System.out.println("Create IMAGE: " + err);
1359 } catch (Exception ex)
1361 ex.printStackTrace();
1369 public AlignmentDimension getAlignmentDimension()
1371 int maxwidth = av.getAlignment().getWidth();
1372 if (av.hasHiddenColumns())
1374 maxwidth = av.getAlignment().getHiddenColumns()
1375 .findColumnPosition(maxwidth);
1378 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1379 + getScalePanel().getHeight();
1380 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1382 if (av.getWrapAlignment())
1384 height = getWrappedHeight();
1387 // need to obtain default alignment width and then add in any
1388 // additional allowance for id margin
1389 // this duplicates the calculation in getWrappedHeight but adjusts for
1391 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1392 - alignFrame.getInsets().left - alignFrame.getInsets().right
1393 - getVisibleIdWidth() + getVisibleIdWidth(false);
1397 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1401 else if (av.isShowAnnotation())
1403 height += getAnnotationPanel().adjustPanelHeight() + 3;
1405 return new AlignmentDimension(width, height);
1412 public void makeEPS(File epsFile)
1414 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1420 public void makePNG(File pngFile)
1422 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1425 public void makeSVG(File svgFile)
1427 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1430 public void makePNGImageMap(File imgMapFile, String imageName)
1432 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1433 // ////////////////////////////////////////////
1434 int idWidth = getVisibleIdWidth(false);
1435 FontMetrics fm = getFontMetrics(av.getFont());
1436 int scaleHeight = av.getCharHeight() + fm.getDescent();
1439 // ////////////////////////////////
1440 if (imgMapFile != null)
1444 int sSize = av.getAlignment().getHeight();
1445 int alwidth = av.getAlignment().getWidth();
1446 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1447 out.println(HTMLOutput.getImageMapHTML());
1448 out.println("<img src=\"" + imageName
1449 + "\" border=\"0\" usemap=\"#Map\" >"
1450 + "<map name=\"Map\">");
1452 for (int s = 0; s < sSize; s++)
1454 int sy = s * av.getCharHeight() + scaleHeight;
1456 SequenceI seq = av.getAlignment().getSequenceAt(s);
1457 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1458 for (int column = 0; column < alwidth; column++)
1460 StringBuilder text = new StringBuilder(512);
1461 String triplet = null;
1462 if (av.getAlignment().isNucleotide())
1464 triplet = ResidueProperties.nucleotideName.get(seq
1465 .getCharAt(column) + "");
1469 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1473 if (triplet == null)
1478 int seqPos = seq.findPosition(column);
1479 int gSize = groups.length;
1480 for (int g = 0; g < gSize; g++)
1482 if (text.length() < 1)
1484 text.append("<area shape=\"rect\" coords=\"")
1485 .append((idWidth + column * av.getCharWidth()))
1486 .append(",").append(sy).append(",")
1487 .append((idWidth + (column + 1) * av.getCharWidth()))
1488 .append(",").append((av.getCharHeight() + sy))
1489 .append("\"").append(" onMouseOver=\"toolTip('")
1490 .append(seqPos).append(" ").append(triplet);
1493 if (groups[g].getStartRes() < column
1494 && groups[g].getEndRes() > column)
1496 text.append("<br><em>").append(groups[g].getName())
1501 if (text.length() < 1)
1503 text.append("<area shape=\"rect\" coords=\"")
1504 .append((idWidth + column * av.getCharWidth()))
1505 .append(",").append(sy).append(",")
1506 .append((idWidth + (column + 1) * av.getCharWidth()))
1507 .append(",").append((av.getCharHeight() + sy))
1508 .append("\"").append(" onMouseOver=\"toolTip('")
1509 .append(seqPos).append(" ").append(triplet);
1511 if (!Comparison.isGap(seq.getCharAt(column)))
1513 List<SequenceFeature> features = seq.findFeatures(column, column);
1514 for (SequenceFeature sf : features)
1516 if (sf.isContactFeature())
1518 text.append("<br>").append(sf.getType()).append(" ")
1519 .append(sf.getBegin()).append(":")
1520 .append(sf.getEnd());
1524 text.append("<br>");
1525 text.append(sf.getType());
1526 String description = sf.getDescription();
1527 if (description != null
1528 && !sf.getType().equals(description))
1530 description = description.replace("\"", """);
1531 text.append(" ").append(description);
1534 String status = sf.getStatus();
1535 if (status != null && !"".equals(status))
1537 text.append(" (").append(status).append(")");
1540 if (text.length() > 1)
1542 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1543 out.println(text.toString());
1548 out.println("</map></body></html>");
1551 } catch (Exception ex)
1553 ex.printStackTrace();
1555 } // /////////END OF IMAGE MAP
1559 int getWrappedHeight()
1561 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1563 if (System.getProperty("java.awt.headless") != null
1564 && System.getProperty("java.awt.headless").equals("true"))
1566 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1567 - vscroll.getPreferredSize().width
1568 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1571 int chunkWidth = getSeqPanel().seqCanvas
1572 .getWrappedCanvasWidth(seqPanelWidth);
1574 int hgap = av.getCharHeight();
1575 if (av.getScaleAboveWrapped())
1577 hgap += av.getCharHeight();
1580 int annotationHeight = 0;
1581 if (av.isShowAnnotation())
1583 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1586 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1589 int maxwidth = av.getAlignment().getWidth();
1590 if (av.hasHiddenColumns())
1592 maxwidth = av.getAlignment().getHiddenColumns()
1593 .findColumnPosition(maxwidth) - 1;
1596 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1602 * close the panel - deregisters all listeners and nulls any references to
1605 public void closePanel()
1607 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1608 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1609 PaintRefresher.RemoveComponent(this);
1614 * try to ensure references are nulled
1616 if (annotationPanel != null)
1618 annotationPanel.dispose();
1623 av.removePropertyChangeListener(propertyChangeListener);
1624 jalview.structure.StructureSelectionManager ssm = av
1625 .getStructureSelectionManager();
1626 ssm.removeStructureViewerListener(getSeqPanel(), null);
1627 ssm.removeSelectionListener(getSeqPanel());
1628 ssm.removeCommandListener(av);
1629 ssm.removeStructureViewerListener(getSeqPanel(), null);
1630 ssm.removeSelectionListener(getSeqPanel());
1636 if (Cache.log.isDebugEnabled())
1638 Cache.log.warn("Closing alignment panel which is already closed.");
1644 * Close any open dialogs that would be orphaned when this one is closed
1646 protected void closeChildFrames()
1648 if (calculationDialog != null)
1650 calculationDialog.closeFrame();
1655 * hides or shows dynamic annotation rows based on groups and av state flags
1657 public void updateAnnotation()
1659 updateAnnotation(false, false);
1662 public void updateAnnotation(boolean applyGlobalSettings)
1664 updateAnnotation(applyGlobalSettings, false);
1667 public void updateAnnotation(boolean applyGlobalSettings,
1668 boolean preserveNewGroupSettings)
1670 av.updateGroupAnnotationSettings(applyGlobalSettings,
1671 preserveNewGroupSettings);
1672 adjustAnnotationHeight();
1676 public AlignmentI getAlignment()
1678 return av == null ? null : av.getAlignment();
1682 public String getViewName()
1688 * Make/Unmake this alignment panel the current input focus
1692 public void setSelected(boolean b)
1696 if (alignFrame.getSplitViewContainer() != null)
1699 * bring enclosing SplitFrame to front first if there is one
1701 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1703 alignFrame.setSelected(b);
1704 } catch (Exception ex)
1710 alignFrame.setDisplayedView(this);
1715 public StructureSelectionManager getStructureSelectionManager()
1717 return av.getStructureSelectionManager();
1721 public void raiseOOMWarning(String string, OutOfMemoryError error)
1723 new OOMWarning(string, error, this);
1727 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1730 return new FeatureRenderer(this);
1734 public jalview.api.FeatureRenderer getFeatureRenderer()
1736 return seqPanel.seqCanvas.getFeatureRenderer();
1739 public void updateFeatureRenderer(
1740 jalview.renderer.seqfeatures.FeatureRenderer fr)
1742 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1745 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1747 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1749 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1753 public ScalePanel getScalePanel()
1758 public void setScalePanel(ScalePanel scalePanel)
1760 this.scalePanel = scalePanel;
1763 public SeqPanel getSeqPanel()
1768 public void setSeqPanel(SeqPanel seqPanel)
1770 this.seqPanel = seqPanel;
1773 public AnnotationPanel getAnnotationPanel()
1775 return annotationPanel;
1778 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1780 this.annotationPanel = annotationPanel;
1783 public AnnotationLabels getAlabels()
1788 public void setAlabels(AnnotationLabels alabels)
1790 this.alabels = alabels;
1793 public IdPanel getIdPanel()
1798 public void setIdPanel(IdPanel idPanel)
1800 this.idPanel = idPanel;
1804 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1805 * The aim is to keep the two alignments 'lined up' on their centre columns.
1808 * holds mapped region(s) of this alignment that we are scrolling
1809 * 'to'; may be modified for sequence offset by this method
1810 * @param verticalOffset
1811 * the number of visible sequences to show above the mapped region
1813 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1816 * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1817 * mapped), we can make the scroll-to location a sequence above the one
1820 SequenceI mappedTo = sr.getResults().get(0).getSequence();
1821 List<SequenceI> seqs = av.getAlignment().getSequences();
1824 * This is like AlignmentI.findIndex(seq) but here we are matching the
1825 * dataset sequence not the aligned sequence
1827 boolean matched = false;
1828 for (SequenceI seq : seqs)
1830 if (mappedTo == seq.getDatasetSequence())
1838 return; // failsafe, shouldn't happen
1842 * Scroll to position but centring the target residue.
1844 scrollToPosition(sr, verticalOffset, true, true);
1848 * Set a flag to say do not scroll any (cDNA/protein) complement.
1852 protected void setToScrollComplementPanel(boolean b)
1854 this.scrollComplementaryPanel = b;
1858 * Get whether to scroll complement panel
1860 * @return true if cDNA/protein complement panels should be scrolled
1862 protected boolean isSetToScrollComplementPanel()
1864 return this.scrollComplementaryPanel;
1870 * @adjustHeight if true, try to recalculate panel height for visible
1873 protected void refresh(boolean adjustHeight)
1875 validateAnnotationDimensions(adjustHeight);
1879 // sort, repaint, update overview
1880 paintAlignment(true);
1884 // lightweight repaint
1891 * Property change event fired when a change is made to the viewport ranges
1892 * object associated with this alignment panel's viewport
1894 public void propertyChange(PropertyChangeEvent evt)
1896 // update this panel's scroll values based on the new viewport ranges values
1897 ViewportRanges ranges = av.getRanges();
1898 int x = ranges.getStartRes();
1899 int y = ranges.getStartSeq();
1900 setScrollValues(x, y);
1902 // now update any complementary alignment (its viewport ranges object
1903 // is different so does not get automatically updated)
1904 if (isSetToScrollComplementPanel())
1906 setToScrollComplementPanel(false);
1907 av.scrollComplementaryAlignment();
1908 setToScrollComplementPanel(true);
1913 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1914 * reference should be nulled when the dialog is closed.
1916 * @param calculationChooser
1918 public void setCalculationDialog(CalculationChooser calculationChooser)
1920 calculationDialog = calculationChooser;
1924 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1927 public CalculationChooser getCalculationDialog()
1929 return calculationDialog;