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.viewmodel.ViewportListenerI;
41 import jalview.viewmodel.ViewportRanges;
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Container;
46 import java.awt.Dimension;
48 import java.awt.FontMetrics;
49 import java.awt.Graphics;
50 import java.awt.Graphics2D;
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
77 * spare space in pixels between sequence id and alignment panel
79 private static final int ID_WIDTH_PADDING = 4;
81 public AlignViewport av;
83 OverviewPanel overviewPanel;
85 private SeqPanel seqPanel;
87 private IdPanel idPanel;
89 private boolean headless;
91 IdwidthAdjuster idwidthAdjuster;
94 public AlignFrame alignFrame;
96 private ScalePanel scalePanel;
98 private AnnotationPanel annotationPanel;
100 private AnnotationLabels alabels;
102 private int hextent = 0;
104 private int vextent = 0;
107 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
108 * false, suppresses invoking the same method recursively.
110 private boolean scrollComplementaryPanel = true;
112 private PropertyChangeListener propertyChangeListener;
114 private CalculationChooser calculationDialog;
117 * Creates a new AlignmentPanel object.
122 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 setSeqPanel(new SeqPanel(av, this));
127 setIdPanel(new IdPanel(av, this));
129 setScalePanel(new ScalePanel(av, this));
131 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
132 idwidthAdjuster = new IdwidthAdjuster(this);
133 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
135 setAnnotationPanel(new AnnotationPanel(this));
136 setAlabels(new AnnotationLabels(this));
138 annotationScroller.setViewportView(getAnnotationPanel());
139 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
141 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
142 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
144 setScrollValues(0, 0);
146 hscroll.addAdjustmentListener(this);
147 vscroll.addAdjustmentListener(this);
149 addComponentListener(new ComponentAdapter()
152 public void componentResized(ComponentEvent evt)
154 // reset the viewport ranges when the alignment panel is resized
155 // in particular, this initialises the end residue value when Jalview
157 ViewportRanges ranges = av.getRanges();
158 if (av.getWrapAlignment())
160 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
161 getSeqPanel().seqCanvas.getWidth());
162 ranges.setViewportWidth(widthInRes);
166 int widthInRes = getSeqPanel().seqCanvas.getWidth()
168 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
169 / av.getCharHeight();
171 ranges.setViewportWidth(widthInRes);
172 ranges.setViewportHeight(heightInSeq);
178 final AlignmentPanel ap = this;
179 propertyChangeListener = new PropertyChangeListener()
182 public void propertyChange(PropertyChangeEvent evt)
184 if (evt.getPropertyName().equals("alignment"))
186 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
191 av.addPropertyChangeListener(propertyChangeListener);
193 av.getRanges().addPropertyChangeListener(this);
195 adjustAnnotationHeight();
200 public AlignViewportI getAlignViewport()
205 public void alignmentChanged()
207 av.alignmentChanged(this);
209 if (getCalculationDialog() != null)
211 getCalculationDialog().validateCalcTypes();
214 alignFrame.updateEditMenuBar();
216 // no idea if we need to update structure
217 paintAlignment(true, 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()));
234 idwidthAdjuster.invalidate();
235 scalePanelHolder.invalidate();
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
248 * Calculate the width of the alignment labels based on the displayed names
249 * and any bounds on label width set in preferences.
251 * @return Dimension giving the maximum width of the alignment label panel
252 * that should be used.
254 public Dimension calculateIdWidth()
256 // calculate sensible default width when no preference is available
258 if (av.getIdWidth() < 0)
260 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
261 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
262 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
263 r = calculateIdWidth(maxwidth);
264 av.setIdWidth(r.width);
269 r.width = av.getIdWidth();
276 * Calculate the width of the alignment labels based on the displayed names
277 * and any bounds on label width set in preferences.
280 * -1 or maximum width allowed for IdWidth
281 * @return Dimension giving the maximum width of the alignment label panel
282 * that should be used.
284 protected Dimension calculateIdWidth(int maxwidth)
286 Container c = new Container();
288 FontMetrics fm = c.getFontMetrics(
289 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
291 AlignmentI al = av.getAlignment();
295 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
297 SequenceI s = al.getSequenceAt(i);
298 String id = s.getDisplayId(av.getShowJVSuffix());
299 int stringWidth = fm.stringWidth(id);
300 idWidth = Math.max(idWidth, stringWidth);
304 // Also check annotation label widths
307 if (al.getAlignmentAnnotation() != null)
309 fm = c.getFontMetrics(getAlabels().getFont());
311 while (i < al.getAlignmentAnnotation().length)
313 String label = al.getAlignmentAnnotation()[i].label;
314 int stringWidth = fm.stringWidth(label);
315 idWidth = Math.max(idWidth, stringWidth);
320 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
321 w += ID_WIDTH_PADDING;
323 return new Dimension(w, 12);
327 * Highlight the given results on the alignment
330 public void highlightSearchResults(SearchResultsI results)
332 boolean scrolled = scrollToPosition(results, 0, false);
334 boolean noFastPaint = scrolled && av.getWrapAlignment();
336 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
340 * Scroll the view to show the position of the highlighted region in results
343 * @param searchResults
346 public boolean scrollToPosition(SearchResultsI searchResults)
348 return scrollToPosition(searchResults, 0, false);
352 * Scrolls the view (if necessary) to show the position of the first
353 * highlighted region in results (if any). Answers true if the view was
354 * scrolled, or false if no matched region was found, or it is already
358 * @param verticalOffset
359 * if greater than zero, allows scrolling to a position below the
360 * first displayed sequence
362 * if true, try to centre the search results horizontally in the view
365 protected boolean scrollToPosition(SearchResultsI results,
366 int verticalOffset, boolean centre)
368 int startv, endv, starts, ends;
369 ViewportRanges ranges = av.getRanges();
371 if (results == null || results.isEmpty() || av == null
372 || av.getAlignment() == null)
376 int seqIndex = av.getAlignment().findIndex(results);
381 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
383 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
392 * To centre results, scroll to positions half the visible width
393 * left/right of the start/end positions
397 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
398 start = Math.max(start - offset, 0);
399 end = end + offset - 1;
405 if (end == seq.getEnd())
410 if (av.hasHiddenColumns())
412 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
413 start = hidden.absoluteToVisibleColumn(start);
414 end = hidden.absoluteToVisibleColumn(end);
417 if (!hidden.isVisible(r[0]))
419 // don't scroll - position isn't visible
426 * allow for offset of target sequence (actually scroll to one above it)
428 seqIndex = Math.max(0, seqIndex - verticalOffset);
429 boolean scrollNeeded = true;
431 if (!av.getWrapAlignment())
433 if ((startv = ranges.getStartRes()) >= start)
436 * Scroll left to make start of search results visible
438 setScrollValues(start, seqIndex);
440 else if ((endv = ranges.getEndRes()) <= end)
443 * Scroll right to make end of search results visible
445 setScrollValues(startv + end - endv, seqIndex);
447 else if ((starts = ranges.getStartSeq()) > seqIndex)
450 * Scroll up to make start of search results visible
452 setScrollValues(ranges.getStartRes(), seqIndex);
454 else if ((ends = ranges.getEndSeq()) <= seqIndex)
457 * Scroll down to make end of search results visible
459 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
463 * Else results are already visible - no need to scroll
465 scrollNeeded = false;
469 scrollNeeded = ranges.scrollToWrappedVisible(start);
472 paintAlignment(false, false);
480 * @return DOCUMENT ME!
482 public OverviewPanel getOverviewPanel()
484 return overviewPanel;
493 public void setOverviewPanel(OverviewPanel op)
501 * Hide or show annotation panel
504 public void setAnnotationVisible(boolean b)
506 if (!av.getWrapAlignment())
508 annotationSpaceFillerHolder.setVisible(b);
509 annotationScroller.setVisible(b);
515 * automatically adjust annotation panel height for new annotation whilst
516 * ensuring the alignment is still visible.
519 public void adjustAnnotationHeight()
521 // TODO: display vertical annotation scrollbar if necessary
522 // this is called after loading new annotation onto alignment
523 if (alignFrame.getHeight() == 0)
525 System.out.println("NEEDS FIXING");
527 validateAnnotationDimensions(true);
529 // TODO: many places call this method and also paintAlignment with various
530 // different settings. this means multiple redraws are triggered...
531 paintAlignment(true, av.needToUpdateStructureViews());
535 * calculate the annotation dimensions and refresh slider values accordingly.
536 * need to do repaints/notifys afterwards.
538 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
540 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
541 annotationHeight = getAnnotationPanel()
542 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
545 annotationScroller.setPreferredSize(
546 new Dimension(annotationScroller.getWidth(), annotationHeight));
548 Dimension e = idPanel.getSize();
549 alabels.setSize(new Dimension(e.width, annotationHeight));
551 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
552 annotationSpaceFillerHolder.getWidth(), annotationHeight));
553 annotationScroller.validate();
554 annotationScroller.addNotify();
558 * update alignment layout for viewport settings
563 public void updateLayout()
566 setAnnotationVisible(av.isShowAnnotation());
567 boolean wrap = av.getWrapAlignment();
568 ViewportRanges ranges = av.getRanges();
569 ranges.setStartSeq(0);
570 scalePanelHolder.setVisible(!wrap);
571 hscroll.setVisible(!wrap);
572 idwidthAdjuster.setVisible(!wrap);
576 annotationScroller.setVisible(false);
577 annotationSpaceFillerHolder.setVisible(false);
579 else if (av.isShowAnnotation())
581 annotationScroller.setVisible(true);
582 annotationSpaceFillerHolder.setVisible(true);
583 validateAnnotationDimensions(false);
586 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
588 { // may not yet be laid out
591 int widthInRes = getSeqPanel().seqCanvas
592 .getWrappedCanvasWidth(canvasWidth);
593 ranges.setViewportWidth(widthInRes);
597 int widthInRes = (canvasWidth / av.getCharWidth());
598 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
599 / av.getCharHeight());
601 ranges.setViewportWidth(widthInRes);
602 ranges.setViewportHeight(heightInSeq);
606 idSpaceFillerPanel1.setVisible(!wrap);
612 * Adjust row/column scrollers to show a visible position in the alignment.
615 * visible column to scroll to
617 * visible row to scroll to
620 public void setScrollValues(int xpos, int ypos)
625 if (av == null || av.getAlignment() == null)
630 if (av.getWrapAlignment())
632 setScrollingForWrappedPanel(x);
636 int width = av.getAlignment().getVisibleWidth();
637 int height = av.getAlignment().getHeight();
639 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
640 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
647 if (vextent > height)
652 if ((hextent + x) > width)
657 if ((vextent + y) > height)
659 y = height - vextent;
672 // update the scroll values
673 hscroll.setValues(x, hextent, 0, width);
674 vscroll.setValues(y, vextent, 0, height);
679 * Respond to adjustment event when horizontal or vertical scrollbar is
683 * adjustment event encoding whether hscroll or vscroll changed
686 public void adjustmentValueChanged(AdjustmentEvent evt)
688 if (av.getWrapAlignment())
690 adjustScrollingWrapped(evt);
694 ViewportRanges ranges = av.getRanges();
696 if (evt.getSource() == hscroll)
698 int oldX = ranges.getStartRes();
699 int oldwidth = ranges.getViewportWidth();
700 int x = hscroll.getValue();
701 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
703 // if we're scrolling to the position we're already at, stop
704 // this prevents infinite recursion of events when the scroll/viewport
705 // ranges values are the same
706 if ((x == oldX) && (width == oldwidth))
710 ranges.setViewportStartAndWidth(x, width);
712 else if (evt.getSource() == vscroll)
714 int oldY = ranges.getStartSeq();
715 int oldheight = ranges.getViewportHeight();
716 int y = vscroll.getValue();
717 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
719 // if we're scrolling to the position we're already at, stop
720 // this prevents infinite recursion of events when the scroll/viewport
721 // ranges values are the same
722 if ((y == oldY) && (height == oldheight))
726 ranges.setViewportStartAndHeight(y, height);
732 * Responds to a scroll change by setting the start position of the viewport.
737 protected void adjustScrollingWrapped(AdjustmentEvent evt)
739 if (evt.getSource() == hscroll)
741 return; // no horizontal scroll when wrapped
743 final ViewportRanges ranges = av.getRanges();
745 if (evt.getSource() == vscroll)
747 int newY = vscroll.getValue();
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
754 int oldX = ranges.getStartRes();
755 int oldY = ranges.getWrappedScrollPosition(oldX);
763 * limit page up/down to one width's worth of positions
765 int rowSize = ranges.getViewportWidth();
766 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
767 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
772 // This is only called if file loaded is a jar file that
773 // was wrapped when saved and user has wrap alignment true
774 // as preference setting
775 SwingUtilities.invokeLater(new Runnable()
780 // When updating scrolling to use ViewportChange events, this code
781 // could not be validated and it is not clear if it is now being
782 // called. Log warning here in case it is called and unforeseen
785 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
787 // scroll to start of panel
788 ranges.setStartRes(0);
789 ranges.setStartSeq(0);
797 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
800 public void paintAlignment(boolean updateOverview,
801 boolean updateStructures)
803 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
804 av.isShowAutocalculatedAbove());
805 sorter.sort(getAlignment().getAlignmentAnnotation(),
806 av.getSortAnnotationsBy());
809 if (updateStructures)
811 av.getStructureSelectionManager().sequenceColoursChanged(this);
816 if (overviewPanel != null)
818 overviewPanel.updateOverviewImage();
830 public void paintComponent(Graphics g)
832 invalidate(); // needed so that the id width adjuster works correctly
834 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
835 idPanelHolder.setPreferredSize(d);
836 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
838 validate(); // needed so that the id width adjuster works correctly
841 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
842 * though I still think this call should be elsewhere.
844 ViewportRanges ranges = av.getRanges();
845 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
849 * Set vertical scroll bar position, and number of increments, for wrapped
852 * @param topLeftColumn
853 * the column position at top left (0..)
855 private void setScrollingForWrappedPanel(int topLeftColumn)
857 ViewportRanges ranges = av.getRanges();
858 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
859 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
862 * a scrollbar's value can be set to at most (maximum-extent)
863 * so we add extent (1) to the maxScroll value
865 vscroll.setUnitIncrement(1);
866 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
879 * @return DOCUMENT ME!
881 * @throws PrinterException
885 public int print(Graphics pg, PageFormat pf, int pi)
886 throws PrinterException
888 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
890 int pwidth = (int) pf.getImageableWidth();
891 int pheight = (int) pf.getImageableHeight();
893 if (av.getWrapAlignment())
895 return printWrappedAlignment(pwidth, pheight, pi, pg);
899 return printUnwrapped(false, pwidth, pheight, pi, pg, pg);
904 * Draws the alignment image, including sequence ids, sequences, and
905 * annotation labels and annotations if shown, on either one or two Graphics
915 * the graphics context for sequence ids and annotation labels
916 * @param alignmentGraphics
917 * the graphics context for sequences and annotations (may or may not
918 * be the same context as idGraphics)
920 * @throws PrinterException
922 public int printUnwrapped(boolean exportSeqPanel, int pageWidth,
923 int pageHeight, int pageIndex,
924 Graphics idGraphics, Graphics alignmentGraphics)
925 throws PrinterException
927 final int idWidth = getVisibleIdWidth(false);
930 * Get the horizontal offset to where we draw the sequences.
931 * This is idWidth if using a single Graphics context, else zero.
933 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
936 FontMetrics fm = getFontMetrics(av.getFont());
937 final int charHeight = av.getCharHeight();
938 final int scaleHeight = charHeight + fm.getDescent();
940 idGraphics.setColor(Color.white);
941 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
942 idGraphics.setFont(av.getFont());
945 * How many sequences and residues can we fit on a printable page?
947 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
949 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
951 final int alignmentWidth = av.getAlignment().getVisibleWidth();
952 int pagesWide = (alignmentWidth / totalRes) + 1;
954 final int startRes = (pageIndex % pagesWide) * totalRes;
955 final int endRes = Math.min(startRes + totalRes - 1,
958 final int startSeq = (pageIndex / pagesWide) * totalSeq;
959 final int alignmentHeight = av.getAlignment().getHeight();
960 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
962 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
964 if (av.isShowAnnotation())
966 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
969 pagesHigh /= pageHeight;
971 if (pageIndex >= (pagesWide * pagesHigh))
973 return Printable.NO_SUCH_PAGE;
975 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
978 * draw the Scale at horizontal offset, then reset to top left (0, 0)
980 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
981 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
982 pageWidth - idWidth, scaleHeight);
983 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
986 * Draw the sequence ids, offset for scale height,
987 * then reset to top left (0, 0)
989 idGraphics.translate(0, scaleHeight);
990 IdCanvas idCanvas = getIdPanel().getIdCanvas();
991 List<SequenceI> selection = av.getSelectionGroup() == null ? null
992 : av.getSelectionGroup().getSequences(null);
993 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
996 idGraphics.setFont(av.getFont());
997 idGraphics.translate(0, -scaleHeight);
1002 * draw the sequences, offset for scale height, and id width (if using a
1003 * single graphics context), then reset to (0, scale height)
1005 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1006 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1007 startRes, endRes, startSeq, endSeq - 1);
1008 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1011 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1014 * draw annotation labels; drawComponent() translates by
1015 * getScrollOffset(), so compensate for that first;
1016 * then reset to (0, scale height)
1018 int offset = getAlabels().getScrollOffset();
1019 idGraphics.translate(0, -offset);
1020 idGraphics.translate(0, alignmentDrawnHeight);
1021 getAlabels().drawComponent(idGraphics, idWidth);
1022 idGraphics.translate(0, -alignmentDrawnHeight);
1025 * draw the annotations starting at
1026 * (idOffset, alignmentHeight) from (0, scaleHeight)
1028 alignmentGraphics.translate(alignmentGraphicsOffset,
1029 alignmentDrawnHeight);
1030 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1031 alignmentGraphics, -1, startRes, endRes + 1);
1034 return Printable.PAGE_EXISTS;
1038 * Prints one page of an alignment in wrapped mode. Returns
1039 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1040 * no page could be drawn (page number out of range).
1050 * @throws PrinterException
1052 public int printWrappedAlignment(int pageWidth,
1053 int pageHeight, int pageNumber,
1054 Graphics g) throws PrinterException
1056 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1058 int annotationHeight = 0;
1059 if (av.isShowAnnotation())
1061 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1064 int hgap = av.getCharHeight();
1065 if (av.getScaleAboveWrapped())
1067 hgap += av.getCharHeight();
1070 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1073 int idWidth = getVisibleIdWidth(false);
1075 int maxwidth = av.getAlignment().getVisibleWidth();
1077 int resWidth = getSeqPanel().seqCanvas
1078 .getWrappedCanvasWidth(pageWidth - idWidth);
1079 av.getRanges().setViewportStartAndWidth(0, resWidth);
1081 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1083 g.setColor(Color.white);
1084 g.fillRect(0, 0, pageWidth, pageHeight);
1085 g.setFont(av.getFont());
1086 g.setColor(Color.black);
1089 * method: print the whole wrapped alignment, but with a clip region that
1090 * is restricted to the requested page; this supports selective print of
1091 * single pages or ranges, (at the cost of repeated processing in the
1092 * 'normal' case, when all pages are printed)
1094 g.translate(0, -pageNumber * pageHeight);
1096 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1099 * draw sequence ids and annotation labels (if shown)
1101 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1102 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1104 g.translate(idWidth, 0);
1106 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1107 pageWidth - idWidth,
1110 if ((pageNumber * pageHeight) < totalHeight)
1112 return Printable.PAGE_EXISTS;
1116 return Printable.NO_SUCH_PAGE;
1121 * get current sequence ID panel width, or nominal value if panel were to be
1122 * displayed using default settings
1126 public int getVisibleIdWidth()
1128 return getVisibleIdWidth(true);
1132 * get current sequence ID panel width, or nominal value if panel were to be
1133 * displayed using default settings
1136 * indicate if the Id width for onscreen or offscreen display should
1140 protected int getVisibleIdWidth(boolean onscreen)
1142 // see if rendering offscreen - check preferences and calc width accordingly
1143 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1145 return calculateIdWidth(-1).width;
1147 Integer idwidth = onscreen ? null
1148 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1149 if (idwidth != null)
1151 return idwidth.intValue() + ID_WIDTH_PADDING;
1154 int w = getIdPanel().getWidth();
1155 return (w > 0 ? w : calculateIdWidth().width);
1158 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1160 makeAlignmentImage(type, file, jalview.bin.Cache
1161 .getDefault("IMAGE_EXPORT_NOSEQUENCES", false));
1164 public void makeAlignmentImage(jalview.util.ImageMaker.TYPE type,
1165 File file, boolean exportSeqPanel)
1167 int boarderBottomOffset = 5;
1168 long pSessionId = System.currentTimeMillis();
1169 headless = (System.getProperty("java.awt.headless") != null
1170 && System.getProperty("java.awt.headless").equals("true"));
1171 if (alignFrame != null && !headless)
1175 alignFrame.setProgressBar(MessageManager
1176 .formatMessage("status.saving_file", new Object[]
1177 { type.getLabel() }), pSessionId);
1182 AlignmentDimension aDimension = getAlignmentDimension();
1185 jalview.util.ImageMaker im;
1186 final String imageAction, imageTitle;
1187 if (type == jalview.util.ImageMaker.TYPE.PNG)
1189 imageAction = "Create PNG image from alignment";
1192 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1194 imageAction = "Create EPS file from alignment";
1195 imageTitle = alignFrame.getTitle();
1199 imageAction = "Create SVG file from alignment";
1200 imageTitle = alignFrame.getTitle();
1203 im = new jalview.util.ImageMaker(this, type, imageAction,
1204 aDimension.getWidth(),
1205 aDimension.getHeight() + boarderBottomOffset, file,
1206 imageTitle, alignFrame, pSessionId, headless);
1207 Graphics graphics = im.getGraphics();
1208 if (av.getWrapAlignment())
1210 if (graphics != null)
1212 printWrappedAlignment(aDimension.getWidth(),
1213 aDimension.getHeight() + boarderBottomOffset, 0,
1220 if (graphics != null)
1222 printUnwrapped(exportSeqPanel, aDimension.getWidth(),
1223 aDimension.getHeight(), 0,
1224 graphics, graphics);
1229 } catch (OutOfMemoryError err)
1232 System.out.println("########################\n" + "OUT OF MEMORY "
1233 + file + "\n" + "########################");
1234 new OOMWarning("Creating Image for " + file, err);
1235 // System.out.println("Create IMAGE: " + err);
1236 } catch (Exception ex)
1238 ex.printStackTrace();
1246 public AlignmentDimension getAlignmentDimension()
1248 int maxwidth = av.getAlignment().getVisibleWidth();
1250 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1251 + getScalePanel().getHeight();
1252 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1254 if (av.getWrapAlignment())
1256 height = getWrappedHeight();
1259 // need to obtain default alignment width and then add in any
1260 // additional allowance for id margin
1261 // this duplicates the calculation in getWrappedHeight but adjusts for
1263 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1264 - alignFrame.getInsets().left - alignFrame.getInsets().right
1265 - getVisibleIdWidth() + getVisibleIdWidth(false);
1269 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1273 else if (av.isShowAnnotation())
1275 height += getAnnotationPanel().adjustPanelHeight() + 3;
1277 return new AlignmentDimension(width, height);
1284 public void makeEPS(File epsFile)
1286 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1292 public void makePNG(File pngFile)
1294 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1297 public void makeSVG(File svgFile)
1299 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1302 public void makePNGImageMap(File imgMapFile, String imageName)
1304 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1305 // ////////////////////////////////////////////
1306 int idWidth = getVisibleIdWidth(false);
1307 FontMetrics fm = getFontMetrics(av.getFont());
1308 int scaleHeight = av.getCharHeight() + fm.getDescent();
1311 // ////////////////////////////////
1312 if (imgMapFile != null)
1316 int sSize = av.getAlignment().getHeight();
1317 int alwidth = av.getAlignment().getWidth();
1318 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1319 out.println(HTMLOutput.getImageMapHTML());
1320 out.println("<img src=\"" + imageName
1321 + "\" border=\"0\" usemap=\"#Map\" >"
1322 + "<map name=\"Map\">");
1324 for (int s = 0; s < sSize; s++)
1326 int sy = s * av.getCharHeight() + scaleHeight;
1328 SequenceI seq = av.getAlignment().getSequenceAt(s);
1329 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1330 for (int column = 0; column < alwidth; column++)
1332 StringBuilder text = new StringBuilder(512);
1333 String triplet = null;
1334 if (av.getAlignment().isNucleotide())
1336 triplet = ResidueProperties.nucleotideName.get(seq
1337 .getCharAt(column) + "");
1341 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1345 if (triplet == null)
1350 int seqPos = seq.findPosition(column);
1351 int gSize = groups.length;
1352 for (int g = 0; g < gSize; g++)
1354 if (text.length() < 1)
1356 text.append("<area shape=\"rect\" coords=\"")
1357 .append((idWidth + column * av.getCharWidth()))
1358 .append(",").append(sy).append(",")
1359 .append((idWidth + (column + 1) * av.getCharWidth()))
1360 .append(",").append((av.getCharHeight() + sy))
1361 .append("\"").append(" onMouseOver=\"toolTip('")
1362 .append(seqPos).append(" ").append(triplet);
1365 if (groups[g].getStartRes() < column
1366 && groups[g].getEndRes() > column)
1368 text.append("<br><em>").append(groups[g].getName())
1373 if (text.length() < 1)
1375 text.append("<area shape=\"rect\" coords=\"")
1376 .append((idWidth + column * av.getCharWidth()))
1377 .append(",").append(sy).append(",")
1378 .append((idWidth + (column + 1) * av.getCharWidth()))
1379 .append(",").append((av.getCharHeight() + sy))
1380 .append("\"").append(" onMouseOver=\"toolTip('")
1381 .append(seqPos).append(" ").append(triplet);
1383 if (!Comparison.isGap(seq.getCharAt(column)))
1385 List<SequenceFeature> features = seq.findFeatures(column, column);
1386 for (SequenceFeature sf : features)
1388 if (sf.isContactFeature())
1390 text.append("<br>").append(sf.getType()).append(" ")
1391 .append(sf.getBegin()).append(":")
1392 .append(sf.getEnd());
1396 text.append("<br>");
1397 text.append(sf.getType());
1398 String description = sf.getDescription();
1399 if (description != null
1400 && !sf.getType().equals(description))
1402 description = description.replace("\"", """);
1403 text.append(" ").append(description);
1406 String status = sf.getStatus();
1407 if (status != null && !"".equals(status))
1409 text.append(" (").append(status).append(")");
1412 if (text.length() > 1)
1414 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1415 out.println(text.toString());
1420 out.println("</map></body></html>");
1423 } catch (Exception ex)
1425 ex.printStackTrace();
1427 } // /////////END OF IMAGE MAP
1432 * Answers the height of the entire alignment in pixels, assuming it is in
1437 int getWrappedHeight()
1439 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1441 if (System.getProperty("java.awt.headless") != null
1442 && System.getProperty("java.awt.headless").equals("true"))
1444 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1445 - vscroll.getPreferredSize().width
1446 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1449 int chunkWidth = getSeqPanel().seqCanvas
1450 .getWrappedCanvasWidth(seqPanelWidth);
1452 int hgap = av.getCharHeight();
1453 if (av.getScaleAboveWrapped())
1455 hgap += av.getCharHeight();
1458 int annotationHeight = 0;
1459 if (av.isShowAnnotation())
1461 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1462 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1465 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1468 int maxwidth = av.getAlignment().getWidth();
1469 if (av.hasHiddenColumns())
1471 maxwidth = av.getAlignment().getHiddenColumns()
1472 .absoluteToVisibleColumn(maxwidth) - 1;
1475 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1481 * close the panel - deregisters all listeners and nulls any references to
1484 public void closePanel()
1486 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1487 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1488 PaintRefresher.RemoveComponent(this);
1493 * try to ensure references are nulled
1495 if (annotationPanel != null)
1497 annotationPanel.dispose();
1498 annotationPanel = null;
1503 av.removePropertyChangeListener(propertyChangeListener);
1504 propertyChangeListener = null;
1505 StructureSelectionManager ssm = av.getStructureSelectionManager();
1506 ssm.removeStructureViewerListener(getSeqPanel(), null);
1507 ssm.removeSelectionListener(getSeqPanel());
1508 ssm.removeCommandListener(av);
1509 ssm.removeStructureViewerListener(getSeqPanel(), null);
1510 ssm.removeSelectionListener(getSeqPanel());
1516 if (Cache.log.isDebugEnabled())
1518 Cache.log.warn("Closing alignment panel which is already closed.");
1524 * Close any open dialogs that would be orphaned when this one is closed
1526 protected void closeChildFrames()
1528 if (overviewPanel != null)
1530 overviewPanel.dispose();
1531 overviewPanel = null;
1533 if (calculationDialog != null)
1535 calculationDialog.closeFrame();
1536 calculationDialog = null;
1541 * hides or shows dynamic annotation rows based on groups and av state flags
1543 public void updateAnnotation()
1545 updateAnnotation(false, false);
1548 public void updateAnnotation(boolean applyGlobalSettings)
1550 updateAnnotation(applyGlobalSettings, false);
1553 public void updateAnnotation(boolean applyGlobalSettings,
1554 boolean preserveNewGroupSettings)
1556 av.updateGroupAnnotationSettings(applyGlobalSettings,
1557 preserveNewGroupSettings);
1558 adjustAnnotationHeight();
1562 public AlignmentI getAlignment()
1564 return av == null ? null : av.getAlignment();
1568 public String getViewName()
1570 return av.getViewName();
1574 * Make/Unmake this alignment panel the current input focus
1578 public void setSelected(boolean b)
1582 if (alignFrame.getSplitViewContainer() != null)
1585 * bring enclosing SplitFrame to front first if there is one
1587 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1589 alignFrame.setSelected(b);
1590 } catch (Exception ex)
1596 alignFrame.setDisplayedView(this);
1601 public StructureSelectionManager getStructureSelectionManager()
1603 return av.getStructureSelectionManager();
1607 public void raiseOOMWarning(String string, OutOfMemoryError error)
1609 new OOMWarning(string, error, this);
1613 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1616 return new FeatureRenderer(this);
1620 public jalview.api.FeatureRenderer getFeatureRenderer()
1622 return seqPanel.seqCanvas.getFeatureRenderer();
1625 public void updateFeatureRenderer(
1626 jalview.renderer.seqfeatures.FeatureRenderer fr)
1628 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1631 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1633 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1635 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1639 public ScalePanel getScalePanel()
1644 public void setScalePanel(ScalePanel scalePanel)
1646 this.scalePanel = scalePanel;
1649 public SeqPanel getSeqPanel()
1654 public void setSeqPanel(SeqPanel seqPanel)
1656 this.seqPanel = seqPanel;
1659 public AnnotationPanel getAnnotationPanel()
1661 return annotationPanel;
1664 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1666 this.annotationPanel = annotationPanel;
1669 public AnnotationLabels getAlabels()
1674 public void setAlabels(AnnotationLabels alabels)
1676 this.alabels = alabels;
1679 public IdPanel getIdPanel()
1684 public void setIdPanel(IdPanel idPanel)
1686 this.idPanel = idPanel;
1690 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1691 * The aim is to keep the two alignments 'lined up' on their centre columns.
1694 * holds mapped region(s) of this alignment that we are scrolling
1695 * 'to'; may be modified for sequence offset by this method
1696 * @param verticalOffset
1697 * the number of visible sequences to show above the mapped region
1699 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1701 scrollToPosition(sr, verticalOffset, true);
1705 * Set a flag to say do not scroll any (cDNA/protein) complement.
1709 protected void setToScrollComplementPanel(boolean b)
1711 this.scrollComplementaryPanel = b;
1715 * Get whether to scroll complement panel
1717 * @return true if cDNA/protein complement panels should be scrolled
1719 protected boolean isSetToScrollComplementPanel()
1721 return this.scrollComplementaryPanel;
1727 * @adjustHeight if true, try to recalculate panel height for visible
1730 protected void refresh(boolean adjustHeight)
1732 validateAnnotationDimensions(adjustHeight);
1736 // sort, repaint, update overview
1737 paintAlignment(true, false);
1741 // lightweight repaint
1748 * Property change event fired when a change is made to the viewport ranges
1749 * object associated with this alignment panel's viewport
1751 public void propertyChange(PropertyChangeEvent evt)
1753 // update this panel's scroll values based on the new viewport ranges values
1754 ViewportRanges ranges = av.getRanges();
1755 int x = ranges.getStartRes();
1756 int y = ranges.getStartSeq();
1757 setScrollValues(x, y);
1759 // now update any complementary alignment (its viewport ranges object
1760 // is different so does not get automatically updated)
1761 if (isSetToScrollComplementPanel())
1763 setToScrollComplementPanel(false);
1764 av.scrollComplementaryAlignment();
1765 setToScrollComplementPanel(true);
1770 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1771 * reference should be nulled when the dialog is closed.
1773 * @param calculationChooser
1775 public void setCalculationDialog(CalculationChooser calculationChooser)
1777 calculationDialog = calculationChooser;
1781 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1784 public CalculationChooser getCalculationDialog()
1786 return calculationDialog;