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.analysis.AnnotationSorter.SequenceAnnotationOrder;
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.bin.Cache;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SearchResultsI;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.io.HTMLOutput;
35 import jalview.jbgui.GAlignmentPanel;
36 import jalview.math.AlignmentDimension;
37 import jalview.schemes.ResidueProperties;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.Comparison;
40 import jalview.util.MessageManager;
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.Graphics2D;
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 private int hextent = 0;
100 private int vextent = 0;
103 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
104 * false, suppresses invoking the same method recursively.
106 private boolean scrollComplementaryPanel = true;
108 private PropertyChangeListener propertyChangeListener;
110 private CalculationChooser calculationDialog;
113 * Creates a new AlignmentPanel object.
118 public AlignmentPanel(AlignFrame af, final AlignViewport av)
122 setSeqPanel(new SeqPanel(av, this));
123 setIdPanel(new IdPanel(av, this));
125 setScalePanel(new ScalePanel(av, this));
127 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
128 idwidthAdjuster = new IdwidthAdjuster(this);
129 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
131 setAnnotationPanel(new AnnotationPanel(this));
132 setAlabels(new AnnotationLabels(this));
134 annotationScroller.setViewportView(getAnnotationPanel());
135 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
137 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
138 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
140 setScrollValues(0, 0);
142 hscroll.addAdjustmentListener(this);
143 vscroll.addAdjustmentListener(this);
145 addComponentListener(new ComponentAdapter()
148 public void componentResized(ComponentEvent evt)
150 // reset the viewport ranges when the alignment panel is resized
151 // in particular, this initialises the end residue value when Jalview
153 ViewportRanges ranges = av.getRanges();
154 if (av.getWrapAlignment())
156 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
157 getSeqPanel().seqCanvas.getWidth());
158 ranges.setViewportWidth(widthInRes);
162 int widthInRes = getSeqPanel().seqCanvas.getWidth()
164 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
165 / av.getCharHeight();
167 ranges.setViewportWidth(widthInRes);
168 ranges.setViewportHeight(heightInSeq);
174 final AlignmentPanel ap = this;
175 propertyChangeListener = new PropertyChangeListener()
178 public void propertyChange(PropertyChangeEvent evt)
180 if (evt.getPropertyName().equals("alignment"))
182 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
187 av.addPropertyChangeListener(propertyChangeListener);
189 av.getRanges().addPropertyChangeListener(this);
191 adjustAnnotationHeight();
196 public AlignViewportI getAlignViewport()
201 public void alignmentChanged()
203 av.alignmentChanged(this);
205 if (getCalculationDialog() != null)
207 getCalculationDialog().validateCalcTypes();
210 alignFrame.updateEditMenuBar();
212 // no idea if we need to update structure
213 paintAlignment(true, true);
220 public void fontChanged()
222 // set idCanvas bufferedImage to null
223 // to prevent drawing old image
224 FontMetrics fm = getFontMetrics(av.getFont());
226 scalePanelHolder.setPreferredSize(
227 new Dimension(10, av.getCharHeight() + fm.getDescent()));
228 idSpaceFillerPanel1.setPreferredSize(
229 new Dimension(10, av.getCharHeight() + fm.getDescent()));
230 idwidthAdjuster.invalidate();
231 scalePanelHolder.invalidate();
232 getIdPanel().getIdCanvas().gg = null;
233 getSeqPanel().seqCanvas.img = null;
234 getAnnotationPanel().adjustPanelHeight();
236 Dimension d = calculateIdWidth();
238 d.setSize(d.width + 4, d.height);
239 getIdPanel().getIdCanvas().setPreferredSize(d);
240 hscrollFillerPanel.setPreferredSize(d);
246 * Calculate the width of the alignment labels based on the displayed names
247 * and any bounds on label width set in preferences.
249 * @return Dimension giving the maximum width of the alignment label panel
250 * that should be used.
252 public Dimension calculateIdWidth()
254 // calculate sensible default width when no preference is available
256 if (av.getIdWidth() < 0)
258 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
259 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
260 r = calculateIdWidth(maxwidth);
261 av.setIdWidth(r.width);
266 r.width = av.getIdWidth();
273 * Calculate the width of the alignment labels based on the displayed names
274 * and any bounds on label width set in preferences.
277 * -1 or maximum width allowed for IdWidth
278 * @return Dimension giving the maximum width of the alignment label panel
279 * that should be used.
281 public Dimension calculateIdWidth(int maxwidth)
283 Container c = new Container();
285 FontMetrics fm = c.getFontMetrics(
286 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
288 AlignmentI al = av.getAlignment();
293 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
295 SequenceI s = al.getSequenceAt(i);
297 id = s.getDisplayId(av.getShowJVSuffix());
299 if (fm.stringWidth(id) > idWidth)
301 idWidth = fm.stringWidth(id);
307 // Also check annotation label widths
310 if (al.getAlignmentAnnotation() != null)
312 fm = c.getFontMetrics(getAlabels().getFont());
314 while (i < al.getAlignmentAnnotation().length)
316 String label = al.getAlignmentAnnotation()[i].label;
318 if (fm.stringWidth(label) > idWidth)
320 idWidth = fm.stringWidth(label);
327 return new Dimension(
328 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
332 * Highlight the given results on the alignment
335 public void highlightSearchResults(SearchResultsI results)
337 boolean scrolled = scrollToPosition(results, 0, false);
339 boolean noFastPaint = scrolled && av.getWrapAlignment();
341 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
345 * Scroll the view to show the position of the highlighted region in results
348 * @param searchResults
351 public boolean scrollToPosition(SearchResultsI searchResults)
353 return scrollToPosition(searchResults, 0, false);
357 * Scrolls the view (if necessary) to show the position of the first
358 * highlighted region in results (if any). Answers true if the view was
359 * scrolled, or false if no matched region was found, or it is already
363 * @param verticalOffset
364 * if greater than zero, allows scrolling to a position below the
365 * first displayed sequence
367 * if true, try to centre the search results horizontally in the view
370 protected boolean scrollToPosition(SearchResultsI results,
371 int verticalOffset, boolean centre)
373 int startv, endv, starts, ends;
374 ViewportRanges ranges = av.getRanges();
376 if (results == null || results.isEmpty() || av == null
377 || av.getAlignment() == null)
381 int seqIndex = av.getAlignment().findIndex(results);
386 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
388 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
397 * To centre results, scroll to positions half the visible width
398 * left/right of the start/end positions
402 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
403 start = Math.max(start - offset, 0);
404 end = end + offset - 1;
410 if (end == seq.getEnd())
415 if (av.hasHiddenColumns())
417 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
418 start = hidden.absoluteToVisibleColumn(start);
419 end = hidden.absoluteToVisibleColumn(end);
422 if (!hidden.isVisible(r[0]))
424 // don't scroll - position isn't visible
431 * allow for offset of target sequence (actually scroll to one above it)
433 seqIndex = Math.max(0, seqIndex - verticalOffset);
434 boolean scrollNeeded = true;
436 if (!av.getWrapAlignment())
438 if ((startv = ranges.getStartRes()) >= start)
441 * Scroll left to make start of search results visible
443 setScrollValues(start, seqIndex);
445 else if ((endv = ranges.getEndRes()) <= end)
448 * Scroll right to make end of search results visible
450 setScrollValues(startv + end - endv, seqIndex);
452 else if ((starts = ranges.getStartSeq()) > seqIndex)
455 * Scroll up to make start of search results visible
457 setScrollValues(ranges.getStartRes(), seqIndex);
459 else if ((ends = ranges.getEndSeq()) <= seqIndex)
462 * Scroll down to make end of search results visible
464 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
468 * Else results are already visible - no need to scroll
470 scrollNeeded = false;
474 scrollNeeded = ranges.scrollToWrappedVisible(start);
477 paintAlignment(false, false);
485 * @return DOCUMENT ME!
487 public OverviewPanel getOverviewPanel()
489 return overviewPanel;
498 public void setOverviewPanel(OverviewPanel op)
506 * Hide or show annotation panel
509 public void setAnnotationVisible(boolean b)
511 if (!av.getWrapAlignment())
513 annotationSpaceFillerHolder.setVisible(b);
514 annotationScroller.setVisible(b);
520 * automatically adjust annotation panel height for new annotation whilst
521 * ensuring the alignment is still visible.
524 public void adjustAnnotationHeight()
526 // TODO: display vertical annotation scrollbar if necessary
527 // this is called after loading new annotation onto alignment
528 if (alignFrame.getHeight() == 0)
530 System.out.println("NEEDS FIXING");
532 validateAnnotationDimensions(true);
534 // TODO: many places call this method and also paintAlignment with various
535 // different settings. this means multiple redraws are triggered...
536 paintAlignment(true, av.needToUpdateStructureViews());
540 * calculate the annotation dimensions and refresh slider values accordingly.
541 * need to do repaints/notifys afterwards.
543 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
545 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
546 annotationHeight = getAnnotationPanel()
547 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
550 annotationScroller.setPreferredSize(
551 new Dimension(annotationScroller.getWidth(), annotationHeight));
553 Dimension e = idPanel.getSize();
554 alabels.setSize(new Dimension(e.width, annotationHeight));
556 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
557 annotationSpaceFillerHolder.getWidth(), annotationHeight));
558 annotationScroller.validate();
559 annotationScroller.addNotify();
563 * update alignment layout for viewport settings
568 public void updateLayout()
571 setAnnotationVisible(av.isShowAnnotation());
572 boolean wrap = av.getWrapAlignment();
573 ViewportRanges ranges = av.getRanges();
574 ranges.setStartSeq(0);
575 scalePanelHolder.setVisible(!wrap);
576 hscroll.setVisible(!wrap);
577 idwidthAdjuster.setVisible(!wrap);
581 annotationScroller.setVisible(false);
582 annotationSpaceFillerHolder.setVisible(false);
584 else if (av.isShowAnnotation())
586 annotationScroller.setVisible(true);
587 annotationSpaceFillerHolder.setVisible(true);
588 validateAnnotationDimensions(false);
591 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
593 { // may not yet be laid out
596 int widthInRes = getSeqPanel().seqCanvas
597 .getWrappedCanvasWidth(canvasWidth);
598 ranges.setViewportWidth(widthInRes);
602 int widthInRes = (canvasWidth / av.getCharWidth());
603 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
604 / av.getCharHeight());
606 ranges.setViewportWidth(widthInRes);
607 ranges.setViewportHeight(heightInSeq);
611 idSpaceFillerPanel1.setVisible(!wrap);
617 * Adjust row/column scrollers to show a visible position in the alignment.
620 * visible column to scroll to
622 * visible row to scroll to
625 public void setScrollValues(int xpos, int ypos)
630 if (av == null || av.getAlignment() == null)
635 if (av.getWrapAlignment())
637 setScrollingForWrappedPanel(x);
641 int width = av.getAlignment().getVisibleWidth();
642 int height = av.getAlignment().getHeight();
644 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
645 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
652 if (vextent > height)
657 if ((hextent + x) > width)
662 if ((vextent + y) > height)
664 y = height - vextent;
677 // update the scroll values
678 hscroll.setValues(x, hextent, 0, width);
679 vscroll.setValues(y, vextent, 0, height);
684 * Respond to adjustment event when horizontal or vertical scrollbar is
688 * adjustment event encoding whether hscroll or vscroll changed
691 public void adjustmentValueChanged(AdjustmentEvent evt)
693 if (av.getWrapAlignment())
695 adjustScrollingWrapped(evt);
699 ViewportRanges ranges = av.getRanges();
701 if (evt.getSource() == hscroll)
703 int oldX = ranges.getStartRes();
704 int oldwidth = ranges.getViewportWidth();
705 int x = hscroll.getValue();
706 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
708 // if we're scrolling to the position we're already at, stop
709 // this prevents infinite recursion of events when the scroll/viewport
710 // ranges values are the same
711 if ((x == oldX) && (width == oldwidth))
715 ranges.setViewportStartAndWidth(x, width);
717 else if (evt.getSource() == vscroll)
719 int oldY = ranges.getStartSeq();
720 int oldheight = ranges.getViewportHeight();
721 int y = vscroll.getValue();
722 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
724 // if we're scrolling to the position we're already at, stop
725 // this prevents infinite recursion of events when the scroll/viewport
726 // ranges values are the same
727 if ((y == oldY) && (height == oldheight))
731 ranges.setViewportStartAndHeight(y, height);
737 * Responds to a scroll change by setting the start position of the viewport.
742 protected void adjustScrollingWrapped(AdjustmentEvent evt)
744 if (evt.getSource() == hscroll)
746 return; // no horizontal scroll when wrapped
748 final ViewportRanges ranges = av.getRanges();
750 if (evt.getSource() == vscroll)
752 int newY = vscroll.getValue();
755 * if we're scrolling to the position we're already at, stop
756 * this prevents infinite recursion of events when the scroll/viewport
757 * ranges values are the same
759 int oldX = ranges.getStartRes();
760 int oldY = ranges.getWrappedScrollPosition(oldX);
768 * limit page up/down to one width's worth of positions
770 int rowSize = ranges.getViewportWidth();
771 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
772 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
777 // This is only called if file loaded is a jar file that
778 // was wrapped when saved and user has wrap alignment true
779 // as preference setting
780 SwingUtilities.invokeLater(new Runnable()
785 // When updating scrolling to use ViewportChange events, this code
786 // could not be validated and it is not clear if it is now being
787 // called. Log warning here in case it is called and unforeseen
790 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
792 // scroll to start of panel
793 ranges.setStartRes(0);
794 ranges.setStartSeq(0);
802 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
805 public void paintAlignment(boolean updateOverview,
806 boolean updateStructures)
810 if (updateStructures)
812 av.getStructureSelectionManager().sequenceColoursChanged(this);
817 if (overviewPanel != null)
819 overviewPanel.updateOverviewImage();
825 * Sorts annotations according to currently selected preferences. Does nothing
826 * if currently set to 'Custom' (manual) ordering.
829 public void sortAnnotations(boolean autoCalcOnly)
831 SequenceAnnotationOrder sortBy = av.getSortAnnotationsBy();
832 if (sortBy != SequenceAnnotationOrder.CUSTOM)
834 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
835 av.isShowAutocalculatedAbove(), autoCalcOnly);
836 sorter.sort(getAlignment().getAlignmentAnnotation(), sortBy);
847 public void paintComponent(Graphics g)
849 invalidate(); // needed so that the id width adjuster works correctly
851 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
852 idPanelHolder.setPreferredSize(d);
853 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
855 validate(); // needed so that the id width adjuster works correctly
858 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
859 * though I still think this call should be elsewhere.
861 ViewportRanges ranges = av.getRanges();
862 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
866 * Set vertical scroll bar position, and number of increments, for wrapped
869 * @param topLeftColumn
870 * the column position at top left (0..)
872 private void setScrollingForWrappedPanel(int topLeftColumn)
874 ViewportRanges ranges = av.getRanges();
875 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
876 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
879 * a scrollbar's value can be set to at most (maximum-extent)
880 * so we add extent (1) to the maxScroll value
882 vscroll.setUnitIncrement(1);
883 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
896 * @return DOCUMENT ME!
898 * @throws PrinterException
902 public int print(Graphics pg, PageFormat pf, int pi)
903 throws PrinterException
905 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
907 int pwidth = (int) pf.getImageableWidth();
908 int pheight = (int) pf.getImageableHeight();
910 if (av.getWrapAlignment())
912 return printWrappedAlignment(pwidth, pheight, pi, pg);
916 return printUnwrapped(pwidth, pheight, pi, pg, pg);
921 * Draws the alignment image, including sequence ids, sequences, and
922 * annotation labels and annotations if shown, on either one or two Graphics
932 * the graphics context for sequence ids and annotation labels
933 * @param alignmentGraphics
934 * the graphics context for sequences and annotations (may or may not
935 * be the same context as idGraphics)
937 * @throws PrinterException
939 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
940 Graphics idGraphics, Graphics alignmentGraphics)
941 throws PrinterException
943 final int idWidth = getVisibleIdWidth(false);
946 * Get the horizontal offset to where we draw the sequences.
947 * This is idWidth if using a single Graphics context, else zero.
949 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
952 FontMetrics fm = getFontMetrics(av.getFont());
953 final int charHeight = av.getCharHeight();
954 final int scaleHeight = charHeight + fm.getDescent();
956 idGraphics.setColor(Color.white);
957 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
958 idGraphics.setFont(av.getFont());
961 * How many sequences and residues can we fit on a printable page?
963 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
965 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
967 final int alignmentWidth = av.getAlignment().getVisibleWidth();
968 int pagesWide = (alignmentWidth / totalRes) + 1;
970 final int startRes = (pageIndex % pagesWide) * totalRes;
971 final int endRes = Math.min(startRes + totalRes - 1,
974 final int startSeq = (pageIndex / pagesWide) * totalSeq;
975 final int alignmentHeight = av.getAlignment().getHeight();
976 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
978 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
980 if (av.isShowAnnotation())
982 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
985 pagesHigh /= pageHeight;
987 if (pageIndex >= (pagesWide * pagesHigh))
989 return Printable.NO_SUCH_PAGE;
991 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
994 * draw the Scale at horizontal offset, then reset to top left (0, 0)
996 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
997 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
998 pageWidth - idWidth, scaleHeight);
999 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1002 * Draw the sequence ids, offset for scale height,
1003 * then reset to top left (0, 0)
1005 idGraphics.translate(0, scaleHeight);
1006 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1007 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1008 : av.getSelectionGroup().getSequences(null);
1009 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1012 idGraphics.setFont(av.getFont());
1013 idGraphics.translate(0, -scaleHeight);
1016 * draw the sequences, offset for scale height, and id width (if using a
1017 * single graphics context), then reset to (0, scale height)
1019 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1020 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1021 endRes, startSeq, endSeq - 1);
1022 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1024 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1027 * draw annotation labels; drawComponent() translates by
1028 * getScrollOffset(), so compensate for that first;
1029 * then reset to (0, scale height)
1031 int offset = getAlabels().getScrollOffset();
1032 idGraphics.translate(0, -offset);
1033 idGraphics.translate(0, alignmentDrawnHeight);
1034 getAlabels().drawComponent(idGraphics, idWidth);
1035 idGraphics.translate(0, -alignmentDrawnHeight);
1038 * draw the annotations starting at
1039 * (idOffset, alignmentHeight) from (0, scaleHeight)
1041 alignmentGraphics.translate(alignmentGraphicsOffset,
1042 alignmentDrawnHeight);
1043 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1044 alignmentGraphics, -1, startRes, endRes + 1);
1047 return Printable.PAGE_EXISTS;
1051 * Prints one page of an alignment in wrapped mode. Returns
1052 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1053 * no page could be drawn (page number out of range).
1063 * @throws PrinterException
1065 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1066 Graphics g) throws PrinterException
1068 int annotationHeight = 0;
1069 if (av.isShowAnnotation())
1071 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1074 int hgap = av.getCharHeight();
1075 if (av.getScaleAboveWrapped())
1077 hgap += av.getCharHeight();
1080 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1083 int idWidth = getVisibleIdWidth(false);
1085 int maxwidth = av.getAlignment().getVisibleWidth();
1087 int resWidth = getSeqPanel().seqCanvas
1088 .getWrappedCanvasWidth(pageWidth - idWidth);
1090 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1092 g.setColor(Color.white);
1093 g.fillRect(0, 0, pageWidth, pageHeight);
1094 g.setFont(av.getFont());
1095 g.setColor(Color.black);
1098 * method: print the whole wrapped alignment, but with a clip region that
1099 * is restricted to the requested page; this supports selective print of
1100 * single pages or ranges, (at the cost of some repeated processing in
1101 * the 'normal' case, when all pages are printed)
1103 g.translate(0, -pageNumber * pageHeight);
1105 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1108 * draw sequence ids and annotation labels (if shown)
1110 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1111 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1113 g.translate(idWidth, 0);
1115 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1118 if ((pageNumber * pageHeight) < totalHeight)
1120 return Printable.PAGE_EXISTS;
1124 return Printable.NO_SUCH_PAGE;
1129 * get current sequence ID panel width, or nominal value if panel were to be
1130 * displayed using default settings
1134 public int getVisibleIdWidth()
1136 return getVisibleIdWidth(true);
1140 * get current sequence ID panel width, or nominal value if panel were to be
1141 * displayed using default settings
1144 * indicate if the Id width for onscreen or offscreen display should
1148 public int getVisibleIdWidth(boolean onscreen)
1150 // see if rendering offscreen - check preferences and calc width accordingly
1151 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1153 return calculateIdWidth(-1).width + 4;
1155 Integer idwidth = null;
1156 if (onscreen || (idwidth = Cache
1157 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1159 int w = getIdPanel().getWidth();
1160 return (w > 0 ? w : calculateIdWidth().width + 4);
1162 return idwidth.intValue() + 4;
1165 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
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(aDimension.getWidth(), aDimension.getHeight(), 0,
1223 graphics, graphics);
1228 } catch (OutOfMemoryError err)
1231 System.out.println("########################\n" + "OUT OF MEMORY "
1232 + file + "\n" + "########################");
1233 new OOMWarning("Creating Image for " + file, err);
1234 // System.out.println("Create IMAGE: " + err);
1235 } catch (Exception ex)
1237 ex.printStackTrace();
1245 public AlignmentDimension getAlignmentDimension()
1247 int maxwidth = av.getAlignment().getVisibleWidth();
1249 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1250 + getScalePanel().getHeight();
1251 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1253 if (av.getWrapAlignment())
1255 height = getWrappedHeight();
1258 // need to obtain default alignment width and then add in any
1259 // additional allowance for id margin
1260 // this duplicates the calculation in getWrappedHeight but adjusts for
1262 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1263 - alignFrame.getInsets().left - alignFrame.getInsets().right
1264 - getVisibleIdWidth() + getVisibleIdWidth(false);
1268 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1272 else if (av.isShowAnnotation())
1274 height += getAnnotationPanel().adjustPanelHeight() + 3;
1276 return new AlignmentDimension(width, height);
1283 public void makeEPS(File epsFile)
1285 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1291 public void makePNG(File pngFile)
1293 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1296 public void makeSVG(File svgFile)
1298 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1301 public void makePNGImageMap(File imgMapFile, String imageName)
1303 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1304 // ////////////////////////////////////////////
1305 int idWidth = getVisibleIdWidth(false);
1306 FontMetrics fm = getFontMetrics(av.getFont());
1307 int scaleHeight = av.getCharHeight() + fm.getDescent();
1310 // ////////////////////////////////
1311 if (imgMapFile != null)
1315 int sSize = av.getAlignment().getHeight();
1316 int alwidth = av.getAlignment().getWidth();
1317 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1318 out.println(HTMLOutput.getImageMapHTML());
1319 out.println("<img src=\"" + imageName
1320 + "\" border=\"0\" usemap=\"#Map\" >"
1321 + "<map name=\"Map\">");
1323 for (int s = 0; s < sSize; s++)
1325 int sy = s * av.getCharHeight() + scaleHeight;
1327 SequenceI seq = av.getAlignment().getSequenceAt(s);
1328 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1329 for (int column = 0; column < alwidth; column++)
1331 StringBuilder text = new StringBuilder(512);
1332 String triplet = null;
1333 if (av.getAlignment().isNucleotide())
1335 triplet = ResidueProperties.nucleotideName.get(seq
1336 .getCharAt(column) + "");
1340 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1344 if (triplet == null)
1349 int seqPos = seq.findPosition(column);
1350 int gSize = groups.length;
1351 for (int g = 0; g < gSize; g++)
1353 if (text.length() < 1)
1355 text.append("<area shape=\"rect\" coords=\"")
1356 .append((idWidth + column * av.getCharWidth()))
1357 .append(",").append(sy).append(",")
1358 .append((idWidth + (column + 1) * av.getCharWidth()))
1359 .append(",").append((av.getCharHeight() + sy))
1360 .append("\"").append(" onMouseOver=\"toolTip('")
1361 .append(seqPos).append(" ").append(triplet);
1364 if (groups[g].getStartRes() < column
1365 && groups[g].getEndRes() > column)
1367 text.append("<br><em>").append(groups[g].getName())
1372 if (text.length() < 1)
1374 text.append("<area shape=\"rect\" coords=\"")
1375 .append((idWidth + column * av.getCharWidth()))
1376 .append(",").append(sy).append(",")
1377 .append((idWidth + (column + 1) * av.getCharWidth()))
1378 .append(",").append((av.getCharHeight() + sy))
1379 .append("\"").append(" onMouseOver=\"toolTip('")
1380 .append(seqPos).append(" ").append(triplet);
1382 if (!Comparison.isGap(seq.getCharAt(column)))
1384 List<SequenceFeature> features = seq.findFeatures(column, column);
1385 for (SequenceFeature sf : features)
1387 if (sf.isContactFeature())
1389 text.append("<br>").append(sf.getType()).append(" ")
1390 .append(sf.getBegin()).append(":")
1391 .append(sf.getEnd());
1395 text.append("<br>");
1396 text.append(sf.getType());
1397 String description = sf.getDescription();
1398 if (description != null
1399 && !sf.getType().equals(description))
1401 description = description.replace("\"", """);
1402 text.append(" ").append(description);
1405 String status = sf.getStatus();
1406 if (status != null && !"".equals(status))
1408 text.append(" (").append(status).append(")");
1411 if (text.length() > 1)
1413 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1414 out.println(text.toString());
1419 out.println("</map></body></html>");
1422 } catch (Exception ex)
1424 ex.printStackTrace();
1426 } // /////////END OF IMAGE MAP
1430 int getWrappedHeight()
1432 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1434 if (System.getProperty("java.awt.headless") != null
1435 && System.getProperty("java.awt.headless").equals("true"))
1437 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1438 - vscroll.getPreferredSize().width
1439 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1442 int chunkWidth = getSeqPanel().seqCanvas
1443 .getWrappedCanvasWidth(seqPanelWidth);
1445 int hgap = av.getCharHeight();
1446 if (av.getScaleAboveWrapped())
1448 hgap += av.getCharHeight();
1451 int annotationHeight = 0;
1452 if (av.isShowAnnotation())
1454 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1457 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1460 int maxwidth = av.getAlignment().getWidth();
1461 if (av.hasHiddenColumns())
1463 maxwidth = av.getAlignment().getHiddenColumns()
1464 .absoluteToVisibleColumn(maxwidth) - 1;
1467 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1473 * close the panel - deregisters all listeners and nulls any references to
1476 public void closePanel()
1478 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1479 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1480 PaintRefresher.RemoveComponent(this);
1485 * try to ensure references are nulled
1487 if (annotationPanel != null)
1489 annotationPanel.dispose();
1490 annotationPanel = null;
1495 av.removePropertyChangeListener(propertyChangeListener);
1496 propertyChangeListener = null;
1497 StructureSelectionManager ssm = av.getStructureSelectionManager();
1498 ssm.removeStructureViewerListener(getSeqPanel(), null);
1499 ssm.removeSelectionListener(getSeqPanel());
1500 ssm.removeCommandListener(av);
1501 ssm.removeStructureViewerListener(getSeqPanel(), null);
1502 ssm.removeSelectionListener(getSeqPanel());
1508 if (Cache.log.isDebugEnabled())
1510 Cache.log.warn("Closing alignment panel which is already closed.");
1516 * Close any open dialogs that would be orphaned when this one is closed
1518 protected void closeChildFrames()
1520 if (overviewPanel != null)
1522 overviewPanel.dispose();
1523 overviewPanel = null;
1525 if (calculationDialog != null)
1527 calculationDialog.closeFrame();
1528 calculationDialog = null;
1533 * hides or shows dynamic annotation rows based on groups and av state flags
1535 public void updateAnnotation()
1537 updateAnnotation(false, false);
1540 public void updateAnnotation(boolean applyGlobalSettings)
1542 updateAnnotation(applyGlobalSettings, false);
1545 public void updateAnnotation(boolean applyGlobalSettings,
1546 boolean preserveNewGroupSettings)
1548 av.updateGroupAnnotationSettings(applyGlobalSettings,
1549 preserveNewGroupSettings);
1550 adjustAnnotationHeight();
1554 public AlignmentI getAlignment()
1556 return av == null ? null : av.getAlignment();
1560 public String getViewName()
1562 return av.getViewName();
1566 * Make/Unmake this alignment panel the current input focus
1570 public void setSelected(boolean b)
1574 if (alignFrame.getSplitViewContainer() != null)
1577 * bring enclosing SplitFrame to front first if there is one
1579 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1581 alignFrame.setSelected(b);
1582 } catch (Exception ex)
1588 alignFrame.setDisplayedView(this);
1593 public StructureSelectionManager getStructureSelectionManager()
1595 return av.getStructureSelectionManager();
1599 public void raiseOOMWarning(String string, OutOfMemoryError error)
1601 new OOMWarning(string, error, this);
1605 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1608 return new FeatureRenderer(this);
1612 public jalview.api.FeatureRenderer getFeatureRenderer()
1614 return seqPanel.seqCanvas.getFeatureRenderer();
1617 public void updateFeatureRenderer(
1618 jalview.renderer.seqfeatures.FeatureRenderer fr)
1620 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1623 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1625 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1627 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1631 public ScalePanel getScalePanel()
1636 public void setScalePanel(ScalePanel scalePanel)
1638 this.scalePanel = scalePanel;
1641 public SeqPanel getSeqPanel()
1646 public void setSeqPanel(SeqPanel seqPanel)
1648 this.seqPanel = seqPanel;
1651 public AnnotationPanel getAnnotationPanel()
1653 return annotationPanel;
1656 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1658 this.annotationPanel = annotationPanel;
1661 public AnnotationLabels getAlabels()
1666 public void setAlabels(AnnotationLabels alabels)
1668 this.alabels = alabels;
1671 public IdPanel getIdPanel()
1676 public void setIdPanel(IdPanel idPanel)
1678 this.idPanel = idPanel;
1682 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1683 * The aim is to keep the two alignments 'lined up' on their centre columns.
1686 * holds mapped region(s) of this alignment that we are scrolling
1687 * 'to'; may be modified for sequence offset by this method
1688 * @param verticalOffset
1689 * the number of visible sequences to show above the mapped region
1691 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1693 scrollToPosition(sr, verticalOffset, true);
1697 * Set a flag to say do not scroll any (cDNA/protein) complement.
1701 protected void setToScrollComplementPanel(boolean b)
1703 this.scrollComplementaryPanel = b;
1707 * Get whether to scroll complement panel
1709 * @return true if cDNA/protein complement panels should be scrolled
1711 protected boolean isSetToScrollComplementPanel()
1713 return this.scrollComplementaryPanel;
1719 * @adjustHeight if true, try to recalculate panel height for visible
1722 protected void refresh(boolean adjustHeight)
1724 validateAnnotationDimensions(adjustHeight);
1728 // sort, repaint, update overview
1729 paintAlignment(true, false);
1733 // lightweight repaint
1740 * Property change event fired when a change is made to the viewport ranges
1741 * object associated with this alignment panel's viewport
1743 public void propertyChange(PropertyChangeEvent evt)
1745 // update this panel's scroll values based on the new viewport ranges values
1746 ViewportRanges ranges = av.getRanges();
1747 int x = ranges.getStartRes();
1748 int y = ranges.getStartSeq();
1749 setScrollValues(x, y);
1751 // now update any complementary alignment (its viewport ranges object
1752 // is different so does not get automatically updated)
1753 if (isSetToScrollComplementPanel())
1755 setToScrollComplementPanel(false);
1756 av.scrollComplementaryAlignment();
1757 setToScrollComplementPanel(true);
1762 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1763 * reference should be nulled when the dialog is closed.
1765 * @param calculationChooser
1767 public void setCalculationDialog(CalculationChooser calculationChooser)
1769 calculationDialog = calculationChooser;
1773 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1776 public CalculationChooser getCalculationDialog()
1778 return calculationDialog;