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.bin.Jalview;
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.gui.ImageExporter.ImageWriterI;
35 import jalview.io.HTMLOutput;
36 import jalview.jbgui.GAlignmentPanel;
37 import jalview.math.AlignmentDimension;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.ImageMaker;
42 import jalview.util.MessageManager;
43 import jalview.util.Platform;
44 import jalview.viewmodel.ViewportListenerI;
45 import jalview.viewmodel.ViewportRanges;
47 import java.awt.BorderLayout;
48 import java.awt.Color;
49 import java.awt.Container;
50 import java.awt.Dimension;
52 import java.awt.FontMetrics;
53 import java.awt.Graphics;
54 import java.awt.Graphics2D;
55 import java.awt.event.AdjustmentEvent;
56 import java.awt.event.AdjustmentListener;
57 import java.awt.event.ComponentAdapter;
58 import java.awt.event.ComponentEvent;
59 import java.awt.print.PageFormat;
60 import java.awt.print.Printable;
61 import java.awt.print.PrinterException;
62 import java.beans.PropertyChangeEvent;
63 import java.beans.PropertyChangeListener;
65 import java.io.FileWriter;
66 import java.io.PrintWriter;
67 import java.util.List;
69 import javax.swing.SwingUtilities;
75 * @version $Revision: 1.161 $
77 public class AlignmentPanel extends GAlignmentPanel implements
78 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
80 public AlignViewport av;
82 OverviewPanel overviewPanel;
84 private SeqPanel seqPanel;
86 private IdPanel idPanel;
88 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, true, false);
339 boolean fastPaint = !(scrolled && av.getWrapAlignment());
341 getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
345 * Scroll the view to show the position of the highlighted region in results
348 * @param searchResults
349 * @param redrawOverview
352 public boolean scrollToPosition(SearchResultsI searchResults,
353 boolean redrawOverview)
355 return scrollToPosition(searchResults, 0, redrawOverview, false);
359 * Scrolls the view (if necessary) to show the position of the first
360 * highlighted region in results (if any). Answers true if the view was
361 * scrolled, or false if no matched region was found, or it is already
365 * @param verticalOffset
366 * if greater than zero, allows scrolling to a position below the
367 * first displayed sequence
368 * @param redrawOverview
369 * - when set, the overview will be recalculated (takes longer)
371 * if true, try to centre the search results horizontally in the view
374 protected boolean scrollToPosition(SearchResultsI results,
375 int verticalOffset, boolean redrawOverview, boolean centre)
377 int startv, endv, starts, ends;
378 ViewportRanges ranges = av.getRanges();
380 if (results == null || results.isEmpty() || av == null
381 || av.getAlignment() == null)
385 int seqIndex = av.getAlignment().findIndex(results);
390 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
392 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
401 * To centre results, scroll to positions half the visible width
402 * left/right of the start/end positions
406 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
407 start = Math.max(start - offset, 0);
408 end = end + offset - 1;
414 if (end == seq.getEnd())
419 if (av.hasHiddenColumns())
421 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
422 start = hidden.absoluteToVisibleColumn(start);
423 end = hidden.absoluteToVisibleColumn(end);
426 if (!hidden.isVisible(r[0]))
428 // don't scroll - position isn't visible
435 * allow for offset of target sequence (actually scroll to one above it)
437 seqIndex = Math.max(0, seqIndex - verticalOffset);
438 boolean scrollNeeded = true;
440 if (!av.getWrapAlignment())
442 if ((startv = ranges.getStartRes()) >= start)
445 * Scroll left to make start of search results visible
447 setScrollValues(start, seqIndex);
449 else if ((endv = ranges.getEndRes()) <= end)
452 * Scroll right to make end of search results visible
454 setScrollValues(startv + end - endv, seqIndex);
456 else if ((starts = ranges.getStartSeq()) > seqIndex)
459 * Scroll up to make start of search results visible
461 setScrollValues(ranges.getStartRes(), seqIndex);
463 else if ((ends = ranges.getEndSeq()) <= seqIndex)
466 * Scroll down to make end of search results visible
468 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
472 * Else results are already visible - no need to scroll
474 scrollNeeded = false;
478 scrollNeeded = ranges.scrollToWrappedVisible(start);
481 paintAlignment(redrawOverview, false);
489 * @return DOCUMENT ME!
491 public OverviewPanel getOverviewPanel()
493 return overviewPanel;
502 public void setOverviewPanel(OverviewPanel op)
510 * Hide or show annotation panel
513 public void setAnnotationVisible(boolean b)
515 if (!av.getWrapAlignment())
517 annotationSpaceFillerHolder.setVisible(b);
518 annotationScroller.setVisible(b);
524 * automatically adjust annotation panel height for new annotation whilst
525 * ensuring the alignment is still visible.
528 public void adjustAnnotationHeight()
530 // TODO: display vertical annotation scrollbar if necessary
531 // this is called after loading new annotation onto alignment
532 if (alignFrame.getHeight() == 0)
534 System.out.println("NEEDS FIXING");
536 validateAnnotationDimensions(true);
538 // TODO: many places call this method and also paintAlignment with various
539 // different settings. this means multiple redraws are triggered...
540 paintAlignment(true, false);
544 * calculate the annotation dimensions and refresh slider values accordingly.
545 * need to do repaints/notifys afterwards.
547 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
549 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
551 if (adjustPanelHeight)
553 int rowHeight = av.getCharHeight();
554 int alignmentHeight = rowHeight * av.getAlignment().getHeight();
557 * Estimate available height in the AlignFrame for alignment +
558 * annotations. Deduct an estimate for title bar, menu bar, scale panel,
559 * hscroll, status bar, insets.
561 int stuff = Platform.isAMac() ? 120 : 140;
562 int availableHeight = alignFrame.getHeight() - stuff;
565 * If not enough vertical space, maximize annotation height while keeping
566 * at least two rows of alignment visible
568 if (annotationHeight + alignmentHeight > availableHeight)
570 annotationHeight = Math.min(annotationHeight,
571 availableHeight - 2 * rowHeight);
576 // maintain same window layout whilst updating sliders
577 annotationHeight = annotationScroller.getSize().height;
581 annotationScroller.setPreferredSize(
582 new Dimension(annotationScroller.getWidth(), annotationHeight));
584 Dimension e = idPanel.getSize();
585 alabels.setSize(new Dimension(e.width, annotationHeight));
587 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
588 annotationSpaceFillerHolder.getWidth(), annotationHeight));
589 annotationScroller.validate();
590 annotationScroller.addNotify();
594 * update alignment layout for viewport settings
599 public void updateLayout()
602 setAnnotationVisible(av.isShowAnnotation());
603 boolean wrap = av.getWrapAlignment();
604 ViewportRanges ranges = av.getRanges();
605 ranges.setStartSeq(0);
606 scalePanelHolder.setVisible(!wrap);
607 hscroll.setVisible(!wrap);
608 idwidthAdjuster.setVisible(!wrap);
612 annotationScroller.setVisible(false);
613 annotationSpaceFillerHolder.setVisible(false);
615 else if (av.isShowAnnotation())
617 annotationScroller.setVisible(true);
618 annotationSpaceFillerHolder.setVisible(true);
621 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
623 { // may not yet be laid out
626 int widthInRes = getSeqPanel().seqCanvas
627 .getWrappedCanvasWidth(canvasWidth);
628 ranges.setViewportWidth(widthInRes);
632 int widthInRes = (canvasWidth / av.getCharWidth());
633 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
634 / av.getCharHeight());
636 ranges.setViewportWidth(widthInRes);
637 ranges.setViewportHeight(heightInSeq);
641 idSpaceFillerPanel1.setVisible(!wrap);
647 * Adjust row/column scrollers to show a visible position in the alignment.
650 * visible column to scroll to
652 * visible row to scroll to
655 public void setScrollValues(int xpos, int ypos)
660 if (av == null || av.getAlignment() == null)
665 if (av.getWrapAlignment())
667 setScrollingForWrappedPanel(x);
671 int width = av.getAlignment().getWidth();
672 int height = av.getAlignment().getHeight();
674 if (av.hasHiddenColumns())
676 // reset the width to exclude hidden columns
677 width = av.getAlignment().getHiddenColumns()
678 .absoluteToVisibleColumn(width);
681 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
682 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
689 if (vextent > height)
694 if ((hextent + x) > width)
699 if ((vextent + y) > height)
701 y = height - vextent;
714 // update the scroll values
715 hscroll.setValues(x, hextent, 0, width);
716 vscroll.setValues(y, vextent, 0, height);
721 * Respond to adjustment event when horizontal or vertical scrollbar is
725 * adjustment event encoding whether hscroll or vscroll changed
728 public void adjustmentValueChanged(AdjustmentEvent evt)
730 if (av.getWrapAlignment())
732 adjustScrollingWrapped(evt);
736 ViewportRanges ranges = av.getRanges();
738 if (evt.getSource() == hscroll)
740 int oldX = ranges.getStartRes();
741 int oldwidth = ranges.getViewportWidth();
742 int x = hscroll.getValue();
743 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
745 // if we're scrolling to the position we're already at, stop
746 // this prevents infinite recursion of events when the scroll/viewport
747 // ranges values are the same
748 if ((x == oldX) && (width == oldwidth))
752 ranges.setViewportStartAndWidth(x, width);
754 else if (evt.getSource() == vscroll)
756 int oldY = ranges.getStartSeq();
757 int oldheight = ranges.getViewportHeight();
758 int y = vscroll.getValue();
759 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
761 // if we're scrolling to the position we're already at, stop
762 // this prevents infinite recursion of events when the scroll/viewport
763 // ranges values are the same
764 if ((y == oldY) && (height == oldheight))
768 ranges.setViewportStartAndHeight(y, height);
774 * Responds to a scroll change by setting the start position of the viewport.
779 protected void adjustScrollingWrapped(AdjustmentEvent evt)
781 if (evt.getSource() == hscroll)
783 return; // no horizontal scroll when wrapped
785 final ViewportRanges ranges = av.getRanges();
787 if (evt.getSource() == vscroll)
789 int newY = vscroll.getValue();
792 * if we're scrolling to the position we're already at, stop
793 * this prevents infinite recursion of events when the scroll/viewport
794 * ranges values are the same
796 int oldX = ranges.getStartRes();
797 int oldY = ranges.getWrappedScrollPosition(oldX);
805 * limit page up/down to one width's worth of positions
807 int rowSize = ranges.getViewportWidth();
808 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
809 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
814 // This is only called if file loaded is a jar file that
815 // was wrapped when saved and user has wrap alignment true
816 // as preference setting
817 SwingUtilities.invokeLater(new Runnable()
822 // When updating scrolling to use ViewportChange events, this code
823 // could not be validated and it is not clear if it is now being
824 // called. Log warning here in case it is called and unforeseen
827 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
829 // scroll to start of panel
830 ranges.setStartRes(0);
831 ranges.setStartSeq(0);
839 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
842 public void paintAlignment(boolean updateOverview,
843 boolean updateStructures)
845 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
846 av.isShowAutocalculatedAbove());
847 sorter.sort(getAlignment().getAlignmentAnnotation(),
848 av.getSortAnnotationsBy());
851 if (updateStructures)
853 av.getStructureSelectionManager().sequenceColoursChanged(this);
858 if (overviewPanel != null)
860 overviewPanel.updateOverviewImage();
872 public void paintComponent(Graphics g)
874 invalidate(); // needed so that the id width adjuster works correctly
876 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
877 idPanelHolder.setPreferredSize(d);
878 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
880 validate(); // needed so that the id width adjuster works correctly
883 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
884 * though I still think this call should be elsewhere.
886 ViewportRanges ranges = av.getRanges();
887 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
891 * Set vertical scroll bar position, and number of increments, for wrapped
894 * @param topLeftColumn
895 * the column position at top left (0..)
897 private void setScrollingForWrappedPanel(int topLeftColumn)
899 ViewportRanges ranges = av.getRanges();
900 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
901 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
904 * a scrollbar's value can be set to at most (maximum-extent)
905 * so we add extent (1) to the maxScroll value
907 vscroll.setUnitIncrement(1);
908 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
921 * @return DOCUMENT ME!
923 * @throws PrinterException
927 public int print(Graphics pg, PageFormat pf, int pi)
928 throws PrinterException
930 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
932 int pwidth = (int) pf.getImageableWidth();
933 int pheight = (int) pf.getImageableHeight();
935 if (av.getWrapAlignment())
937 return printWrappedAlignment(pwidth, pheight, pi, pg);
941 return printUnwrapped(pwidth, pheight, pi, pg, pg);
946 * Draws the alignment image, including sequence ids, sequences, and
947 * annotation labels and annotations if shown, on either one or two Graphics
957 * the graphics context for sequence ids and annotation labels
958 * @param alignmentGraphics
959 * the graphics context for sequences and annotations (may or may not
960 * be the same context as idGraphics)
962 * @throws PrinterException
964 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
965 Graphics idGraphics, Graphics alignmentGraphics)
966 throws PrinterException
968 final int idWidth = getVisibleIdWidth(false);
971 * Get the horizontal offset to where we draw the sequences.
972 * This is idWidth if using a single Graphics context, else zero.
974 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
977 FontMetrics fm = getFontMetrics(av.getFont());
978 final int charHeight = av.getCharHeight();
979 final int scaleHeight = charHeight + fm.getDescent();
981 idGraphics.setColor(Color.white);
982 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
983 idGraphics.setFont(av.getFont());
986 * How many sequences and residues can we fit on a printable page?
988 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
990 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
992 final int alignmentWidth = av.getAlignment().getWidth();
993 final int pagesWide = (alignmentWidth / totalRes) + 1;
995 final int startRes = (pageIndex % pagesWide) * totalRes;
996 final int endRes = Math.min(startRes + totalRes - 1,
999 final int startSeq = (pageIndex / pagesWide) * totalSeq;
1000 final int alignmentHeight = av.getAlignment().getHeight();
1001 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1003 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1005 if (av.isShowAnnotation())
1007 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1010 pagesHigh /= pageHeight;
1012 if (pageIndex >= (pagesWide * pagesHigh))
1014 return Printable.NO_SUCH_PAGE;
1016 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1019 * draw the Scale at horizontal offset, then reset to top left (0, 0)
1021 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1022 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1023 pageWidth - idWidth, scaleHeight);
1024 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1027 * Draw the sequence ids, offset for scale height,
1028 * then reset to top left (0, 0)
1030 idGraphics.translate(0, scaleHeight);
1031 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1032 List<SequenceI> selection = av.getSelectionGroup() == null ? null
1033 : av.getSelectionGroup().getSequences(null);
1034 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1037 idGraphics.setFont(av.getFont());
1038 idGraphics.translate(0, -scaleHeight);
1041 * draw the sequences, offset for scale height, and id width (if using a
1042 * single graphics context), then reset to (0, scale height)
1044 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1045 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1046 endRes, startSeq, endSeq - 1);
1047 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1049 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1052 * draw annotation labels; drawComponent() translates by
1053 * getScrollOffset(), so compensate for that first;
1054 * then reset to (0, scale height)
1056 int offset = getAlabels().getScrollOffset();
1057 idGraphics.translate(0, -offset);
1058 idGraphics.translate(0, alignmentDrawnHeight);
1059 getAlabels().drawComponent(idGraphics, idWidth);
1060 idGraphics.translate(0, -alignmentDrawnHeight);
1063 * draw the annotations starting at
1064 * (idOffset, alignmentHeight) from (0, scaleHeight)
1066 alignmentGraphics.translate(alignmentGraphicsOffset,
1067 alignmentDrawnHeight);
1068 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1069 alignmentGraphics, -1, startRes, endRes + 1);
1072 return Printable.PAGE_EXISTS;
1076 * Prints one page of an alignment in wrapped mode. Returns
1077 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1078 * no page could be drawn (page number out of range).
1088 * @throws PrinterException
1090 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1091 Graphics g) throws PrinterException
1093 int annotationHeight = 0;
1094 if (av.isShowAnnotation())
1096 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1099 int hgap = av.getCharHeight();
1100 if (av.getScaleAboveWrapped())
1102 hgap += av.getCharHeight();
1105 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1108 int idWidth = getVisibleIdWidth(false);
1110 int maxwidth = av.getAlignment().getWidth();
1111 if (av.hasHiddenColumns())
1113 maxwidth = av.getAlignment().getHiddenColumns()
1114 .absoluteToVisibleColumn(maxwidth) - 1;
1117 int resWidth = getSeqPanel().seqCanvas
1118 .getWrappedCanvasWidth(pageWidth - idWidth);
1120 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1122 g.setColor(Color.white);
1123 g.fillRect(0, 0, pageWidth, pageHeight);
1124 g.setFont(av.getFont());
1125 g.setColor(Color.black);
1128 * method: print the whole wrapped alignment, but with a clip region that
1129 * is restricted to the requested page; this supports selective print of
1130 * single pages or ranges, (at the cost of some repeated processing in
1131 * the 'normal' case, when all pages are printed)
1133 g.translate(0, -pageNumber * pageHeight);
1135 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1138 * draw sequence ids and annotation labels (if shown)
1140 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1141 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1143 g.translate(idWidth, 0);
1145 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1148 if ((pageNumber * pageHeight) < totalHeight)
1150 return Printable.PAGE_EXISTS;
1154 return Printable.NO_SUCH_PAGE;
1159 * get current sequence ID panel width, or nominal value if panel were to be
1160 * displayed using default settings
1164 public int getVisibleIdWidth()
1166 return getVisibleIdWidth(true);
1170 * get current sequence ID panel width, or nominal value if panel were to be
1171 * displayed using default settings
1174 * indicate if the Id width for onscreen or offscreen display should
1178 public int getVisibleIdWidth(boolean onscreen)
1180 // see if rendering offscreen - check preferences and calc width accordingly
1181 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1183 return calculateIdWidth(-1).width + 4;
1185 Integer idwidth = null;
1186 if (onscreen || (idwidth = Cache
1187 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1189 int w = getIdPanel().getWidth();
1190 return (w > 0 ? w : calculateIdWidth().width + 4);
1192 return idwidth.intValue() + 4;
1196 * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1197 * writes it to the specified file
1202 void makeAlignmentImage(ImageMaker.TYPE type, File file)
1204 final int borderBottomOffset = 5;
1206 AlignmentDimension aDimension = getAlignmentDimension();
1207 // todo use a lambda function in place of callback here?
1208 ImageWriterI writer = new ImageWriterI()
1211 public void exportImage(Graphics graphics) throws Exception
1213 if (av.getWrapAlignment())
1215 printWrappedAlignment(aDimension.getWidth(),
1216 aDimension.getHeight() + borderBottomOffset, 0, graphics);
1220 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1221 graphics, graphics);
1226 String fileTitle = alignFrame.getTitle();
1227 ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1229 int imageWidth = aDimension.getWidth();
1230 int imageHeight = aDimension.getHeight() + borderBottomOffset;
1231 String of = MessageManager.getString("label.alignment");
1232 exporter.doExport(file, this, imageWidth, imageHeight, of);
1236 * Calculates and returns a suitable width and height (in pixels) for an
1241 public AlignmentDimension getAlignmentDimension()
1243 int maxwidth = av.getAlignment().getWidth();
1244 if (av.hasHiddenColumns())
1246 maxwidth = av.getAlignment().getHiddenColumns()
1247 .absoluteToVisibleColumn(maxwidth);
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();
1257 if (Jalview.isHeadlessMode())
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);
1281 public void makePNGImageMap(File imgMapFile, String imageName)
1283 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1284 // ////////////////////////////////////////////
1285 int idWidth = getVisibleIdWidth(false);
1286 FontMetrics fm = getFontMetrics(av.getFont());
1287 int scaleHeight = av.getCharHeight() + fm.getDescent();
1290 // ////////////////////////////////
1291 if (imgMapFile != null)
1295 int sSize = av.getAlignment().getHeight();
1296 int alwidth = av.getAlignment().getWidth();
1297 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1298 out.println(HTMLOutput.getImageMapHTML());
1299 out.println("<img src=\"" + imageName
1300 + "\" border=\"0\" usemap=\"#Map\" >"
1301 + "<map name=\"Map\">");
1303 for (int s = 0; s < sSize; s++)
1305 int sy = s * av.getCharHeight() + scaleHeight;
1307 SequenceI seq = av.getAlignment().getSequenceAt(s);
1308 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1309 for (int column = 0; column < alwidth; column++)
1311 StringBuilder text = new StringBuilder(512);
1312 String triplet = null;
1313 if (av.getAlignment().isNucleotide())
1315 triplet = ResidueProperties.nucleotideName.get(seq
1316 .getCharAt(column) + "");
1320 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1324 if (triplet == null)
1329 int seqPos = seq.findPosition(column);
1330 int gSize = groups.length;
1331 for (int g = 0; g < gSize; g++)
1333 if (text.length() < 1)
1335 text.append("<area shape=\"rect\" coords=\"")
1336 .append((idWidth + column * av.getCharWidth()))
1337 .append(",").append(sy).append(",")
1338 .append((idWidth + (column + 1) * av.getCharWidth()))
1339 .append(",").append((av.getCharHeight() + sy))
1340 .append("\"").append(" onMouseOver=\"toolTip('")
1341 .append(seqPos).append(" ").append(triplet);
1344 if (groups[g].getStartRes() < column
1345 && groups[g].getEndRes() > column)
1347 text.append("<br><em>").append(groups[g].getName())
1352 if (text.length() < 1)
1354 text.append("<area shape=\"rect\" coords=\"")
1355 .append((idWidth + column * av.getCharWidth()))
1356 .append(",").append(sy).append(",")
1357 .append((idWidth + (column + 1) * av.getCharWidth()))
1358 .append(",").append((av.getCharHeight() + sy))
1359 .append("\"").append(" onMouseOver=\"toolTip('")
1360 .append(seqPos).append(" ").append(triplet);
1362 if (!Comparison.isGap(seq.getCharAt(column)))
1364 List<SequenceFeature> features = seq.findFeatures(column, column);
1365 for (SequenceFeature sf : features)
1367 if (sf.isContactFeature())
1369 text.append("<br>").append(sf.getType()).append(" ")
1370 .append(sf.getBegin()).append(":")
1371 .append(sf.getEnd());
1375 text.append("<br>");
1376 text.append(sf.getType());
1377 String description = sf.getDescription();
1378 if (description != null
1379 && !sf.getType().equals(description))
1381 description = description.replace("\"", """);
1382 text.append(" ").append(description);
1385 String status = sf.getStatus();
1386 if (status != null && !"".equals(status))
1388 text.append(" (").append(status).append(")");
1391 if (text.length() > 1)
1393 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1394 out.println(text.toString());
1399 out.println("</map></body></html>");
1402 } catch (Exception ex)
1404 ex.printStackTrace();
1406 } // /////////END OF IMAGE MAP
1410 int getWrappedHeight()
1412 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1414 if (System.getProperty("java.awt.headless") != null
1415 && System.getProperty("java.awt.headless").equals("true"))
1417 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1418 - vscroll.getPreferredSize().width
1419 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1422 int chunkWidth = getSeqPanel().seqCanvas
1423 .getWrappedCanvasWidth(seqPanelWidth);
1425 int hgap = av.getCharHeight();
1426 if (av.getScaleAboveWrapped())
1428 hgap += av.getCharHeight();
1431 int annotationHeight = 0;
1432 if (av.isShowAnnotation())
1434 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1437 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1440 int maxwidth = av.getAlignment().getWidth();
1441 if (av.hasHiddenColumns())
1443 maxwidth = av.getAlignment().getHiddenColumns()
1444 .absoluteToVisibleColumn(maxwidth) - 1;
1447 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1453 * close the panel - deregisters all listeners and nulls any references to
1456 public void closePanel()
1458 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1459 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1460 PaintRefresher.RemoveComponent(this);
1465 * try to ensure references are nulled
1467 if (annotationPanel != null)
1469 annotationPanel.dispose();
1470 annotationPanel = null;
1475 av.removePropertyChangeListener(propertyChangeListener);
1476 propertyChangeListener = null;
1477 StructureSelectionManager ssm = av.getStructureSelectionManager();
1478 ssm.removeStructureViewerListener(getSeqPanel(), null);
1479 ssm.removeSelectionListener(getSeqPanel());
1480 ssm.removeCommandListener(av);
1481 ssm.removeStructureViewerListener(getSeqPanel(), null);
1482 ssm.removeSelectionListener(getSeqPanel());
1488 if (Cache.log.isDebugEnabled())
1490 Cache.log.warn("Closing alignment panel which is already closed.");
1496 * Close any open dialogs that would be orphaned when this one is closed
1498 protected void closeChildFrames()
1500 if (overviewPanel != null)
1502 overviewPanel.dispose();
1503 overviewPanel = null;
1505 if (calculationDialog != null)
1507 calculationDialog.closeFrame();
1508 calculationDialog = null;
1513 * hides or shows dynamic annotation rows based on groups and av state flags
1515 public void updateAnnotation()
1517 updateAnnotation(false, false);
1520 public void updateAnnotation(boolean applyGlobalSettings)
1522 updateAnnotation(applyGlobalSettings, false);
1525 public void updateAnnotation(boolean applyGlobalSettings,
1526 boolean preserveNewGroupSettings)
1528 av.updateGroupAnnotationSettings(applyGlobalSettings,
1529 preserveNewGroupSettings);
1530 adjustAnnotationHeight();
1534 public AlignmentI getAlignment()
1536 return av == null ? null : av.getAlignment();
1540 public String getViewName()
1546 * Make/Unmake this alignment panel the current input focus
1550 public void setSelected(boolean b)
1554 if (alignFrame.getSplitViewContainer() != null)
1557 * bring enclosing SplitFrame to front first if there is one
1559 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1561 alignFrame.setSelected(b);
1562 } catch (Exception ex)
1568 alignFrame.setDisplayedView(this);
1573 public StructureSelectionManager getStructureSelectionManager()
1575 return av.getStructureSelectionManager();
1579 public void raiseOOMWarning(String string, OutOfMemoryError error)
1581 new OOMWarning(string, error, this);
1585 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1588 return new FeatureRenderer(this);
1592 public jalview.api.FeatureRenderer getFeatureRenderer()
1594 return seqPanel.seqCanvas.getFeatureRenderer();
1597 public void updateFeatureRenderer(
1598 jalview.renderer.seqfeatures.FeatureRenderer fr)
1600 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1603 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1605 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1607 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1611 public ScalePanel getScalePanel()
1616 public void setScalePanel(ScalePanel scalePanel)
1618 this.scalePanel = scalePanel;
1621 public SeqPanel getSeqPanel()
1626 public void setSeqPanel(SeqPanel seqPanel)
1628 this.seqPanel = seqPanel;
1631 public AnnotationPanel getAnnotationPanel()
1633 return annotationPanel;
1636 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1638 this.annotationPanel = annotationPanel;
1641 public AnnotationLabels getAlabels()
1646 public void setAlabels(AnnotationLabels alabels)
1648 this.alabels = alabels;
1651 public IdPanel getIdPanel()
1656 public void setIdPanel(IdPanel idPanel)
1658 this.idPanel = idPanel;
1662 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1663 * The aim is to keep the two alignments 'lined up' on their centre columns.
1666 * holds mapped region(s) of this alignment that we are scrolling
1667 * 'to'; may be modified for sequence offset by this method
1668 * @param verticalOffset
1669 * the number of visible sequences to show above the mapped region
1671 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1673 scrollToPosition(sr, verticalOffset, true, true);
1677 * Set a flag to say do not scroll any (cDNA/protein) complement.
1681 protected void setToScrollComplementPanel(boolean b)
1683 this.scrollComplementaryPanel = b;
1687 * Get whether to scroll complement panel
1689 * @return true if cDNA/protein complement panels should be scrolled
1691 protected boolean isSetToScrollComplementPanel()
1693 return this.scrollComplementaryPanel;
1699 * @adjustHeight if true, try to recalculate panel height for visible
1702 protected void refresh(boolean adjustHeight)
1704 validateAnnotationDimensions(adjustHeight);
1708 // sort, repaint, update overview
1709 paintAlignment(true, false);
1713 // lightweight repaint
1720 * Property change event fired when a change is made to the viewport ranges
1721 * object associated with this alignment panel's viewport
1723 public void propertyChange(PropertyChangeEvent evt)
1725 // update this panel's scroll values based on the new viewport ranges values
1726 ViewportRanges ranges = av.getRanges();
1727 int x = ranges.getStartRes();
1728 int y = ranges.getStartSeq();
1729 setScrollValues(x, y);
1731 // now update any complementary alignment (its viewport ranges object
1732 // is different so does not get automatically updated)
1733 if (isSetToScrollComplementPanel())
1735 setToScrollComplementPanel(false);
1736 av.scrollComplementaryAlignment();
1737 setToScrollComplementPanel(true);
1742 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1743 * reference should be nulled when the dialog is closed.
1745 * @param calculationChooser
1747 public void setCalculationDialog(CalculationChooser calculationChooser)
1749 calculationDialog = calculationChooser;
1753 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1756 public CalculationChooser getCalculationDialog()
1758 return calculationDialog;