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
76 public AlignViewport av;
78 OverviewPanel overviewPanel;
80 private SeqPanel seqPanel;
82 private IdPanel idPanel;
84 private boolean headless;
86 IdwidthAdjuster idwidthAdjuster;
89 public AlignFrame alignFrame;
91 private ScalePanel scalePanel;
93 private AnnotationPanel annotationPanel;
95 private AnnotationLabels alabels;
97 private int hextent = 0;
99 private int vextent = 0;
102 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
103 * false, suppresses invoking the same method recursively.
105 private boolean scrollComplementaryPanel = true;
107 private PropertyChangeListener propertyChangeListener;
109 private CalculationChooser calculationDialog;
112 * Creates a new AlignmentPanel object.
117 public AlignmentPanel(AlignFrame af, final AlignViewport av)
121 setSeqPanel(new SeqPanel(av, this));
122 setIdPanel(new IdPanel(av, this));
124 setScalePanel(new ScalePanel(av, this));
126 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
127 idwidthAdjuster = new IdwidthAdjuster(this);
128 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
130 setAnnotationPanel(new AnnotationPanel(this));
131 setAlabels(new AnnotationLabels(this));
133 annotationScroller.setViewportView(getAnnotationPanel());
134 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
136 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
137 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
139 setScrollValues(0, 0);
141 hscroll.addAdjustmentListener(this);
142 vscroll.addAdjustmentListener(this);
144 addComponentListener(new ComponentAdapter()
147 public void componentResized(ComponentEvent evt)
149 // reset the viewport ranges when the alignment panel is resized
150 // in particular, this initialises the end residue value when Jalview
152 ViewportRanges ranges = av.getRanges();
153 if (av.getWrapAlignment())
155 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
156 getSeqPanel().seqCanvas.getWidth());
157 ranges.setViewportWidth(widthInRes);
161 int widthInRes = getSeqPanel().seqCanvas.getWidth()
163 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
164 / av.getCharHeight();
166 ranges.setViewportWidth(widthInRes);
167 ranges.setViewportHeight(heightInSeq);
173 final AlignmentPanel ap = this;
174 propertyChangeListener = new PropertyChangeListener()
177 public void propertyChange(PropertyChangeEvent evt)
179 if (evt.getPropertyName().equals("alignment"))
181 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
186 av.addPropertyChangeListener(propertyChangeListener);
188 av.getRanges().addPropertyChangeListener(this);
190 adjustAnnotationHeight();
195 public AlignViewportI getAlignViewport()
200 public void alignmentChanged()
202 av.alignmentChanged(this);
204 if (getCalculationDialog() != null)
206 getCalculationDialog().validateCalcTypes();
209 alignFrame.updateEditMenuBar();
211 // no idea if we need to update structure
212 paintAlignment(true, true);
219 public void fontChanged()
221 // set idCanvas bufferedImage to null
222 // to prevent drawing old image
223 FontMetrics fm = getFontMetrics(av.getFont());
225 scalePanelHolder.setPreferredSize(
226 new Dimension(10, av.getCharHeight() + fm.getDescent()));
227 idSpaceFillerPanel1.setPreferredSize(
228 new Dimension(10, av.getCharHeight() + fm.getDescent()));
229 idwidthAdjuster.invalidate();
230 scalePanelHolder.invalidate();
231 getIdPanel().getIdCanvas().gg = null;
232 getSeqPanel().seqCanvas.img = null;
233 getAnnotationPanel().adjustPanelHeight();
235 Dimension d = calculateIdWidth();
237 d.setSize(d.width + 4, d.height);
238 getIdPanel().getIdCanvas().setPreferredSize(d);
239 hscrollFillerPanel.setPreferredSize(d);
245 * Calculate the width of the alignment labels based on the displayed names
246 * and any bounds on label width set in preferences.
248 * @return Dimension giving the maximum width of the alignment label panel
249 * that should be used.
251 public Dimension calculateIdWidth()
253 // calculate sensible default width when no preference is available
255 if (av.getIdWidth() < 0)
257 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
258 int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
259 r = calculateIdWidth(maxwidth);
260 av.setIdWidth(r.width);
265 r.width = av.getIdWidth();
272 * Calculate the width of the alignment labels based on the displayed names
273 * and any bounds on label width set in preferences.
276 * -1 or maximum width allowed for IdWidth
277 * @return Dimension giving the maximum width of the alignment label panel
278 * that should be used.
280 public Dimension calculateIdWidth(int maxwidth)
282 Container c = new Container();
284 FontMetrics fm = c.getFontMetrics(
285 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
287 AlignmentI al = av.getAlignment();
292 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
294 SequenceI s = al.getSequenceAt(i);
296 id = s.getDisplayId(av.getShowJVSuffix());
298 if (fm.stringWidth(id) > idWidth)
300 idWidth = fm.stringWidth(id);
306 // Also check annotation label widths
309 if (al.getAlignmentAnnotation() != null)
311 fm = c.getFontMetrics(getAlabels().getFont());
313 while (i < al.getAlignmentAnnotation().length)
315 String label = al.getAlignmentAnnotation()[i].label;
317 if (fm.stringWidth(label) > idWidth)
319 idWidth = fm.stringWidth(label);
326 return new Dimension(
327 maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
331 * Highlight the given results on the alignment
334 public void highlightSearchResults(SearchResultsI results)
336 boolean scrolled = scrollToPosition(results, 0, false);
338 boolean noFastPaint = scrolled && av.getWrapAlignment();
340 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
344 * Scroll the view to show the position of the highlighted region in results
347 * @param searchResults
350 public boolean scrollToPosition(SearchResultsI searchResults)
352 return scrollToPosition(searchResults, 0, false);
356 * Scrolls the view (if necessary) to show the position of the first
357 * highlighted region in results (if any). Answers true if the view was
358 * scrolled, or false if no matched region was found, or it is already
362 * @param verticalOffset
363 * if greater than zero, allows scrolling to a position below the
364 * first displayed sequence
366 * if true, try to centre the search results horizontally in the view
369 protected boolean scrollToPosition(SearchResultsI results,
370 int verticalOffset, boolean centre)
372 int startv, endv, starts, ends;
373 ViewportRanges ranges = av.getRanges();
375 if (results == null || results.isEmpty() || av == null
376 || av.getAlignment() == null)
380 int seqIndex = av.getAlignment().findIndex(results);
385 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
387 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
396 * To centre results, scroll to positions half the visible width
397 * left/right of the start/end positions
401 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
402 start = Math.max(start - offset, 0);
403 end = end + offset - 1;
409 if (end == seq.getEnd())
414 if (av.hasHiddenColumns())
416 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
417 start = hidden.absoluteToVisibleColumn(start);
418 end = hidden.absoluteToVisibleColumn(end);
421 if (!hidden.isVisible(r[0]))
423 // don't scroll - position isn't visible
430 * allow for offset of target sequence (actually scroll to one above it)
432 seqIndex = Math.max(0, seqIndex - verticalOffset);
433 boolean scrollNeeded = true;
435 if (!av.getWrapAlignment())
437 if ((startv = ranges.getStartRes()) >= start)
440 * Scroll left to make start of search results visible
442 setScrollValues(start, seqIndex);
444 else if ((endv = ranges.getEndRes()) <= end)
447 * Scroll right to make end of search results visible
449 setScrollValues(startv + end - endv, seqIndex);
451 else if ((starts = ranges.getStartSeq()) > seqIndex)
454 * Scroll up to make start of search results visible
456 setScrollValues(ranges.getStartRes(), seqIndex);
458 else if ((ends = ranges.getEndSeq()) <= seqIndex)
461 * Scroll down to make end of search results visible
463 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
467 * Else results are already visible - no need to scroll
469 scrollNeeded = false;
473 scrollNeeded = ranges.scrollToWrappedVisible(start);
476 paintAlignment(false, false);
484 * @return DOCUMENT ME!
486 public OverviewPanel getOverviewPanel()
488 return overviewPanel;
497 public void setOverviewPanel(OverviewPanel op)
505 * Hide or show annotation panel
508 public void setAnnotationVisible(boolean b)
510 if (!av.getWrapAlignment())
512 annotationSpaceFillerHolder.setVisible(b);
513 annotationScroller.setVisible(b);
519 * automatically adjust annotation panel height for new annotation whilst
520 * ensuring the alignment is still visible.
523 public void adjustAnnotationHeight()
525 // TODO: display vertical annotation scrollbar if necessary
526 // this is called after loading new annotation onto alignment
527 if (alignFrame.getHeight() == 0)
529 System.out.println("NEEDS FIXING");
531 validateAnnotationDimensions(true);
533 // TODO: many places call this method and also paintAlignment with various
534 // different settings. this means multiple redraws are triggered...
535 paintAlignment(true, av.needToUpdateStructureViews());
539 * calculate the annotation dimensions and refresh slider values accordingly.
540 * need to do repaints/notifys afterwards.
542 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
544 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
545 annotationHeight = getAnnotationPanel()
546 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
549 annotationScroller.setPreferredSize(
550 new Dimension(annotationScroller.getWidth(), annotationHeight));
552 Dimension e = idPanel.getSize();
553 alabels.setSize(new Dimension(e.width, annotationHeight));
555 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
556 annotationSpaceFillerHolder.getWidth(), annotationHeight));
557 annotationScroller.validate();
558 annotationScroller.addNotify();
562 * update alignment layout for viewport settings
567 public void updateLayout()
570 setAnnotationVisible(av.isShowAnnotation());
571 boolean wrap = av.getWrapAlignment();
572 ViewportRanges ranges = av.getRanges();
573 ranges.setStartSeq(0);
574 scalePanelHolder.setVisible(!wrap);
575 hscroll.setVisible(!wrap);
576 idwidthAdjuster.setVisible(!wrap);
580 annotationScroller.setVisible(false);
581 annotationSpaceFillerHolder.setVisible(false);
583 else if (av.isShowAnnotation())
585 annotationScroller.setVisible(true);
586 annotationSpaceFillerHolder.setVisible(true);
587 validateAnnotationDimensions(false);
590 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
592 { // may not yet be laid out
595 int widthInRes = getSeqPanel().seqCanvas
596 .getWrappedCanvasWidth(canvasWidth);
597 ranges.setViewportWidth(widthInRes);
601 int widthInRes = (canvasWidth / av.getCharWidth());
602 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
603 / av.getCharHeight());
605 ranges.setViewportWidth(widthInRes);
606 ranges.setViewportHeight(heightInSeq);
610 idSpaceFillerPanel1.setVisible(!wrap);
616 * Adjust row/column scrollers to show a visible position in the alignment.
619 * visible column to scroll to
621 * visible row to scroll to
624 public void setScrollValues(int xpos, int ypos)
629 if (av == null || av.getAlignment() == null)
634 if (av.getWrapAlignment())
636 setScrollingForWrappedPanel(x);
640 int width = av.getAlignment().getVisibleWidth();
641 int height = av.getAlignment().getHeight();
643 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
644 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
651 if (vextent > height)
656 if ((hextent + x) > width)
661 if ((vextent + y) > height)
663 y = height - vextent;
676 // update the scroll values
677 hscroll.setValues(x, hextent, 0, width);
678 vscroll.setValues(y, vextent, 0, height);
683 * Respond to adjustment event when horizontal or vertical scrollbar is
687 * adjustment event encoding whether hscroll or vscroll changed
690 public void adjustmentValueChanged(AdjustmentEvent evt)
692 if (av.getWrapAlignment())
694 adjustScrollingWrapped(evt);
698 ViewportRanges ranges = av.getRanges();
700 if (evt.getSource() == hscroll)
702 int oldX = ranges.getStartRes();
703 int oldwidth = ranges.getViewportWidth();
704 int x = hscroll.getValue();
705 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
707 // if we're scrolling to the position we're already at, stop
708 // this prevents infinite recursion of events when the scroll/viewport
709 // ranges values are the same
710 if ((x == oldX) && (width == oldwidth))
714 ranges.setViewportStartAndWidth(x, width);
716 else if (evt.getSource() == vscroll)
718 int oldY = ranges.getStartSeq();
719 int oldheight = ranges.getViewportHeight();
720 int y = vscroll.getValue();
721 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
723 // if we're scrolling to the position we're already at, stop
724 // this prevents infinite recursion of events when the scroll/viewport
725 // ranges values are the same
726 if ((y == oldY) && (height == oldheight))
730 ranges.setViewportStartAndHeight(y, height);
736 * Responds to a scroll change by setting the start position of the viewport.
741 protected void adjustScrollingWrapped(AdjustmentEvent evt)
743 if (evt.getSource() == hscroll)
745 return; // no horizontal scroll when wrapped
747 final ViewportRanges ranges = av.getRanges();
749 if (evt.getSource() == vscroll)
751 int newY = vscroll.getValue();
754 * if we're scrolling to the position we're already at, stop
755 * this prevents infinite recursion of events when the scroll/viewport
756 * ranges values are the same
758 int oldX = ranges.getStartRes();
759 int oldY = ranges.getWrappedScrollPosition(oldX);
767 * limit page up/down to one width's worth of positions
769 int rowSize = ranges.getViewportWidth();
770 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
771 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
776 // This is only called if file loaded is a jar file that
777 // was wrapped when saved and user has wrap alignment true
778 // as preference setting
779 SwingUtilities.invokeLater(new Runnable()
784 // When updating scrolling to use ViewportChange events, this code
785 // could not be validated and it is not clear if it is now being
786 // called. Log warning here in case it is called and unforeseen
789 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
791 // scroll to start of panel
792 ranges.setStartRes(0);
793 ranges.setStartSeq(0);
801 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
804 public void paintAlignment(boolean updateOverview,
805 boolean updateStructures)
807 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
808 av.isShowAutocalculatedAbove());
809 sorter.sort(getAlignment().getAlignmentAnnotation(),
810 av.getSortAnnotationsBy());
813 if (updateStructures)
815 av.getStructureSelectionManager().sequenceColoursChanged(this);
820 if (overviewPanel != null)
822 overviewPanel.updateOverviewImage();
834 public void paintComponent(Graphics g)
836 invalidate(); // needed so that the id width adjuster works correctly
838 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
839 idPanelHolder.setPreferredSize(d);
840 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
842 validate(); // needed so that the id width adjuster works correctly
845 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
846 * though I still think this call should be elsewhere.
848 ViewportRanges ranges = av.getRanges();
849 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
853 * Set vertical scroll bar position, and number of increments, for wrapped
856 * @param topLeftColumn
857 * the column position at top left (0..)
859 private void setScrollingForWrappedPanel(int topLeftColumn)
861 ViewportRanges ranges = av.getRanges();
862 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
863 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
866 * a scrollbar's value can be set to at most (maximum-extent)
867 * so we add extent (1) to the maxScroll value
869 vscroll.setUnitIncrement(1);
870 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
883 * @return DOCUMENT ME!
885 * @throws PrinterException
889 public int print(Graphics pg, PageFormat pf, int pi)
890 throws PrinterException
892 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
894 int pwidth = (int) pf.getImageableWidth();
895 int pheight = (int) pf.getImageableHeight();
897 if (av.getWrapAlignment())
899 return printWrappedAlignment(pwidth, pheight, pi, pg);
903 return printUnwrapped(pwidth, pheight, pi, pg, pg);
908 * Draws the alignment image, including sequence ids, sequences, and
909 * annotation labels and annotations if shown, on either one or two Graphics
919 * the graphics context for sequence ids and annotation labels
920 * @param alignmentGraphics
921 * the graphics context for sequences and annotations (may or may not
922 * be the same context as idGraphics)
924 * @throws PrinterException
926 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
927 Graphics idGraphics, Graphics alignmentGraphics)
928 throws PrinterException
930 final int idWidth = getVisibleIdWidth(false);
933 * Get the horizontal offset to where we draw the sequences.
934 * This is idWidth if using a single Graphics context, else zero.
936 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
939 FontMetrics fm = getFontMetrics(av.getFont());
940 final int charHeight = av.getCharHeight();
941 final int scaleHeight = charHeight + fm.getDescent();
943 idGraphics.setColor(Color.white);
944 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
945 idGraphics.setFont(av.getFont());
948 * How many sequences and residues can we fit on a printable page?
950 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
952 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
954 final int alignmentWidth = av.getAlignment().getVisibleWidth();
955 int pagesWide = (alignmentWidth / totalRes) + 1;
957 final int startRes = (pageIndex % pagesWide) * totalRes;
958 final int endRes = Math.min(startRes + totalRes - 1,
961 final int startSeq = (pageIndex / pagesWide) * totalSeq;
962 final int alignmentHeight = av.getAlignment().getHeight();
963 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
965 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
967 if (av.isShowAnnotation())
969 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
972 pagesHigh /= pageHeight;
974 if (pageIndex >= (pagesWide * pagesHigh))
976 return Printable.NO_SUCH_PAGE;
978 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
981 * draw the Scale at horizontal offset, then reset to top left (0, 0)
983 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
984 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
985 pageWidth - idWidth, scaleHeight);
986 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
989 * Draw the sequence ids, offset for scale height,
990 * then reset to top left (0, 0)
992 idGraphics.translate(0, scaleHeight);
993 IdCanvas idCanvas = getIdPanel().getIdCanvas();
994 List<SequenceI> selection = av.getSelectionGroup() == null ? null
995 : av.getSelectionGroup().getSequences(null);
996 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
999 idGraphics.setFont(av.getFont());
1000 idGraphics.translate(0, -scaleHeight);
1003 * draw the sequences, offset for scale height, and id width (if using a
1004 * single graphics context), then reset to (0, scale height)
1006 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1007 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1008 endRes, startSeq, endSeq - 1);
1009 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1011 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1014 * draw annotation labels; drawComponent() translates by
1015 * getScrollOffset(), so compensate for that first;
1016 * then reset to (0, scale height)
1018 int offset = getAlabels().getScrollOffset();
1019 idGraphics.translate(0, -offset);
1020 idGraphics.translate(0, alignmentDrawnHeight);
1021 getAlabels().drawComponent(idGraphics, idWidth);
1022 idGraphics.translate(0, -alignmentDrawnHeight);
1025 * draw the annotations starting at
1026 * (idOffset, alignmentHeight) from (0, scaleHeight)
1028 alignmentGraphics.translate(alignmentGraphicsOffset,
1029 alignmentDrawnHeight);
1030 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1031 alignmentGraphics, -1, startRes, endRes + 1);
1034 return Printable.PAGE_EXISTS;
1038 * Prints one page of an alignment in wrapped mode. Returns
1039 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1040 * no page could be drawn (page number out of range).
1050 * @throws PrinterException
1052 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1053 Graphics g) throws PrinterException
1055 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1057 int annotationHeight = 0;
1058 if (av.isShowAnnotation())
1060 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1063 int hgap = av.getCharHeight();
1064 if (av.getScaleAboveWrapped())
1066 hgap += av.getCharHeight();
1069 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1072 int idWidth = getVisibleIdWidth(false);
1074 int maxwidth = av.getAlignment().getVisibleWidth();
1076 int resWidth = getSeqPanel().seqCanvas
1077 .getWrappedCanvasWidth(pageWidth - idWidth);
1078 av.getRanges().setViewportStartAndWidth(0, resWidth);
1080 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1082 g.setColor(Color.white);
1083 g.fillRect(0, 0, pageWidth, pageHeight);
1084 g.setFont(av.getFont());
1085 g.setColor(Color.black);
1088 * method: print the whole wrapped alignment, but with a clip region that
1089 * is restricted to the requested page; this supports selective print of
1090 * single pages or ranges, (at the cost of repeated processing in the
1091 * 'normal' case, when all pages are printed)
1093 g.translate(0, -pageNumber * pageHeight);
1095 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1098 * draw sequence ids and annotation labels (if shown)
1100 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1101 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1103 g.translate(idWidth, 0);
1105 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1108 if ((pageNumber * pageHeight) < totalHeight)
1110 return Printable.PAGE_EXISTS;
1114 return Printable.NO_SUCH_PAGE;
1119 * get current sequence ID panel width, or nominal value if panel were to be
1120 * displayed using default settings
1124 public int getVisibleIdWidth()
1126 return getVisibleIdWidth(true);
1130 * get current sequence ID panel width, or nominal value if panel were to be
1131 * displayed using default settings
1134 * indicate if the Id width for onscreen or offscreen display should
1138 public int getVisibleIdWidth(boolean onscreen)
1140 // see if rendering offscreen - check preferences and calc width accordingly
1141 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1143 return calculateIdWidth(-1).width + 4;
1145 Integer idwidth = null;
1146 if (onscreen || (idwidth = Cache
1147 .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1149 int w = getIdPanel().getWidth();
1150 return (w > 0 ? w : calculateIdWidth().width + 4);
1152 return idwidth.intValue() + 4;
1155 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1157 int boarderBottomOffset = 5;
1158 long pSessionId = System.currentTimeMillis();
1159 headless = (System.getProperty("java.awt.headless") != null
1160 && System.getProperty("java.awt.headless").equals("true"));
1161 if (alignFrame != null && !headless)
1165 alignFrame.setProgressBar(MessageManager
1166 .formatMessage("status.saving_file", new Object[]
1167 { type.getLabel() }), pSessionId);
1172 AlignmentDimension aDimension = getAlignmentDimension();
1175 jalview.util.ImageMaker im;
1176 final String imageAction, imageTitle;
1177 if (type == jalview.util.ImageMaker.TYPE.PNG)
1179 imageAction = "Create PNG image from alignment";
1182 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1184 imageAction = "Create EPS file from alignment";
1185 imageTitle = alignFrame.getTitle();
1189 imageAction = "Create SVG file from alignment";
1190 imageTitle = alignFrame.getTitle();
1193 im = new jalview.util.ImageMaker(this, type, imageAction,
1194 aDimension.getWidth(),
1195 aDimension.getHeight() + boarderBottomOffset, file,
1196 imageTitle, alignFrame, pSessionId, headless);
1197 Graphics graphics = im.getGraphics();
1198 if (av.getWrapAlignment())
1200 if (graphics != null)
1202 printWrappedAlignment(aDimension.getWidth(),
1203 aDimension.getHeight() + boarderBottomOffset, 0,
1210 if (graphics != null)
1212 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1213 graphics, graphics);
1218 } catch (OutOfMemoryError err)
1221 System.out.println("########################\n" + "OUT OF MEMORY "
1222 + file + "\n" + "########################");
1223 new OOMWarning("Creating Image for " + file, err);
1224 // System.out.println("Create IMAGE: " + err);
1225 } catch (Exception ex)
1227 ex.printStackTrace();
1235 public AlignmentDimension getAlignmentDimension()
1237 int maxwidth = av.getAlignment().getVisibleWidth();
1239 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1240 + getScalePanel().getHeight();
1241 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1243 if (av.getWrapAlignment())
1245 height = getWrappedHeight();
1248 // need to obtain default alignment width and then add in any
1249 // additional allowance for id margin
1250 // this duplicates the calculation in getWrappedHeight but adjusts for
1252 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1253 - alignFrame.getInsets().left - alignFrame.getInsets().right
1254 - getVisibleIdWidth() + getVisibleIdWidth(false);
1258 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1262 else if (av.isShowAnnotation())
1264 height += getAnnotationPanel().adjustPanelHeight() + 3;
1266 return new AlignmentDimension(width, height);
1273 public void makeEPS(File epsFile)
1275 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1281 public void makePNG(File pngFile)
1283 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1286 public void makeSVG(File svgFile)
1288 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1291 public void makePNGImageMap(File imgMapFile, String imageName)
1293 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1294 // ////////////////////////////////////////////
1295 int idWidth = getVisibleIdWidth(false);
1296 FontMetrics fm = getFontMetrics(av.getFont());
1297 int scaleHeight = av.getCharHeight() + fm.getDescent();
1300 // ////////////////////////////////
1301 if (imgMapFile != null)
1305 int sSize = av.getAlignment().getHeight();
1306 int alwidth = av.getAlignment().getWidth();
1307 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1308 out.println(HTMLOutput.getImageMapHTML());
1309 out.println("<img src=\"" + imageName
1310 + "\" border=\"0\" usemap=\"#Map\" >"
1311 + "<map name=\"Map\">");
1313 for (int s = 0; s < sSize; s++)
1315 int sy = s * av.getCharHeight() + scaleHeight;
1317 SequenceI seq = av.getAlignment().getSequenceAt(s);
1318 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1319 for (int column = 0; column < alwidth; column++)
1321 StringBuilder text = new StringBuilder(512);
1322 String triplet = null;
1323 if (av.getAlignment().isNucleotide())
1325 triplet = ResidueProperties.nucleotideName.get(seq
1326 .getCharAt(column) + "");
1330 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1334 if (triplet == null)
1339 int seqPos = seq.findPosition(column);
1340 int gSize = groups.length;
1341 for (int g = 0; g < gSize; g++)
1343 if (text.length() < 1)
1345 text.append("<area shape=\"rect\" coords=\"")
1346 .append((idWidth + column * av.getCharWidth()))
1347 .append(",").append(sy).append(",")
1348 .append((idWidth + (column + 1) * av.getCharWidth()))
1349 .append(",").append((av.getCharHeight() + sy))
1350 .append("\"").append(" onMouseOver=\"toolTip('")
1351 .append(seqPos).append(" ").append(triplet);
1354 if (groups[g].getStartRes() < column
1355 && groups[g].getEndRes() > column)
1357 text.append("<br><em>").append(groups[g].getName())
1362 if (text.length() < 1)
1364 text.append("<area shape=\"rect\" coords=\"")
1365 .append((idWidth + column * av.getCharWidth()))
1366 .append(",").append(sy).append(",")
1367 .append((idWidth + (column + 1) * av.getCharWidth()))
1368 .append(",").append((av.getCharHeight() + sy))
1369 .append("\"").append(" onMouseOver=\"toolTip('")
1370 .append(seqPos).append(" ").append(triplet);
1372 if (!Comparison.isGap(seq.getCharAt(column)))
1374 List<SequenceFeature> features = seq.findFeatures(column, column);
1375 for (SequenceFeature sf : features)
1377 if (sf.isContactFeature())
1379 text.append("<br>").append(sf.getType()).append(" ")
1380 .append(sf.getBegin()).append(":")
1381 .append(sf.getEnd());
1385 text.append("<br>");
1386 text.append(sf.getType());
1387 String description = sf.getDescription();
1388 if (description != null
1389 && !sf.getType().equals(description))
1391 description = description.replace("\"", """);
1392 text.append(" ").append(description);
1395 String status = sf.getStatus();
1396 if (status != null && !"".equals(status))
1398 text.append(" (").append(status).append(")");
1401 if (text.length() > 1)
1403 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1404 out.println(text.toString());
1409 out.println("</map></body></html>");
1412 } catch (Exception ex)
1414 ex.printStackTrace();
1416 } // /////////END OF IMAGE MAP
1421 * Answers the height of the entire alignment in pixels, assuming it is in
1426 int getWrappedHeight()
1428 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1430 if (System.getProperty("java.awt.headless") != null
1431 && System.getProperty("java.awt.headless").equals("true"))
1433 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1434 - vscroll.getPreferredSize().width
1435 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1438 int chunkWidth = getSeqPanel().seqCanvas
1439 .getWrappedCanvasWidth(seqPanelWidth);
1441 int hgap = av.getCharHeight();
1442 if (av.getScaleAboveWrapped())
1444 hgap += av.getCharHeight();
1447 int annotationHeight = 0;
1448 if (av.isShowAnnotation())
1450 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1451 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1454 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1457 int maxwidth = av.getAlignment().getWidth();
1458 if (av.hasHiddenColumns())
1460 maxwidth = av.getAlignment().getHiddenColumns()
1461 .absoluteToVisibleColumn(maxwidth) - 1;
1464 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1470 * close the panel - deregisters all listeners and nulls any references to
1473 public void closePanel()
1475 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1476 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1477 PaintRefresher.RemoveComponent(this);
1482 * try to ensure references are nulled
1484 if (annotationPanel != null)
1486 annotationPanel.dispose();
1487 annotationPanel = null;
1492 av.removePropertyChangeListener(propertyChangeListener);
1493 propertyChangeListener = null;
1494 StructureSelectionManager ssm = av.getStructureSelectionManager();
1495 ssm.removeStructureViewerListener(getSeqPanel(), null);
1496 ssm.removeSelectionListener(getSeqPanel());
1497 ssm.removeCommandListener(av);
1498 ssm.removeStructureViewerListener(getSeqPanel(), null);
1499 ssm.removeSelectionListener(getSeqPanel());
1505 if (Cache.log.isDebugEnabled())
1507 Cache.log.warn("Closing alignment panel which is already closed.");
1513 * Close any open dialogs that would be orphaned when this one is closed
1515 protected void closeChildFrames()
1517 if (overviewPanel != null)
1519 overviewPanel.dispose();
1520 overviewPanel = null;
1522 if (calculationDialog != null)
1524 calculationDialog.closeFrame();
1525 calculationDialog = null;
1530 * hides or shows dynamic annotation rows based on groups and av state flags
1532 public void updateAnnotation()
1534 updateAnnotation(false, false);
1537 public void updateAnnotation(boolean applyGlobalSettings)
1539 updateAnnotation(applyGlobalSettings, false);
1542 public void updateAnnotation(boolean applyGlobalSettings,
1543 boolean preserveNewGroupSettings)
1545 av.updateGroupAnnotationSettings(applyGlobalSettings,
1546 preserveNewGroupSettings);
1547 adjustAnnotationHeight();
1551 public AlignmentI getAlignment()
1553 return av == null ? null : av.getAlignment();
1557 public String getViewName()
1559 return av.getViewName();
1563 * Make/Unmake this alignment panel the current input focus
1567 public void setSelected(boolean b)
1571 if (alignFrame.getSplitViewContainer() != null)
1574 * bring enclosing SplitFrame to front first if there is one
1576 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1578 alignFrame.setSelected(b);
1579 } catch (Exception ex)
1585 alignFrame.setDisplayedView(this);
1590 public StructureSelectionManager getStructureSelectionManager()
1592 return av.getStructureSelectionManager();
1596 public void raiseOOMWarning(String string, OutOfMemoryError error)
1598 new OOMWarning(string, error, this);
1602 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1605 return new FeatureRenderer(this);
1609 public jalview.api.FeatureRenderer getFeatureRenderer()
1611 return seqPanel.seqCanvas.getFeatureRenderer();
1614 public void updateFeatureRenderer(
1615 jalview.renderer.seqfeatures.FeatureRenderer fr)
1617 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1620 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1622 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1624 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1628 public ScalePanel getScalePanel()
1633 public void setScalePanel(ScalePanel scalePanel)
1635 this.scalePanel = scalePanel;
1638 public SeqPanel getSeqPanel()
1643 public void setSeqPanel(SeqPanel seqPanel)
1645 this.seqPanel = seqPanel;
1648 public AnnotationPanel getAnnotationPanel()
1650 return annotationPanel;
1653 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1655 this.annotationPanel = annotationPanel;
1658 public AnnotationLabels getAlabels()
1663 public void setAlabels(AnnotationLabels alabels)
1665 this.alabels = alabels;
1668 public IdPanel getIdPanel()
1673 public void setIdPanel(IdPanel idPanel)
1675 this.idPanel = idPanel;
1679 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1680 * The aim is to keep the two alignments 'lined up' on their centre columns.
1683 * holds mapped region(s) of this alignment that we are scrolling
1684 * 'to'; may be modified for sequence offset by this method
1685 * @param verticalOffset
1686 * the number of visible sequences to show above the mapped region
1688 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1690 scrollToPosition(sr, verticalOffset, true);
1694 * Set a flag to say do not scroll any (cDNA/protein) complement.
1698 protected void setToScrollComplementPanel(boolean b)
1700 this.scrollComplementaryPanel = b;
1704 * Get whether to scroll complement panel
1706 * @return true if cDNA/protein complement panels should be scrolled
1708 protected boolean isSetToScrollComplementPanel()
1710 return this.scrollComplementaryPanel;
1716 * @adjustHeight if true, try to recalculate panel height for visible
1719 protected void refresh(boolean adjustHeight)
1721 validateAnnotationDimensions(adjustHeight);
1725 // sort, repaint, update overview
1726 paintAlignment(true, false);
1730 // lightweight repaint
1737 * Property change event fired when a change is made to the viewport ranges
1738 * object associated with this alignment panel's viewport
1740 public void propertyChange(PropertyChangeEvent evt)
1742 // update this panel's scroll values based on the new viewport ranges values
1743 ViewportRanges ranges = av.getRanges();
1744 int x = ranges.getStartRes();
1745 int y = ranges.getStartSeq();
1746 setScrollValues(x, y);
1748 // now update any complementary alignment (its viewport ranges object
1749 // is different so does not get automatically updated)
1750 if (isSetToScrollComplementPanel())
1752 setToScrollComplementPanel(false);
1753 av.scrollComplementaryAlignment();
1754 setToScrollComplementPanel(true);
1759 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1760 * reference should be nulled when the dialog is closed.
1762 * @param calculationChooser
1764 public void setCalculationDialog(CalculationChooser calculationChooser)
1766 calculationDialog = calculationChooser;
1770 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1773 public CalculationChooser getCalculationDialog()
1775 return calculationDialog;