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.event.AdjustmentEvent;
52 import java.awt.event.AdjustmentListener;
53 import java.awt.event.ComponentAdapter;
54 import java.awt.event.ComponentEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.Printable;
57 import java.awt.print.PrinterException;
58 import java.beans.PropertyChangeEvent;
59 import java.beans.PropertyChangeListener;
61 import java.io.FileWriter;
62 import java.io.PrintWriter;
63 import java.util.List;
65 import javax.swing.SwingUtilities;
71 * @version $Revision: 1.161 $
73 public class AlignmentPanel extends GAlignmentPanel implements
74 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
76 public AlignViewport av;
78 OverviewPanel overviewPanel;
80 private SeqPanel seqPanel;
82 private IdPanel idPanel;
84 private boolean headless;
86 IdwidthAdjuster idwidthAdjuster;
89 public AlignFrame alignFrame;
91 private ScalePanel scalePanel;
93 private AnnotationPanel annotationPanel;
95 private AnnotationLabels alabels;
97 private int hextent = 0;
99 private int vextent = 0;
102 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
103 * false, suppresses invoking the same method recursively.
105 private boolean scrollComplementaryPanel = true;
107 private PropertyChangeListener propertyChangeListener;
109 private CalculationChooser calculationDialog;
112 * Creates a new AlignmentPanel object.
117 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 setSeqPanel(new SeqPanel(av, this));
122 setIdPanel(new IdPanel(av, this));
124 setScalePanel(new ScalePanel(av, this));
126 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
127 idwidthAdjuster = new IdwidthAdjuster(this);
128 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
130 setAnnotationPanel(new AnnotationPanel(this));
131 setAlabels(new AnnotationLabels(this));
133 annotationScroller.setViewportView(getAnnotationPanel());
134 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
136 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
137 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
139 setScrollValues(0, 0);
141 hscroll.addAdjustmentListener(this);
142 vscroll.addAdjustmentListener(this);
144 addComponentListener(new ComponentAdapter()
147 public void componentResized(ComponentEvent evt)
149 // reset the viewport ranges when the alignment panel is resized
150 // in particular, this initialises the end residue value when Jalview
152 ViewportRanges ranges = av.getRanges();
153 if (av.getWrapAlignment())
155 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
156 getSeqPanel().seqCanvas.getWidth());
157 ranges.setViewportWidth(widthInRes);
161 int widthInRes = getSeqPanel().seqCanvas.getWidth()
163 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
164 / av.getCharHeight();
166 ranges.setViewportWidth(widthInRes);
167 ranges.setViewportHeight(heightInSeq);
173 final AlignmentPanel ap = this;
174 propertyChangeListener = new PropertyChangeListener()
177 public void propertyChange(PropertyChangeEvent evt)
179 if (evt.getPropertyName().equals("alignment"))
181 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
186 av.addPropertyChangeListener(propertyChangeListener);
188 av.getRanges().addPropertyChangeListener(this);
190 adjustAnnotationHeight();
195 public AlignViewportI getAlignViewport()
200 public void alignmentChanged()
202 av.alignmentChanged(this);
204 if (getCalculationDialog() != null)
206 getCalculationDialog().validateCalcTypes();
209 alignFrame.updateEditMenuBar();
211 // no idea if we need to update structure
212 paintAlignment(true, true);
219 public void fontChanged()
221 // set idCanvas bufferedImage to null
222 // to prevent drawing old image
223 FontMetrics fm = getFontMetrics(av.getFont());
225 scalePanelHolder.setPreferredSize(
226 new Dimension(10, av.getCharHeight() + fm.getDescent()));
227 idSpaceFillerPanel1.setPreferredSize(
228 new Dimension(10, av.getCharHeight() + fm.getDescent()));
229 idwidthAdjuster.invalidate();
230 scalePanelHolder.invalidate();
231 getIdPanel().getIdCanvas().gg = null;
232 getSeqPanel().seqCanvas.img = null;
233 getAnnotationPanel().adjustPanelHeight();
235 Dimension d = calculateIdWidth();
237 d.setSize(d.width + 4, d.height);
238 getIdPanel().getIdCanvas().setPreferredSize(d);
239 hscrollFillerPanel.setPreferredSize(d);
245 * Calculate the width of the alignment labels based on the displayed names
246 * and any bounds on label width set in preferences.
248 * @return Dimension giving the maximum width of the alignment label panel
249 * that should be used.
251 public Dimension calculateIdWidth()
253 // calculate sensible default width when no preference is available
255 if (av.getIdWidth() < 0)
257 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
258 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
259 r = calculateIdWidth(maxwidth);
260 av.setIdWidth(r.width);
265 r.width = av.getIdWidth();
272 * Calculate the width of the alignment labels based on the displayed names
273 * and any bounds on label width set in preferences.
276 * -1 or maximum width allowed for IdWidth
277 * @return Dimension giving the maximum width of the alignment label panel
278 * that should be used.
280 public Dimension calculateIdWidth(int maxwidth)
282 Container c = new Container();
284 FontMetrics fm = c.getFontMetrics(
285 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
287 AlignmentI al = av.getAlignment();
292 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
294 SequenceI s = al.getSequenceAt(i);
296 id = s.getDisplayId(av.getShowJVSuffix());
298 if (fm.stringWidth(id) > idWidth)
300 idWidth = fm.stringWidth(id);
306 // Also check annotation label widths
309 if (al.getAlignmentAnnotation() != null)
311 fm = c.getFontMetrics(getAlabels().getFont());
313 while (i < al.getAlignmentAnnotation().length)
315 String label = al.getAlignmentAnnotation()[i].label;
317 if (fm.stringWidth(label) > idWidth)
319 idWidth = fm.stringWidth(label);
326 return new Dimension(
327 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
331 * Highlight the given results on the alignment.
334 public void highlightSearchResults(SearchResultsI results)
336 boolean scrolled = scrollToPosition(results, 0, true, false);
338 boolean noFastPaint = scrolled && av.getWrapAlignment();
340 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
344 * Scroll the view to show the position of the highlighted region in results
347 * @param searchResults
348 * @param redrawOverview
351 public boolean scrollToPosition(SearchResultsI searchResults,
352 boolean redrawOverview)
354 return scrollToPosition(searchResults, 0, redrawOverview, false);
358 * Scrolls the view (if necessary) to show the position of the first
359 * highlighted region in results (if any). Answers true if the view was
360 * scrolled, or false if no matched region was found, or it is already
364 * @param verticalOffset
365 * if greater than zero, allows scrolling to a position below the
366 * first displayed sequence
367 * @param redrawOverview
368 * - when set, the overview will be recalculated (takes longer)
370 * if true, try to centre the search results horizontally in the view
373 protected boolean scrollToPosition(SearchResultsI results,
374 int verticalOffset, boolean redrawOverview, boolean centre)
376 int startv, endv, starts, ends;
377 ViewportRanges ranges = av.getRanges();
379 if (results == null || results.isEmpty() || av == null
380 || av.getAlignment() == null)
384 int seqIndex = av.getAlignment().findIndex(results);
389 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
391 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
400 * To centre results, scroll to positions half the visible width
401 * left/right of the start/end positions
405 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
406 start = Math.max(start - offset, 0);
407 end = end + offset - 1;
413 if (end == seq.getEnd())
418 if (av.hasHiddenColumns())
420 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
421 start = hidden.absoluteToVisibleColumn(start);
422 end = hidden.absoluteToVisibleColumn(end);
425 if (!hidden.isVisible(r[0]))
427 // don't scroll - position isn't visible
434 * allow for offset of target sequence (actually scroll to one above it)
436 seqIndex = Math.max(0, seqIndex - verticalOffset);
437 boolean scrollNeeded = true;
439 if (!av.getWrapAlignment())
441 if ((startv = ranges.getStartRes()) >= start)
444 * Scroll left to make start of search results visible
446 setScrollValues(start, seqIndex);
448 else if ((endv = ranges.getEndRes()) <= end)
451 * Scroll right to make end of search results visible
453 setScrollValues(startv + end - endv, seqIndex);
455 else if ((starts = ranges.getStartSeq()) > seqIndex)
458 * Scroll up to make start of search results visible
460 setScrollValues(ranges.getStartRes(), seqIndex);
462 else if ((ends = ranges.getEndSeq()) <= seqIndex)
465 * Scroll down to make end of search results visible
467 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
471 * Else results are already visible - no need to scroll
473 scrollNeeded = false;
477 scrollNeeded = ranges.scrollToWrappedVisible(start);
480 paintAlignment(redrawOverview, false);
488 * @return DOCUMENT ME!
490 public OverviewPanel getOverviewPanel()
492 return overviewPanel;
501 public void setOverviewPanel(OverviewPanel op)
509 * Hide or show annotation panel
512 public void setAnnotationVisible(boolean b)
514 if (!av.getWrapAlignment())
516 annotationSpaceFillerHolder.setVisible(b);
517 annotationScroller.setVisible(b);
523 * automatically adjust annotation panel height for new annotation whilst
524 * ensuring the alignment is still visible.
527 public void adjustAnnotationHeight()
529 // TODO: display vertical annotation scrollbar if necessary
530 // this is called after loading new annotation onto alignment
531 if (alignFrame.getHeight() == 0)
533 System.out.println("NEEDS FIXING");
535 validateAnnotationDimensions(true);
537 // TODO: many places call this method and also paintAlignment with various
538 // different settings. this means multiple redraws are triggered...
539 paintAlignment(true, false);
543 * calculate the annotation dimensions and refresh slider values accordingly.
544 * need to do repaints/notifys afterwards.
546 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
548 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
550 if (adjustPanelHeight)
552 int rowHeight = av.getCharHeight();
553 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
556 * Estimate available height in the AlignFrame for alignment +
557 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
558 * hscroll, status bar, insets.
560 int stuff = Platform.isAMac() ? 120 : 140;
561 int availableHeight = alignFrame.getHeight() - stuff;
564 * If not enough vertical space, maximize annotation height while keeping
565 * at least two rows of alignment visible
567 if (annotationHeight + alignmentHeight > availableHeight)
569 annotationHeight = Math.min(annotationHeight,
570 availableHeight - 2 * rowHeight);
575 // maintain same window layout whilst updating sliders
576 annotationHeight = annotationScroller.getSize().height;
580 annotationScroller.setPreferredSize(
581 new Dimension(annotationScroller.getWidth(), annotationHeight));
583 Dimension e = idPanel.getSize();
584 alabels.setSize(new Dimension(e.width, annotationHeight));
586 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
587 annotationSpaceFillerHolder.getWidth(), annotationHeight));
588 annotationScroller.validate();
589 annotationScroller.addNotify();
593 * update alignment layout for viewport settings
598 public void updateLayout()
601 setAnnotationVisible(av.isShowAnnotation());
602 boolean wrap = av.getWrapAlignment();
603 ViewportRanges ranges = av.getRanges();
604 ranges.setStartSeq(0);
605 scalePanelHolder.setVisible(!wrap);
606 hscroll.setVisible(!wrap);
607 idwidthAdjuster.setVisible(!wrap);
611 annotationScroller.setVisible(false);
612 annotationSpaceFillerHolder.setVisible(false);
614 else if (av.isShowAnnotation())
616 annotationScroller.setVisible(true);
617 annotationSpaceFillerHolder.setVisible(true);
620 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
622 { // may not yet be laid out
625 int widthInRes = getSeqPanel().seqCanvas
626 .getWrappedCanvasWidth(canvasWidth);
627 ranges.setViewportWidth(widthInRes);
631 int widthInRes = (canvasWidth / av.getCharWidth());
632 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
633 / av.getCharHeight());
635 ranges.setViewportWidth(widthInRes);
636 ranges.setViewportHeight(heightInSeq);
640 idSpaceFillerPanel1.setVisible(!wrap);
646 * Adjust row/column scrollers to show a visible position in the alignment.
649 * visible column to scroll to
651 * visible row to scroll to
654 public void setScrollValues(int xpos, int ypos)
659 if (av == null || av.getAlignment() == null)
664 if (av.getWrapAlignment())
666 setScrollingForWrappedPanel(x);
670 int width = av.getAlignment().getWidth();
671 int height = av.getAlignment().getHeight();
673 if (av.hasHiddenColumns())
675 // reset the width to exclude hidden columns
676 width = av.getAlignment().getHiddenColumns()
677 .absoluteToVisibleColumn(width);
680 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
681 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
688 if (vextent > height)
693 if ((hextent + x) > width)
698 if ((vextent + y) > height)
700 y = height - vextent;
713 // update the scroll values
714 hscroll.setValues(x, hextent, 0, width);
715 vscroll.setValues(y, vextent, 0, height);
720 * Respond to adjustment event when horizontal or vertical scrollbar is
724 * adjustment event encoding whether hscroll or vscroll changed
727 public void adjustmentValueChanged(AdjustmentEvent evt)
729 if (av.getWrapAlignment())
731 adjustScrollingWrapped(evt);
735 ViewportRanges ranges = av.getRanges();
737 if (evt.getSource() == hscroll)
739 int oldX = ranges.getStartRes();
740 int oldwidth = ranges.getViewportWidth();
741 int x = hscroll.getValue();
742 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
744 // if we're scrolling to the position we're already at, stop
745 // this prevents infinite recursion of events when the scroll/viewport
746 // ranges values are the same
747 if ((x == oldX) && (width == oldwidth))
751 ranges.setViewportStartAndWidth(x, width);
753 else if (evt.getSource() == vscroll)
755 int oldY = ranges.getStartSeq();
756 int oldheight = ranges.getViewportHeight();
757 int y = vscroll.getValue();
758 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
760 // if we're scrolling to the position we're already at, stop
761 // this prevents infinite recursion of events when the scroll/viewport
762 // ranges values are the same
763 if ((y == oldY) && (height == oldheight))
767 ranges.setViewportStartAndHeight(y, height);
773 * Responds to a scroll change by setting the start position of the viewport.
778 protected void adjustScrollingWrapped(AdjustmentEvent evt)
780 if (evt.getSource() == hscroll)
782 return; // no horizontal scroll when wrapped
784 final ViewportRanges ranges = av.getRanges();
786 if (evt.getSource() == vscroll)
788 int newY = vscroll.getValue();
791 * if we're scrolling to the position we're already at, stop
792 * this prevents infinite recursion of events when the scroll/viewport
793 * ranges values are the same
795 int oldX = ranges.getStartRes();
796 int oldY = ranges.getWrappedScrollPosition(oldX);
804 * limit page up/down to one width's worth of positions
806 int rowSize = ranges.getViewportWidth();
807 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
808 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
813 // This is only called if file loaded is a jar file that
814 // was wrapped when saved and user has wrap alignment true
815 // as preference setting
816 SwingUtilities.invokeLater(new Runnable()
821 // When updating scrolling to use ViewportChange events, this code
822 // could not be validated and it is not clear if it is now being
823 // called. Log warning here in case it is called and unforeseen
826 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
828 // scroll to start of panel
829 ranges.setStartRes(0);
830 ranges.setStartSeq(0);
838 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
841 public void paintAlignment(boolean updateOverview,
842 boolean updateStructures)
844 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
845 av.isShowAutocalculatedAbove());
846 sorter.sort(getAlignment().getAlignmentAnnotation(),
847 av.getSortAnnotationsBy());
850 if (updateStructures)
852 av.getStructureSelectionManager().sequenceColoursChanged(this);
857 if (overviewPanel != null)
859 overviewPanel.updateOverviewImage();
871 public void paintComponent(Graphics g)
873 invalidate(); // needed so that the id width adjuster works correctly
875 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
876 idPanelHolder.setPreferredSize(d);
877 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
879 validate(); // needed so that the id width adjuster works correctly
882 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
883 * though I still think this call should be elsewhere.
885 ViewportRanges ranges = av.getRanges();
886 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
890 * Set vertical scroll bar position, and number of increments, for wrapped
893 * @param topLeftColumn
894 * the column position at top left (0..)
896 private void setScrollingForWrappedPanel(int topLeftColumn)
898 ViewportRanges ranges = av.getRanges();
899 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
900 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
903 * a scrollbar's value can be set to at most (maximum-extent)
904 * so we add extent (1) to the maxScroll value
906 vscroll.setUnitIncrement(1);
907 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
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
990 FontMetrics fm = getFontMetrics(av.getFont());
991 int charHeight = av.getCharHeight();
992 int scaleHeight = charHeight + fm.getDescent();
994 idGraphics.setColor(Color.white);
995 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
996 idGraphics.setFont(av.getFont());
999 * How many sequences and residues can we fit on a printable page?
1001 int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1003 int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1005 int alignmentWidth = av.getAlignment().getWidth();
1006 int pagesWide = (alignmentWidth / totalRes) + 1;
1008 final int startRes = (pi % pagesWide) * totalRes;
1009 int endRes = (startRes + totalRes) - 1;
1011 if (endRes > (alignmentWidth - 1))
1013 endRes = alignmentWidth - 1;
1016 final int startSeq = (pi / pagesWide) * totalSeq;
1017 int endSeq = startSeq + totalSeq;
1019 int alignmentHeight = av.getAlignment().getHeight();
1020 if (endSeq > alignmentHeight)
1022 endSeq = alignmentHeight;
1025 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
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 + 3;
1041 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1043 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1044 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1045 pageWidth - idWidth, scaleHeight);
1046 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1049 * Draw the sequence ids, offset for scale height,
1050 * then reset to top left (0, 0)
1052 idGraphics.translate(0, scaleHeight);
1053 idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1054 Color currentColor = null;
1055 Color currentTextColor = null;
1058 for (int i = startSeq; i < endSeq; i++)
1060 seq = av.getAlignment().getSequenceAt(i);
1061 if ((av.getSelectionGroup() != null)
1062 && av.getSelectionGroup().getSequences(null).contains(seq))
1065 * gray out ids of sequences in selection group (if any)
1067 currentColor = Color.gray;
1068 currentTextColor = Color.black;
1072 currentColor = av.getSequenceColour(seq);
1073 currentTextColor = Color.black;
1076 idGraphics.setColor(currentColor);
1077 idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1080 idGraphics.setColor(currentTextColor);
1083 String displayId = seq.getDisplayId(av.getShowJVSuffix());
1084 if (av.isRightAlignIds())
1086 fm = idGraphics.getFontMetrics();
1087 xPos = idWidth - fm.stringWidth(displayId) - 4;
1090 idGraphics.drawString(displayId, xPos,
1091 (((i - startSeq) * charHeight) + charHeight)
1092 - (charHeight / 5));
1094 idGraphics.setFont(av.getFont());
1095 idGraphics.translate(0, -scaleHeight);
1098 * draw the sequences, offset for scale height, and id width (if using a
1099 * single graphics context), then reset to (0, scale height)
1101 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1102 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1103 endRes, startSeq, endSeq);
1104 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1106 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1109 * draw annotation labels; drawComponent() translates by
1110 * getScrollOffset(), so compensate for that first;
1111 * then reset to (0, scale height)
1113 int offset = getAlabels().getScrollOffset();
1114 idGraphics.translate(0, -offset);
1115 idGraphics.translate(0, alignmentDrawnHeight);
1116 getAlabels().drawComponent(idGraphics, idWidth);
1117 idGraphics.translate(0, -alignmentDrawnHeight);
1120 * draw the annotations starting at
1121 * (idOffset, alignmentHeight) from (0, scaleHeight)
1123 alignmentGraphics.translate(alignmentGraphicsOffset,
1124 alignmentDrawnHeight);
1125 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1126 alignmentGraphics, -1, startRes, endRes + 1);
1129 return Printable.PAGE_EXISTS;
1144 * @return DOCUMENT ME!
1146 * @throws PrinterException
1149 public int printWrappedAlignment(int pwidth, int pheight, int pi,
1150 Graphics pg) throws PrinterException
1152 int annotationHeight = 0;
1153 AnnotationLabels labels = null;
1154 if (av.isShowAnnotation())
1156 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1157 labels = new AnnotationLabels(av);
1160 int hgap = av.getCharHeight();
1161 if (av.getScaleAboveWrapped())
1163 hgap += av.getCharHeight();
1166 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1169 int idWidth = getVisibleIdWidth(false);
1171 int maxwidth = av.getAlignment().getWidth();
1172 if (av.hasHiddenColumns())
1174 maxwidth = av.getAlignment().getHiddenColumns()
1175 .absoluteToVisibleColumn(maxwidth) - 1;
1178 int resWidth = getSeqPanel().seqCanvas
1179 .getWrappedCanvasWidth(pwidth - idWidth);
1181 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1183 pg.setColor(Color.white);
1184 pg.fillRect(0, 0, pwidth, pheight);
1185 pg.setFont(av.getFont());
1189 pg.setColor(Color.black);
1191 pg.translate(0, -pi * pheight);
1193 pg.setClip(0, pi * pheight, pwidth, pheight);
1199 for (int i = 0; i < av.getAlignment().getHeight(); i++)
1201 pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1202 SequenceI s = av.getAlignment().getSequenceAt(i);
1203 String string = s.getDisplayId(av.getShowJVSuffix());
1205 if (av.isRightAlignIds())
1207 FontMetrics fm = pg.getFontMetrics();
1208 xPos = idWidth - fm.stringWidth(string) - 4;
1210 pg.drawString(string, xPos,
1211 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1212 - (av.getCharHeight() / 5));
1216 pg.translate(-3, ypos
1217 + (av.getAlignment().getHeight() * av.getCharHeight()));
1219 pg.setFont(av.getFont());
1220 labels.drawComponent(pg, idWidth);
1221 pg.translate(+3, -ypos
1222 - (av.getAlignment().getHeight() * av.getCharHeight()));
1226 } while (ypos < totalHeight);
1228 pg.translate(idWidth, 0);
1230 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1233 if ((pi * pheight) < totalHeight)
1235 return Printable.PAGE_EXISTS;
1240 return Printable.NO_SUCH_PAGE;
1245 * get current sequence ID panel width, or nominal value if panel were to be
1246 * displayed using default settings
1250 public int getVisibleIdWidth()
1252 return getVisibleIdWidth(true);
1256 * get current sequence ID panel width, or nominal value if panel were to be
1257 * displayed using default settings
1260 * indicate if the Id width for onscreen or offscreen display should
1264 public int getVisibleIdWidth(boolean onscreen)
1266 // see if rendering offscreen - check preferences and calc width accordingly
1267 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1269 return calculateIdWidth(-1).width + 4;
1271 Integer idwidth = null;
1272 if (onscreen || (idwidth = Cache
1273 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1275 int w = getIdPanel().getWidth();
1276 return (w > 0 ? w : calculateIdWidth().width + 4);
1278 return idwidth.intValue() + 4;
1281 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1283 int boarderBottomOffset = 5;
1284 long pSessionId = System.currentTimeMillis();
1285 headless = (System.getProperty("java.awt.headless") != null
1286 && System.getProperty("java.awt.headless").equals("true"));
1287 if (alignFrame != null && !headless)
1291 alignFrame.setProgressBar(MessageManager
1292 .formatMessage("status.saving_file", new Object[]
1293 { type.getLabel() }), pSessionId);
1298 AlignmentDimension aDimension = getAlignmentDimension();
1301 jalview.util.ImageMaker im;
1302 final String imageAction, imageTitle;
1303 if (type == jalview.util.ImageMaker.TYPE.PNG)
1305 imageAction = "Create PNG image from alignment";
1308 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1310 imageAction = "Create EPS file from alignment";
1311 imageTitle = alignFrame.getTitle();
1315 imageAction = "Create SVG file from alignment";
1316 imageTitle = alignFrame.getTitle();
1319 im = new jalview.util.ImageMaker(this, type, imageAction,
1320 aDimension.getWidth(),
1321 aDimension.getHeight() + boarderBottomOffset, file,
1322 imageTitle, alignFrame, pSessionId, headless);
1323 Graphics graphics = im.getGraphics();
1324 if (av.getWrapAlignment())
1326 if (graphics != null)
1328 printWrappedAlignment(aDimension.getWidth(),
1329 aDimension.getHeight() + boarderBottomOffset, 0,
1336 if (graphics != null)
1338 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1339 graphics, graphics);
1344 } catch (OutOfMemoryError err)
1347 System.out.println("########################\n" + "OUT OF MEMORY "
1348 + file + "\n" + "########################");
1349 new OOMWarning("Creating Image for " + file, err);
1350 // System.out.println("Create IMAGE: " + err);
1351 } catch (Exception ex)
1353 ex.printStackTrace();
1361 public AlignmentDimension getAlignmentDimension()
1363 int maxwidth = av.getAlignment().getWidth();
1364 if (av.hasHiddenColumns())
1366 maxwidth = av.getAlignment().getHiddenColumns()
1367 .absoluteToVisibleColumn(maxwidth);
1370 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1371 + getScalePanel().getHeight();
1372 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1374 if (av.getWrapAlignment())
1376 height = getWrappedHeight();
1379 // need to obtain default alignment width and then add in any
1380 // additional allowance for id margin
1381 // this duplicates the calculation in getWrappedHeight but adjusts for
1383 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1384 - alignFrame.getInsets().left - alignFrame.getInsets().right
1385 - getVisibleIdWidth() + getVisibleIdWidth(false);
1389 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1393 else if (av.isShowAnnotation())
1395 height += getAnnotationPanel().adjustPanelHeight() + 3;
1397 return new AlignmentDimension(width, height);
1404 public void makeEPS(File epsFile)
1406 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1412 public void makePNG(File pngFile)
1414 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1417 public void makeSVG(File svgFile)
1419 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1422 public void makePNGImageMap(File imgMapFile, String imageName)
1424 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1425 // ////////////////////////////////////////////
1426 int idWidth = getVisibleIdWidth(false);
1427 FontMetrics fm = getFontMetrics(av.getFont());
1428 int scaleHeight = av.getCharHeight() + fm.getDescent();
1431 // ////////////////////////////////
1432 if (imgMapFile != null)
1436 int sSize = av.getAlignment().getHeight();
1437 int alwidth = av.getAlignment().getWidth();
1438 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1439 out.println(HTMLOutput.getImageMapHTML());
1440 out.println("<img src=\"" + imageName
1441 + "\" border=\"0\" usemap=\"#Map\" >"
1442 + "<map name=\"Map\">");
1444 for (int s = 0; s < sSize; s++)
1446 int sy = s * av.getCharHeight() + scaleHeight;
1448 SequenceI seq = av.getAlignment().getSequenceAt(s);
1449 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1450 for (int column = 0; column < alwidth; column++)
1452 StringBuilder text = new StringBuilder(512);
1453 String triplet = null;
1454 if (av.getAlignment().isNucleotide())
1456 triplet = ResidueProperties.nucleotideName.get(seq
1457 .getCharAt(column) + "");
1461 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1465 if (triplet == null)
1470 int seqPos = seq.findPosition(column);
1471 int gSize = groups.length;
1472 for (int g = 0; g < gSize; g++)
1474 if (text.length() < 1)
1476 text.append("<area shape=\"rect\" coords=\"")
1477 .append((idWidth + column * av.getCharWidth()))
1478 .append(",").append(sy).append(",")
1479 .append((idWidth + (column + 1) * av.getCharWidth()))
1480 .append(",").append((av.getCharHeight() + sy))
1481 .append("\"").append(" onMouseOver=\"toolTip('")
1482 .append(seqPos).append(" ").append(triplet);
1485 if (groups[g].getStartRes() < column
1486 && groups[g].getEndRes() > column)
1488 text.append("<br><em>").append(groups[g].getName())
1493 if (text.length() < 1)
1495 text.append("<area shape=\"rect\" coords=\"")
1496 .append((idWidth + column * av.getCharWidth()))
1497 .append(",").append(sy).append(",")
1498 .append((idWidth + (column + 1) * av.getCharWidth()))
1499 .append(",").append((av.getCharHeight() + sy))
1500 .append("\"").append(" onMouseOver=\"toolTip('")
1501 .append(seqPos).append(" ").append(triplet);
1503 if (!Comparison.isGap(seq.getCharAt(column)))
1505 List<SequenceFeature> features = seq.findFeatures(column, column);
1506 for (SequenceFeature sf : features)
1508 if (sf.isContactFeature())
1510 text.append("<br>").append(sf.getType()).append(" ")
1511 .append(sf.getBegin()).append(":")
1512 .append(sf.getEnd());
1516 text.append("<br>");
1517 text.append(sf.getType());
1518 String description = sf.getDescription();
1519 if (description != null
1520 && !sf.getType().equals(description))
1522 description = description.replace("\"", """);
1523 text.append(" ").append(description);
1526 String status = sf.getStatus();
1527 if (status != null && !"".equals(status))
1529 text.append(" (").append(status).append(")");
1532 if (text.length() > 1)
1534 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1535 out.println(text.toString());
1540 out.println("</map></body></html>");
1543 } catch (Exception ex)
1545 ex.printStackTrace();
1547 } // /////////END OF IMAGE MAP
1551 int getWrappedHeight()
1553 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1555 if (System.getProperty("java.awt.headless") != null
1556 && System.getProperty("java.awt.headless").equals("true"))
1558 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1559 - vscroll.getPreferredSize().width
1560 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1563 int chunkWidth = getSeqPanel().seqCanvas
1564 .getWrappedCanvasWidth(seqPanelWidth);
1566 int hgap = av.getCharHeight();
1567 if (av.getScaleAboveWrapped())
1569 hgap += av.getCharHeight();
1572 int annotationHeight = 0;
1573 if (av.isShowAnnotation())
1575 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1578 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1581 int maxwidth = av.getAlignment().getWidth();
1582 if (av.hasHiddenColumns())
1584 maxwidth = av.getAlignment().getHiddenColumns()
1585 .absoluteToVisibleColumn(maxwidth) - 1;
1588 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1594 * close the panel - deregisters all listeners and nulls any references to
1597 public void closePanel()
1599 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1600 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1601 PaintRefresher.RemoveComponent(this);
1606 * try to ensure references are nulled
1608 if (annotationPanel != null)
1610 annotationPanel.dispose();
1611 annotationPanel = null;
1616 av.removePropertyChangeListener(propertyChangeListener);
1617 propertyChangeListener = null;
1618 StructureSelectionManager ssm = av.getStructureSelectionManager();
1619 ssm.removeStructureViewerListener(getSeqPanel(), null);
1620 ssm.removeSelectionListener(getSeqPanel());
1621 ssm.removeCommandListener(av);
1622 ssm.removeStructureViewerListener(getSeqPanel(), null);
1623 ssm.removeSelectionListener(getSeqPanel());
1629 if (Cache.log.isDebugEnabled())
1631 Cache.log.warn("Closing alignment panel which is already closed.");
1637 * Close any open dialogs that would be orphaned when this one is closed
1639 protected void closeChildFrames()
1641 if (overviewPanel != null)
1643 overviewPanel.dispose();
1644 overviewPanel = null;
1646 if (calculationDialog != null)
1648 calculationDialog.closeFrame();
1649 calculationDialog = null;
1654 * hides or shows dynamic annotation rows based on groups and av state flags
1656 public void updateAnnotation()
1658 updateAnnotation(false, false);
1661 public void updateAnnotation(boolean applyGlobalSettings)
1663 updateAnnotation(applyGlobalSettings, false);
1666 public void updateAnnotation(boolean applyGlobalSettings,
1667 boolean preserveNewGroupSettings)
1669 av.updateGroupAnnotationSettings(applyGlobalSettings,
1670 preserveNewGroupSettings);
1671 adjustAnnotationHeight();
1675 public AlignmentI getAlignment()
1677 return av == null ? null : av.getAlignment();
1681 public String getViewName()
1687 * Make/Unmake this alignment panel the current input focus
1691 public void setSelected(boolean b)
1695 if (alignFrame.getSplitViewContainer() != null)
1698 * bring enclosing SplitFrame to front first if there is one
1700 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1702 alignFrame.setSelected(b);
1703 } catch (Exception ex)
1709 alignFrame.setDisplayedView(this);
1714 public StructureSelectionManager getStructureSelectionManager()
1716 return av.getStructureSelectionManager();
1720 public void raiseOOMWarning(String string, OutOfMemoryError error)
1722 new OOMWarning(string, error, this);
1726 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1729 return new FeatureRenderer(this);
1733 public jalview.api.FeatureRenderer getFeatureRenderer()
1735 return seqPanel.seqCanvas.getFeatureRenderer();
1738 public void updateFeatureRenderer(
1739 jalview.renderer.seqfeatures.FeatureRenderer fr)
1741 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1744 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1746 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1748 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1752 public ScalePanel getScalePanel()
1757 public void setScalePanel(ScalePanel scalePanel)
1759 this.scalePanel = scalePanel;
1762 public SeqPanel getSeqPanel()
1767 public void setSeqPanel(SeqPanel seqPanel)
1769 this.seqPanel = seqPanel;
1772 public AnnotationPanel getAnnotationPanel()
1774 return annotationPanel;
1777 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1779 this.annotationPanel = annotationPanel;
1782 public AnnotationLabels getAlabels()
1787 public void setAlabels(AnnotationLabels alabels)
1789 this.alabels = alabels;
1792 public IdPanel getIdPanel()
1797 public void setIdPanel(IdPanel idPanel)
1799 this.idPanel = idPanel;
1803 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1804 * The aim is to keep the two alignments 'lined up' on their centre columns.
1807 * holds mapped region(s) of this alignment that we are scrolling
1808 * 'to'; may be modified for sequence offset by this method
1809 * @param verticalOffset
1810 * the number of visible sequences to show above the mapped region
1812 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1814 scrollToPosition(sr, verticalOffset, true, true);
1818 * Set a flag to say do not scroll any (cDNA/protein) complement.
1822 protected void setToScrollComplementPanel(boolean b)
1824 this.scrollComplementaryPanel = b;
1828 * Get whether to scroll complement panel
1830 * @return true if cDNA/protein complement panels should be scrolled
1832 protected boolean isSetToScrollComplementPanel()
1834 return this.scrollComplementaryPanel;
1840 * @adjustHeight if true, try to recalculate panel height for visible
1843 protected void refresh(boolean adjustHeight)
1845 validateAnnotationDimensions(adjustHeight);
1849 // sort, repaint, update overview
1850 paintAlignment(true, false);
1854 // lightweight repaint
1861 * Property change event fired when a change is made to the viewport ranges
1862 * object associated with this alignment panel's viewport
1864 public void propertyChange(PropertyChangeEvent evt)
1866 // update this panel's scroll values based on the new viewport ranges values
1867 ViewportRanges ranges = av.getRanges();
1868 int x = ranges.getStartRes();
1869 int y = ranges.getStartSeq();
1870 setScrollValues(x, y);
1872 // now update any complementary alignment (its viewport ranges object
1873 // is different so does not get automatically updated)
1874 if (isSetToScrollComplementPanel())
1876 setToScrollComplementPanel(false);
1877 av.scrollComplementaryAlignment();
1878 setToScrollComplementPanel(true);
1883 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1884 * reference should be nulled when the dialog is closed.
1886 * @param calculationChooser
1888 public void setCalculationDialog(CalculationChooser calculationChooser)
1890 calculationDialog = calculationChooser;
1894 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1897 public CalculationChooser getCalculationDialog()
1899 return calculationDialog;