2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.HTMLOutput;
34 import jalview.jbgui.GAlignmentPanel;
35 import jalview.math.AlignmentDimension;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.Comparison;
39 import jalview.util.MessageManager;
40 import jalview.viewmodel.ViewportListenerI;
41 import jalview.viewmodel.ViewportRanges;
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Container;
46 import java.awt.Dimension;
48 import java.awt.FontMetrics;
49 import java.awt.Graphics;
50 import java.awt.Graphics2D;
51 import java.awt.event.AdjustmentEvent;
52 import java.awt.event.AdjustmentListener;
53 import java.awt.event.ComponentAdapter;
54 import java.awt.event.ComponentEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.Printable;
57 import java.awt.print.PrinterException;
58 import java.beans.PropertyChangeEvent;
59 import java.beans.PropertyChangeListener;
61 import java.io.FileWriter;
62 import java.io.PrintWriter;
63 import java.util.List;
65 import javax.swing.SwingUtilities;
71 * @version $Revision: 1.161 $
73 public class AlignmentPanel extends GAlignmentPanel implements
74 AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
77 * spare space in pixels between sequence id and alignment panel
79 private static final int ID_WIDTH_PADDING = 4;
81 public AlignViewport av;
83 OverviewPanel overviewPanel;
85 private SeqPanel seqPanel;
87 private IdPanel idPanel;
89 private boolean headless;
91 IdwidthAdjuster idwidthAdjuster;
94 public AlignFrame alignFrame;
96 private ScalePanel scalePanel;
98 private AnnotationPanel annotationPanel;
100 private AnnotationLabels alabels;
102 private int hextent = 0;
104 private int vextent = 0;
107 * Flag set while scrolling to follow complementary cDNA/protein scroll. When
108 * false, suppresses invoking the same method recursively.
110 private boolean scrollComplementaryPanel = true;
112 private PropertyChangeListener propertyChangeListener;
114 private CalculationChooser calculationDialog;
117 * Creates a new AlignmentPanel object.
122 public AlignmentPanel(AlignFrame af, final AlignViewport av)
126 setSeqPanel(new SeqPanel(av, this));
127 setIdPanel(new IdPanel(av, this));
129 setScalePanel(new ScalePanel(av, this));
131 idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
132 idwidthAdjuster = new IdwidthAdjuster(this);
133 idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
135 setAnnotationPanel(new AnnotationPanel(this));
136 setAlabels(new AnnotationLabels(this));
138 annotationScroller.setViewportView(getAnnotationPanel());
139 annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
141 scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
142 seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
144 setScrollValues(0, 0);
146 hscroll.addAdjustmentListener(this);
147 vscroll.addAdjustmentListener(this);
149 addComponentListener(new ComponentAdapter()
152 public void componentResized(ComponentEvent evt)
154 // reset the viewport ranges when the alignment panel is resized
155 // in particular, this initialises the end residue value when Jalview
157 ViewportRanges ranges = av.getRanges();
158 if (av.getWrapAlignment())
160 int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
161 getSeqPanel().seqCanvas.getWidth());
162 ranges.setViewportWidth(widthInRes);
166 int widthInRes = getSeqPanel().seqCanvas.getWidth()
168 int heightInSeq = getSeqPanel().seqCanvas.getHeight()
169 / av.getCharHeight();
171 ranges.setViewportWidth(widthInRes);
172 ranges.setViewportHeight(heightInSeq);
178 final AlignmentPanel ap = this;
179 propertyChangeListener = new PropertyChangeListener()
182 public void propertyChange(PropertyChangeEvent evt)
184 if (evt.getPropertyName().equals("alignment"))
186 PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
191 av.addPropertyChangeListener(propertyChangeListener);
193 av.getRanges().addPropertyChangeListener(this);
195 adjustAnnotationHeight();
200 public AlignViewportI getAlignViewport()
205 public void alignmentChanged()
207 av.alignmentChanged(this);
209 if (getCalculationDialog() != null)
211 getCalculationDialog().validateCalcTypes();
214 alignFrame.updateEditMenuBar();
216 // no idea if we need to update structure
217 paintAlignment(true, true);
224 public void fontChanged()
226 // set idCanvas bufferedImage to null
227 // to prevent drawing old image
228 FontMetrics fm = getFontMetrics(av.getFont());
230 scalePanelHolder.setPreferredSize(
231 new Dimension(10, av.getCharHeight() + fm.getDescent()));
232 idSpaceFillerPanel1.setPreferredSize(
233 new Dimension(10, av.getCharHeight() + fm.getDescent()));
234 idwidthAdjuster.invalidate();
235 scalePanelHolder.invalidate();
236 getIdPanel().getIdCanvas().gg = null;
237 getSeqPanel().seqCanvas.img = null;
238 getAnnotationPanel().adjustPanelHeight();
240 Dimension d = calculateIdWidth();
241 getIdPanel().getIdCanvas().setPreferredSize(d);
242 hscrollFillerPanel.setPreferredSize(d);
248 * Calculate the width of the alignment labels based on the displayed names
249 * and any bounds on label width set in preferences.
251 * @return Dimension giving the maximum width of the alignment label panel
252 * that should be used.
254 public Dimension calculateIdWidth()
256 // calculate sensible default width when no preference is available
258 if (av.getIdWidth() < 0)
260 int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
261 int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
262 int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
263 r = calculateIdWidth(maxwidth);
264 av.setIdWidth(r.width);
269 r.width = av.getIdWidth();
276 * Calculate the width of the alignment labels based on the displayed names
277 * and any bounds on label width set in preferences.
280 * -1 or maximum width allowed for IdWidth
281 * @return Dimension giving the maximum width of the alignment label panel
282 * that should be used.
284 protected Dimension calculateIdWidth(int maxwidth)
286 Container c = new Container();
288 FontMetrics fm = c.getFontMetrics(
289 new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
291 AlignmentI al = av.getAlignment();
295 while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
297 SequenceI s = al.getSequenceAt(i);
298 String id = s.getDisplayId(av.getShowJVSuffix());
299 int stringWidth = fm.stringWidth(id);
300 idWidth = Math.max(idWidth, stringWidth);
304 // Also check annotation label widths
307 if (al.getAlignmentAnnotation() != null)
309 fm = c.getFontMetrics(getAlabels().getFont());
311 while (i < al.getAlignmentAnnotation().length)
313 String label = al.getAlignmentAnnotation()[i].label;
314 int stringWidth = fm.stringWidth(label);
315 idWidth = Math.max(idWidth, stringWidth);
320 int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
321 w += ID_WIDTH_PADDING;
323 return new Dimension(w, 12);
327 * Highlight the given results on the alignment
330 public void highlightSearchResults(SearchResultsI results)
332 boolean scrolled = scrollToPosition(results, 0, false);
334 boolean noFastPaint = scrolled && av.getWrapAlignment();
336 getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
340 * Scroll the view to show the position of the highlighted region in results
343 * @param searchResults
346 public boolean scrollToPosition(SearchResultsI searchResults)
348 return scrollToPosition(searchResults, 0, false);
352 * Scrolls the view (if necessary) to show the position of the first
353 * highlighted region in results (if any). Answers true if the view was
354 * scrolled, or false if no matched region was found, or it is already
358 * @param verticalOffset
359 * if greater than zero, allows scrolling to a position below the
360 * first displayed sequence
362 * if true, try to centre the search results horizontally in the view
365 protected boolean scrollToPosition(SearchResultsI results,
366 int verticalOffset, boolean centre)
368 int startv, endv, starts, ends;
369 ViewportRanges ranges = av.getRanges();
371 if (results == null || results.isEmpty() || av == null
372 || av.getAlignment() == null)
376 int seqIndex = av.getAlignment().findIndex(results);
381 SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
383 int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
392 * To centre results, scroll to positions half the visible width
393 * left/right of the start/end positions
397 int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
398 start = Math.max(start - offset, 0);
399 end = end + offset - 1;
405 if (end == seq.getEnd())
410 if (av.hasHiddenColumns())
412 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
413 start = hidden.absoluteToVisibleColumn(start);
414 end = hidden.absoluteToVisibleColumn(end);
417 if (!hidden.isVisible(r[0]))
419 // don't scroll - position isn't visible
426 * allow for offset of target sequence (actually scroll to one above it)
428 seqIndex = Math.max(0, seqIndex - verticalOffset);
429 boolean scrollNeeded = true;
431 if (!av.getWrapAlignment())
433 if ((startv = ranges.getStartRes()) >= start)
436 * Scroll left to make start of search results visible
438 setScrollValues(start, seqIndex);
440 else if ((endv = ranges.getEndRes()) <= end)
443 * Scroll right to make end of search results visible
445 setScrollValues(startv + end - endv, seqIndex);
447 else if ((starts = ranges.getStartSeq()) > seqIndex)
450 * Scroll up to make start of search results visible
452 setScrollValues(ranges.getStartRes(), seqIndex);
454 else if ((ends = ranges.getEndSeq()) <= seqIndex)
457 * Scroll down to make end of search results visible
459 setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
463 * Else results are already visible - no need to scroll
465 scrollNeeded = false;
469 scrollNeeded = ranges.scrollToWrappedVisible(start);
472 paintAlignment(false, false);
480 * @return DOCUMENT ME!
482 public OverviewPanel getOverviewPanel()
484 return overviewPanel;
493 public void setOverviewPanel(OverviewPanel op)
501 * Hide or show annotation panel
504 public void setAnnotationVisible(boolean b)
506 if (!av.getWrapAlignment())
508 annotationSpaceFillerHolder.setVisible(b);
509 annotationScroller.setVisible(b);
515 * automatically adjust annotation panel height for new annotation whilst
516 * ensuring the alignment is still visible.
519 public void adjustAnnotationHeight()
521 // TODO: display vertical annotation scrollbar if necessary
522 // this is called after loading new annotation onto alignment
523 if (alignFrame.getHeight() == 0)
525 System.out.println("NEEDS FIXING");
527 validateAnnotationDimensions(true);
529 // TODO: many places call this method and also paintAlignment with various
530 // different settings. this means multiple redraws are triggered...
531 paintAlignment(true, av.needToUpdateStructureViews());
535 * calculate the annotation dimensions and refresh slider values accordingly.
536 * need to do repaints/notifys afterwards.
538 protected void validateAnnotationDimensions(boolean adjustPanelHeight)
540 int annotationHeight = getAnnotationPanel().adjustPanelHeight();
541 annotationHeight = getAnnotationPanel()
542 .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
545 annotationScroller.setPreferredSize(
546 new Dimension(annotationScroller.getWidth(), annotationHeight));
548 Dimension e = idPanel.getSize();
549 alabels.setSize(new Dimension(e.width, annotationHeight));
551 annotationSpaceFillerHolder.setPreferredSize(new Dimension(
552 annotationSpaceFillerHolder.getWidth(), annotationHeight));
553 annotationScroller.validate();
554 annotationScroller.addNotify();
558 * update alignment layout for viewport settings
563 public void updateLayout()
566 setAnnotationVisible(av.isShowAnnotation());
567 boolean wrap = av.getWrapAlignment();
568 ViewportRanges ranges = av.getRanges();
569 ranges.setStartSeq(0);
570 scalePanelHolder.setVisible(!wrap);
571 hscroll.setVisible(!wrap);
572 idwidthAdjuster.setVisible(!wrap);
576 annotationScroller.setVisible(false);
577 annotationSpaceFillerHolder.setVisible(false);
579 else if (av.isShowAnnotation())
581 annotationScroller.setVisible(true);
582 annotationSpaceFillerHolder.setVisible(true);
583 validateAnnotationDimensions(false);
586 int canvasWidth = getSeqPanel().seqCanvas.getWidth();
588 { // may not yet be laid out
591 int widthInRes = getSeqPanel().seqCanvas
592 .getWrappedCanvasWidth(canvasWidth);
593 ranges.setViewportWidth(widthInRes);
597 int widthInRes = (canvasWidth / av.getCharWidth());
598 int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
599 / av.getCharHeight());
601 ranges.setViewportWidth(widthInRes);
602 ranges.setViewportHeight(heightInSeq);
606 idSpaceFillerPanel1.setVisible(!wrap);
612 * Adjust row/column scrollers to show a visible position in the alignment.
615 * visible column to scroll to
617 * visible row to scroll to
620 public void setScrollValues(int xpos, int ypos)
625 if (av == null || av.getAlignment() == null)
630 if (av.getWrapAlignment())
632 setScrollingForWrappedPanel(x);
636 int width = av.getAlignment().getVisibleWidth();
637 int height = av.getAlignment().getHeight();
639 hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
640 vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
647 if (vextent > height)
652 if ((hextent + x) > width)
657 if ((vextent + y) > height)
659 y = height - vextent;
672 // update the scroll values
673 hscroll.setValues(x, hextent, 0, width);
674 vscroll.setValues(y, vextent, 0, height);
679 * Respond to adjustment event when horizontal or vertical scrollbar is
683 * adjustment event encoding whether hscroll or vscroll changed
686 public void adjustmentValueChanged(AdjustmentEvent evt)
688 if (av.getWrapAlignment())
690 adjustScrollingWrapped(evt);
694 ViewportRanges ranges = av.getRanges();
696 if (evt.getSource() == hscroll)
698 int oldX = ranges.getStartRes();
699 int oldwidth = ranges.getViewportWidth();
700 int x = hscroll.getValue();
701 int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
703 // if we're scrolling to the position we're already at, stop
704 // this prevents infinite recursion of events when the scroll/viewport
705 // ranges values are the same
706 if ((x == oldX) && (width == oldwidth))
710 ranges.setViewportStartAndWidth(x, width);
712 else if (evt.getSource() == vscroll)
714 int oldY = ranges.getStartSeq();
715 int oldheight = ranges.getViewportHeight();
716 int y = vscroll.getValue();
717 int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
719 // if we're scrolling to the position we're already at, stop
720 // this prevents infinite recursion of events when the scroll/viewport
721 // ranges values are the same
722 if ((y == oldY) && (height == oldheight))
726 ranges.setViewportStartAndHeight(y, height);
732 * Responds to a scroll change by setting the start position of the viewport.
737 protected void adjustScrollingWrapped(AdjustmentEvent evt)
739 if (evt.getSource() == hscroll)
741 return; // no horizontal scroll when wrapped
743 final ViewportRanges ranges = av.getRanges();
745 if (evt.getSource() == vscroll)
747 int newY = vscroll.getValue();
750 * if we're scrolling to the position we're already at, stop
751 * this prevents infinite recursion of events when the scroll/viewport
752 * ranges values are the same
754 int oldX = ranges.getStartRes();
755 int oldY = ranges.getWrappedScrollPosition(oldX);
763 * limit page up/down to one width's worth of positions
765 int rowSize = ranges.getViewportWidth();
766 int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
767 ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
772 // This is only called if file loaded is a jar file that
773 // was wrapped when saved and user has wrap alignment true
774 // as preference setting
775 SwingUtilities.invokeLater(new Runnable()
780 // When updating scrolling to use ViewportChange events, this code
781 // could not be validated and it is not clear if it is now being
782 // called. Log warning here in case it is called and unforeseen
785 "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
787 // scroll to start of panel
788 ranges.setStartRes(0);
789 ranges.setStartSeq(0);
797 * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
800 public void paintAlignment(boolean updateOverview,
801 boolean updateStructures)
803 final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
804 av.isShowAutocalculatedAbove());
805 sorter.sort(getAlignment().getAlignmentAnnotation(),
806 av.getSortAnnotationsBy());
809 if (updateStructures)
811 av.getStructureSelectionManager().sequenceColoursChanged(this);
816 if (overviewPanel != null)
818 overviewPanel.updateOverviewImage();
830 public void paintComponent(Graphics g)
832 invalidate(); // needed so that the id width adjuster works correctly
834 Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
835 idPanelHolder.setPreferredSize(d);
836 hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
838 validate(); // needed so that the id width adjuster works correctly
841 * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
842 * though I still think this call should be elsewhere.
844 ViewportRanges ranges = av.getRanges();
845 setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
849 * Set vertical scroll bar position, and number of increments, for wrapped
852 * @param topLeftColumn
853 * the column position at top left (0..)
855 private void setScrollingForWrappedPanel(int topLeftColumn)
857 ViewportRanges ranges = av.getRanges();
858 int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
859 int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
862 * a scrollbar's value can be set to at most (maximum-extent)
863 * so we add extent (1) to the maxScroll value
865 vscroll.setUnitIncrement(1);
866 vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
879 * @return DOCUMENT ME!
881 * @throws PrinterException
885 public int print(Graphics pg, PageFormat pf, int pi)
886 throws PrinterException
888 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
890 int pwidth = (int) pf.getImageableWidth();
891 int pheight = (int) pf.getImageableHeight();
893 if (av.getWrapAlignment())
895 return printWrappedAlignment(pwidth, pheight, pi, pg);
899 return printUnwrapped(pwidth, pheight, pi, pg, pg);
904 * Draws the alignment image, including sequence ids, sequences, and
905 * annotation labels and annotations if shown, on either one or two Graphics
915 * the graphics context for sequence ids and annotation labels
916 * @param alignmentGraphics
917 * the graphics context for sequences and annotations (may or may not
918 * be the same context as idGraphics)
920 * @throws PrinterException
922 public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
923 Graphics idGraphics, Graphics alignmentGraphics)
924 throws PrinterException
926 final int idWidth = getVisibleIdWidth(false);
929 * Get the horizontal offset to where we draw the sequences.
930 * This is idWidth if using a single Graphics context, else zero.
932 final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
935 FontMetrics fm = getFontMetrics(av.getFont());
936 final int charHeight = av.getCharHeight();
937 final int scaleHeight = charHeight + fm.getDescent();
939 idGraphics.setColor(Color.white);
940 idGraphics.fillRect(0, 0, pageWidth, pageHeight);
941 idGraphics.setFont(av.getFont());
944 * How many sequences and residues can we fit on a printable page?
946 final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
948 final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
950 final int alignmentWidth = av.getAlignment().getVisibleWidth();
951 int pagesWide = (alignmentWidth / totalRes) + 1;
953 final int startRes = (pageIndex % pagesWide) * totalRes;
954 final int endRes = Math.min(startRes + totalRes - 1,
957 final int startSeq = (pageIndex / pagesWide) * totalSeq;
958 final int alignmentHeight = av.getAlignment().getHeight();
959 final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
961 int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
963 if (av.isShowAnnotation())
965 pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
968 pagesHigh /= pageHeight;
970 if (pageIndex >= (pagesWide * pagesHigh))
972 return Printable.NO_SUCH_PAGE;
974 final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
977 * draw the Scale at horizontal offset, then reset to top left (0, 0)
979 alignmentGraphics.translate(alignmentGraphicsOffset, 0);
980 getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
981 pageWidth - idWidth, scaleHeight);
982 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
985 * Draw the sequence ids, offset for scale height,
986 * then reset to top left (0, 0)
988 idGraphics.translate(0, scaleHeight);
989 IdCanvas idCanvas = getIdPanel().getIdCanvas();
990 List<SequenceI> selection = av.getSelectionGroup() == null ? null
991 : av.getSelectionGroup().getSequences(null);
992 idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
995 idGraphics.setFont(av.getFont());
996 idGraphics.translate(0, -scaleHeight);
999 * draw the sequences, offset for scale height, and id width (if using a
1000 * single graphics context), then reset to (0, scale height)
1002 alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1003 getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1004 endRes, startSeq, endSeq - 1);
1005 alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1007 if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1010 * draw annotation labels; drawComponent() translates by
1011 * getScrollOffset(), so compensate for that first;
1012 * then reset to (0, scale height)
1014 int offset = getAlabels().getScrollOffset();
1015 idGraphics.translate(0, -offset);
1016 idGraphics.translate(0, alignmentDrawnHeight);
1017 getAlabels().drawComponent(idGraphics, idWidth);
1018 idGraphics.translate(0, -alignmentDrawnHeight);
1021 * draw the annotations starting at
1022 * (idOffset, alignmentHeight) from (0, scaleHeight)
1024 alignmentGraphics.translate(alignmentGraphicsOffset,
1025 alignmentDrawnHeight);
1026 getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1027 alignmentGraphics, -1, startRes, endRes + 1);
1030 return Printable.PAGE_EXISTS;
1034 * Prints one page of an alignment in wrapped mode. Returns
1035 * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1036 * no page could be drawn (page number out of range).
1046 * @throws PrinterException
1048 public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1049 Graphics g) throws PrinterException
1051 getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1053 int annotationHeight = 0;
1054 if (av.isShowAnnotation())
1056 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1059 int hgap = av.getCharHeight();
1060 if (av.getScaleAboveWrapped())
1062 hgap += av.getCharHeight();
1065 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1068 int idWidth = getVisibleIdWidth(false);
1070 int maxwidth = av.getAlignment().getVisibleWidth();
1072 int resWidth = getSeqPanel().seqCanvas
1073 .getWrappedCanvasWidth(pageWidth - idWidth);
1074 av.getRanges().setViewportStartAndWidth(0, resWidth);
1076 int totalHeight = cHeight * (maxwidth / resWidth + 1);
1078 g.setColor(Color.white);
1079 g.fillRect(0, 0, pageWidth, pageHeight);
1080 g.setFont(av.getFont());
1081 g.setColor(Color.black);
1084 * method: print the whole wrapped alignment, but with a clip region that
1085 * is restricted to the requested page; this supports selective print of
1086 * single pages or ranges, (at the cost of repeated processing in the
1087 * 'normal' case, when all pages are printed)
1089 g.translate(0, -pageNumber * pageHeight);
1091 g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1094 * draw sequence ids and annotation labels (if shown)
1096 IdCanvas idCanvas = getIdPanel().getIdCanvas();
1097 idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1099 g.translate(idWidth, 0);
1101 getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1104 if ((pageNumber * pageHeight) < totalHeight)
1106 return Printable.PAGE_EXISTS;
1110 return Printable.NO_SUCH_PAGE;
1115 * get current sequence ID panel width, or nominal value if panel were to be
1116 * displayed using default settings
1120 public int getVisibleIdWidth()
1122 return getVisibleIdWidth(true);
1126 * get current sequence ID panel width, or nominal value if panel were to be
1127 * displayed using default settings
1130 * indicate if the Id width for onscreen or offscreen display should
1134 protected int getVisibleIdWidth(boolean onscreen)
1136 // see if rendering offscreen - check preferences and calc width accordingly
1137 if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1139 return calculateIdWidth(-1).width;
1141 Integer idwidth = onscreen ? null
1142 : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1143 if (idwidth != null)
1145 return idwidth.intValue() + ID_WIDTH_PADDING;
1148 int w = getIdPanel().getWidth();
1149 return (w > 0 ? w : calculateIdWidth().width);
1152 void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1154 int boarderBottomOffset = 5;
1155 long pSessionId = System.currentTimeMillis();
1156 headless = (System.getProperty("java.awt.headless") != null
1157 && System.getProperty("java.awt.headless").equals("true"));
1158 if (alignFrame != null && !headless)
1162 alignFrame.setProgressBar(MessageManager
1163 .formatMessage("status.saving_file", new Object[]
1164 { type.getLabel() }), pSessionId);
1169 AlignmentDimension aDimension = getAlignmentDimension();
1172 jalview.util.ImageMaker im;
1173 final String imageAction, imageTitle;
1174 if (type == jalview.util.ImageMaker.TYPE.PNG)
1176 imageAction = "Create PNG image from alignment";
1179 else if (type == jalview.util.ImageMaker.TYPE.EPS)
1181 imageAction = "Create EPS file from alignment";
1182 imageTitle = alignFrame.getTitle();
1186 imageAction = "Create SVG file from alignment";
1187 imageTitle = alignFrame.getTitle();
1190 im = new jalview.util.ImageMaker(this, type, imageAction,
1191 aDimension.getWidth(),
1192 aDimension.getHeight() + boarderBottomOffset, file,
1193 imageTitle, alignFrame, pSessionId, headless);
1194 Graphics graphics = im.getGraphics();
1195 if (av.getWrapAlignment())
1197 if (graphics != null)
1199 printWrappedAlignment(aDimension.getWidth(),
1200 aDimension.getHeight() + boarderBottomOffset, 0,
1207 if (graphics != null)
1209 printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1210 graphics, graphics);
1215 } catch (OutOfMemoryError err)
1218 System.out.println("########################\n" + "OUT OF MEMORY "
1219 + file + "\n" + "########################");
1220 new OOMWarning("Creating Image for " + file, err);
1221 // System.out.println("Create IMAGE: " + err);
1222 } catch (Exception ex)
1224 ex.printStackTrace();
1232 public AlignmentDimension getAlignmentDimension()
1234 int maxwidth = av.getAlignment().getVisibleWidth();
1236 int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1237 + getScalePanel().getHeight();
1238 int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1240 if (av.getWrapAlignment())
1242 height = getWrappedHeight();
1245 // need to obtain default alignment width and then add in any
1246 // additional allowance for id margin
1247 // this duplicates the calculation in getWrappedHeight but adjusts for
1249 width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1250 - alignFrame.getInsets().left - alignFrame.getInsets().right
1251 - getVisibleIdWidth() + getVisibleIdWidth(false);
1255 width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1259 else if (av.isShowAnnotation())
1261 height += getAnnotationPanel().adjustPanelHeight() + 3;
1263 return new AlignmentDimension(width, height);
1270 public void makeEPS(File epsFile)
1272 makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1278 public void makePNG(File pngFile)
1280 makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1283 public void makeSVG(File svgFile)
1285 makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1288 public void makePNGImageMap(File imgMapFile, String imageName)
1290 // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1291 // ////////////////////////////////////////////
1292 int idWidth = getVisibleIdWidth(false);
1293 FontMetrics fm = getFontMetrics(av.getFont());
1294 int scaleHeight = av.getCharHeight() + fm.getDescent();
1297 // ////////////////////////////////
1298 if (imgMapFile != null)
1302 int sSize = av.getAlignment().getHeight();
1303 int alwidth = av.getAlignment().getWidth();
1304 PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1305 out.println(HTMLOutput.getImageMapHTML());
1306 out.println("<img src=\"" + imageName
1307 + "\" border=\"0\" usemap=\"#Map\" >"
1308 + "<map name=\"Map\">");
1310 for (int s = 0; s < sSize; s++)
1312 int sy = s * av.getCharHeight() + scaleHeight;
1314 SequenceI seq = av.getAlignment().getSequenceAt(s);
1315 SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1316 for (int column = 0; column < alwidth; column++)
1318 StringBuilder text = new StringBuilder(512);
1319 String triplet = null;
1320 if (av.getAlignment().isNucleotide())
1322 triplet = ResidueProperties.nucleotideName.get(seq
1323 .getCharAt(column) + "");
1327 triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1331 if (triplet == null)
1336 int seqPos = seq.findPosition(column);
1337 int gSize = groups.length;
1338 for (int g = 0; g < gSize; g++)
1340 if (text.length() < 1)
1342 text.append("<area shape=\"rect\" coords=\"")
1343 .append((idWidth + column * av.getCharWidth()))
1344 .append(",").append(sy).append(",")
1345 .append((idWidth + (column + 1) * av.getCharWidth()))
1346 .append(",").append((av.getCharHeight() + sy))
1347 .append("\"").append(" onMouseOver=\"toolTip('")
1348 .append(seqPos).append(" ").append(triplet);
1351 if (groups[g].getStartRes() < column
1352 && groups[g].getEndRes() > column)
1354 text.append("<br><em>").append(groups[g].getName())
1359 if (text.length() < 1)
1361 text.append("<area shape=\"rect\" coords=\"")
1362 .append((idWidth + column * av.getCharWidth()))
1363 .append(",").append(sy).append(",")
1364 .append((idWidth + (column + 1) * av.getCharWidth()))
1365 .append(",").append((av.getCharHeight() + sy))
1366 .append("\"").append(" onMouseOver=\"toolTip('")
1367 .append(seqPos).append(" ").append(triplet);
1369 if (!Comparison.isGap(seq.getCharAt(column)))
1371 List<SequenceFeature> features = seq.findFeatures(column, column);
1372 for (SequenceFeature sf : features)
1374 if (sf.isContactFeature())
1376 text.append("<br>").append(sf.getType()).append(" ")
1377 .append(sf.getBegin()).append(":")
1378 .append(sf.getEnd());
1382 text.append("<br>");
1383 text.append(sf.getType());
1384 String description = sf.getDescription();
1385 if (description != null
1386 && !sf.getType().equals(description))
1388 description = description.replace("\"", """);
1389 text.append(" ").append(description);
1392 String status = sf.getStatus();
1393 if (status != null && !"".equals(status))
1395 text.append(" (").append(status).append(")");
1398 if (text.length() > 1)
1400 text.append("')\"; onMouseOut=\"toolTip()\"; href=\"#\">");
1401 out.println(text.toString());
1406 out.println("</map></body></html>");
1409 } catch (Exception ex)
1411 ex.printStackTrace();
1413 } // /////////END OF IMAGE MAP
1418 * Answers the height of the entire alignment in pixels, assuming it is in
1423 int getWrappedHeight()
1425 int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1427 if (System.getProperty("java.awt.headless") != null
1428 && System.getProperty("java.awt.headless").equals("true"))
1430 seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1431 - vscroll.getPreferredSize().width
1432 - alignFrame.getInsets().left - alignFrame.getInsets().right;
1435 int chunkWidth = getSeqPanel().seqCanvas
1436 .getWrappedCanvasWidth(seqPanelWidth);
1438 int hgap = av.getCharHeight();
1439 if (av.getScaleAboveWrapped())
1441 hgap += av.getCharHeight();
1444 int annotationHeight = 0;
1445 if (av.isShowAnnotation())
1447 hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1448 annotationHeight = getAnnotationPanel().adjustPanelHeight();
1451 int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1454 int maxwidth = av.getAlignment().getWidth();
1455 if (av.hasHiddenColumns())
1457 maxwidth = av.getAlignment().getHiddenColumns()
1458 .absoluteToVisibleColumn(maxwidth) - 1;
1461 int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1467 * close the panel - deregisters all listeners and nulls any references to
1470 public void closePanel()
1472 PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1473 PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1474 PaintRefresher.RemoveComponent(this);
1479 * try to ensure references are nulled
1481 if (annotationPanel != null)
1483 annotationPanel.dispose();
1484 annotationPanel = null;
1489 av.removePropertyChangeListener(propertyChangeListener);
1490 propertyChangeListener = null;
1491 StructureSelectionManager ssm = av.getStructureSelectionManager();
1492 ssm.removeStructureViewerListener(getSeqPanel(), null);
1493 ssm.removeSelectionListener(getSeqPanel());
1494 ssm.removeCommandListener(av);
1495 ssm.removeStructureViewerListener(getSeqPanel(), null);
1496 ssm.removeSelectionListener(getSeqPanel());
1502 if (Cache.log.isDebugEnabled())
1504 Cache.log.warn("Closing alignment panel which is already closed.");
1510 * Close any open dialogs that would be orphaned when this one is closed
1512 protected void closeChildFrames()
1514 if (overviewPanel != null)
1516 overviewPanel.dispose();
1517 overviewPanel = null;
1519 if (calculationDialog != null)
1521 calculationDialog.closeFrame();
1522 calculationDialog = null;
1527 * hides or shows dynamic annotation rows based on groups and av state flags
1529 public void updateAnnotation()
1531 updateAnnotation(false, false);
1534 public void updateAnnotation(boolean applyGlobalSettings)
1536 updateAnnotation(applyGlobalSettings, false);
1539 public void updateAnnotation(boolean applyGlobalSettings,
1540 boolean preserveNewGroupSettings)
1542 av.updateGroupAnnotationSettings(applyGlobalSettings,
1543 preserveNewGroupSettings);
1544 adjustAnnotationHeight();
1548 public AlignmentI getAlignment()
1550 return av == null ? null : av.getAlignment();
1554 public String getViewName()
1556 return av.getViewName();
1560 * Make/Unmake this alignment panel the current input focus
1564 public void setSelected(boolean b)
1568 if (alignFrame.getSplitViewContainer() != null)
1571 * bring enclosing SplitFrame to front first if there is one
1573 ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1575 alignFrame.setSelected(b);
1576 } catch (Exception ex)
1582 alignFrame.setDisplayedView(this);
1587 public StructureSelectionManager getStructureSelectionManager()
1589 return av.getStructureSelectionManager();
1593 public void raiseOOMWarning(String string, OutOfMemoryError error)
1595 new OOMWarning(string, error, this);
1599 public jalview.api.FeatureRenderer cloneFeatureRenderer()
1602 return new FeatureRenderer(this);
1606 public jalview.api.FeatureRenderer getFeatureRenderer()
1608 return seqPanel.seqCanvas.getFeatureRenderer();
1611 public void updateFeatureRenderer(
1612 jalview.renderer.seqfeatures.FeatureRenderer fr)
1614 fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1617 public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1619 if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1621 getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1625 public ScalePanel getScalePanel()
1630 public void setScalePanel(ScalePanel scalePanel)
1632 this.scalePanel = scalePanel;
1635 public SeqPanel getSeqPanel()
1640 public void setSeqPanel(SeqPanel seqPanel)
1642 this.seqPanel = seqPanel;
1645 public AnnotationPanel getAnnotationPanel()
1647 return annotationPanel;
1650 public void setAnnotationPanel(AnnotationPanel annotationPanel)
1652 this.annotationPanel = annotationPanel;
1655 public AnnotationLabels getAlabels()
1660 public void setAlabels(AnnotationLabels alabels)
1662 this.alabels = alabels;
1665 public IdPanel getIdPanel()
1670 public void setIdPanel(IdPanel idPanel)
1672 this.idPanel = idPanel;
1676 * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1677 * The aim is to keep the two alignments 'lined up' on their centre columns.
1680 * holds mapped region(s) of this alignment that we are scrolling
1681 * 'to'; may be modified for sequence offset by this method
1682 * @param verticalOffset
1683 * the number of visible sequences to show above the mapped region
1685 protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1687 scrollToPosition(sr, verticalOffset, true);
1691 * Set a flag to say do not scroll any (cDNA/protein) complement.
1695 protected void setToScrollComplementPanel(boolean b)
1697 this.scrollComplementaryPanel = b;
1701 * Get whether to scroll complement panel
1703 * @return true if cDNA/protein complement panels should be scrolled
1705 protected boolean isSetToScrollComplementPanel()
1707 return this.scrollComplementaryPanel;
1713 * @adjustHeight if true, try to recalculate panel height for visible
1716 protected void refresh(boolean adjustHeight)
1718 validateAnnotationDimensions(adjustHeight);
1722 // sort, repaint, update overview
1723 paintAlignment(true, false);
1727 // lightweight repaint
1734 * Property change event fired when a change is made to the viewport ranges
1735 * object associated with this alignment panel's viewport
1737 public void propertyChange(PropertyChangeEvent evt)
1739 // update this panel's scroll values based on the new viewport ranges values
1740 ViewportRanges ranges = av.getRanges();
1741 int x = ranges.getStartRes();
1742 int y = ranges.getStartSeq();
1743 setScrollValues(x, y);
1745 // now update any complementary alignment (its viewport ranges object
1746 // is different so does not get automatically updated)
1747 if (isSetToScrollComplementPanel())
1749 setToScrollComplementPanel(false);
1750 av.scrollComplementaryAlignment();
1751 setToScrollComplementPanel(true);
1756 * Set the reference to the PCA/Tree chooser dialog for this panel. This
1757 * reference should be nulled when the dialog is closed.
1759 * @param calculationChooser
1761 public void setCalculationDialog(CalculationChooser calculationChooser)
1763 calculationDialog = calculationChooser;
1767 * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1770 public CalculationChooser getCalculationDialog()
1772 return calculationDialog;