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 * Calculates the width of the alignment labels based on the displayed names
249 * and any bounds on label width set in preferences. The calculated width is
250 * also set as a property of the viewport.
252 * @return Dimension giving the maximum width of the alignment label panel
253 * that should be used.
255 public Dimension calculateIdWidth()
257 int oldWidth = av.getIdWidth();
259 // calculate sensible default width when no preference is available
261 if (av.getIdWidth() < 0)
263 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
264 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
265 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
266 r = calculateIdWidth(maxwidth);
267 av.setIdWidth(r.width);
272 r.width = av.getIdWidth();
277 * fudge: if desired width has changed, update layout
278 * (see also paintComponent - updates layout on a repaint)
280 if (r.width != oldWidth)
282 idPanelHolder.setPreferredSize(r);
289 * Calculate the width of the alignment labels based on the displayed names
290 * and any bounds on label width set in preferences.
293 * -1 or maximum width allowed for IdWidth
294 * @return Dimension giving the maximum width of the alignment label panel
295 * that should be used.
297 protected Dimension calculateIdWidth(int maxwidth)
299 Container c = new Container();
301 FontMetrics fm = c.getFontMetrics(
302 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
304 AlignmentI al = av.getAlignment();
308 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
310 SequenceI s = al.getSequenceAt(i);
311 String id = s.getDisplayId(av.getShowJVSuffix());
312 int stringWidth = fm.stringWidth(id);
313 idWidth = Math.max(idWidth, stringWidth);
317 // Also check annotation label widths
320 if (al.getAlignmentAnnotation() != null)
322 fm = c.getFontMetrics(getAlabels().getFont());
324 while (i < al.getAlignmentAnnotation().length)
326 String label = al.getAlignmentAnnotation()[i].label;
327 int stringWidth = fm.stringWidth(label);
328 idWidth = Math.max(idWidth, stringWidth);
333 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
334 w += ID_WIDTH_PADDING;
336 return new Dimension(w, 12);
340 * Highlight the given results on the alignment
343 public void highlightSearchResults(SearchResultsI results)
345 boolean scrolled = scrollToPosition(results, 0, false);
347 boolean noFastPaint = scrolled && av.getWrapAlignment();
349 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
353 * Scroll the view to show the position of the highlighted region in results
356 * @param searchResults
359 public boolean scrollToPosition(SearchResultsI searchResults)
361 return scrollToPosition(searchResults, 0, false);
365 * Scrolls the view (if necessary) to show the position of the first
366 * highlighted region in results (if any). Answers true if the view was
367 * scrolled, or false if no matched region was found, or it is already
371 * @param verticalOffset
372 * if greater than zero, allows scrolling to a position below the
373 * first displayed sequence
375 * if true, try to centre the search results horizontally in the view
378 protected boolean scrollToPosition(SearchResultsI results,
379 int verticalOffset, boolean centre)
381 int startv, endv, starts, ends;
382 ViewportRanges ranges = av.getRanges();
384 if (results == null || results.isEmpty() || av == null
385 || av.getAlignment() == null)
389 int seqIndex = av.getAlignment().findIndex(results);
394 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
396 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
405 * To centre results, scroll to positions half the visible width
406 * left/right of the start/end positions
410 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
411 start = Math.max(start - offset, 0);
412 end = end + offset - 1;
418 if (end == seq.getEnd())
423 if (av.hasHiddenColumns())
425 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
426 start = hidden.absoluteToVisibleColumn(start);
427 end = hidden.absoluteToVisibleColumn(end);
430 if (!hidden.isVisible(r[0]))
432 // don't scroll - position isn't visible
439 * allow for offset of target sequence (actually scroll to one above it)
441 seqIndex = Math.max(0, seqIndex - verticalOffset);
442 boolean scrollNeeded = true;
444 if (!av.getWrapAlignment())
446 if ((startv = ranges.getStartRes()) >= start)
449 * Scroll left to make start of search results visible
451 setScrollValues(start, seqIndex);
453 else if ((endv = ranges.getEndRes()) <= end)
456 * Scroll right to make end of search results visible
458 setScrollValues(startv + end - endv, seqIndex);
460 else if ((starts = ranges.getStartSeq()) > seqIndex)
463 * Scroll up to make start of search results visible
465 setScrollValues(ranges.getStartRes(), seqIndex);
467 else if ((ends = ranges.getEndSeq()) <= seqIndex)
470 * Scroll down to make end of search results visible
472 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
476 * Else results are already visible - no need to scroll
478 scrollNeeded = false;
482 scrollNeeded = ranges.scrollToWrappedVisible(start);
485 paintAlignment(false, false);
493 * @return DOCUMENT ME!
495 public OverviewPanel getOverviewPanel()
497 return overviewPanel;
506 public void setOverviewPanel(OverviewPanel op)
514 * Hide or show annotation panel
517 public void setAnnotationVisible(boolean b)
519 if (!av.getWrapAlignment())
521 annotationSpaceFillerHolder.setVisible(b);
522 annotationScroller.setVisible(b);
528 * automatically adjust annotation panel height for new annotation whilst
529 * ensuring the alignment is still visible.
532 public void adjustAnnotationHeight()
534 // TODO: display vertical annotation scrollbar if necessary
535 // this is called after loading new annotation onto alignment
536 if (alignFrame.getHeight() == 0)
538 System.out.println("NEEDS FIXING");
540 validateAnnotationDimensions(true);
542 // TODO: many places call this method and also paintAlignment with various
543 // different settings. this means multiple redraws are triggered...
544 paintAlignment(true, av.needToUpdateStructureViews());
548 * calculate the annotation dimensions and refresh slider values accordingly.
549 * need to do repaints/notifys afterwards.
551 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
553 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
554 annotationHeight = getAnnotationPanel()
555 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
558 annotationScroller.setPreferredSize(
559 new Dimension(annotationScroller.getWidth(), annotationHeight));
561 Dimension e = idPanel.getSize();
562 alabels.setSize(new Dimension(e.width, annotationHeight));
564 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
565 annotationSpaceFillerHolder.getWidth(), annotationHeight));
566 annotationScroller.validate();
567 annotationScroller.addNotify();
571 * update alignment layout for viewport settings
576 public void updateLayout()
579 setAnnotationVisible(av.isShowAnnotation());
580 boolean wrap = av.getWrapAlignment();
581 ViewportRanges ranges = av.getRanges();
582 ranges.setStartSeq(0);
583 scalePanelHolder.setVisible(!wrap);
584 hscroll.setVisible(!wrap);
585 idwidthAdjuster.setVisible(!wrap);
589 annotationScroller.setVisible(false);
590 annotationSpaceFillerHolder.setVisible(false);
592 else if (av.isShowAnnotation())
594 annotationScroller.setVisible(true);
595 annotationSpaceFillerHolder.setVisible(true);
596 validateAnnotationDimensions(false);
599 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
601 { // may not yet be laid out
604 int widthInRes = getSeqPanel().seqCanvas
605 .getWrappedCanvasWidth(canvasWidth);
606 ranges.setViewportWidth(widthInRes);
610 int widthInRes = (canvasWidth / av.getCharWidth());
611 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
612 / av.getCharHeight());
614 ranges.setViewportWidth(widthInRes);
615 ranges.setViewportHeight(heightInSeq);
619 idSpaceFillerPanel1.setVisible(!wrap);
625 * Adjust row/column scrollers to show a visible position in the alignment.
628 * visible column to scroll to
630 * visible row to scroll to
633 public void setScrollValues(int xpos, int ypos)
638 if (av == null || av.getAlignment() == null)
643 if (av.getWrapAlignment())
645 setScrollingForWrappedPanel(x);
649 int width = av.getAlignment().getVisibleWidth();
650 int height = av.getAlignment().getHeight();
652 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
653 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
660 if (vextent > height)
665 if ((hextent + x) > width)
670 if ((vextent + y) > height)
672 y = height - vextent;
685 // update the scroll values
686 hscroll.setValues(x, hextent, 0, width);
687 vscroll.setValues(y, vextent, 0, height);
692 * Respond to adjustment event when horizontal or vertical scrollbar is
696 * adjustment event encoding whether hscroll or vscroll changed
699 public void adjustmentValueChanged(AdjustmentEvent evt)
701 if (av.getWrapAlignment())
703 adjustScrollingWrapped(evt);
707 ViewportRanges ranges = av.getRanges();
709 if (evt.getSource() == hscroll)
711 int oldX = ranges.getStartRes();
712 int oldwidth = ranges.getViewportWidth();
713 int x = hscroll.getValue();
714 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
716 // if we're scrolling to the position we're already at, stop
717 // this prevents infinite recursion of events when the scroll/viewport
718 // ranges values are the same
719 if ((x == oldX) && (width == oldwidth))
723 ranges.setViewportStartAndWidth(x, width);
725 else if (evt.getSource() == vscroll)
727 int oldY = ranges.getStartSeq();
728 int oldheight = ranges.getViewportHeight();
729 int y = vscroll.getValue();
730 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
732 // if we're scrolling to the position we're already at, stop
733 // this prevents infinite recursion of events when the scroll/viewport
734 // ranges values are the same
735 if ((y == oldY) && (height == oldheight))
739 ranges.setViewportStartAndHeight(y, height);
745 * Responds to a scroll change by setting the start position of the viewport.
750 protected void adjustScrollingWrapped(AdjustmentEvent evt)
752 if (evt.getSource() == hscroll)
754 return; // no horizontal scroll when wrapped
756 final ViewportRanges ranges = av.getRanges();
758 if (evt.getSource() == vscroll)
760 int newY = vscroll.getValue();
763 * if we're scrolling to the position we're already at, stop
764 * this prevents infinite recursion of events when the scroll/viewport
765 * ranges values are the same
767 int oldX = ranges.getStartRes();
768 int oldY = ranges.getWrappedScrollPosition(oldX);
776 * limit page up/down to one width's worth of positions
778 int rowSize = ranges.getViewportWidth();
779 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
780 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
785 // This is only called if file loaded is a jar file that
786 // was wrapped when saved and user has wrap alignment true
787 // as preference setting
788 SwingUtilities.invokeLater(new Runnable()
793 // When updating scrolling to use ViewportChange events, this code
794 // could not be validated and it is not clear if it is now being
795 // called. Log warning here in case it is called and unforeseen
798 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
800 // scroll to start of panel
801 ranges.setStartRes(0);
802 ranges.setStartSeq(0);
810 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
813 public void paintAlignment(boolean updateOverview,
814 boolean updateStructures)
816 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
817 av.isShowAutocalculatedAbove());
818 sorter.sort(getAlignment().getAlignmentAnnotation(),
819 av.getSortAnnotationsBy());
822 if (updateStructures)
824 av.getStructureSelectionManager().sequenceColoursChanged(this);
829 if (overviewPanel != null)
831 overviewPanel.updateOverviewImage();
837 public void paintComponent(Graphics g)
839 invalidate(); // needed so that the id width adjuster works correctly
841 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
842 idPanelHolder.setPreferredSize(d);
843 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
845 validate(); // needed so that the id width adjuster works correctly
848 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
849 * though I still think this call should be elsewhere.
851 ViewportRanges ranges = av.getRanges();
852 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
856 * Set vertical scroll bar position, and number of increments, for wrapped
859 * @param topLeftColumn
860 * the column position at top left (0..)
862 private void setScrollingForWrappedPanel(int topLeftColumn)
864 ViewportRanges ranges = av.getRanges();
865 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
866 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
869 * a scrollbar's value can be set to at most (maximum-extent)
870 * so we add extent (1) to the maxScroll value
872 vscroll.setUnitIncrement(1);
873 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
886 * @return DOCUMENT ME!
888 * @throws PrinterException
892 public int print(Graphics pg, PageFormat pf, int pi)
893 throws PrinterException
895 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
897 int pwidth = (int) pf.getImageableWidth();
898 int pheight = (int) pf.getImageableHeight();
900 if (av.getWrapAlignment())
902 return printWrappedAlignment(pwidth, pheight, pi, pg);
906 return printUnwrapped(pwidth, pheight, pi, pg, pg);
911 * Draws the alignment image, including sequence ids, sequences, and
912 * annotation labels and annotations if shown, on either one or two Graphics
922 * the graphics context for sequence ids and annotation labels
923 * @param alignmentGraphics
924 * the graphics context for sequences and annotations (may or may not
925 * be the same context as idGraphics)
927 * @throws PrinterException
929 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
930 Graphics idGraphics, Graphics alignmentGraphics)
931 throws PrinterException
933 final int idWidth = getVisibleIdWidth(false);
936 * Get the horizontal offset to where we draw the sequences.
937 * This is idWidth if using a single Graphics context, else zero.
939 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
942 FontMetrics fm = getFontMetrics(av.getFont());
943 final int charHeight = av.getCharHeight();
944 final int scaleHeight = charHeight + fm.getDescent();
946 idGraphics.setColor(Color.white);
947 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
948 idGraphics.setFont(av.getFont());
951 * How many sequences and residues can we fit on a printable page?
953 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
955 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
957 final int alignmentWidth = av.getAlignment().getVisibleWidth();
958 int pagesWide = (alignmentWidth / totalRes) + 1;
960 final int startRes = (pageIndex % pagesWide) * totalRes;
961 final int endRes = Math.min(startRes + totalRes - 1,
964 final int startSeq = (pageIndex / pagesWide) * totalSeq;
965 final int alignmentHeight = av.getAlignment().getHeight();
966 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
968 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
970 if (av.isShowAnnotation())
972 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
975 pagesHigh /= pageHeight;
977 if (pageIndex >= (pagesWide * pagesHigh))
979 return Printable.NO_SUCH_PAGE;
981 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
984 * draw the Scale at horizontal offset, then reset to top left (0, 0)
986 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
987 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
988 pageWidth - idWidth, scaleHeight);
989 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
992 * Draw the sequence ids, offset for scale height,
993 * then reset to top left (0, 0)
995 idGraphics.translate(0, scaleHeight);
996 IdCanvas idCanvas = getIdPanel().getIdCanvas();
997 List<SequenceI> selection = av.getSelectionGroup() == null ? null
998 : av.getSelectionGroup().getSequences(null);
999 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1002 idGraphics.setFont(av.getFont());
1003 idGraphics.translate(0, -scaleHeight);
1006 * draw the sequences, offset for scale height, and id width (if using a
1007 * single graphics context), then reset to (0, scale height)
1009 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1010 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1011 endRes, startSeq, endSeq - 1);
1012 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1014 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1017 * draw annotation labels; drawComponent() translates by
1018 * getScrollOffset(), so compensate for that first;
1019 * then reset to (0, scale height)
1021 int offset = getAlabels().getScrollOffset();
1022 idGraphics.translate(0, -offset);
1023 idGraphics.translate(0, alignmentDrawnHeight);
1024 getAlabels().drawComponent(idGraphics, idWidth);
1025 idGraphics.translate(0, -alignmentDrawnHeight);
1028 * draw the annotations starting at
1029 * (idOffset, alignmentHeight) from (0, scaleHeight)
1031 alignmentGraphics.translate(alignmentGraphicsOffset,
1032 alignmentDrawnHeight);
1033 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1034 alignmentGraphics, -1, startRes, endRes + 1);
1037 return Printable.PAGE_EXISTS;
1041 * Prints one page of an alignment in wrapped mode. Returns
1042 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1043 * no page could be drawn (page number out of range).
1053 * @throws PrinterException
1055 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1056 Graphics g) throws PrinterException
1058 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1060 int annotationHeight = 0;
1061 if (av.isShowAnnotation())
1063 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1066 int hgap = av.getCharHeight();
1067 if (av.getScaleAboveWrapped())
1069 hgap += av.getCharHeight();
1072 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1075 int idWidth = getVisibleIdWidth(false);
1077 int maxwidth = av.getAlignment().getVisibleWidth();
1079 int resWidth = getSeqPanel().seqCanvas
1080 .getWrappedCanvasWidth(pageWidth - idWidth);
1081 av.getRanges().setViewportStartAndWidth(0, resWidth);
1083 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1085 g.setColor(Color.white);
1086 g.fillRect(0, 0, pageWidth, pageHeight);
1087 g.setFont(av.getFont());
1088 g.setColor(Color.black);
1091 * method: print the whole wrapped alignment, but with a clip region that
1092 * is restricted to the requested page; this supports selective print of
1093 * single pages or ranges, (at the cost of repeated processing in the
1094 * 'normal' case, when all pages are printed)
1096 g.translate(0, -pageNumber * pageHeight);
1098 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1101 * draw sequence ids and annotation labels (if shown)
1103 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1104 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1106 g.translate(idWidth, 0);
1108 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1111 if ((pageNumber * pageHeight) < totalHeight)
1113 return Printable.PAGE_EXISTS;
1117 return Printable.NO_SUCH_PAGE;
1122 * get current sequence ID panel width, or nominal value if panel were to be
1123 * displayed using default settings
1127 public int getVisibleIdWidth()
1129 return getVisibleIdWidth(true);
1133 * get current sequence ID panel width, or nominal value if panel were to be
1134 * displayed using default settings
1137 * indicate if the Id width for onscreen or offscreen display should
1141 protected int getVisibleIdWidth(boolean onscreen)
1143 // see if rendering offscreen - check preferences and calc width accordingly
1144 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1146 return calculateIdWidth(-1).width;
1148 Integer idwidth = onscreen ? null
1149 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1150 if (idwidth != null)
1152 return idwidth.intValue() + ID_WIDTH_PADDING;
1155 int w = getIdPanel().getWidth();
1156 return (w > 0 ? w : calculateIdWidth().width);
1159 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1161 int boarderBottomOffset = 5;
1162 long pSessionId = System.currentTimeMillis();
1163 headless = (System.getProperty("java.awt.headless") != null
1164 && System.getProperty("java.awt.headless").equals("true"));
1165 if (alignFrame != null && !headless)
1169 alignFrame.setProgressBar(MessageManager
1170 .formatMessage("status.saving_file", new Object[]
1171 { type.getLabel() }), pSessionId);
1176 AlignmentDimension aDimension = getAlignmentDimension();
1179 jalview.util.ImageMaker im;
1180 final String imageAction, imageTitle;
1181 if (type == jalview.util.ImageMaker.TYPE.PNG)
1183 imageAction = "Create PNG image from alignment";
1186 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1188 imageAction = "Create EPS file from alignment";
1189 imageTitle = alignFrame.getTitle();
1193 imageAction = "Create SVG file from alignment";
1194 imageTitle = alignFrame.getTitle();
1197 im = new jalview.util.ImageMaker(this, type, imageAction,
1198 aDimension.getWidth(),
1199 aDimension.getHeight() + boarderBottomOffset, file,
1200 imageTitle, alignFrame, pSessionId, headless);
1201 Graphics graphics = im.getGraphics();
1202 if (av.getWrapAlignment())
1204 if (graphics != null)
1206 printWrappedAlignment(aDimension.getWidth(),
1207 aDimension.getHeight() + boarderBottomOffset, 0,
1214 if (graphics != null)
1216 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1217 graphics, graphics);
1222 } catch (OutOfMemoryError err)
1225 System.out.println("########################\n" + "OUT OF MEMORY "
1226 + file + "\n" + "########################");
1227 new OOMWarning("Creating Image for " + file, err);
1228 // System.out.println("Create IMAGE: " + err);
1229 } catch (Exception ex)
1231 ex.printStackTrace();
1239 public AlignmentDimension getAlignmentDimension()
1241 int maxwidth = av.getAlignment().getVisibleWidth();
1243 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1244 + getScalePanel().getHeight();
1245 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1247 if (av.getWrapAlignment())
1249 height = getWrappedHeight();
1252 // need to obtain default alignment width and then add in any
1253 // additional allowance for id margin
1254 // this duplicates the calculation in getWrappedHeight but adjusts for
1256 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1257 - alignFrame.getInsets().left - alignFrame.getInsets().right
1258 - getVisibleIdWidth() + getVisibleIdWidth(false);
1262 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1266 else if (av.isShowAnnotation())
1268 height += getAnnotationPanel().adjustPanelHeight() + 3;
1270 return new AlignmentDimension(width, height);
1277 public void makeEPS(File epsFile)
1279 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1285 public void makePNG(File pngFile)
1287 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1290 public void makeSVG(File svgFile)
1292 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1295 public void makePNGImageMap(File imgMapFile, String imageName)
1297 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1298 // ////////////////////////////////////////////
1299 int idWidth = getVisibleIdWidth(false);
1300 FontMetrics fm = getFontMetrics(av.getFont());
1301 int scaleHeight = av.getCharHeight() + fm.getDescent();
1304 // ////////////////////////////////
1305 if (imgMapFile != null)
1309 int sSize = av.getAlignment().getHeight();
1310 int alwidth = av.getAlignment().getWidth();
1311 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1312 out.println(HTMLOutput.getImageMapHTML());
1313 out.println("<img src=\"" + imageName
1314 + "\" border=\"0\" usemap=\"#Map\" >"
1315 + "<map name=\"Map\">");
1317 for (int s = 0; s < sSize; s++)
1319 int sy = s * av.getCharHeight() + scaleHeight;
1321 SequenceI seq = av.getAlignment().getSequenceAt(s);
1322 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1323 for (int column = 0; column < alwidth; column++)
1325 StringBuilder text = new StringBuilder(512);
1326 String triplet = null;
1327 if (av.getAlignment().isNucleotide())
1329 triplet = ResidueProperties.nucleotideName.get(seq
1330 .getCharAt(column) + "");
1334 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1338 if (triplet == null)
1343 int seqPos = seq.findPosition(column);
1344 int gSize = groups.length;
1345 for (int g = 0; g < gSize; g++)
1347 if (text.length() < 1)
1349 text.append("<area shape=\"rect\" coords=\"")
1350 .append((idWidth + column * av.getCharWidth()))
1351 .append(",").append(sy).append(",")
1352 .append((idWidth + (column + 1) * av.getCharWidth()))
1353 .append(",").append((av.getCharHeight() + sy))
1354 .append("\"").append(" onMouseOver=\"toolTip('")
1355 .append(seqPos).append(" ").append(triplet);
1358 if (groups[g].getStartRes() < column
1359 && groups[g].getEndRes() > column)
1361 text.append("<br><em>").append(groups[g].getName())
1366 if (text.length() < 1)
1368 text.append("<area shape=\"rect\" coords=\"")
1369 .append((idWidth + column * av.getCharWidth()))
1370 .append(",").append(sy).append(",")
1371 .append((idWidth + (column + 1) * av.getCharWidth()))
1372 .append(",").append((av.getCharHeight() + sy))
1373 .append("\"").append(" onMouseOver=\"toolTip('")
1374 .append(seqPos).append(" ").append(triplet);
1376 if (!Comparison.isGap(seq.getCharAt(column)))
1378 List<SequenceFeature> features = seq.findFeatures(column, column);
1379 for (SequenceFeature sf : features)
1381 if (sf.isContactFeature())
1383 text.append("<br>").append(sf.getType()).append(" ")
1384 .append(sf.getBegin()).append(":")
1385 .append(sf.getEnd());
1389 text.append("<br>");
1390 text.append(sf.getType());
1391 String description = sf.getDescription();
1392 if (description != null
1393 && !sf.getType().equals(description))
1395 description = description.replace("\"", """);
1396 text.append(" ").append(description);
1399 String status = sf.getStatus();
1400 if (status != null && !"".equals(status))
1402 text.append(" (").append(status).append(")");
1405 if (text.length() > 1)
1407 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1408 out.println(text.toString());
1413 out.println("</map></body></html>");
1416 } catch (Exception ex)
1418 ex.printStackTrace();
1420 } // /////////END OF IMAGE MAP
1425 * Answers the height of the entire alignment in pixels, assuming it is in
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 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1455 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1458 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1461 int maxwidth = av.getAlignment().getWidth();
1462 if (av.hasHiddenColumns())
1464 maxwidth = av.getAlignment().getHiddenColumns()
1465 .absoluteToVisibleColumn(maxwidth) - 1;
1468 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1474 * close the panel - deregisters all listeners and nulls any references to
1477 public void closePanel()
1479 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1480 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1481 PaintRefresher.RemoveComponent(this);
1486 * try to ensure references are nulled
1488 if (annotationPanel != null)
1490 annotationPanel.dispose();
1491 annotationPanel = null;
1496 av.removePropertyChangeListener(propertyChangeListener);
1497 propertyChangeListener = null;
1498 StructureSelectionManager ssm = av.getStructureSelectionManager();
1499 ssm.removeStructureViewerListener(getSeqPanel(), null);
1500 ssm.removeSelectionListener(getSeqPanel());
1501 ssm.removeCommandListener(av);
1502 ssm.removeStructureViewerListener(getSeqPanel(), null);
1503 ssm.removeSelectionListener(getSeqPanel());
1509 if (Cache.log.isDebugEnabled())
1511 Cache.log.warn("Closing alignment panel which is already closed.");
1517 * Close any open dialogs that would be orphaned when this one is closed
1519 protected void closeChildFrames()
1521 if (overviewPanel != null)
1523 overviewPanel.dispose();
1524 overviewPanel = null;
1526 if (calculationDialog != null)
1528 calculationDialog.closeFrame();
1529 calculationDialog = null;
1534 * hides or shows dynamic annotation rows based on groups and av state flags
1536 public void updateAnnotation()
1538 updateAnnotation(false, false);
1541 public void updateAnnotation(boolean applyGlobalSettings)
1543 updateAnnotation(applyGlobalSettings, false);
1546 public void updateAnnotation(boolean applyGlobalSettings,
1547 boolean preserveNewGroupSettings)
1549 av.updateGroupAnnotationSettings(applyGlobalSettings,
1550 preserveNewGroupSettings);
1551 adjustAnnotationHeight();
1555 public AlignmentI getAlignment()
1557 return av == null ? null : av.getAlignment();
1561 public String getViewName()
1563 return av.getViewName();
1567 * Make/Unmake this alignment panel the current input focus
1571 public void setSelected(boolean b)
1575 if (alignFrame.getSplitViewContainer() != null)
1578 * bring enclosing SplitFrame to front first if there is one
1580 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1582 alignFrame.setSelected(b);
1583 } catch (Exception ex)
1589 alignFrame.setDisplayedView(this);
1594 public StructureSelectionManager getStructureSelectionManager()
1596 return av.getStructureSelectionManager();
1600 public void raiseOOMWarning(String string, OutOfMemoryError error)
1602 new OOMWarning(string, error, this);
1606 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1609 return new FeatureRenderer(this);
1613 public jalview.api.FeatureRenderer getFeatureRenderer()
1615 return seqPanel.seqCanvas.getFeatureRenderer();
1618 public void updateFeatureRenderer(
1619 jalview.renderer.seqfeatures.FeatureRenderer fr)
1621 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1624 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1626 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1628 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1632 public ScalePanel getScalePanel()
1637 public void setScalePanel(ScalePanel scalePanel)
1639 this.scalePanel = scalePanel;
1642 public SeqPanel getSeqPanel()
1647 public void setSeqPanel(SeqPanel seqPanel)
1649 this.seqPanel = seqPanel;
1652 public AnnotationPanel getAnnotationPanel()
1654 return annotationPanel;
1657 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1659 this.annotationPanel = annotationPanel;
1662 public AnnotationLabels getAlabels()
1667 public void setAlabels(AnnotationLabels alabels)
1669 this.alabels = alabels;
1672 public IdPanel getIdPanel()
1677 public void setIdPanel(IdPanel idPanel)
1679 this.idPanel = idPanel;
1683 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1684 * The aim is to keep the two alignments 'lined up' on their centre columns.
1687 * holds mapped region(s) of this alignment that we are scrolling
1688 * 'to'; may be modified for sequence offset by this method
1689 * @param verticalOffset
1690 * the number of visible sequences to show above the mapped region
1692 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1694 scrollToPosition(sr, verticalOffset, true);
1698 * Set a flag to say do not scroll any (cDNA/protein) complement.
1702 protected void setToScrollComplementPanel(boolean b)
1704 this.scrollComplementaryPanel = b;
1708 * Get whether to scroll complement panel
1710 * @return true if cDNA/protein complement panels should be scrolled
1712 protected boolean isSetToScrollComplementPanel()
1714 return this.scrollComplementaryPanel;
1720 * @adjustHeight if true, try to recalculate panel height for visible
1723 protected void refresh(boolean adjustHeight)
1725 validateAnnotationDimensions(adjustHeight);
1729 // sort, repaint, update overview
1730 paintAlignment(true, false);
1734 // lightweight repaint
1741 * Property change event fired when a change is made to the viewport ranges
1742 * object associated with this alignment panel's viewport
1744 public void propertyChange(PropertyChangeEvent evt)
1746 // update this panel's scroll values based on the new viewport ranges values
1747 ViewportRanges ranges = av.getRanges();
1748 int x = ranges.getStartRes();
1749 int y = ranges.getStartSeq();
1750 setScrollValues(x, y);
1752 // now update any complementary alignment (its viewport ranges object
1753 // is different so does not get automatically updated)
1754 if (isSetToScrollComplementPanel())
1756 setToScrollComplementPanel(false);
1757 av.scrollComplementaryAlignment();
1758 setToScrollComplementPanel(true);
1763 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1764 * reference should be nulled when the dialog is closed.
1766 * @param calculationChooser
1768 public void setCalculationDialog(CalculationChooser calculationChooser)
1770 calculationDialog = calculationChooser;
1774 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1777 public CalculationChooser getCalculationDialog()
1779 return calculationDialog;